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.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Gemstar.BSPMS.HotelScanOrder.Common.Common
{
/// <summary>
/// 在有些action是由前端异步请求时,并且返回的数据是json时,增加此属性,以便在发生异常时,返回失败对应的json格式,以便前端可以正常处理,而不是前端无法处理,直接没有任何反应
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class JsonExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled)
{
//返回异常JSON
filterContext.Result = new JsonResult
{
Data = JsonResultData.Failure(filterContext.Exception)
};
}
}
}
}
| 29.62069 | 99 | 0.643772 | [
"Apache-2.0"
] | PoetSnow/Web-API | Gemstar.BSPMS.HotelScanOrder.Common/Common/JsonExceptionAttribute.cs | 1,023 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Chime.Model
{
/// <summary>
/// The phone number and proxy phone number for a participant in an Amazon Chime Voice
/// Connector proxy session.
/// </summary>
public partial class Participant
{
private string _phoneNumber;
private string _proxyPhoneNumber;
/// <summary>
/// Gets and sets the property PhoneNumber.
/// <para>
/// The participant's phone number.
/// </para>
/// </summary>
public string PhoneNumber
{
get { return this._phoneNumber; }
set { this._phoneNumber = value; }
}
// Check to see if PhoneNumber property is set
internal bool IsSetPhoneNumber()
{
return this._phoneNumber != null;
}
/// <summary>
/// Gets and sets the property ProxyPhoneNumber.
/// <para>
/// The participant's proxy phone number.
/// </para>
/// </summary>
public string ProxyPhoneNumber
{
get { return this._proxyPhoneNumber; }
set { this._proxyPhoneNumber = value; }
}
// Check to see if ProxyPhoneNumber property is set
internal bool IsSetProxyPhoneNumber()
{
return this._proxyPhoneNumber != null;
}
}
} | 29.038961 | 103 | 0.626118 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Chime/Generated/Model/Participant.cs | 2,236 | C# |
using HeroesData.Parser.Overrides.DataOverrides;
using System;
using System.Xml.Linq;
namespace HeroesData.Parser.Overrides
{
public class SprayOverrideLoader : OverrideLoaderBase<SprayDataOverride>, IOverrideLoader
{
public SprayOverrideLoader(int? hotsBuild)
: base(hotsBuild)
{
}
public SprayOverrideLoader(string appPath, int? hotsBuild)
: base(appPath, hotsBuild)
{
}
protected override string OverrideFileName => $"spray-{base.OverrideFileName}";
protected override string OverrideElementName => "CSpray";
protected override void SetOverride(XElement element)
{
throw new NotImplementedException();
}
}
}
| 25.965517 | 93 | 0.658699 | [
"MIT"
] | HeroesToolChest/HeroesDataParser | HeroesData.Parser/Overrides/SprayOverrideLoader.cs | 755 | C# |
using Microsoft.Azure.Cosmos.Table;
namespace USCIS.Common;
public class ReceiptStatus : Receipt
{
public string? CurrentStatus { get; set; }
public string? CurrentStatusDetails { get; set; }
public bool HasNewStatus { get; set; }
public DateTime LastChecked { get; set; }
public string ToStatusString(bool colored = false)
{
var statusString = HasNewStatus ? "(NEW STATUS)" : "(UNCHANGED)";
return colored ? $"[{(HasNewStatus ? "green" : "grey")}]{statusString}[/]" : statusString;
}
}
public class Receipt
{
public string ReceiptNumber { get; set; }
}
public class ReceiptEntity : TableEntity
{
public ReceiptEntity(string receiptNumber)
{
PartitionKey = "USCIS";
RowKey = receiptNumber;
}
public ReceiptEntity() {}
public string? CurrentStatus { get; set; } = "";
public string? CurrentStatusDetails { get; set; } = "";
public DateTime LastCheckedOn { get; set; }
public bool HasNewStatus { get; set; }
} | 26.578947 | 98 | 0.654455 | [
"MIT"
] | vpetkovic/USCIS-Case-Status-Tracker | src/USCIS.Common/Models/CaseReceiptModel.cs | 1,010 | C# |
namespace ZetaResourceEditor.RuntimeBusinessLogic.ExportImportExcel.Import
{
using System.Collections.Generic;
public class ExcelImportResult
{
public int ImportedRowCount { get; internal set; }
public List<string> ImportMessages { get; } = new();
}
} | 28.5 | 75 | 0.708772 | [
"MIT"
] | UweKeim/ZetaResourceEditor | Source/RuntimeBusinessLogic/ExportImportExcel/Import/ExcelImportResult.cs | 287 | C# |
using UnityEngine;
//using System.Reflection;
namespace Arj2D
{
public static class UnityEngineExtensions
{
#region TRASNFORM
public static void X(this Transform _transform, float _newX)
{
_transform.position = new Vector3(_newX, _transform.position.y, _transform.position.z);
}
public static void Y(this Transform _transform, float _newY)
{
_transform.position = new Vector3(_transform.position.x, _newY, _transform.position.z);
}
public static void Z(this Transform _transform, float _newZ)
{
_transform.position = new Vector3(_transform.position.x, _transform.position.y, _newZ);
}
public static void SetPos(this Transform _transform, float _posX, float _posY, float _posZ = 0.0f)
{
_transform.position = new Vector3(_posX, _posY, _posZ);
}
public static void SetPosXY(this Transform _transform, float _posX, float _posY)
{
_transform.position = new Vector3(_posX, _posY, _transform.position.z);
}
public static float GetX(this Transform _transform)
{
return _transform.position.x;
}
public static float GetY(this Transform _transform)
{
return _transform.position.y;
}
public static float GetZ(this Transform _transform)
{
return _transform.position.z;
}
public static void ShiftX(this Transform _transform, float _offsetX)
{
_transform.position = new Vector3(_transform.position.x + _offsetX, _transform.position.y, _transform.position.z);
}
public static void ShiftY(this Transform _transform, float _offsetY)
{
_transform.position = new Vector3(_transform.position.x, _transform.position.y + _offsetY, _transform.position.z);
}
public static void ShiftZ(this Transform _transform, float _offsetZ)
{
_transform.position = new Vector3(_transform.position.x, _transform.position.y, _transform.position.z + _offsetZ);
}
public static void Move(this Transform _transform, Vector2 _offset)
{
_transform.position = new Vector3(_transform.position.x + _offset.x, _transform.position.y + _offset.y, _transform.position.z);
}
public static void Move(this Transform _transform, Vector3 _offset)
{
_transform.position = new Vector3(_transform.position.x + _offset.x, _transform.position.y + _offset.y, _transform.position.z + _offset.z);
}
public static void Move(this Transform _transform, float _offsetX, float _offsetY)
{
_transform.position = new Vector3(_transform.position.x + _offsetX, _transform.position.y + _offsetY, _transform.position.z);
}
public static void Move(this Transform _transform, float _offsetX, float _offsetY, float _offsetZ)
{
_transform.position = new Vector3(_transform.position.x + _offsetX, _transform.position.y + _offsetY, _transform.position.z + _offsetZ);
}
public static void SetLocalX(this Transform _transform, float _newX)
{
_transform.localPosition = new Vector3(_newX, _transform.position.y, _transform.position.z);
}
public static void SetLocalY(this Transform _transform, float _newY)
{
_transform.localPosition = new Vector3(_transform.position.x, _newY, _transform.position.z);
}
public static void SetLocalZ(this Transform _transform, float _newZ)
{
_transform.localPosition = new Vector3(_transform.position.x, _transform.position.y, _newZ);
}
public static void SetLocalPos(this Transform _transform, float _posX, float _posY, float _posZ = 0.0f)
{
_transform.localPosition = new Vector3(_posX, _posY, _posZ);
}
public static void SetLocalPosXY(this Transform _transform, float _posX, float _posY)
{
_transform.localPosition = new Vector3(_posX, _posY, _transform.localPosition.z);
}
public static float GetLocalX(this Transform _transform)
{
return _transform.localPosition.x;
}
public static float GetLocalY(this Transform _transform)
{
return _transform.localPosition.y;
}
public static float GetLocalZ(this Transform _transform)
{
return _transform.localPosition.z;
}
public static void MoveLocal(this Transform _transform, Vector2 _offset)
{
_transform.localPosition = new Vector3(_transform.localPosition.x + _offset.x, _transform.localPosition.y + _offset.y, _transform.localPosition.z);
}
public static void MoveLocal(this Transform _transform, Vector3 _offset)
{
_transform.localPosition = new Vector3(_transform.localPosition.x + _offset.x, _transform.localPosition.y + _offset.y, _transform.localPosition.z + _offset.z);
}
public static void MoveLocal(this Transform _transform, float _offsetX, float _offsetY)
{
_transform.localPosition = new Vector3(_transform.localPosition.x + _offsetX, _transform.localPosition.y + _offsetY, _transform.localPosition.z);
}
public static void MoveLocal(this Transform _transform, float _offsetX, float _offsetY, float _offsetZ)
{
_transform.localPosition = new Vector3(_transform.localPosition.x + _offsetX, _transform.localPosition.y + _offsetY, _transform.localPosition.z + _offsetZ);
}
/// <summary>
/// Flip a transform, use for Flip Sprite
/// </summary>
public static void Flip(this Transform _transform)
{
_transform.localScale = new Vector3(_transform.localScale.x * -1f, _transform.localScale.y, _transform.localScale.z);
}
/// <summary>
/// Flip a transform, use for Flip Sprite
/// </summary>
public static void Flip(this Transform _transform, bool _facingRight)
{
Vector3 theScale = _transform.localScale;
if (_facingRight)
theScale.x = Mathf.Abs(theScale.x);
else
theScale.x = -Mathf.Abs(theScale.x);
_transform.localScale = theScale;
}
/// <summary>
/// Reset only position and rotation. Scale is not affected
/// </summary>
public static void ResetTransform(this Transform _transform)
{
_transform.position = Vector3.zero;
_transform.rotation = Quaternion.identity;
}
/// <summary>
/// Reset position, rotation and scale.
/// </summary>
public static void ResetTransformAll(this Transform _transform)
{
_transform.position = Vector3.zero;
_transform.rotation = Quaternion.identity;
_transform.localScale = Vector3.zero;
}
public static void LookAt2D(this Transform _transform, Transform _target, float _offset = 0f)
{
Vector3 relative = _transform.InverseTransformPoint(_target.position);
float angle = Mathf.Atan2(relative.x, relative.y) * Mathf.Rad2Deg - _offset;
_transform.Rotate(0, 0, -angle, Space.Self);
}
public static void LookAt2D(this Transform _transform, Vector3 _pos, float _offset)
{
Vector3 relative = _transform.InverseTransformPoint(_pos);
float angle = Mathf.Atan2(relative.x, relative.y) * Mathf.Rad2Deg - _offset;
_transform.Rotate(0, 0, -angle, Space.Self);
}
#endregion
#region GAMEOBJECT
public static int GetCollisionMask(this GameObject _gameObject, int _layer = -1)
{
if (_layer == -1)
_layer = _gameObject.layer;
int mask = 0;
for (int i = 0; i < 32; i++)
mask |= (Physics2D.GetIgnoreLayerCollision(_layer, i) ? 0 : 1) << i;
return mask;
}
public static bool IsInLayerMask(this GameObject _gameObject, LayerMask _layerMask)
{
int objLayerMask = (1 << _gameObject.layer);
return (_layerMask.value & objLayerMask) > 0;
}
public static T[] GetComponentsOnlyInChildren<T>(this GameObject _gameObject, bool _includeInactive = true) where T : Component
{
T[] tmp = _gameObject.GetComponentsInChildren<T>(_includeInactive);
if (tmp[0].gameObject.GetInstanceID() == _gameObject.GetInstanceID())
{
System.Collections.Generic.List<T> list = new System.Collections.Generic.List<T>(tmp);
list.RemoveAt(0);
return list.ToArray();
}
return tmp;
}
/// <summary>
/// Try to get a component, if the gameobject dont have that component, add it
/// </summary>
/// <typeparam name="T">Component</typeparam>
/// <param name="_gameObject">Self GameObject</param>
/// <param name="_component">Component</param>
/// <returns>the component or new component</returns>
public static T GetOrAddComponent<T>(this GameObject _gameObject) where T : Component
{
T component = _gameObject.GetComponent<T>();
if (component == null)
{
component = _gameObject.AddComponent<T>();
}
return component;
}
/// <summary>
/// Find the first GameObject with a name,, starting in a father and search in each children of children until first GameObject with the name
/// </summary>
/// <param name="_gameObject">GameObject where start</param>
/// <param name="name">Name of GameObject to find</param>
/// <returns>GameObject with the name, searching</returns>
public static GameObject FindGameObjectByNameRecursive(this GameObject _gameObject, string name)
{
if (_gameObject.name == name)
{
return _gameObject;
}
//first find it in children
Transform found = _gameObject.transform.Find(name);
if (found != null)
{
return found.gameObject;
}
//if not, find it inside each child
int children = _gameObject.transform.childCount;
for (int i = 0; i < children; ++i)
{
GameObject go = FindGameObjectByNameRecursive(_gameObject.transform.GetChild(i).gameObject, name);
if (go != null)
{
return go;
}
}
return null;
}
/// <summary>
/// Return the full path in the Hierachy of the GameObject.
/// </summary>
/// <param name="_gameObject">GameObject to find Hierachy</param>
/// <returns>String of path of GameObject,, example "Father/OneGameObject/GameObject"</returns>
public static string GetFullPath(this GameObject _gameObject)
{
System.Collections.Generic.List<string> path = new System.Collections.Generic.List<string>();
Transform current = _gameObject.transform;
path.Add(current.name);
while (current.parent != null)
{
path.Insert(0, current.parent.name);
current = current.parent;
}
return string.Join("/", path.ToArray());
}
/*
/// <summary>
/// Like SendMessage but is not necessary the GameObject be active
/// </summary>
/// <param name="_gameObject">GameObject to BroadCastMenssage</param>
/// <param name="_methodName">Name of function to call</param>
/// <param name="_parameters">Parameters (optional)</param>
public static void SendMessageSpecial(this GameObject _gameObject, string _methodName, params object[] _parameters)
{
MonoBehaviour[] components = _gameObject.GetComponents<MonoBehaviour>();
for (int i = 0; i < components.Length; i++)
{
Type scriptType = components[i].GetType();//Get ScriptType //This not return MonoBehaviour
MethodInfo methodInfo = scriptType.GetMethod(_methodName);
if (scriptType.GetMethod(_methodName) != null) //This script contains this Method?
{
methodInfo.Invoke(components[i], _parameters); //call It
}
}
}
/// <summary>
/// Like SendMEssageUpwards but is not necessary the GameObject be active
/// </summary>
/// <param name="_gameObject">GameObject to SendMenssage</param>
/// <param name="_methodName">Name of function to call</param>
/// <param name="_parameters">Parameters (optional)</param>
public static void SendMessageUpwardsSpecial(this GameObject _gameObject, string _methodName, params object[] _parameters)
{
Transform tranform = _gameObject.transform;
while (tranform != null)
{
tranform.gameObject.SendMessageSpecial(_methodName, _parameters);
tranform = tranform.parent;
}
}
/// <summary>
/// Like BroadCastMessage but is not necessary the GameObject be active
/// </summary>
/// <param name="_gameObject">GameObject to BroadCastMenssage</param>
/// <param name="_methodName">Name of function to call</param>
/// <param name="_parameters">Parameters (optional)</param>
public static void BroadCastMessageSpecial(this GameObject _gameObject, string _methodName, params object[] _parameters)
{
MonoBehaviour[] components = _gameObject.GetComponentsInChildren<MonoBehaviour>(true);
for (int i = 0; i < components.Length; i++)
{
Type scriptType = components[i].GetType();//Get ScriptType //This not return MonoBehaviour
MethodInfo methodInfo = scriptType.GetMethod(_methodName);
if (scriptType.GetMethod(_methodName) != null) //This script contains this Method?
{
methodInfo.Invoke(components[i], _parameters); //call It
}
}
}*/
#endregion
#region TEXTURE2D
public static Texture2D FlipHorizontally(this Texture2D _texture)
{
Color[] image = _texture.GetPixels();
Color[] newImage = new Color[image.Length];
int width = _texture.width;
int height = _texture.height;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
newImage[y * width + (x - width - 1)] = image[y * width + x];
}
}
Texture2D result = new Texture2D(width, height);
result.SetPixels(newImage);
result.Apply();
return result;
}
public static Texture2D FlipVertically(this Texture2D _texture)
{
Color[] image = _texture.GetPixels();
Color[] newImage = new Color[image.Length];
int width = _texture.width;
int height = _texture.height;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
newImage[(height - y - 1) * width + x] = image[y * width + x];
}
}
Texture2D result = new Texture2D(width, height);
result.SetPixels(newImage);
result.Apply();
return result;
}
#endregion
#region VECTOR2
public static Vector3 ToVector3(this Vector2 _vector2, float _z = 0f)
{
return new Vector3(_vector2.x, _vector2.y, _z);
}
public static Vector2 RotateRad(this Vector2 _vector2, float _rad)
{
float c = Mathf.Cos(_rad);
float s = Mathf.Sin(_rad);
return new Vector2(_vector2.x * c - _vector2.y * s, _vector2.y = _vector2.x * s + _vector2.y * c);
}
public static Vector2 Rotate(this Vector2 v, float degrees)
{
float s = Mathf.Sin(degrees * Mathf.Deg2Rad);
float c = Mathf.Cos(degrees * Mathf.Deg2Rad);
float tx = v.x;
float ty = v.y;
v.x = (c * tx) - (s * ty);
v.y = (s * tx) + (c * ty);
return v;
}
/// <summary>
/// Return Vector2( X value, 0f)
/// </summary>
/// <param name="_vector2"></param>
/// <returns></returns>
public static Vector2 OnlyX(this Vector2 _vector2)
{
return new Vector2(_vector2.x, 0f);
}
/// <summary>
/// Return Vector2( 0f, Y value)
/// </summary>
/// <param name="_vector2"></param>
/// <returns></returns>
public static Vector2 OnlyY(this Vector2 _vector2)
{
return new Vector2(0f, _vector2.y);
}
#endregion
#region VECTOR3
public static Vector2 ToVector2(this Vector3 _vector3)
{
return new Vector2(_vector3.x, _vector3.y);
}
/// <summary>
/// Return new Vector3( X value, 0f, 0f)
/// </summary>
/// <param name="_vector3"></param>
/// <returns></returns>
public static Vector3 OnlyX(this Vector3 _vector3)
{
return new Vector3(_vector3.x, 0f, 0f);
}
/// <summary>
/// Return new Vector3( 0f, y value, 0f)
/// </summary>
/// <param name="_vector3"></param>
/// <returns></returns>
public static Vector3 OnlyY(this Vector3 _vector3)
{
return new Vector3(0f, _vector3.y, 0f);
}
/// <summary>
/// Return new Vector3( 0f, 0f, z value)
/// </summary>
/// <param name="_vector3"></param>
/// <returns></returns>
public static Vector3 OnlyZ(this Vector3 _vector3)
{
return new Vector3(0f, 0f, _vector3.z);
}
#endregion
#region COLOR
/// <summary>
/// Returns inverted color with the same alpha
/// </summary>
public static Color Inverted(this Color _color)
{
Color result = Color.white - _color;
result.a = _color.a;
return result;
}
/// <summary>
/// Returns new color with modified red channel
/// </summary>
public static Color SetR(this Color _color, float _r)
{
return new Color(_r, _color.g, _color.b, _color.a);
}
/// <summary>
/// Returns new color with modified green channel
/// </summary>
public static Color SetG(this Color _color, float _g)
{
return new Color(_color.r, _g, _color.b, _color.a);
}
/// <summary>
/// Returns new color with modified blue channel
/// </summary>
public static Color SetB(this Color _color, float _b)
{
return new Color(_color.r, _color.g, _b, _color.a);
}
/// <summary>
/// Returns new color with modified alpha channel
/// </summary>
public static Color SetA(this Color _color, float _a)
{
return new Color(_color.r, _color.g, _color.b, _a);
}
#endregion
#region RENDERER
public static bool IsVisibleInCamera(this Renderer _renderer, Camera camera)
{
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(camera);
return GeometryUtility.TestPlanesAABB(planes, _renderer.bounds);
}
#endregion
#region SPRITERENDER
public static bool IsVisibleInCamera(this SpriteRenderer _spriteRenderer, Camera _camera)
{
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(_camera);
return GeometryUtility.TestPlanesAABB(planes, _spriteRenderer.bounds);
}
#endregion
#region CANVAS
//SET IT TO anchoredPosition
public static Vector2 WorldToCanvasPosition(this Canvas canvas, Vector3 _worldPosition, Camera _camera = null)
{
if (_camera == null)
{
_camera = Camera.main;
}
Vector3 viewport_position = _camera.WorldToViewportPoint(_worldPosition);
RectTransform canvas_rect = canvas.GetComponent<RectTransform>();
return new Vector2((viewport_position.x * canvas_rect.sizeDelta.x) - (canvas_rect.sizeDelta.x * 0.5f), (viewport_position.y * canvas_rect.sizeDelta.y) - (canvas_rect.sizeDelta.y * 0.5f));
}
#endregion
#region RectTrasnform
public static Vector3 ToWolrdPosition(this RectTransform _recTransform)
{
return _recTransform.TransformPoint(_recTransform.rect.center);
}
#endregion
#region ARRAYS
/// <summary>
/// Check if array is null or empty
/// </summary>
/// <typeparam name="T">Type of list</typeparam>
/// <param name="_array">Array to test</param>
/// <returns>if is null or empty return true, otherwise return false</returns>
public static bool IsNullOrEmpty<T>(this T[] _array)
{
if (_array == null)
return true;
if (_array.Length == 0)
return true;
return false;
}
#endregion
}
} | 40.130037 | 199 | 0.581991 | [
"BSD-2-Clause"
] | arkms/Arj2D-Unity-FrameWork | Assets/Arj2D/Scripts/UnityEngineExtensions.cs | 21,913 | C# |
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Data.Entity.Core.Metadata.Edm;
using System.Linq;
namespace PhotoGalleryService.Data.Helpers
{
public class SoftDeleteQueryVisitor : DefaultExpressionVisitor
{
public override DbExpression Visit(DbScanExpression expression)
{
var column = SoftDeleteAttribute.GetSoftDeleteColumnName(expression.Target.ElementType);
if (column != null)
{
var table = (EntityType)expression.Target.ElementType;
if (table.Properties.Any(p => p.Name == column))
{
var binding = DbExpressionBuilder.Bind(expression);
return DbExpressionBuilder.Filter(
binding,
DbExpressionBuilder.NotEqual(
DbExpressionBuilder.Property(
DbExpressionBuilder.Variable(binding.VariableType, binding.VariableName),
column),
DbExpression.FromBoolean(true)));
}
}
return base.Visit(expression);
}
}
} | 39.375 | 105 | 0.580952 | [
"MIT"
] | QuinntyneBrown/PhotoGalleryService | src/PhotoGalleryService/Data/Helpers/SoftDeleteQueryVisitor.cs | 1,262 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
using NetOffice.WordApi;
namespace NetOffice.WordApi.Behind
{
/// <summary>
/// DispatchInterface OMathPhantom
/// SupportByVersion Word, 12,14,15,16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff822693.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
[EntityType(EntityType.IsDispatchInterface)]
public class OMathPhantom : COMObject, NetOffice.WordApi.OMathPhantom
{
#pragma warning disable
#region Type Information
/// <summary>
/// Contract Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type ContractType
{
get
{
if(null == _contractType)
_contractType = typeof(NetOffice.WordApi.OMathPhantom);
return _contractType;
}
}
private static Type _contractType;
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(OMathPhantom);
return _type;
}
}
#endregion
#region Ctor
/// <summary>
/// Stub Ctor, not indented to use
/// </summary>
public OMathPhantom() : base()
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff195931.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
public virtual NetOffice.WordApi.Application Application
{
get
{
return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.WordApi.Application>(this, "Application", typeof(NetOffice.WordApi.Application));
}
}
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff192553.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
public virtual Int32 Creator
{
get
{
return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "Creator");
}
}
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff839696.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16), ProxyResult]
public virtual object Parent
{
get
{
return InvokerService.InvokeInternal.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff836090.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
public virtual NetOffice.WordApi.OMath E
{
get
{
return InvokerService.InvokeInternal.ExecuteKnownReferencePropertyGet<NetOffice.WordApi.OMath>(this, "E", typeof(NetOffice.WordApi.OMath));
}
}
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff193436.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
public virtual bool Show
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "Show");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Show", value);
}
}
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff822400.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
public virtual bool ZeroWid
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "ZeroWid");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "ZeroWid", value);
}
}
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff845709.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
public virtual bool ZeroAsc
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "ZeroAsc");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "ZeroAsc", value);
}
}
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196106.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
public virtual bool ZeroDesc
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "ZeroDesc");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "ZeroDesc", value);
}
}
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194657.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
public virtual bool Transp
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "Transp");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Transp", value);
}
}
/// <summary>
/// SupportByVersion Word 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff821572.aspx </remarks>
[SupportByVersion("Word", 12,14,15,16)]
public virtual bool Smash
{
get
{
return InvokerService.InvokeInternal.ExecuteBoolPropertyGet(this, "Smash");
}
set
{
InvokerService.InvokeInternal.ExecuteValuePropertySet(this, "Smash", value);
}
}
#endregion
#region Methods
#endregion
#pragma warning restore
}
}
| 25.748031 | 165 | 0.65367 | [
"MIT"
] | igoreksiz/NetOffice | Source/Word/Behind/DispatchInterfaces/OMathPhantom.cs | 6,542 | C# |
/*
* Copyright (C) 2021 - 2021, SanteSuite Inc. and the SanteSuite Contributors (See NOTICE.md for full copyright notices)
* Copyright (C) 2019 - 2021, Fyfe Software Inc. and the SanteSuite Contributors
* Portions Copyright (C) 2015-2018 Mohawk College of Applied Arts and Technology
*
* 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.
*
* User: fyfej
* Date: 2021-8-5
*/
using SanteDB.Core.Model.Security;
namespace SanteDB.Core.Security
{
/// <summary>
/// Represents a policy instance which
/// </summary>
public interface IPolicyInstance
{
/// <summary>
/// Security policy instance
/// </summary>
IPolicy Policy { get; }
/// <summary>
/// Gets the policy grant
/// </summary>
PolicyGrantType Rule { get; }
/// <summary>
/// Gets the securable
/// </summary>
object Securable { get; }
}
}
| 29.265306 | 120 | 0.654812 | [
"Apache-2.0"
] | santedb/santedb-api | SanteDB.Core.Api/Security/IPolicyInstance.cs | 1,436 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace helloworldConsoleApp1
{
class Adventurer
{
public int id;
public string name;
public float max_hp;
public float hp;
public int max_stamina;
public int stamina;
public int max_mana;
public int mana;
public int level;
public int str;
public int agi;
public int inte;
public int gold;
public Adventurer(int id, string name)
{
this.id = id;
this.name = name;
}
public void Init()
{
this.max_hp = DataMgr.GetInstance().GetCharacterData(this.id).max_hp;
this.hp = this.max_hp;
this.max_stamina = DataMgr.GetInstance().GetCharacterData(this.id).max_stamina;
this.stamina = this.max_stamina;
this.max_mana = DataMgr.GetInstance().GetCharacterData(this.id).max_mana;
this.mana = this.max_mana;
this.level = 1;
this.str = 0;
this.agi = 0;
this.inte = 0;
this.gold = 0;
}
}
}
| 25.911111 | 91 | 0.548885 | [
"MIT"
] | hanamc99/LearnGameProgramming | Adventurer.cs | 1,168 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Slack.NetStandard.Messages.Blocks;
namespace Slack.NetStandard.Messages.Elements
{
public class Image:IContextElement,IMessageElement
{
public string Type => nameof(Image).ToLower();
[JsonProperty("image_url")]
public string ImageUrl { get; set; }
[JsonProperty("alt_text")]
public string AltText { get; set; }
}
}
| 23.35 | 54 | 0.689507 | [
"MIT"
] | AbsShek/Slack.NetStandard | Slack.NetStandard/Messages/Elements/Image.cs | 469 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace SkbKontur.SqlStorageCore.Tests.Migrations
{
public partial class AddRequiredFieldToTestUpsertSqlEntry : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "RequiredValue",
table: "TestUpsertSqlEntry",
nullable: false,
defaultValue: "");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "RequiredValue",
table: "TestUpsertSqlEntry");
}
}
}
| 29.208333 | 73 | 0.60913 | [
"MIT"
] | skbkontur/SqlStorage.Core | SqlStorageCoreTests/Migrations/20181109113940_AddRequiredFieldToTestUpsertSqlEntry.cs | 703 | C# |
using System;
using InstagramApiSharp.Classes.Models;
using InstagramApiSharp.Classes.ResponseWrappers;
namespace InstagramApiSharp.Converters
{
internal class InstaMediaImageConverter : IObjectConverter<InstaImage, ImageResponse>
{
public ImageResponse SourceObject { get; set; }
public InstaImage Convert()
{
if (SourceObject == null) throw new ArgumentNullException($"Source object");
var image = new InstaImage(SourceObject.Url, int.Parse(SourceObject.Width), int.Parse(SourceObject.Height));
return image;
}
}
} | 33.222222 | 120 | 0.702341 | [
"MIT"
] | AMP-VTV/InstagramApiSharp | src/InstagramApiSharp/Converters/Media/InstaMediaImageConverter.cs | 598 | C# |
namespace Nancy.Diagnostics
{
using Configuration;
/// <summary>
/// Abstract base class for Nancy diagnostics module.
/// </summary>
/// <seealso cref="Nancy.NancyModule" />
public abstract class DiagnosticModule : NancyModule
{
private readonly INancyEnvironment environment;
/// <summary>
/// Initializes a new instance of the <see cref="DiagnosticModule"/> class.
/// </summary>
protected DiagnosticModule()
: this(string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DiagnosticModule"/> class, with
/// the provided <paramref name="basePath"/>.
/// </summary>
/// <param name="basePath">The base path.</param>
protected DiagnosticModule(string basePath)
: base(basePath)
{
this.environment = new DefaultNancyEnvironment();
this.environment.AddValue(ViewConfiguration.Default);
}
/// <summary>
/// Renders a view from inside a route handler.
/// </summary>
/// <value> A <see cref="ViewRenderer" /> instance that is used to determine which view that should be rendered. </value>
public new DiagnosticsViewRenderer View
{
get { return new DiagnosticsViewRenderer(this.Context, this.environment); }
}
}
}
| 33.744186 | 131 | 0.576154 | [
"MIT"
] | 0x414c49/Nancy | src/Nancy/Diagnostics/DiagnosticModule.cs | 1,453 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace Importer
{
class EadResultsDataTable
{
public void ProcessEadResultsDataTable(DataTable dataTable)
{
EadResultList theFuncList = GlobalVariables.mp_fdaStudy.GetEadResultList();
double[,] valuesFunc = null;
string theMemoFieldStr = "";
int numRowsMemo = 0;
int numColsMemo = 0;
int i = 0, j = 0;
//Process Each Record (Row) in _dataTable and create new Ead Result and Add
for (int irec = 0; irec < dataTable.Rows.Count; irec++)
{
EadResult theFunc = new EadResult();
for (int ifield = 0; ifield < dataTable.Columns.Count; ifield++)
{
//Console.Write($"{_dataTable.Columns[icol].ColumnName.PadRight(12)}");
string colName = dataTable.Columns[ifield].ColumnName;
if (colName == "ID_EADRES")
theFunc.Id = (int)dataTable.Rows[irec][ifield];
else if (colName == "NAME_EADRS")
theFunc.Name = (string)dataTable.Rows[irec][ifield];
else if (colName == "DESC_EADRS")
theFunc.Description = (string)dataTable.Rows[irec][ifield];
else if (colName == "ID_PLAN")
theFunc.IdPlan = (int)dataTable.Rows[irec][ifield];
else if (colName == "ID_YEAR")
theFunc.IdYear = (int)dataTable.Rows[irec][ifield];
else if (colName == "ID_STREAM")
theFunc.IdStream = (int)dataTable.Rows[irec][ifield];
else if (colName == "ID_IMPAREA")
theFunc.IdReach = (int)dataTable.Rows[irec][ifield];
else if (colName == "FDA_REF")
theFunc.NumRefs = (int)dataTable.Rows[irec][ifield];
else if (colName == "DATE")
theFunc.CalculationDate = (string)dataTable.Rows[irec][ifield];
else if (colName == "META_DATA")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
theFunc.MetaData = theMemoFieldStr;
}
else if (colName == "IUNC")
theFunc.Iunc = (int)dataTable.Rows[irec][ifield];
else if (colName == "PTARG")
theFunc.Ptarg = (double)dataTable.Rows[irec][ifield];
else if (colName == "FDMTRG")
theFunc.Fdmtrg = (double)dataTable.Rows[irec][ifield];
else if (colName == "NYEARS")
theFunc.Nyears = (int)dataTable.Rows[irec][ifield];
else if (colName == "DRATE")
theFunc.Drate = (double)dataTable.Rows[irec][ifield];
else if (colName == "ISTICS")
theFunc.Istics = (int)dataTable.Rows[irec][ifield];
else if (colName == "NSTICS")
theFunc.Nstics = (int)dataTable.Rows[irec][ifield];
else if (colName == "NCALC")
theFunc.Ncalc = (int)dataTable.Rows[irec][ifield];
else if (colName == "NFR")
theFunc.Nfr = (int)dataTable.Rows[irec][ifield];
else if (colName == "STARG")
theFunc.Starg = (double)dataTable.Rows[irec][ifield];
else if (colName == "PARGMN")
theFunc.Pargmn = (double)dataTable.Rows[irec][ifield];
else if (colName == "PARGMD")
theFunc.Pargmd = (double)dataTable.Rows[irec][ifield];
else if (colName == "NEVENT")
theFunc.Nevent = (int)dataTable.Rows[irec][ifield];
else if (colName == "NEVSTP")
theFunc.Nevstp = (int)dataTable.Rows[irec][ifield];
else if (colName == "NRISK")
theFunc.Nrisk = (int)dataTable.Rows[irec][ifield];
else if (colName == "NCAT")
theFunc.Ncat = (int)dataTable.Rows[irec][ifield];
else if (colName == "NETBL")
theFunc.NetBl = (int)dataTable.Rows[irec][ifield];
else if (colName == "SIMSTATTBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
//Study.PrintTable(numRowsMemo, numColsMemo, "SIMSTATTBL", valuesFunc);
double[] dmean = new double[numRowsMemo];
double[] dsdev = new double[numRowsMemo];
double[] dskew = new double[numRowsMemo];
for(i = 0; i < numRowsMemo; i++)
{
dmean[i] = valuesFunc[i, 0];
dsdev[i] = valuesFunc[i, 1];
dskew[i] = valuesFunc[i, 2];
}
theFunc.NumRows_SimStatTable = numRowsMemo;
theFunc.Dmean = dmean;
theFunc.Dsdev = dsdev;
theFunc.Dskew = dskew;
if(GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) theFunc.Print_SIMSTATTBL();
}
else if (colName == "EADCUM_TBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
double[] pcalc = new double[numRowsMemo];
int[] ntable = new int[numRowsMemo];
double[] cead = new double[numRowsMemo];
for(i = 0; i < numRowsMemo; i++)
{
pcalc[i] = valuesFunc[i, 0];
ntable[i] = (int)Math.Round(valuesFunc[i, 1]);
cead[i] = valuesFunc[i, 2];
}
//theFunc.Ncalc = numRowsMemo;
theFunc.NumRows_EadCum_Tbl = numRowsMemo;
theFunc.Pcalc = pcalc;
theFunc.Ntable = ntable;
theFunc.Cead = cead;
if (GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) theFunc.Print_EADCUM_TBL();
}
else if (colName == "SIMAVG_TBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
double[] prob = new double[numRowsMemo];
double[] qprob = new double[numRowsMemo];
double[] qtprob = new double[numRowsMemo];
double[] stprob = new double[numRowsMemo];
double[] dprob = new double[numRowsMemo * (numColsMemo - 4)];
for(i = 0; i < numRowsMemo; i++)
{
prob[i] = valuesFunc[i, 0];
qprob[i] = valuesFunc[i, 1];
qtprob[i] = valuesFunc[i, 2];
stprob[i] = valuesFunc[i, 3];
for (j = 4; j < numColsMemo; j++)
{
int m = i * (numColsMemo-4) + j - 4;
dprob[m] = valuesFunc[i, j];
}
}
theFunc.Ncat = numColsMemo - 5;
theFunc.Nfr = numRowsMemo;
theFunc.Prob = prob;
theFunc.Qprob = qprob;
theFunc.Qtprob = qtprob;
theFunc.Stprob = stprob;
theFunc.Dprob = dprob;
if (GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) theFunc.Print_SIMAVG_TBL();
}
else if (colName == "PPNONEXTAR")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
double[] pevent = new double[numRowsMemo];
double[] targev = new double[numRowsMemo];
for(i = 0; i < numRowsMemo; i++)
{
pevent[i] = valuesFunc[i, 0];
targev[i] = valuesFunc[i, 1];
}
//theFunc.Nevent = numRowsMemo; rdc critical;07Nov2018
theFunc.NumRows_Ppnonextar = numRowsMemo;
theFunc.NumCols_Ppnonextar = numColsMemo;
theFunc.Pevent = pevent;
theFunc.Targev = targev;
if (GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) theFunc.Print_PPNONEXTAR();
}
else if (colName == "PPNONEXTBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
double[] pevent = new double[numRowsMemo];
double[] sevent = new double[numRowsMemo * (numColsMemo - 1)];
//theFunc.Ncalc = numRowsMemo;rdc critical; Use Nevent?
for(i = 0; i < numRowsMemo; i++)
{
pevent[i] = valuesFunc[i, 0];
for(j = 1; j < numColsMemo; j++)
{
int m = i * (numColsMemo-1) + j-1;
sevent[m] = valuesFunc[i, j];
}
}
theFunc.NumRows_PPNONEXTBL = numRowsMemo;
theFunc.NumCols_PPNONEXTBL = numColsMemo;
theFunc.Pevent = pevent;
theFunc.Sevent = sevent;
if (GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) theFunc.Print_PPNONEXTBL();
}
else if (colName == "LTRISK_TBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
double[] targyr = new double[numRowsMemo];
double[] targrk = new double[numRowsMemo];
theFunc.Nrisk = numRowsMemo;
for(i = 0; i < numRowsMemo; i++)
{
targyr[i] = valuesFunc[i, 0];
targrk[i] = valuesFunc[i, 1];
}
theFunc.Targyr = targyr;
theFunc.Targrk = targrk;
if (GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) theFunc.Print_LTRISK_TBL();
}
else if (colName == "SIMEAD_TBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
int[] idCat = new int[numRowsMemo];
double[] ead = new double[numRowsMemo];
for(i = 0; i < numRowsMemo; i++)
{
idCat[i] = (int)Math.Round(valuesFunc[i, 0]);
ead[i] = valuesFunc[i, 1];
}
theFunc.NumRows_SIMEAD_TBL = numRowsMemo;
theFunc.IdCat = idCat;
theFunc.Ead = ead;
if (GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) theFunc.Print_SIMEAD_TBL();
}
else if (colName == "EADDISTTBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
double[] probCtead = new double[numRowsMemo];
double[] ctead = new double[numRowsMemo];
theFunc.NetBl = numRowsMemo;
for(i = 0; i < numRowsMemo; i++)
{
probCtead[i] = valuesFunc[i, 0];
ctead[i] = valuesFunc[i, 1];
}
theFunc.Ptead = probCtead;
theFunc.Ctead = ctead;
if (GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) theFunc.Print_EADDISTTB();
}
else if (colName == "EADDISXTBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
double[] eadClass = new double[numRowsMemo];
int[] nhitEad = new int[numRowsMemo];
double[] eadFreq = new double[numRowsMemo];
double[] eadFreqI = new double[numRowsMemo];
for(i = 0; i < numRowsMemo; i++)
{
eadClass[i] = valuesFunc[i, 0];
nhitEad[i] = (int)(valuesFunc[i, 1] + 0.01);
eadFreq[i] = valuesFunc[i, 2];
eadFreqI[i] = valuesFunc[i, 3];
}
theFunc.NumClassEad = numRowsMemo;
theFunc.EadClass = eadClass;
theFunc.NhitEad = nhitEad;
theFunc.EadFreq = eadFreq;
theFunc.EadFreqI = eadFreqI;
if (GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) theFunc.Print_EADDISXTBL();
}
else if (colName == "AEPDISXTBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
double[] aepClass = new double[numRowsMemo];
int[] nhitAep = new int[numRowsMemo];
double[] aepFreq = new double[numRowsMemo];
double[] aepFreqI = new double[numRowsMemo];
for (i = 0; i < numRowsMemo; i++)
{
aepClass[i] = valuesFunc[i, 0];
nhitAep[i] = (int)(valuesFunc[i, 1] + 0.01);
aepFreq[i] = valuesFunc[i, 2];
aepFreqI[i] = valuesFunc[i, 3];
}
theFunc.NumClassAep = numRowsMemo;
theFunc.AepClass = aepClass;
theFunc.NhitAep = nhitAep;
theFunc.AepFreq = aepFreq;
theFunc.AepFreqI = aepFreqI;
if (GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) theFunc.Print_AEPDISXTBL();
}
else if (colName == "AEPDISSTBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
double[] aepStandard = new double[numRowsMemo];
double[] freqStandard = new double[numRowsMemo];
double[] freqStandardI = new double[numRowsMemo];
for (i = 0; i < numRowsMemo; i++)
{
aepStandard[i] = valuesFunc[i, 0];
freqStandard[i] = valuesFunc[i, 1];
freqStandardI[i] = valuesFunc[i, 2];
}
theFunc.NclassStd = numRowsMemo;
theFunc.AepStandard = aepStandard;
theFunc.FreqStandard = freqStandard;
theFunc.FreqStandardI = freqStandardI;
if (GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) theFunc.Print_AEPDISSTBL();
}
else if (colName == "VERDATEMTH")
theFunc.SetVersionDateMethod((string)dataTable.Rows[irec][ifield]);
else if (colName == "EADWOUNTBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
}
else if (colName == "PROBDAMTBL")
{
theMemoFieldStr = dataTable.Rows[irec][ifield].ToString();
numRowsMemo = 0;
numColsMemo = 0;
MemoDataField.ProcessMemoDataField(theMemoFieldStr, ref numRowsMemo, ref numColsMemo, ref valuesFunc);
}
}
theFuncList.Add(theFunc);
}
}
}
}
| 48.192214 | 126 | 0.445398 | [
"MIT"
] | HydrologicEngineeringCenter/HEC-FDA | Importer/Ead/EadResultsDataTable.cs | 19,809 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
using ObjCRuntime;
namespace UOCApp.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, "AppDelegate");
}
}
}
| 19.863636 | 82 | 0.7254 | [
"MIT"
] | CrystalP1976/UOCA | UOCApp/UOCApp.iOS/Main.cs | 439 | C# |
// <auto-generated />
using System;
using Common.DataAccess.EFCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace Common.DataAccess.EFCore.Migrations
{
[DbContext(typeof(DataContext))]
[Migration("20200305161207_Initial")]
partial class Initial
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn)
.HasAnnotation("ProductVersion", "3.1.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
modelBuilder.Entity("Common.Entities.Role", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("IsDelete")
.HasColumnType("boolean");
b.Property<DateTime>("ModifyDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Name")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Roles");
});
modelBuilder.Entity("Common.Entities.Settings", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("IsDelete")
.HasColumnType("boolean");
b.Property<DateTime>("ModifyDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("ThemeName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Settings");
});
modelBuilder.Entity("Common.Entities.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AddressCity")
.HasColumnName("City")
.HasColumnType("text");
b.Property<double?>("AddressLat")
.HasColumnName("Lat")
.HasColumnType("double precision");
b.Property<double?>("AddressLng")
.HasColumnName("Lng")
.HasColumnType("double precision");
b.Property<string>("AddressStreet")
.HasColumnName("Street")
.HasColumnType("text");
b.Property<string>("AddressZipCode")
.HasColumnName("ZipCode")
.HasColumnType("text");
b.Property<int?>("Age")
.HasColumnType("integer");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("FirstName")
.HasColumnType("text");
b.Property<bool>("IsDelete")
.HasColumnType("boolean");
b.Property<string>("LastName")
.HasColumnType("text");
b.Property<DateTime>("ModifyDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("NormalizedEmail")
.IsRequired()
.HasColumnType("text");
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.HasColumnType("text");
b.Property<string>("TimeZoneId")
.HasColumnType("text");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Common.Entities.UserClaim", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("ClaimType")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ClaimValue")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<bool>("IsDelete")
.HasColumnType("boolean");
b.Property<DateTime>("ModifyDate")
.HasColumnType("timestamp without time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("UserClaims");
});
modelBuilder.Entity("Common.Entities.UserPhoto", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uuid");
b.Property<DateTime>("CreationDate")
.HasColumnType("timestamp without time zone");
b.Property<byte[]>("Image")
.IsRequired()
.HasColumnType("bytea");
b.Property<bool>("IsDelete")
.HasColumnType("boolean");
b.Property<DateTime>("ModifyDate")
.HasColumnType("timestamp without time zone");
b.HasKey("Id");
b.ToTable("UserPhotos");
});
modelBuilder.Entity("Common.Entities.UserRole", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<Guid>("RoleId")
.HasColumnType("uuid");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("UserRoles");
});
modelBuilder.Entity("Common.Entities.Settings", b =>
{
b.HasOne("Common.Entities.User", "User")
.WithOne("Settings")
.HasForeignKey("Common.Entities.Settings", "Id")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Common.Entities.UserClaim", b =>
{
b.HasOne("Common.Entities.User", null)
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Common.Entities.UserPhoto", b =>
{
b.HasOne("Common.Entities.User", "User")
.WithOne("Photo")
.HasForeignKey("Common.Entities.UserPhoto", "Id")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Common.Entities.UserRole", b =>
{
b.HasOne("Common.Entities.Role", "Role")
.WithMany("UserRoles")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Common.Entities.User", null)
.WithMany("UserRoles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 35.081712 | 119 | 0.441992 | [
"Apache-2.0"
] | MursalovAltun/ArticlesWebApi | Common/Common.DataAccess.EFCore/Migrations/20200305161207_Initial.Designer.cs | 9,018 | C# |
using System;
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.Transforms;
namespace Samples.Dynamic
{
// This example demonstrates hashing of categorical string and integer data types by using Hash transform's
// advanced options API.
public static class HashWithOptions
{
public static void Example()
{
// Create a new ML context, for ML.NET operations. It can be used for
// exception tracking and logging, as well as the source of randomness.
var mlContext = new MLContext(seed: 1);
// Get a small dataset as an IEnumerable.
var rawData = new[] {
new DataPoint() { Category = "MLB" , Age = 18 },
new DataPoint() { Category = "NFL" , Age = 14 },
new DataPoint() { Category = "NFL" , Age = 15 },
new DataPoint() { Category = "MLB" , Age = 18 },
new DataPoint() { Category = "MLS" , Age = 14 },
};
var data = mlContext.Data.LoadFromEnumerable(rawData);
// Construct the pipeline that would hash the two columns and store the
// results in new columns. The first transform hashes the string column
// and the second transform hashes the integer column.
//
// Hashing is not a reversible operation, so there is no way to retrive
// the original value from the hashed value. Sometimes, for debugging,
// or model explainability, users will need to know what values in the
// original columns generated the values in the hashed columns, since
// the algorithms will mostly use the hashed values for further
// computations. The Hash method will preserve the mapping from the
// original values to the hashed values in the Annotations of the newly
// created column (column populated with the hashed values).
//
// Setting the maximumNumberOfInverts parameters to -1 will preserve the
// full map. If that parameter is left to the default 0 value, the
// mapping is not preserved.
var pipeline = mlContext.Transforms.Conversion.Hash(
new[]
{
new HashingEstimator.ColumnOptions(
"CategoryHashed",
"Category",
16,
useOrderedHashing: false,
maximumNumberOfInverts: -1),
new HashingEstimator.ColumnOptions(
"AgeHashed",
"Age",
8,
useOrderedHashing: false)
});
// Let's fit our pipeline, and then apply it to the same data.
var transformer = pipeline.Fit(data);
var transformedData = transformer.Transform(data);
// Convert the post transformation from the IDataView format to an
// IEnumerable <TransformedData> for easy consumption.
var convertedData = mlContext.Data.CreateEnumerable<
TransformedDataPoint>(transformedData, true);
Console.WriteLine("Category CategoryHashed\t Age\t AgeHashed");
foreach (var item in convertedData)
Console.WriteLine($"{item.Category}\t {item.CategoryHashed}\t\t " +
$"{item.Age}\t {item.AgeHashed}");
// Expected data after the transformation.
//
// Category CategoryHashed Age AgeHashed
// MLB 36206 18 127
// NFL 19015 14 62
// NFL 19015 15 43
// MLB 36206 18 127
// MLS 6013 14 62
// For the Category column, where we set the maximumNumberOfInverts
// parameter, the names of the original categories, and their
// correspondance with the generated hash values is preserved in the
// Annotations in the format of indices and values.the indices array
// will have the hashed values, and the corresponding element,
// position -wise, in the values array will contain the original value.
//
// See below for an example on how to retrieve the mapping.
var slotNames = new VBuffer<ReadOnlyMemory<char>>();
transformedData.Schema["CategoryHashed"].Annotations.GetValue(
"KeyValues", ref slotNames);
var indices = slotNames.GetIndices();
var categoryNames = slotNames.GetValues();
for (int i = 0; i < indices.Length; i++)
Console.WriteLine($"The original value of the {indices[i]} " +
$"category is {categoryNames[i]}");
// Output Data
//
// The original value of the 6012 category is MLS
// The original value of the 19014 category is NFL
// The original value of the 36205 category is MLB
}
public class DataPoint
{
public string Category { get; set; }
public uint Age { get; set; }
}
public class TransformedDataPoint : DataPoint
{
public uint CategoryHashed { get; set; }
public uint AgeHashed { get; set; }
}
}
} | 45.266129 | 112 | 0.543738 | [
"MIT"
] | FrancisChung/machinelearning | docs/samples/Microsoft.ML.Samples/Dynamic/Transforms/Conversion/HashWithOptions.cs | 5,615 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/codecapi.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("0EE437C6-38A7-4C5C-944C-68AB42116B85")]
public partial struct CODECAPI_AVDecCommonMeanBitRateInterval
{
}
}
| 32.333333 | 145 | 0.764948 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | sources/Interop/Windows/um/codecapi/CODECAPI_AVDecCommonMeanBitRateInterval.cs | 487 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Globalization;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SubstitutedPropertySymbol : WrappedPropertySymbol
{
private readonly SubstitutedNamedTypeSymbol _containingType;
private TypeSymbol _lazyType;
private ImmutableArray<ParameterSymbol> _lazyParameters;
internal SubstitutedPropertySymbol(SubstitutedNamedTypeSymbol containingType, PropertySymbol originalDefinition)
: base(originalDefinition)
{
_containingType = containingType;
}
public override TypeSymbol Type
{
get
{
if ((object)_lazyType == null)
{
Interlocked.CompareExchange(ref _lazyType, _containingType.TypeSubstitution.SubstituteTypeWithTupleUnification(OriginalDefinition.Type).Type, null);
}
return _lazyType;
}
}
public override Symbol ContainingSymbol
{
get
{
return _containingType;
}
}
public override NamedTypeSymbol ContainingType
{
get
{
return _containingType;
}
}
public override PropertySymbol OriginalDefinition
{
get
{
return _underlyingProperty;
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return OriginalDefinition.GetAttributes();
}
public override ImmutableArray<CustomModifier> TypeCustomModifiers
{
get { return _containingType.TypeSubstitution.SubstituteCustomModifiers(OriginalDefinition.Type, OriginalDefinition.TypeCustomModifiers); }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get
{
if (_lazyParameters.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyParameters, SubstituteParameters(), default(ImmutableArray<ParameterSymbol>));
}
return _lazyParameters;
}
}
public override MethodSymbol GetMethod
{
get
{
MethodSymbol originalGetMethod = OriginalDefinition.GetMethod;
return (object)originalGetMethod == null ? null : originalGetMethod.AsMember(_containingType);
}
}
public override MethodSymbol SetMethod
{
get
{
MethodSymbol originalSetMethod = OriginalDefinition.SetMethod;
return (object)originalSetMethod == null ? null : originalSetMethod.AsMember(_containingType);
}
}
internal override bool IsExplicitInterfaceImplementation
{
get { return OriginalDefinition.IsExplicitInterfaceImplementation; }
}
//we want to compute this lazily since it may be expensive for the underlying symbol
private ImmutableArray<PropertySymbol> _lazyExplicitInterfaceImplementations;
private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers;
public override ImmutableArray<PropertySymbol> ExplicitInterfaceImplementations
{
get
{
if (_lazyExplicitInterfaceImplementations.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(
ref _lazyExplicitInterfaceImplementations,
ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementations(OriginalDefinition.ExplicitInterfaceImplementations, _containingType.TypeSubstitution),
default(ImmutableArray<PropertySymbol>));
}
return _lazyExplicitInterfaceImplementations;
}
}
internal override bool MustCallMethodsDirectly
{
get { return OriginalDefinition.MustCallMethodsDirectly; }
}
internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers
{
get
{
if (_lazyOverriddenOrHiddenMembers == null)
{
Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null);
}
return _lazyOverriddenOrHiddenMembers;
}
}
private ImmutableArray<ParameterSymbol> SubstituteParameters()
{
var unsubstitutedParameters = OriginalDefinition.Parameters;
if (unsubstitutedParameters.IsEmpty)
{
return unsubstitutedParameters;
}
else
{
int count = unsubstitutedParameters.Length;
var substituted = new ParameterSymbol[count];
for (int i = 0; i < count; i++)
{
substituted[i] = new SubstitutedParameterSymbol(this, _containingType.TypeSubstitution, unsubstitutedParameters[i]);
}
return substituted.AsImmutableOrNull();
}
}
}
}
| 33.808383 | 179 | 0.609635 | [
"Apache-2.0"
] | OceanYan/roslyn | src/Compilers/CSharp/Portable/Symbols/SubstitutedPropertySymbol.cs | 5,648 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Evaluation
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Merry Christmas");
PascalTriangle.DisplayPascalTriangle(25);
}
}
}
| 18.722222 | 53 | 0.643917 | [
"MIT"
] | BUSHIRIERASME/CDADWWM2111 | CSharp/src/Eval_Prog_Procedurale/Evaluation/Program.cs | 339 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Help;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Tracing;
using System.Net;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The base class of all updatable help system cmdlets (Update-Help, Save-Help)
/// </summary>
public class UpdatableHelpCommandBase : PSCmdlet
{
internal const string PathParameterSetName = "Path";
internal const string LiteralPathParameterSetName = "LiteralPath";
internal UpdatableHelpCommandType _commandType;
internal UpdatableHelpSystem _helpSystem;
internal bool _stopping;
internal int activityId;
private readonly Dictionary<string, UpdatableHelpExceptionContext> _exceptions;
#region Parameters
/// <summary>
/// Specifies the languages to update.
/// </summary>
[Parameter(Position = 2)]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CultureInfo[] UICulture
{
get
{
CultureInfo[] result = null;
if (_language != null)
{
result = new CultureInfo[_language.Length];
for (int index = 0; index < _language.Length; index++)
{
result[index] = new CultureInfo(_language[index]);
}
}
return result;
}
set
{
if (value == null) return;
_language = new string[value.Length];
for (int index = 0; index < value.Length; index++)
{
_language[index] = value[index].Name;
}
}
}
internal string[] _language;
/// <summary>
/// Gets or sets the credential parameter.
/// </summary>
[Parameter()]
[Credential()]
public PSCredential Credential
{
get { return _credential; }
set { _credential = value; }
}
internal PSCredential _credential;
/// <summary>
/// Directs System.Net.WebClient whether or not to use default credentials.
/// </summary>
[Parameter]
public SwitchParameter UseDefaultCredentials
{
get
{
return _useDefaultCredentials;
}
set
{
_useDefaultCredentials = value;
}
}
private bool _useDefaultCredentials = false;
/// <summary>
/// Forces the operation to complete.
/// </summary>
[Parameter]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
internal bool _force;
/// <summary>
/// Sets the scope to which help is saved.
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)]
public UpdateHelpScope Scope
{
get;
set;
}
#endregion
#region Events
/// <summary>
/// Handles help system progress events.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event arguments.</param>
private void HandleProgressChanged(object sender, UpdatableHelpProgressEventArgs e)
{
Debug.Assert(e.CommandType == UpdatableHelpCommandType.UpdateHelpCommand
|| e.CommandType == UpdatableHelpCommandType.SaveHelpCommand);
string activity = (e.CommandType == UpdatableHelpCommandType.UpdateHelpCommand) ?
HelpDisplayStrings.UpdateProgressActivityForModule : HelpDisplayStrings.SaveProgressActivityForModule;
ProgressRecord progress = new ProgressRecord(activityId, StringUtil.Format(activity, e.ModuleName), e.ProgressStatus);
progress.PercentComplete = e.ProgressPercent;
WriteProgress(progress);
}
#endregion
#region Constructor
private static readonly Dictionary<string, string> s_metadataCache;
/// <summary>
/// Static constructor
///
/// NOTE: FWLinks for core PowerShell modules are needed since they get loaded as snapins in a Remoting Endpoint.
/// When we moved to modules in V3, we were not able to make this change as it was a risky change to make at that time.
/// </summary>
static UpdatableHelpCommandBase()
{
s_metadataCache = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
// TODO: assign real TechNet addresses
s_metadataCache.Add("Microsoft.PowerShell.Diagnostics", "https://aka.ms/powershell71-help");
s_metadataCache.Add("Microsoft.PowerShell.Core", "https://aka.ms/powershell71-help");
s_metadataCache.Add("Microsoft.PowerShell.Utility", "https://aka.ms/powershell71-help");
s_metadataCache.Add("Microsoft.PowerShell.Host", "https://aka.ms/powershell71-help");
s_metadataCache.Add("Microsoft.PowerShell.Management", "https://aka.ms/powershell71-help");
s_metadataCache.Add("Microsoft.PowerShell.Security", "https://aka.ms/powershell71-help");
s_metadataCache.Add("Microsoft.WSMan.Management", "https://aka.ms/powershell71-help");
}
/// <summary>
/// Checks if a module is a system module, a module is a system module
/// if it exists in the metadata cache.
/// </summary>
/// <param name="module">Module name.</param>
/// <returns>True if system module, false if not.</returns>
internal static bool IsSystemModule(string module)
{
return s_metadataCache.ContainsKey(module);
}
/// <summary>
/// Class constructor.
/// </summary>
/// <param name="commandType">Command type.</param>
internal UpdatableHelpCommandBase(UpdatableHelpCommandType commandType)
{
_commandType = commandType;
_helpSystem = new UpdatableHelpSystem(this, _useDefaultCredentials);
_exceptions = new Dictionary<string, UpdatableHelpExceptionContext>();
_helpSystem.OnProgressChanged += HandleProgressChanged;
Random rand = new Random();
activityId = rand.Next();
}
#endregion
#region Implementation
private void ProcessSingleModuleObject(PSModuleInfo module, ExecutionContext context, Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> helpModules, bool noErrors)
{
if (InitialSessionState.IsEngineModule(module.Name) && !InitialSessionState.IsNestedEngineModule(module.Name))
{
WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", module.Name, module.Guid));
var keyTuple = new Tuple<string, Version>(module.Name, module.Version);
if (!helpModules.ContainsKey(keyTuple))
{
helpModules.Add(keyTuple, new UpdatableHelpModuleInfo(module.Name, module.Guid,
Utils.GetApplicationBase(context.ShellID), s_metadataCache[module.Name]));
}
return;
}
else if (InitialSessionState.IsNestedEngineModule(module.Name))
{
return;
}
if (string.IsNullOrEmpty(module.HelpInfoUri))
{
if (!noErrors)
{
ProcessException(module.Name, null, new UpdatableHelpSystemException(
"HelpInfoUriNotFound", StringUtil.Format(HelpDisplayStrings.HelpInfoUriNotFound),
ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
}
return;
}
if (!(module.HelpInfoUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || module.HelpInfoUri.StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
{
if (!noErrors)
{
ProcessException(module.Name, null, new UpdatableHelpSystemException(
"InvalidHelpInfoUriFormat", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUriFormat, module.HelpInfoUri),
ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
}
return;
}
var keyTuple2 = new Tuple<string, Version>(module.Name, module.Version);
if (!helpModules.ContainsKey(keyTuple2))
{
helpModules.Add(keyTuple2, new UpdatableHelpModuleInfo(module.Name, module.Guid, module.ModuleBase, module.HelpInfoUri));
}
}
/// <summary>
/// Gets a list of modules from the given pattern.
/// </summary>
/// <param name="context">Execution context.</param>
/// <param name="pattern">Pattern to search.</param>
/// <param name="fullyQualifiedName">Module Specification.</param>
/// <param name="noErrors">Do not generate errors for modules without HelpInfoUri.</param>
/// <returns>A list of modules.</returns>
private Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> GetModuleInfo(ExecutionContext context, string pattern, ModuleSpecification fullyQualifiedName, bool noErrors)
{
List<PSModuleInfo> modules = null;
string moduleNamePattern = null;
if (pattern != null)
{
moduleNamePattern = pattern;
modules = Utils.GetModules(pattern, context);
}
else if (fullyQualifiedName != null)
{
moduleNamePattern = fullyQualifiedName.Name;
modules = Utils.GetModules(fullyQualifiedName, context);
}
var helpModules = new Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo>();
if (modules != null)
{
foreach (PSModuleInfo module in modules)
{
ProcessSingleModuleObject(module, context, helpModules, noErrors);
}
}
IEnumerable<WildcardPattern> patternList = SessionStateUtilities.CreateWildcardsFromStrings(
globPatterns: new[] { moduleNamePattern },
options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
foreach (KeyValuePair<string, string> name in s_metadataCache)
{
if (SessionStateUtilities.MatchesAnyWildcardPattern(name.Key, patternList, true))
{
// For core snapin, there are no GUIDs. So, we need to construct the HelpInfo slightly differently
if (!name.Key.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase))
{
var keyTuple = new Tuple<string, Version>(name.Key, new Version("1.0"));
if (!helpModules.ContainsKey(keyTuple))
{
List<PSModuleInfo> availableModules = Utils.GetModules(name.Key, context);
if (availableModules != null)
{
foreach (PSModuleInfo module in availableModules)
{
keyTuple = new Tuple<string, Version>(module.Name, module.Version);
if (!helpModules.ContainsKey(keyTuple))
{
WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", module.Name, module.Guid));
helpModules.Add(keyTuple, new UpdatableHelpModuleInfo(module.Name,
module.Guid, Utils.GetApplicationBase(context.ShellID), s_metadataCache[module.Name]));
}
}
}
}
}
else
{
var keyTuple2 = new Tuple<string, Version>(name.Key, new Version("1.0"));
if (!helpModules.ContainsKey(keyTuple2))
{
helpModules.Add(keyTuple2,
new UpdatableHelpModuleInfo(name.Key, Guid.Empty,
Utils.GetApplicationBase(context.ShellID),
name.Value));
}
}
}
}
return helpModules;
}
/// <summary>
/// Handles Ctrl+C.
/// </summary>
protected override void StopProcessing()
{
_stopping = true;
_helpSystem.CancelDownload();
}
/// <summary>
/// End processing.
/// </summary>
protected override void EndProcessing()
{
foreach (UpdatableHelpExceptionContext exception in _exceptions.Values)
{
UpdatableHelpExceptionContext e = exception;
if ((exception.Exception.FullyQualifiedErrorId == "HelpCultureNotSupported") &&
((exception.Cultures != null && exception.Cultures.Count > 1) ||
(exception.Modules != null && exception.Modules.Count > 1)))
{
// Win8: 744749 Rewriting the error message only in the case where either
// multiple cultures or multiple modules are involved.
e = new UpdatableHelpExceptionContext(new UpdatableHelpSystemException(
"HelpCultureNotSupported", StringUtil.Format(HelpDisplayStrings.CannotMatchUICulturePattern,
string.Join(", ", exception.Cultures)),
ErrorCategory.InvalidArgument, exception.Cultures, null));
e.Modules = exception.Modules;
e.Cultures = exception.Cultures;
}
WriteError(e.CreateErrorRecord(_commandType));
LogContext context = MshLog.GetLogContext(Context, MyInvocation);
context.Severity = "Error";
PSEtwLog.LogOperationalError(PSEventId.Pipeline_Detail, PSOpcode.Exception, PSTask.ExecutePipeline,
context, e.GetExceptionMessage(_commandType));
}
}
/// <summary>
/// Main cmdlet logic for processing module names or fully qualified module names.
/// </summary>
/// <param name="moduleNames">Module names given by the user.</param>
/// <param name="fullyQualifiedNames">FullyQualifiedNames.</param>
internal void Process(IEnumerable<string> moduleNames, IEnumerable<ModuleSpecification> fullyQualifiedNames)
{
_helpSystem.UseDefaultCredentials = _useDefaultCredentials;
if (moduleNames != null)
{
foreach (string name in moduleNames)
{
if (_stopping)
{
break;
}
ProcessModuleWithGlobbing(name);
}
}
else if (fullyQualifiedNames != null)
{
foreach (var fullyQualifiedName in fullyQualifiedNames)
{
if (_stopping)
{
break;
}
ProcessModuleWithGlobbing(fullyQualifiedName);
}
}
else
{
foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> module in GetModuleInfo("*", null, true))
{
if (_stopping)
{
break;
}
ProcessModule(module.Value);
}
}
}
/// <summary>
/// Processing module objects for Save-Help.
/// </summary>
/// <param name="modules">Module objects given by the user.</param>
internal void Process(IEnumerable<PSModuleInfo> modules)
{
if (modules == null || !modules.Any()) { return; }
var helpModules = new Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo>();
foreach (PSModuleInfo module in modules)
{
ProcessSingleModuleObject(module, Context, helpModules, false);
}
foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> helpModule in helpModules)
{
ProcessModule(helpModule.Value);
}
}
/// <summary>
/// Processes a module with potential globbing.
/// </summary>
/// <param name="name">Module name with globbing.</param>
private void ProcessModuleWithGlobbing(string name)
{
if (string.IsNullOrEmpty(name))
{
PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ModuleNameNullOrEmpty));
WriteError(e.ErrorRecord);
return;
}
foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> module in GetModuleInfo(name, null, false))
{
ProcessModule(module.Value);
}
}
/// <summary>
/// Processes a ModuleSpecification with potential globbing.
/// </summary>
/// <param name="fullyQualifiedName">ModuleSpecification.</param>
private void ProcessModuleWithGlobbing(ModuleSpecification fullyQualifiedName)
{
foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> module in GetModuleInfo(null, fullyQualifiedName, false))
{
ProcessModule(module.Value);
}
}
/// <summary>
/// Processes a single module with multiple cultures.
/// </summary>
/// <param name="module">Module to process.</param>
private void ProcessModule(UpdatableHelpModuleInfo module)
{
_helpSystem.CurrentModule = module.ModuleName;
if (this is UpdateHelpCommand && !Directory.Exists(module.ModuleBase))
{
ProcessException(module.ModuleName, null,
new UpdatableHelpSystemException("ModuleBaseMustExist",
StringUtil.Format(HelpDisplayStrings.ModuleBaseMustExist),
ErrorCategory.InvalidOperation, null, null));
return;
}
// Win8: 572882 When the system locale is English and the UI is JPN,
// running "update-help" still downs English help content.
var cultures = _language ?? _helpSystem.GetCurrentUICulture();
foreach (string culture in cultures)
{
bool installed = true;
if (_stopping)
{
break;
}
try
{
ProcessModuleWithCulture(module, culture);
}
catch (IOException e)
{
ProcessException(module.ModuleName, culture, new UpdatableHelpSystemException("FailedToCopyFile",
e.Message, ErrorCategory.InvalidOperation, null, e));
}
catch (UnauthorizedAccessException e)
{
ProcessException(module.ModuleName, culture, new UpdatableHelpSystemException("AccessIsDenied",
e.Message, ErrorCategory.PermissionDenied, null, e));
}
#if !CORECLR
catch (WebException e)
{
if (e.InnerException != null && e.InnerException is UnauthorizedAccessException)
{
ProcessException(module.ModuleName, culture, new UpdatableHelpSystemException("AccessIsDenied",
e.InnerException.Message, ErrorCategory.PermissionDenied, null, e));
}
else
{
ProcessException(module.ModuleName, culture, e);
}
}
#endif
catch (UpdatableHelpSystemException e)
{
if (e.FullyQualifiedErrorId == "HelpCultureNotSupported")
{
installed = false;
if (_language != null)
{
// Display the error message only if we are not using the fallback chain
ProcessException(module.ModuleName, culture, e);
}
}
else
{
ProcessException(module.ModuleName, culture, e);
}
}
catch (Exception e)
{
ProcessException(module.ModuleName, culture, e);
}
finally
{
if (_helpSystem.Errors.Count != 0)
{
foreach (Exception error in _helpSystem.Errors)
{
ProcessException(module.ModuleName, culture, error);
}
_helpSystem.Errors.Clear();
}
}
// If -Language is not specified, we only install
// one culture from the fallback chain
if (_language == null && installed)
{
break;
}
}
}
/// <summary>
/// Process a single module with a given culture.
/// </summary>
/// <param name="module">Module to process.</param>
/// <param name="culture">Culture to use.</param>
/// <returns>True if the module has been processed, false if not.</returns>
internal virtual bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture)
{
return false;
}
#endregion
#region Common methods
/// <summary>
/// Gets a list of modules from the given pattern or ModuleSpecification.
/// </summary>
/// <param name="pattern">Pattern to match.</param>
/// <param name="fullyQualifiedName">ModuleSpecification.</param>
/// <param name="noErrors">Skip errors.</param>
/// <returns>A list of modules.</returns>
internal Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> GetModuleInfo(string pattern, ModuleSpecification fullyQualifiedName, bool noErrors)
{
Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> modules = GetModuleInfo(Context, pattern, fullyQualifiedName, noErrors);
if (modules.Count == 0 && _exceptions.Count == 0 && !noErrors)
{
var errorMessage = fullyQualifiedName != null ? StringUtil.Format(HelpDisplayStrings.ModuleNotFoundWithFullyQualifiedName, fullyQualifiedName)
: StringUtil.Format(HelpDisplayStrings.CannotMatchModulePattern, pattern);
ErrorRecord errorRecord = new ErrorRecord(new Exception(errorMessage),
"ModuleNotFound", ErrorCategory.InvalidArgument, pattern);
WriteError(errorRecord);
}
return modules;
}
/// <summary>
/// Checks if it is necessary to update help.
/// </summary>
/// <param name="module">ModuleInfo.</param>
/// <param name="currentHelpInfo">Current HelpInfo.xml.</param>
/// <param name="newHelpInfo">New HelpInfo.xml.</param>
/// <param name="culture">Current culture.</param>
/// <param name="force">Force update.</param>
/// <returns>True if it is necessary to update help, false if not.</returns>
internal bool IsUpdateNecessary(UpdatableHelpModuleInfo module, UpdatableHelpInfo currentHelpInfo,
UpdatableHelpInfo newHelpInfo, CultureInfo culture, bool force)
{
Debug.Assert(module != null);
if (newHelpInfo == null)
{
throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml",
StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture.Name), ErrorCategory.ResourceUnavailable,
null, null);
}
// Culture check
if (!newHelpInfo.IsCultureSupported(culture))
{
throw new UpdatableHelpSystemException("HelpCultureNotSupported",
StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupported,
culture.Name, newHelpInfo.GetSupportedCultures()), ErrorCategory.InvalidOperation, null, null);
}
// Version check
if (!force && currentHelpInfo != null && !currentHelpInfo.IsNewerVersion(newHelpInfo, culture))
{
return false;
}
return true;
}
/// <summary>
/// Checks if the user has attempted to update more than once per day per module.
/// </summary>
/// <param name="moduleName">Module name.</param>
/// <param name="path">Path to help info.</param>
/// <param name="filename">Help info file name.</param>
/// <param name="time">Current time (UTC).</param>
/// <param name="force">If -Force is specified.</param>
/// <returns>True if we are okay to update, false if not.</returns>
internal bool CheckOncePerDayPerModule(string moduleName, string path, string filename, DateTime time, bool force)
{
// Update if -Force is specified
if (force)
{
return true;
}
string helpInfoFilePath = SessionState.Path.Combine(path, filename);
// No HelpInfo.xml
if (!File.Exists(helpInfoFilePath))
{
return true;
}
DateTime lastModified = File.GetLastWriteTimeUtc(helpInfoFilePath);
TimeSpan difference = time - lastModified;
if (difference.Days >= 1)
{
return true;
}
if (_commandType == UpdatableHelpCommandType.UpdateHelpCommand)
{
WriteVerbose(StringUtil.Format(HelpDisplayStrings.UseForceToUpdateHelp, moduleName));
}
else if (_commandType == UpdatableHelpCommandType.SaveHelpCommand)
{
WriteVerbose(StringUtil.Format(HelpDisplayStrings.UseForceToSaveHelp, moduleName));
}
return false;
}
/// <summary>
/// Resolves a given path to a list of directories.
/// </summary>
/// <param name="path">Path to resolve.</param>
/// <param name="recurse">Resolve recursively?</param>
/// <param name="isLiteralPath">Treat the path / start path as a literal path?</param>///
/// <returns>A list of directories.</returns>
internal IEnumerable<string> ResolvePath(string path, bool recurse, bool isLiteralPath)
{
List<string> resolvedPaths = new List<string>();
if (isLiteralPath)
{
string newPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
if (!Directory.Exists(newPath))
{
throw new UpdatableHelpSystemException("PathMustBeValidContainers",
StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument,
null, new ItemNotFoundException());
}
resolvedPaths.Add(newPath);
}
else
{
Collection<PathInfo> resolvedPathInfos = SessionState.Path.GetResolvedPSPathFromPSPath(path);
foreach (PathInfo resolvedPath in resolvedPathInfos)
{
ValidatePathProvider(resolvedPath);
resolvedPaths.Add(resolvedPath.ProviderPath);
}
}
foreach (string resolvedPath in resolvedPaths)
{
if (recurse)
{
foreach (string innerResolvedPath in RecursiveResolvePathHelper(resolvedPath))
{
yield return innerResolvedPath;
}
}
else
{
// Win8: 566738
CmdletProviderContext context = new CmdletProviderContext(this.Context);
// resolvedPath is already resolved..so no need to expand wildcards anymore
context.SuppressWildcardExpansion = true;
if (isLiteralPath || InvokeProvider.Item.IsContainer(resolvedPath, context))
{
yield return resolvedPath;
}
}
}
yield break;
}
/// <summary>
/// Resolves a given path to a list of directories recursively.
/// </summary>
/// <param name="path">Path to resolve.</param>
/// <returns>A list of directories.</returns>
private IEnumerable<string> RecursiveResolvePathHelper(string path)
{
if (System.IO.Directory.Exists(path))
{
yield return path;
foreach (string subDirectory in Directory.EnumerateDirectories(path))
{
foreach (string subDirectory2 in RecursiveResolvePathHelper(subDirectory))
{
yield return subDirectory2;
}
}
}
yield break;
}
#endregion
#region Static methods
/// <summary>
/// Validates the provider of the path, only FileSystem provider is accepted.
/// </summary>
/// <param name="path">Path to validate.</param>
internal void ValidatePathProvider(PathInfo path)
{
if (path.Provider == null || path.Provider.Name != FileSystemProvider.ProviderName)
{
throw new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ProviderIsNotFileSystem,
path.Path));
}
}
#endregion
#region Logging
/// <summary>
/// Logs a command message.
/// </summary>
/// <param name="message">Message to log.</param>
internal void LogMessage(string message)
{
List<string> details = new List<string>() { message };
PSEtwLog.LogPipelineExecutionDetailEvent(MshLog.GetLogContext(Context, Context.CurrentCommandProcessor.Command.MyInvocation), details);
}
#endregion
#region Exception processing
/// <summary>
/// Processes an exception for help cmdlets.
/// </summary>
/// <param name="moduleName">Module name.</param>
/// <param name="culture">Culture info.</param>
/// <param name="e">Exception to check.</param>
internal void ProcessException(string moduleName, string culture, Exception e)
{
UpdatableHelpSystemException except = null;
if (e is UpdatableHelpSystemException)
{
except = (UpdatableHelpSystemException)e;
}
#if !CORECLR
else if (e is WebException)
{
except = new UpdatableHelpSystemException("UnableToConnect",
StringUtil.Format(HelpDisplayStrings.UnableToConnect), ErrorCategory.InvalidOperation, null, e);
}
#endif
else if (e is PSArgumentException)
{
except = new UpdatableHelpSystemException("InvalidArgument",
e.Message, ErrorCategory.InvalidArgument, null, e);
}
else
{
except = new UpdatableHelpSystemException("UnknownErrorId",
e.Message, ErrorCategory.InvalidOperation, null, e);
}
if (!_exceptions.ContainsKey(except.FullyQualifiedErrorId))
{
_exceptions.Add(except.FullyQualifiedErrorId, new UpdatableHelpExceptionContext(except));
}
_exceptions[except.FullyQualifiedErrorId].Modules.Add(moduleName);
if (culture != null)
{
_exceptions[except.FullyQualifiedErrorId].Cultures.Add(culture);
}
}
#endregion
}
/// <summary>
/// Scope to which the help should be saved.
/// </summary>
public enum UpdateHelpScope
{
/// <summary>
/// Save the help content to the user directory.
CurrentUser,
/// <summary>
/// Save the help content to the module directory. This is the default behavior.
/// </summary>
AllUsers
}
}
| 38.471572 | 186 | 0.545684 | [
"MIT"
] | 2bon/PowerShell | src/System.Management.Automation/help/UpdatableHelpCommandBase.cs | 34,509 | C# |
// <auto-generated/>
#pragma warning disable 1591
namespace Test
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
public partial class TestComponent : Microsoft.AspNetCore.Components.ComponentBase
{
#pragma warning disable 219
private void __RazorDirectiveTokenHelpers__() {
}
#pragma warning restore 219
#pragma warning disable 0414
private static System.Object __o = null;
#pragma warning restore 0414
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
__builder.AddAttribute(-1, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => {
}
));
#nullable restore
#line 3 "x:\dir\subdir\Test\TestComponent.cshtml"
__o = typeof(SomeOtherComponent);
#line default
#line hidden
#nullable disable
}
#pragma warning restore 1998
}
}
#pragma warning restore 1591
| 30.105263 | 121 | 0.689685 | [
"Apache-2.0"
] | 1175169074/aspnetcore | src/Razor/Microsoft.AspNetCore.Razor.Language/test/TestFiles/IntegrationTests/ComponentDesignTimeCodeGenerationTest/Legacy_3_1_TrailingWhiteSpace_WithComponent/TestComponent.codegen.cs | 1,144 | C# |
using Godot;
public class Enemy : Npc
{
[Export] public Stats Stats;
[Export(PropertyHint.Range, "1, 100")] private int _customLevel = 1;
public override void _Ready()
{
base._Ready();
Stats = Stats.Duplicate() as Stats;
Stats.Level = _customLevel;
}
private void OnPlayerDetectionAreaPlayerEnteredArea(Player player)
{
Global.BattleManager.StartBattle(this);
}
}
| 18.285714 | 69 | 0.723958 | [
"MIT"
] | Guimica-gml/RPG | Enemy/Enemy.cs | 384 | C# |
#define EFL_BETA
#pragma warning disable CS1591
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.ComponentModel;
namespace Efl {
namespace Ui {
/// <summary>Efl Ui Selection class</summary>
/// <remarks>This is a <b>BETA</b> class. It can be modified or removed in the future. Do not use it for product development.</remarks>
[Efl.Ui.ISelectionConcrete.NativeMethods]
[Efl.Eo.BindingEntity]
public interface ISelection :
Efl.Eo.IWrapper, IDisposable
{
/// <summary>Set the selection data to the object</summary>
/// <param name="type">Selection Type</param>
/// <param name="format">Selection Format</param>
/// <param name="data">Selection data</param>
/// <param name="seat">Specified seat for multiple seats case.</param>
/// <returns>Future for tracking when the selection is lost</returns>
Eina.Future SetSelection(Efl.Ui.SelectionType type, Efl.Ui.SelectionFormat format, Eina.Slice data, uint seat);
/// <summary>Get the data from the object that has selection</summary>
/// <param name="type">Selection Type</param>
/// <param name="format">Selection Format</param>
/// <param name="data_func">Data ready function pointer</param>
/// <param name="seat">Specified seat for multiple seats case.</param>
void GetSelection(Efl.Ui.SelectionType type, Efl.Ui.SelectionFormat format, Efl.Ui.SelectionDataReady data_func, uint seat);
/// <summary>Clear the selection data from the object</summary>
/// <param name="type">Selection Type</param>
/// <param name="seat">Specified seat for multiple seats case.</param>
void ClearSelection(Efl.Ui.SelectionType type, uint seat);
/// <summary>Determine whether the selection data has owner</summary>
/// <param name="type">Selection type</param>
/// <param name="seat">Specified seat for multiple seats case.</param>
/// <returns>EINA_TRUE if there is object owns selection, otherwise EINA_FALSE</returns>
bool HasOwner(Efl.Ui.SelectionType type, uint seat);
/// <summary>Async wrapper for <see cref="SetSelection" />.</summary>
/// <param name="type">Selection Type</param>
/// <param name="format">Selection Format</param>
/// <param name="data">Selection data</param>
/// <param name="seat">Specified seat for multiple seats case.</param>
/// <param name="token">Token to notify the async operation of external request to cancel.</param>
/// <returns>An async task wrapping the result of the operation.</returns>
System.Threading.Tasks.Task<Eina.Value> SetSelectionAsync(Efl.Ui.SelectionType type,Efl.Ui.SelectionFormat format,Eina.Slice data,uint seat, System.Threading.CancellationToken token = default(System.Threading.CancellationToken));
/// <summary>Called when display server's selection has changed</summary>
/// <value><see cref="Efl.Ui.ISelectionWmSelectionChangedEvt_Args"/></value>
event EventHandler<Efl.Ui.ISelectionWmSelectionChangedEvt_Args> WmSelectionChangedEvt;
}
/// <summary>Event argument wrapper for event <see cref="Efl.Ui.ISelection.WmSelectionChangedEvt"/>.</summary>
[Efl.Eo.BindingEntity]
public class ISelectionWmSelectionChangedEvt_Args : EventArgs {
/// <summary>Actual event payload.</summary>
/// <value>Called when display server's selection has changed</value>
public Efl.Ui.SelectionChanged arg { get; set; }
}
/// <summary>Efl Ui Selection class</summary>
/// <remarks>This is a <b>BETA</b> class. It can be modified or removed in the future. Do not use it for product development.</remarks>
sealed public class ISelectionConcrete :
Efl.Eo.EoWrapper
, ISelection
{
/// <summary>Pointer to the native class description.</summary>
public override System.IntPtr NativeClass
{
get
{
if (((object)this).GetType() == typeof(ISelectionConcrete))
{
return GetEflClassStatic();
}
else
{
return Efl.Eo.ClassRegister.klassFromType[((object)this).GetType()];
}
}
}
/// <summary>Subclasses should override this constructor if they are expected to be instantiated from native code.
/// Do not call this constructor directly.</summary>
/// <param name="ch">Tag struct storing the native handle of the object being constructed.</param>
private ISelectionConcrete(ConstructingHandle ch) : base(ch)
{
}
[System.Runtime.InteropServices.DllImport(efl.Libs.Elementary)] internal static extern System.IntPtr
efl_ui_selection_mixin_get();
/// <summary>Initializes a new instance of the <see cref="ISelection"/> class.
/// Internal usage: This is used when interacting with C code and should not be used directly.</summary>
/// <param name="wh">The native pointer to be wrapped.</param>
private ISelectionConcrete(Efl.Eo.Globals.WrappingHandle wh) : base(wh)
{
}
/// <summary>Called when display server's selection has changed</summary>
/// <value><see cref="Efl.Ui.ISelectionWmSelectionChangedEvt_Args"/></value>
public event EventHandler<Efl.Ui.ISelectionWmSelectionChangedEvt_Args> WmSelectionChangedEvt
{
add
{
lock (eflBindingEventLock)
{
Efl.EventCb callerCb = (IntPtr data, ref Efl.Event.NativeStruct evt) =>
{
var obj = Efl.Eo.Globals.WrapperSupervisorPtrToManaged(data).Target;
if (obj != null)
{
Efl.Ui.ISelectionWmSelectionChangedEvt_Args args = new Efl.Ui.ISelectionWmSelectionChangedEvt_Args();
args.arg = evt.Info;
try
{
value?.Invoke(obj, args);
}
catch (Exception e)
{
Eina.Log.Error(e.ToString());
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
};
string key = "_EFL_UI_SELECTION_EVENT_WM_SELECTION_CHANGED";
AddNativeEventHandler(efl.Libs.Elementary, key, callerCb, value);
}
}
remove
{
lock (eflBindingEventLock)
{
string key = "_EFL_UI_SELECTION_EVENT_WM_SELECTION_CHANGED";
RemoveNativeEventHandler(efl.Libs.Elementary, key, value);
}
}
}
/// <summary>Method to raise event WmSelectionChangedEvt.</summary>
public void OnWmSelectionChangedEvt(Efl.Ui.ISelectionWmSelectionChangedEvt_Args e)
{
var key = "_EFL_UI_SELECTION_EVENT_WM_SELECTION_CHANGED";
IntPtr desc = Efl.EventDescription.GetNative(efl.Libs.Elementary, key);
if (desc == IntPtr.Zero)
{
Eina.Log.Error($"Failed to get native event {key}");
return;
}
IntPtr info = Marshal.AllocHGlobal(Marshal.SizeOf(e.arg));
try
{
Marshal.StructureToPtr(e.arg, info, false);
Efl.Eo.Globals.efl_event_callback_call(this.NativeHandle, desc, info);
}
finally
{
Marshal.FreeHGlobal(info);
}
}
/// <summary>Set the selection data to the object</summary>
/// <param name="type">Selection Type</param>
/// <param name="format">Selection Format</param>
/// <param name="data">Selection data</param>
/// <param name="seat">Specified seat for multiple seats case.</param>
/// <returns>Future for tracking when the selection is lost</returns>
public Eina.Future SetSelection(Efl.Ui.SelectionType type, Efl.Ui.SelectionFormat format, Eina.Slice data, uint seat) {
var _ret_var = Efl.Ui.ISelectionConcrete.NativeMethods.efl_ui_selection_set_ptr.Value.Delegate(this.NativeHandle,type, format, data, seat);
Eina.Error.RaiseIfUnhandledException();
return _ret_var;
}
/// <summary>Get the data from the object that has selection</summary>
/// <param name="type">Selection Type</param>
/// <param name="format">Selection Format</param>
/// <param name="data_func">Data ready function pointer</param>
/// <param name="seat">Specified seat for multiple seats case.</param>
public void GetSelection(Efl.Ui.SelectionType type, Efl.Ui.SelectionFormat format, Efl.Ui.SelectionDataReady data_func, uint seat) {
GCHandle data_func_handle = GCHandle.Alloc(data_func);
Efl.Ui.ISelectionConcrete.NativeMethods.efl_ui_selection_get_ptr.Value.Delegate(this.NativeHandle,type, format, GCHandle.ToIntPtr(data_func_handle), Efl.Ui.SelectionDataReadyWrapper.Cb, Efl.Eo.Globals.free_gchandle, seat);
Eina.Error.RaiseIfUnhandledException();
}
/// <summary>Clear the selection data from the object</summary>
/// <param name="type">Selection Type</param>
/// <param name="seat">Specified seat for multiple seats case.</param>
public void ClearSelection(Efl.Ui.SelectionType type, uint seat) {
Efl.Ui.ISelectionConcrete.NativeMethods.efl_ui_selection_clear_ptr.Value.Delegate(this.NativeHandle,type, seat);
Eina.Error.RaiseIfUnhandledException();
}
/// <summary>Determine whether the selection data has owner</summary>
/// <param name="type">Selection type</param>
/// <param name="seat">Specified seat for multiple seats case.</param>
/// <returns>EINA_TRUE if there is object owns selection, otherwise EINA_FALSE</returns>
public bool HasOwner(Efl.Ui.SelectionType type, uint seat) {
var _ret_var = Efl.Ui.ISelectionConcrete.NativeMethods.efl_ui_selection_has_owner_ptr.Value.Delegate(this.NativeHandle,type, seat);
Eina.Error.RaiseIfUnhandledException();
return _ret_var;
}
/// <summary>Async wrapper for <see cref="SetSelection" />.</summary>
/// <param name="type">Selection Type</param>
/// <param name="format">Selection Format</param>
/// <param name="data">Selection data</param>
/// <param name="seat">Specified seat for multiple seats case.</param>
/// <param name="token">Token to notify the async operation of external request to cancel.</param>
/// <returns>An async task wrapping the result of the operation.</returns>
public System.Threading.Tasks.Task<Eina.Value> SetSelectionAsync(Efl.Ui.SelectionType type,Efl.Ui.SelectionFormat format,Eina.Slice data,uint seat, System.Threading.CancellationToken token = default(System.Threading.CancellationToken))
{
Eina.Future future = SetSelection( type, format, data, seat);
return Efl.Eo.Globals.WrapAsync(future, token);
}
private static IntPtr GetEflClassStatic()
{
return Efl.Ui.ISelectionConcrete.efl_ui_selection_mixin_get();
}
/// <summary>Wrapper for native methods and virtual method delegates.
/// For internal use by generated code only.</summary>
public new class NativeMethods : Efl.Eo.EoWrapper.NativeMethods
{
private static Efl.Eo.NativeModule Module = new Efl.Eo.NativeModule( efl.Libs.Elementary);
/// <summary>Gets the list of Eo operations to override.</summary>
/// <returns>The list of Eo operations to be overload.</returns>
public override System.Collections.Generic.List<Efl_Op_Description> GetEoOps(System.Type type)
{
var descs = new System.Collections.Generic.List<Efl_Op_Description>();
var methods = Efl.Eo.Globals.GetUserMethods(type);
if (efl_ui_selection_set_static_delegate == null)
{
efl_ui_selection_set_static_delegate = new efl_ui_selection_set_delegate(selection_set);
}
if (methods.FirstOrDefault(m => m.Name == "SetSelection") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_ui_selection_set"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_selection_set_static_delegate) });
}
if (efl_ui_selection_get_static_delegate == null)
{
efl_ui_selection_get_static_delegate = new efl_ui_selection_get_delegate(selection_get);
}
if (methods.FirstOrDefault(m => m.Name == "GetSelection") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_ui_selection_get"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_selection_get_static_delegate) });
}
if (efl_ui_selection_clear_static_delegate == null)
{
efl_ui_selection_clear_static_delegate = new efl_ui_selection_clear_delegate(selection_clear);
}
if (methods.FirstOrDefault(m => m.Name == "ClearSelection") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_ui_selection_clear"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_selection_clear_static_delegate) });
}
if (efl_ui_selection_has_owner_static_delegate == null)
{
efl_ui_selection_has_owner_static_delegate = new efl_ui_selection_has_owner_delegate(has_owner);
}
if (methods.FirstOrDefault(m => m.Name == "HasOwner") != null)
{
descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_ui_selection_has_owner"), func = Marshal.GetFunctionPointerForDelegate(efl_ui_selection_has_owner_static_delegate) });
}
return descs;
}
/// <summary>Returns the Eo class for the native methods of this class.</summary>
/// <returns>The native class pointer.</returns>
public override IntPtr GetEflClass()
{
return Efl.Ui.ISelectionConcrete.efl_ui_selection_mixin_get();
}
#pragma warning disable CA1707, CS1591, SA1300, SA1600
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Eina.FutureMarshaler))]
private delegate Eina.Future efl_ui_selection_set_delegate(System.IntPtr obj, System.IntPtr pd, Efl.Ui.SelectionType type, Efl.Ui.SelectionFormat format, Eina.Slice data, uint seat);
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(Eina.FutureMarshaler))]
public delegate Eina.Future efl_ui_selection_set_api_delegate(System.IntPtr obj, Efl.Ui.SelectionType type, Efl.Ui.SelectionFormat format, Eina.Slice data, uint seat);
public static Efl.Eo.FunctionWrapper<efl_ui_selection_set_api_delegate> efl_ui_selection_set_ptr = new Efl.Eo.FunctionWrapper<efl_ui_selection_set_api_delegate>(Module, "efl_ui_selection_set");
private static Eina.Future selection_set(System.IntPtr obj, System.IntPtr pd, Efl.Ui.SelectionType type, Efl.Ui.SelectionFormat format, Eina.Slice data, uint seat)
{
Eina.Log.Debug("function efl_ui_selection_set was called");
var ws = Efl.Eo.Globals.GetWrapperSupervisor(obj);
if (ws != null)
{
Eina.Future _ret_var = default( Eina.Future);
try
{
_ret_var = ((ISelection)ws.Target).SetSelection(type, format, data, seat);
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
return _ret_var;
}
else
{
return efl_ui_selection_set_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), type, format, data, seat);
}
}
private static efl_ui_selection_set_delegate efl_ui_selection_set_static_delegate;
private delegate void efl_ui_selection_get_delegate(System.IntPtr obj, System.IntPtr pd, Efl.Ui.SelectionType type, Efl.Ui.SelectionFormat format, IntPtr data_func_data, Efl.Ui.SelectionDataReadyInternal data_func, EinaFreeCb data_func_free_cb, uint seat);
public delegate void efl_ui_selection_get_api_delegate(System.IntPtr obj, Efl.Ui.SelectionType type, Efl.Ui.SelectionFormat format, IntPtr data_func_data, Efl.Ui.SelectionDataReadyInternal data_func, EinaFreeCb data_func_free_cb, uint seat);
public static Efl.Eo.FunctionWrapper<efl_ui_selection_get_api_delegate> efl_ui_selection_get_ptr = new Efl.Eo.FunctionWrapper<efl_ui_selection_get_api_delegate>(Module, "efl_ui_selection_get");
private static void selection_get(System.IntPtr obj, System.IntPtr pd, Efl.Ui.SelectionType type, Efl.Ui.SelectionFormat format, IntPtr data_func_data, Efl.Ui.SelectionDataReadyInternal data_func, EinaFreeCb data_func_free_cb, uint seat)
{
Eina.Log.Debug("function efl_ui_selection_get was called");
var ws = Efl.Eo.Globals.GetWrapperSupervisor(obj);
if (ws != null)
{
Efl.Ui.SelectionDataReadyWrapper data_func_wrapper = new Efl.Ui.SelectionDataReadyWrapper(data_func, data_func_data, data_func_free_cb);
try
{
((ISelection)ws.Target).GetSelection(type, format, data_func_wrapper.ManagedCb, seat);
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
else
{
efl_ui_selection_get_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), type, format, data_func_data, data_func, data_func_free_cb, seat);
}
}
private static efl_ui_selection_get_delegate efl_ui_selection_get_static_delegate;
private delegate void efl_ui_selection_clear_delegate(System.IntPtr obj, System.IntPtr pd, Efl.Ui.SelectionType type, uint seat);
public delegate void efl_ui_selection_clear_api_delegate(System.IntPtr obj, Efl.Ui.SelectionType type, uint seat);
public static Efl.Eo.FunctionWrapper<efl_ui_selection_clear_api_delegate> efl_ui_selection_clear_ptr = new Efl.Eo.FunctionWrapper<efl_ui_selection_clear_api_delegate>(Module, "efl_ui_selection_clear");
private static void selection_clear(System.IntPtr obj, System.IntPtr pd, Efl.Ui.SelectionType type, uint seat)
{
Eina.Log.Debug("function efl_ui_selection_clear was called");
var ws = Efl.Eo.Globals.GetWrapperSupervisor(obj);
if (ws != null)
{
try
{
((ISelection)ws.Target).ClearSelection(type, seat);
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
}
else
{
efl_ui_selection_clear_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), type, seat);
}
}
private static efl_ui_selection_clear_delegate efl_ui_selection_clear_static_delegate;
[return: MarshalAs(UnmanagedType.U1)]
private delegate bool efl_ui_selection_has_owner_delegate(System.IntPtr obj, System.IntPtr pd, Efl.Ui.SelectionType type, uint seat);
[return: MarshalAs(UnmanagedType.U1)]
public delegate bool efl_ui_selection_has_owner_api_delegate(System.IntPtr obj, Efl.Ui.SelectionType type, uint seat);
public static Efl.Eo.FunctionWrapper<efl_ui_selection_has_owner_api_delegate> efl_ui_selection_has_owner_ptr = new Efl.Eo.FunctionWrapper<efl_ui_selection_has_owner_api_delegate>(Module, "efl_ui_selection_has_owner");
private static bool has_owner(System.IntPtr obj, System.IntPtr pd, Efl.Ui.SelectionType type, uint seat)
{
Eina.Log.Debug("function efl_ui_selection_has_owner was called");
var ws = Efl.Eo.Globals.GetWrapperSupervisor(obj);
if (ws != null)
{
bool _ret_var = default(bool);
try
{
_ret_var = ((ISelection)ws.Target).HasOwner(type, seat);
}
catch (Exception e)
{
Eina.Log.Warning($"Callback error: {e.ToString()}");
Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION);
}
return _ret_var;
}
else
{
return efl_ui_selection_has_owner_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), type, seat);
}
}
private static efl_ui_selection_has_owner_delegate efl_ui_selection_has_owner_static_delegate;
#pragma warning restore CA1707, CS1591, SA1300, SA1600
}
}
}
}
#if EFL_BETA
#pragma warning disable CS1591
public static class Efl_UiISelectionConcrete_ExtensionMethods {
}
#pragma warning restore CS1591
#endif
| 51.216895 | 268 | 0.635626 | [
"Apache-2.0",
"MIT"
] | JoogabYun/TizenFX | internals/src/EflSharp/EflSharp/efl/efl_ui_selection.eo.cs | 22,433 | C# |
// Copyright (c) Jeremy W. Kuhne. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace MacIO;
public abstract class Record
{
/// <summary>
/// The stream backing the record.
/// </summary>
protected Stream Stream { get; }
/// <summary>
/// True if the stream is read only.
/// </summary>
protected bool ReadOnly { get; }
protected Record(Stream stream, bool readOnly = true)
{
Stream = readOnly && stream.CanWrite ? new ReadOnlyStream(stream) : stream;
ReadOnly = readOnly;
}
/// <summary>
/// Persist back to the stream backing the record.
/// </summary>
public abstract void Save();
}
| 25.931034 | 101 | 0.631649 | [
"MIT"
] | JeremyKuhne/MacIO | MacIOLibrary/Record.cs | 754 | C# |
using System.Linq;
using System;
using System.Collections.Generic;
using Accord.Math;
namespace ai_from_scratch
{
class Program
{
private static double[][] inputs = new[]
{
new[] {1.0, 2.0, 3.0, 2.5},
new[] {2.0, 5.0, -1.0, 2.0},
new[] {-1.5, 2.7, 3.3, -0.8}
};
// Each neuron has its own weight and bias
private static double[][] weights = new[]
{
new[] { 0.2, 0.8, -0.5, 1.0 },
new[] { 0.5, -0.91, 0.26, -0.5 },
new[] { -0.26, -0.27, 0.17, 0.87 }
};
private static double[] biases = new[] { 2.0, 3.0, 0.5 };
private static double[][] weights2 = new[]
{
new[] { 0.1, -0.14, 0.5},
new[] { -0.5, 0.12, -0.33},
new[] { -0.44, 0.73, -0.13}
};
private static double[] biases2 = new[] { -1, 2, -0.5 };
static void Main(string[] args)
{
var newLayer = new LayerDense(inputs, 6);
var result = newLayer.DotProduct;
//var weighted_output = Matrix.Dot( inputs, weights.Transpose())
// .Select(val=> val.Select((s, i) => s + biases[i]).ToArray())
// .ToArray();
foreach (var items in result)
{
foreach (var item in items)
{
Console.Write($"{item.ToString()}, ");
}
Console.WriteLine();
}
}
}
}
| 28.962264 | 82 | 0.426059 | [
"MIT"
] | bkstephen/ai_from_scratch | C# version/Program.cs | 1,537 | C# |
using System.Text.Json.Serialization;
namespace Fpl.Client.Models;
public record EventStatusResponse
{
[JsonPropertyName("status")]
public ICollection<EventStatus> Status { get; set; } = new List<EventStatus>();
[JsonPropertyName("leagues")]
public string Leagues { get; set; }
}
public record EventStatus
{
[JsonPropertyName("bonus_added")]
public bool BonusAdded { get; set; }
/// <summary>
/// YYYY-MM-dd
/// </summary>
[JsonPropertyName("date")]
public string Date { get; set; }
[JsonPropertyName("event")]
public int Event { get; set; }
[JsonPropertyName("points")]
public string PointsStatus { get; set; }
}
public class EventStatusConstants
{
public class LeaguesStatus
{
public const string Nothing = "";
public const string Updating = "Updating";
public const string Updated = "Updated";
}
public class PointStatus
{
public const string Nothing = "";
public const string Live = "l";
public const string Ready = "r";
}
}
| 22.291667 | 83 | 0.637383 | [
"MIT"
] | Eszra92/fplbot | src/Fpl.Client/Models/EventStatus.cs | 1,070 | C# |
//-----------------------------------------------------------------------------
// <copyright file="InternalTransaction.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace System.Transactions
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Threading;
using System.Transactions.Diagnostics;
// InternalTransaction
//
// This class holds the state and all data common to a transaction instance
class InternalTransaction : IDisposable
{
// This variable manages the state of the transaction it should be one of the
// static elements of TransactionState derived from TransactionState.
protected TransactionState transactionState;
internal TransactionState State
{
get
{
return transactionState;
}
set
{
transactionState = value;
}
}
// This variable holds the state that the transaction will promote to. By
// default it uses the straight forward TransactionStatePromoted. If the
// transaction has a promotable single phase enlistment however it must use
// a different state so that it is promoted correctly.
internal TransactionState promoteState;
// The PromoterType for the transaction.
// This is set when a PSPE enlistment is created via Transaction.EnlistPromotableSinglePhase.
// It is also set when a transaction promotes without a PSPE enlistment.
internal Guid promoterType = Guid.Empty;
// The promoted token for the transaction.
// This is set when the transaction is promoted. For an MSDTC transaction, it is the
// same as the DTC propagation token.
internal byte[] promotedToken;
// This is only used if the promoter type is different than TransactionInterop.PromoterTypeDtc.
// The promoter is supposed to tell us what the distributed transaction id after promoting it.
// We store the value here.
internal Guid distributedTransactionIdentifierNonMSDTC = Guid.Empty;
#if DEBUG
// Keep a history of th transaction states
internal const int MaxStateHist = 20;
internal TransactionState[] stateHistory = new TransactionState[MaxStateHist];
internal int currentStateHist;
#endif
// Finalized object see class definition for the use of this object
internal FinalizedObject finalizedObject;
internal int transactionHash;
internal int TransactionHash
{
get
{
return this.transactionHash;
}
}
internal static int nextHash;
// timeout stores a relative timeout for the transaction. absoluteTimeout stores
// the actual time in ticks.
private long absoluteTimeout;
internal long AbsoluteTimeout
{
get
{
return this.absoluteTimeout;
}
}
// record the current number of ticks active when the transaction is created.
private Int64 creationTime;
internal Int64 CreationTime
{
get
{
return this.creationTime;
}
set
{
this.creationTime = value;
}
}
// The goal for the LTM is to only allocate as few heap objects as possible for a given
// transaction and all of its enlistments. To accomplish this, enlistment objects are
// held in system arrays. The transaction contains one enlistment for the single durable
// enlistment it can handle and a small array of volatile enlistments. If the number of
// enlistments for a given transaction exceeds the capacity of the current array a new
// larger array will be created and the contents of the old array will be copied into it.
// Heuristic data based on TransactionType can be created to avoid this sort of copy
// operation repeatedly for a given type of transaction. So if a transaction of a specific
// type continually causes the array size to be increased the LTM could start
// allocating a larger array initially for transactions of that type.
internal InternalEnlistment durableEnlistment;
internal VolatileEnlistmentSet phase0Volatiles;
internal VolatileEnlistmentSet phase1Volatiles;
// This member stores the number of phase 0 volatiles for the last wave
internal int phase0VolatileWaveCount;
// These members are used for promoted waves of dependent blocking clones. The Ltm
// does not register individually for each blocking clone created in phase 0. Instead
// it multiplexes a single phase 0 blocking clone only created after phase 0 has started.
internal Oletx.OletxDependentTransaction phase0WaveDependentClone;
internal int phase0WaveDependentCloneCount;
// These members are used for keeping track of aborting dependent clones if we promote
// BEFORE we get an aborting dependent clone or a Ph1 volatile enlistment. If we
// promote before we get either of these, then we never create a Ph1 volatile enlistment
// on the distributed TM. If we promote AFTER an aborting dependent clone or Ph1 volatile
// enlistment is created, then we create a Ph1 volatile enlistment on the distributed TM
// as part of promotion, so these won't be used. In that case, the Ph1 volatile enlistment
// on the distributed TM takes care of checking to make sure all the aborting dependent
// clones have completed as part of its Prepare processing. These are used in conjunction with
// phase1volatiles.dependentclones.
internal Oletx.OletxDependentTransaction abortingDependentClone;
internal int abortingDependentCloneCount;
// When the size of the volatile enlistment array grows increase it by this amount.
internal const int volatileArrayIncrement = 8;
// Data maintained for TransactionTable participation
internal Bucket tableBucket;
internal int bucketIndex;
// Delegate to fire on transaction completion
internal TransactionCompletedEventHandler transactionCompletedDelegate;
// If this transaction get's promoted keep a reference to the promoted transaction
private Oletx.OletxTransaction promotedTransaction;
internal Oletx.OletxTransaction PromotedTransaction
{
get
{
return this.promotedTransaction;
}
set
{
Debug.Assert( this.promotedTransaction == null, "A transaction can only be promoted once!" );
this.promotedTransaction = value;
}
}
// If there was an exception that happened during promotion save that exception so that it
// can be used as an inner exception to the transaciton aborted exception.
internal Exception innerException = null;
// Note the number of Transaction objects supported by this object
internal int cloneCount;
// The number of enlistments on this transaction.
internal int enlistmentCount = 0;
// Double-checked locking pattern requires volatile for read/write synchronization
// Manual Reset event for IAsyncResult support
internal volatile ManualResetEvent asyncResultEvent;
// Store the callback and state for the caller of BeginCommit
internal bool asyncCommit;
internal AsyncCallback asyncCallback;
internal object asyncState;
// Flag to indicate if we need to be pulsed for tx completion
internal bool needPulse;
// Store the transaction information object
internal TransactionInformation transactionInformation;
// Store a reference to the owning Committable Transaction
internal CommittableTransaction committableTransaction;
// Store a reference to the outcome source
internal Transaction outcomeSource;
// Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) )
private static object classSyncObject;
internal static object ClassSyncObject
{
get
{
if ( classSyncObject == null )
{
object o = new object();
Interlocked.CompareExchange( ref classSyncObject, o, null );
}
return classSyncObject;
}
}
internal Guid DistributedTxId
{
get
{
return this.State.get_Identifier(this);
}
}
// Double-checked locking pattern requires volatile for read/write synchronization
static volatile string instanceIdentifier;
static internal string InstanceIdentifier
{
get
{
if ( instanceIdentifier == null )
{
lock ( ClassSyncObject )
{
if ( instanceIdentifier == null )
{
string temp = Guid.NewGuid().ToString() + ":";
instanceIdentifier = temp;
}
}
}
return instanceIdentifier;
}
}
// Double-checked locking pattern requires volatile for read/write synchronization
private volatile bool traceIdentifierInited = false;
// The trace identifier for the internal transaction.
private TransactionTraceIdentifier traceIdentifier;
internal TransactionTraceIdentifier TransactionTraceId
{
get
{
if (!traceIdentifierInited)
{
lock ( this )
{
if (!traceIdentifierInited)
{
TransactionTraceIdentifier temp = new TransactionTraceIdentifier(
InstanceIdentifier + Convert.ToString( this.transactionHash, CultureInfo.InvariantCulture ),
0 );
this.traceIdentifier = temp;
traceIdentifierInited = true;
}
}
}
return this.traceIdentifier;
}
}
internal ITransactionPromoter promoter;
// This member is used to allow a PSPE enlistment to call Transaction.PSPEPromoteAndConvertToEnlistDurable when it is
// asked to promote a transaction. The value is set to true in TransactionStatePSPEOperation.PSPEPromote before the
// Promote call is made and set back to false after the call returns (or an exception is thrown). The value is
// checked for true in TransactionStatePSPEOperation.PSPEPromoteAndConvertToEnlistDurable to make sure the transaction
// is in the process of promoting via a PSPE enlistment.
internal bool attemptingPSPEPromote = false;
// This is called from TransactionStatePromoted.EnterState. We assume we are promoting to MSDTC.
internal void SetPromoterTypeToMSDTC()
{
// The promoter type should either not yet be set or should already be TransactionInterop.PromoterTypeDtc in this case.
if ((this.promoterType != Guid.Empty) && (this.promoterType != TransactionInterop.PromoterTypeDtc))
{
throw new InvalidOperationException(SR.GetString(SR.PromoterTypeInvalid));
}
this.promoterType = TransactionInterop.PromoterTypeDtc;
}
// Throws a TransactionPromotionException if the promoterType is NOT
// Guid.Empty AND NOT TransactionInterop.PromoterTypeDtc.
internal void ThrowIfPromoterTypeIsNotMSDTC()
{
if ((this.promoterType != Guid.Empty) && (this.promoterType != TransactionInterop.PromoterTypeDtc))
{
throw new TransactionPromotionException(string.Format(CultureInfo.CurrentCulture,
SR.GetString(SR.PromoterTypeUnrecognized), this.promoterType.ToString()),
this.innerException);
}
}
// Construct an internal transaction
internal InternalTransaction( TimeSpan timeout, CommittableTransaction committableTransaction )
{
if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform();
// Calculate the absolute timeout for this transaction
this.absoluteTimeout = TransactionManager.TransactionTable.TimeoutTicks( timeout );
// Start the transaction off as active
TransactionState._TransactionStateActive.EnterState( this );
// Until otherwise noted this transaction uses normal promotion.
this.promoteState = TransactionState._TransactionStatePromoted;
// Keep a reference to the commitable transaction
this.committableTransaction = committableTransaction;
this.outcomeSource = committableTransaction;
// Initialize the hash
this.transactionHash = TransactionManager.TransactionTable.Add( this );
}
// Construct an internal transaction
internal InternalTransaction( Transaction outcomeSource, Oletx.OletxTransaction distributedTx )
{
if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform();
this.promotedTransaction = distributedTx;
this.absoluteTimeout = long.MaxValue;
// Store the initial creater as it will be the source of outcome events
this.outcomeSource = outcomeSource;
// Initialize the hash
this.transactionHash = TransactionManager.TransactionTable.Add( this );
// Start the transaction off as active
TransactionState._TransactionStateNonCommittablePromoted.EnterState( this );
// Until otherwise noted this transaction uses normal promotion.
this.promoteState = TransactionState._TransactionStateNonCommittablePromoted;
}
// Construct an internal transaction
internal InternalTransaction( Transaction outcomeSource, ITransactionPromoter promoter )
{
if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform();
this.absoluteTimeout = long.MaxValue;
// Store the initial creater as it will be the source of outcome events
this.outcomeSource = outcomeSource;
// Initialize the hash
this.transactionHash = TransactionManager.TransactionTable.Add( this );
// Save the transaction promoter.
this.promoter = promoter;
// This transaction starts in a special state.
TransactionState._TransactionStateSubordinateActive.EnterState( this );
// This transaction promotes through delegation
this.promoteState = TransactionState._TransactionStateDelegatedSubordinate;
}
internal static void DistributedTransactionOutcome( InternalTransaction tx, TransactionStatus status )
{
FinalizedObject fo = null;
lock ( tx )
{
if ( null == tx.innerException )
{
tx.innerException = tx.PromotedTransaction.InnerException;
}
switch (status)
{
case TransactionStatus.Committed:
{
tx.State.ChangeStatePromotedCommitted( tx );
break;
}
case TransactionStatus.Aborted:
{
tx.State.ChangeStatePromotedAborted( tx );
break;
}
case TransactionStatus.InDoubt:
{
tx.State.InDoubtFromDtc( tx );
break;
}
default:
{
Debug.Assert( false, "InternalTransaction.DistributedTransactionOutcome - Unexpected TransactionStatus" );
TransactionException.CreateInvalidOperationException( SR.GetString( SR.TraceSourceLtm ),
"",
null,
tx.DistributedTxId
);
break;
}
}
fo = tx.finalizedObject;
}
if ( null != fo )
{
fo.Dispose();
}
}
#region Outcome Events
// Signal Waiters anyone waiting for transaction outcome.
internal void SignalAsyncCompletion()
{
if ( this.asyncResultEvent != null )
{
this.asyncResultEvent.Set();
}
if ( this.asyncCallback != null )
{
System.Threading.Monitor.Exit( this ); // Don't hold a lock calling user code.
try
{
this.asyncCallback( this.committableTransaction );
}
finally
{
#pragma warning disable 0618
//@
System.Threading.Monitor.Enter(this);
#pragma warning restore 0618
}
}
}
// Fire completion to anyone registered for outcome
internal void FireCompletion( )
{
TransactionCompletedEventHandler eventHandlers = this.transactionCompletedDelegate;
if ( eventHandlers != null )
{
TransactionEventArgs args = new TransactionEventArgs();
args.transaction = this.outcomeSource.InternalClone();
eventHandlers( args.transaction, args );
}
}
#endregion
#region IDisposable Members
// FXCop wants us to dispose nextLink, which is another InternalTransaction, and thus disposable. But we don't
// want to do that here. That link is for the list of all InternalTransactions.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed")]
public void Dispose()
{
if ( this.promotedTransaction != null )
{
// If there is a promoted transaction dispose it.
this.promotedTransaction.Dispose();
}
}
#endregion
}
// Finalized Object
//
// This object is created if the InternalTransaction needs some kind of finalization. An
// InternalTransaction will only need finalization if it is promoted so having a finalizer
// would only hurt performance for the unpromoted case. When the Ltm does promote it creates this
// object which is finalized and will handle the necessary cleanup.
sealed class FinalizedObject : IDisposable
{
// Keep the identifier separate. Since it is a struct it wont be finalized out from under
// this object.
Guid identifier;
InternalTransaction internalTransaction;
internal FinalizedObject( InternalTransaction internalTransaction, Guid identifier )
{
this.internalTransaction = internalTransaction;
this.identifier = identifier;
}
private void Dispose( bool disposing )
{
if ( disposing )
{
GC.SuppressFinalize(this);
}
// We need to remove the entry for the transaction from the static
// LightweightTransactionManager.PromotedTransactionTable.
Hashtable promotedTransactionTable = TransactionManager.PromotedTransactionTable;
lock ( promotedTransactionTable )
{
WeakReference weakRef = (WeakReference)promotedTransactionTable[this.identifier];
if ( null != weakRef )
{
if ( weakRef.Target != null )
{
weakRef.Target = null;
}
}
promotedTransactionTable.Remove( this.identifier );
}
}
public void Dispose()
{
Dispose(true);
}
~FinalizedObject()
{
Dispose(false);
}
}
}
| 38.669091 | 131 | 0.599304 | [
"MIT"
] | shuaiagain/.NetSourceCode | dotnet461TH2/Source/ndp/cdf/src/NetFx20/system.transactions/System/Transactions/InternalTransaction.cs | 21,268 | C# |
// Jeebs Unit Tests
// Copyright (c) bfren.uk - licensed under https://mit.bfren.uk/2013
using Xunit;
namespace Jeebs.None_Tests
{
public class Constructor_Tests
{
[Fact]
public void Sets_Reason()
{
// Arrange
var reason = new TestMsg();
// Act
var result = new None<string>(reason);
// Assert
Assert.Equal(reason, result.Reason);
}
}
public record TestMsg : IMsg { }
}
| 15.615385 | 68 | 0.652709 | [
"MIT"
] | bencgreen/jeebs | tests/Tests.Jeebs.Option/_/None/Constructor_Tests.cs | 408 | C# |
using Codeless.Ecma.Runtime;
using NUnit.Framework;
using static Codeless.Ecma.Global;
using static Codeless.Ecma.Keywords;
using static Codeless.Ecma.Literal;
using static Codeless.Ecma.UnitTest.Assert;
using static Codeless.Ecma.UnitTest.StaticHelper;
namespace Codeless.Ecma.UnitTest.Tests {
public class IteratorPrototype : TestBase {
[Test, RuntimeFunctionInjection]
public void Iterator(RuntimeFunction iterator) {
IsUnconstructableFunctionWLength(iterator, "[Symbol.iterator]", 0);
EcmaValue iterProto = Object.Invoke("getPrototypeOf", Object.Invoke("getPrototypeOf", Array.Construct().Invoke(Symbol.Iterator)));
That(iterProto, Has.OwnProperty(Symbol.Iterator, iterator, EcmaPropertyAttributes.DefaultMethodProperty));
EcmaValue thisValue = Object.Construct();
Case(thisValue, thisValue);
}
}
}
| 37.086957 | 136 | 0.771395 | [
"MIT"
] | misonou/codeless-ecma | src/Codeless.Ecma.UnitTest/Tests/IteratorPrototype.cs | 855 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RockPaperScissors.Models;
namespace RockPaperScissors.Models.Tests
{
[TestClass]
public class RockPaperScissorTest
{
[TestMethod]
public void PlayerOneRock_PlayerOneWins_False()
{
RockPaperScissor newGame = new RockPaperScissor();
newGame.PlayerOneRock("Paper");
int POS = newGame.GetPlayerOneScore();
Assert.AreEqual(POS, 0);
}
[TestMethod]
public void PlayerOneRock_PlayerOneWins_True()
{
RockPaperScissor newGame = new RockPaperScissor();
newGame.PlayerOneRock("Scissors");
int POS = newGame.GetPlayerOneScore();
Assert.AreEqual(POS, 1);
}
[TestMethod]
public void PlayerOnePaper_PlayerOneWins_True()
{
RockPaperScissor newGame = new RockPaperScissor();
newGame.PlayerOnePaper("Rock");
int POS = newGame.GetPlayerOneScore();
Assert.AreEqual(POS, 1);
}
[TestMethod]
public void PlayerOnePaper_PlayerOneWins_False()
{
RockPaperScissor newGame = new RockPaperScissor();
newGame.PlayerOnePaper("Scissors");
int POS = newGame.GetPlayerOneScore();
Assert.AreEqual(POS, 0);
}
[TestMethod]
public void PlayerOneScissors_PlayerOneWins_True()
{
RockPaperScissor newGame = new RockPaperScissor();
newGame.PlayerOneScissor("Paper");
int POS = newGame.GetPlayerOneScore();
Assert.AreEqual(POS, 1);
}
[TestMethod]
public void PlayerOneScissors_PlayerOneWins_False()
{
RockPaperScissor newGame = new RockPaperScissor();
newGame.PlayerOneScissor("Rock");
int POS = newGame.GetPlayerOneScore();
Assert.AreEqual(POS, 0);
}
}
}
| 26.875 | 56 | 0.684884 | [
"MIT"
] | hamzilitary/Rock-Paper-Scissor | RockPaperScissor.Tests/ModelsTest/RockPaperScissorTest.cs | 1,720 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/IPExport.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="IP_ADAPTER_INDEX_MAP" /> struct.</summary>
public static unsafe partial class IP_ADAPTER_INDEX_MAPTests
{
/// <summary>Validates that the <see cref="IP_ADAPTER_INDEX_MAP" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IP_ADAPTER_INDEX_MAP>(), Is.EqualTo(sizeof(IP_ADAPTER_INDEX_MAP)));
}
/// <summary>Validates that the <see cref="IP_ADAPTER_INDEX_MAP" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IP_ADAPTER_INDEX_MAP).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IP_ADAPTER_INDEX_MAP" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(IP_ADAPTER_INDEX_MAP), Is.EqualTo(260));
}
}
| 38.4 | 145 | 0.725446 | [
"MIT"
] | reflectronic/terrafx.interop.windows | tests/Interop/Windows/Windows/um/IPExport/IP_ADAPTER_INDEX_MAPTests.cs | 1,346 | 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 Costmanagement.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The configuration of dataset in the report.
/// </summary>
public partial class ReportConfigDatasetConfiguration
{
/// <summary>
/// Initializes a new instance of the ReportConfigDatasetConfiguration
/// class.
/// </summary>
public ReportConfigDatasetConfiguration()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ReportConfigDatasetConfiguration
/// class.
/// </summary>
/// <param name="columns">Array of column names to be included in the
/// report. Any valid report column name is allowed. If not provided,
/// then report includes all columns.</param>
public ReportConfigDatasetConfiguration(IList<string> columns = default(IList<string>))
{
Columns = columns;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets array of column names to be included in the report.
/// Any valid report column name is allowed. If not provided, then
/// report includes all columns.
/// </summary>
[JsonProperty(PropertyName = "columns")]
public IList<string> Columns { get; set; }
}
}
| 32.416667 | 95 | 0.627249 | [
"MIT"
] | bgsky/azure-sdk-for-net | src/SDKs/CostManagement/Management.CostManagement/Generated/Models/ReportConfigDatasetConfiguration.cs | 1,945 | C# |
namespace GraphQL.Models.Entities
{
public abstract class UpdatedByEntity : TableEntity
{
public string UpdatedBy { get; set; }
public User UpdatedByUser { get; set; }
}
} | 25 | 55 | 0.655 | [
"MIT"
] | dylanberry/GraphQL_POC | GraphQL.Models/Entities/Base/UpdatedByEntity.cs | 202 | C# |
//-----------------------------------------------------------------------------
// Filename: IceSession.cs
//
// Description: Represents a ICE Session as described in the Interactive
// Connectivity Establishment RFC8445 https://tools.ietf.org/html/rfc8445.
//
// Additionally support for the following standards or proposed standards
// is included:
// - "Trickle ICE" as per draft RFC
// https://tools.ietf.org/html/draft-ietf-ice-trickle-21.
// - "WebRTC IP Address Handling Requirements" as per draft RFC
// https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12
// SECURITY NOTE: See https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12#section-5.2
// for recommendations on how a WebRTC application should expose a
// hosts IP address information. This implementation is using Mode 2.
// - Traversal Using Relays around NAT (TURN): Relay Extensions to
// Session Traversal Utilities for NAT(STUN)
// https://tools.ietf.org/html/rfc5766
//
// Notes:
// The source from Chromium that performs the equivalent of this IceSession class
// (and much more) is:
// https://chromium.googlesource.com/external/webrtc/+/refs/heads/master/p2p/base/p2p_transport_channel.cc
//
// Multicast DNS: Chromium (and possibly other WebRTC stacks) make use of *.local
// DNS hostnames. Support for such hostnames is currently NOT implemented in
// this library as it would mean introducing another dependency for what is
// currently deemed to be a narrow edge case. Windows 10 has recently introduced a level
// of support for these domains so perhaps it will make it into the .Net Core
// plumbing in the not too distant future.
// https://tools.ietf.org/html/rfc6762: Multicast DNS (for ".local" Top Level Domain lookups on macos)
//
// Author(s):
// Aaron Clauson (aaron@sipsorcery.com)
//
// History:
// 15 Mar 2020 Aaron Clauson Created, Dublin, Ireland.
//
// License:
// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SIPSorcery.Sys;
[assembly: InternalsVisibleToAttribute("SIPSorcery.UnitTests")]
namespace SIPSorcery.Net
{
/// <summary>
/// An ICE session carries out connectivity checks with a remote peer in an
/// attempt to determine the best destination end point to communicate with the
/// remote party.
/// </summary>
/// <remarks>
/// Limitations:
/// - To reduce complexity only a single checklist is used. This is based on the main
/// webrtc use case where RTP (audio and video) and RTCP are all multiplexed on a
/// single socket pair. Therefore there only needs to be a single component and single
/// data stream. If an additional use case occurs then multiple checklists could be added.
/// </remarks>
public class IceSession
{
private static DnsClient.LookupClient _dnsLookupClient;
/// <summary>
/// List of state conditions for a check list entry as the connectivity checks are
/// carried out.
/// </summary>
internal enum ChecklistEntryState
{
/// <summary>
/// A check has not been sent for this pair, but the pair is not Frozen.
/// </summary>
Waiting,
/// <summary>
/// A check has been sent for this pair, but the transaction is in progress.
/// </summary>
InProgress,
/// <summary>
/// A check has been sent for this pair, and it produced a successful result.
/// </summary>
Succeeded,
/// <summary>
/// A check has been sent for this pair, and it failed (a response to the
/// check was never received, or a failure response was received).
/// </summary>
Failed,
/// <summary>
/// A check for this pair has not been sent, and it cannot be sent until the
/// pair is unfrozen and moved into the Waiting state.
/// </summary>
Frozen
}
/// <summary>
/// Represents the state of the ICE checks for a checklist.
/// </summary>
/// <remarks>
/// As specified in https://tools.ietf.org/html/rfc8445#section-6.1.2.1.
/// </remarks>
internal enum ChecklistState
{
/// <summary>
/// The checklist is neither Completed nor Failed yet.
/// Checklists are initially set to the Running state.
/// </summary>
Running,
/// <summary>
/// The checklist contains a nominated pair for each
/// component of the data stream.
/// </summary>
Completed,
/// <summary>
/// The checklist does not have a valid pair for each component
/// of the data stream, and all of the candidate pairs in the
/// checklist are in either the Failed or the Succeeded state. In
/// other words, at least one component of the checklist has candidate
/// pairs that are all in the Failed state, which means the component
/// has failed, which means the checklist has failed.
/// </summary>
Failed
}
/// <summary>
/// A check list entry represents an ICE candidate pair (local candidate + remote candidate)
/// that is being checked for connectivity. If the overall ICE session does succeed it will
/// be due to one of these checklist entries successfully completing the ICE checks.
/// </summary>
internal class ChecklistEntry : IComparable
{
public RTCIceCandidate LocalCandidate;
public RTCIceCandidate RemoteCandidate;
/// <summary>
/// The current state of this checklist entry. Indicates whether a STUN check has been
/// sent, responded to, timed out etc.
/// </summary>
/// <remarks>
/// See https://tools.ietf.org/html/rfc8445#section-6.1.2.6 for the state
/// transition diagram for a check list entry.
/// </remarks>
public ChecklistEntryState State = ChecklistEntryState.Frozen;
/// <summary>
/// The candidate pairs whose local and remote candidates are both the
/// default candidates for a particular component is called the "default
/// candidate pair" for that component. This is the pair that would be
/// used to transmit data if both agents had not been ICE aware.
/// </summary>
public bool Default;
/// <summary>
/// Gets set to true when the connectivity checks for the candidate pair are
/// successful. Valid entries are eligible to be set as nominated.
/// </summary>
public bool Valid;
/// <summary>
/// Gets set to true if this entry is selected as the single nominated entry to be
/// used for the session communications. Setting a check list entry as nominated
/// indicates the ICE checks have been successful and the application can begin
/// normal communications.
/// </summary>
public bool Nominated;
/// <summary>
/// The priority for the candidate pair:
/// - Let G be the priority for the candidate provided by the controlling agent.
/// - Let D be the priority for the candidate provided by the controlled agent.
/// Pair Priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
/// </summary>
/// <remarks>
/// See https://tools.ietf.org/html/rfc8445#section-6.1.2.3.
/// </remarks>
public ulong Priority { get; private set; }
/// <summary>
/// Timestamp the last connectivity check (STUN binding request) was sent at.
/// </summary>
public DateTime LastCheckSentAt = DateTime.MinValue;
/// <summary>
/// The number of checks that have been sent without a response.
/// </summary>
public int ChecksSent;
/// <summary>
/// The transaction ID that was set in the last STUN request connectivity check.
/// </summary>
public string RequestTransactionID;
/// <summary>
/// Creates a new entry for the ICE session checklist.
/// </summary>
/// <param name="localCandidate">The local candidate for the checklist pair.</param>
/// <param name="remoteCandidate">The remote candidate for the checklist pair.</param>
/// <param name="isLocalController">True if we are acting as the controlling agent in the ICE session.</param>
public ChecklistEntry(RTCIceCandidate localCandidate, RTCIceCandidate remoteCandidate, bool isLocalController)
{
LocalCandidate = localCandidate;
RemoteCandidate = remoteCandidate;
var controllingCandidate = (isLocalController) ? localCandidate : remoteCandidate;
var controlledCandidate = (isLocalController) ? remoteCandidate : localCandidate;
Priority = (2 << 32) * Math.Min(controllingCandidate.priority, controlledCandidate.priority) +
(ulong)2 * Math.Max(controllingCandidate.priority, controlledCandidate.priority) +
(ulong)((controllingCandidate.priority > controlledCandidate.priority) ? 1 : 0);
}
/// <summary>
/// Compare method to allow the checklist to be sorted in priority order.
/// </summary>
public int CompareTo(Object other)
{
if (other is ChecklistEntry)
{
//return Priority.CompareTo((other as ChecklistEntry).Priority);
return (other as ChecklistEntry).Priority.CompareTo(Priority);
}
else
{
throw new ApplicationException("CompareTo is not implemented for ChecklistEntry and arbitrary types.");
}
}
}
/// <summary>
/// If ICE servers (STUN or TURN) are being used with the session this class is used to track
/// the connection state for each server that gets used.
/// </summary>
internal class IceServerConnectionState
{
/// <summary>
/// The maximum number of requests to send to an ICE server without getting
/// a response.
/// </summary>
internal const int MAX_REQUESTS = 6;
internal STUNUri _uri;
internal string _username;
internal string _password;
/// <summary>
/// The end point for this STUN or TURN server. Will be set asynchronously once
/// any required DNS lookup completes.
/// </summary>
internal IPEndPoint ServerEndPoint { get; set; }
/// <summary>
/// The transaction ID to use in STUN requests. It is used to match responses
/// with connection checks for this ICE serve entry.
/// </summary>
internal string TransactionID { get; private set; }
/// <summary>
/// The number of requests that have been sent to the server.
/// </summary>
internal int RequestsSent { get; set; }
/// <summary>
/// The timestamp the most recent binding request was sent at.
/// </summary>
internal DateTime LastRequestSentAt { get; set; }
/// <summary>
/// The timestamp of the most recent response received from the ICE server.
/// </summary>
internal DateTime LastResponseReceivedAt { get; set; } = DateTime.MinValue;
/// <summary>
/// Records the failure message if there was an error configuring or contacting
/// the STUN or TURN server.
/// </summary>
internal SocketError Error { get; set; } = SocketError.Success;
/// <summary>
/// If the connection check is successful this will hold the resultant ICE candidate.
/// The type will be either "server reflexive" or "relay".
/// </summary>
internal RTCIceCandidate Candidate { get; set; }
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="uri">The STUN or TURN server URI the connection is being attempted to.</param>
/// <param name="username">Optional. If authentication is required the username to use.</param>
/// <param name="password">Optional. If authentication is required the password to use.</param>
internal IceServerConnectionState(STUNUri uri, string username, string password)
{
_uri = uri;
_username = username;
_password = password;
TransactionID = Crypto.GetRandomString(STUNHeader.TRANSACTION_ID_LENGTH);
}
}
private const int ICE_UFRAG_LENGTH = 4;
private const int ICE_PASSWORD_LENGTH = 24;
private const int MAX_CHECKLIST_ENTRIES = 25; // Maximum number of entries that can be added to the checklist of candidate pairs.
private const string MDNS_TLD = ".local"; // Top Level Domain name for multicast lookups as per RFC6762.
public const string SDP_MID = "0";
public const int SDP_MLINE_INDEX = 0;
/// <summary>
/// ICE transaction spacing interval in milliseconds.
/// </summary>
/// <remarks>
/// See https://tools.ietf.org/html/rfc8445#section-14.
/// </remarks>
private const int Ta = 50;
/// <summary>
/// The number of connectivity checks to carry out.
/// </summary>
private const int N = 5;
private static readonly ILogger logger = Log.Logger;
private RTPChannel _rtpChannel;
private IPAddress _remoteSignallingAddress;
private List<RTCIceServer> _iceServers;
private RTCIceTransportPolicy _policy;
private ConcurrentDictionary<STUNUri, IceServerConnectionState> _iceServerConnections;
public RTCIceComponent Component { get; private set; }
public RTCIceGatheringState GatheringState { get; private set; } = RTCIceGatheringState.@new;
public RTCIceConnectionState ConnectionState { get; private set; } = RTCIceConnectionState.@new;
/// <summary>
/// True if we are the "controlling" ICE agent (we initiated the communications) or
/// false if we are the "controlled" agent.
/// </summary>
public bool IsController { get; internal set; }
/// <summary>
/// The list of host ICE candidates that have been gathered for this peer.
/// </summary>
public List<RTCIceCandidate> Candidates
{
get
{
return _candidates;
}
}
private List<RTCIceCandidate> _candidates = new List<RTCIceCandidate>();
private List<RTCIceCandidate> _remoteCandidates = new List<RTCIceCandidate>();
/// <summary>
/// The state of the checklist as the ICE checks are carried out.
/// </summary>
internal ChecklistState _checklistState = ChecklistState.Running;
/// <summary>
/// The checklist of local and remote candidate pairs
/// </summary>
internal List<ChecklistEntry> _checklist = new List<ChecklistEntry>();
/// <summary>
/// For local candidates this implementation takes a shortcut to reduce complexity.
/// The RTP socket will always be bound to one of:
/// - IPAddress.IPv6Any [::],
/// - IPAddress.Any 0.0.0.0, or,
/// - a specific single IP address.
/// As such it's only necessary to create a single checklist entry for each remote
/// candidate.
/// Real host candidates must still be generated based on all local IP addresses. Those
/// local candidates need to be transmitted to the remote peer but they don't need to
/// be used when populating the checklist.
/// </summary>
internal readonly RTCIceCandidate _localChecklistCandidate;
/// <summary>
/// If the connectivity checks are successful this will hold the nominated
/// remote candidate.
/// </summary>
public RTCIceCandidate NominatedCandidate { get; private set; }
/// <summary>
/// If the session has successfully connected this returns the remote end point of
/// the nominate candidate.
/// </summary>
public IPEndPoint ConnectedRemoteEndPoint
{
get { return (NominatedCandidate != null) ? NominatedCandidate.DestinationEndPoint : null; }
}
/// <summary>
/// Retransmission timer for STUN transactions, measured in milliseconds.
/// </summary>
/// <remarks>
/// As specified in https://tools.ietf.org/html/rfc8445#section-14.
/// </remarks>
internal int RTO
{
get
{
if (GatheringState == RTCIceGatheringState.gathering)
{
return Math.Max(500, Ta * Candidates.Count(x => x.type == RTCIceCandidateType.srflx || x.type == RTCIceCandidateType.relay));
}
else
{
return Math.Max(500, Ta * N * (_checklist.Count(x => x.State == ChecklistEntryState.Waiting) + _checklist.Count(x => x.State == ChecklistEntryState.InProgress)));
}
}
}
public readonly string LocalIceUser;
public readonly string LocalIcePassword;
public string RemoteIceUser { get; private set; }
public string RemoteIcePassword { get; private set; }
private bool _closed = false;
private Timer _processChecklistTimer;
private Timer _processIceServersTimer;
public event Action<RTCIceCandidate> OnIceCandidate;
public event Action<RTCIceConnectionState> OnIceConnectionStateChange;
public event Action<RTCIceGatheringState> OnIceGatheringStateChange;
public event Action OnIceCandidateError;
/// <summary>
/// Creates a new instance of an ICE session.
/// </summary>
/// <param name="rtpChannel">The RTP channel is the object managing the socket
/// doing the media sending and receiving. Its the same socket the ICE session
/// will need to initiate all the connectivity checks on.</param>
/// <param name="component">The component (RTP or RTCP) the channel is being used for. Note
/// for cases where RTP and RTCP are multiplexed the component is set to RTP.</param>
/// <param name="remoteSignallingAddress"> Optional. If supplied this address will
/// dictate which local interface host ICE candidates will be gathered from.
/// Restricting the host candidate IP addresses to a single interface is
/// as per the recommendation at:
/// https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12#section-5.2.
/// If this is not set then the default is to use the Internet facing interface as
/// returned by the OS routing table.</param>
/// <param name="iceServers">A list of STUN or TURN servers that can be used by this ICE agent.</param>
/// <param name="policy">Determines which ICE candidates can be used in this ICE session.</param>
public IceSession(RTPChannel rtpChannel,
RTCIceComponent component,
IPAddress remoteSignallingAddress,
List<RTCIceServer> iceServers = null,
RTCIceTransportPolicy policy = RTCIceTransportPolicy.all)
{
if (rtpChannel == null)
{
throw new ArgumentNullException("rtpChannel");
}
if (_dnsLookupClient == null)
{
_dnsLookupClient = new DnsClient.LookupClient();
}
_rtpChannel = rtpChannel;
Component = component;
_remoteSignallingAddress = remoteSignallingAddress;
_iceServers = iceServers;
_policy = policy;
LocalIceUser = Crypto.GetRandomString(ICE_UFRAG_LENGTH);
LocalIcePassword = Crypto.GetRandomString(ICE_PASSWORD_LENGTH);
_localChecklistCandidate = new RTCIceCandidate(new RTCIceCandidateInit
{
sdpMid = SDP_MID,
sdpMLineIndex = SDP_MLINE_INDEX,
usernameFragment = LocalIceUser
});
_localChecklistCandidate.SetAddressProperties(
RTCIceProtocol.udp,
_rtpChannel.RTPLocalEndPoint.Address,
(ushort)_rtpChannel.RTPLocalEndPoint.Port,
RTCIceCandidateType.host,
null,
0);
}
/// <summary>
/// We've been given the green light to start the ICE candidate gathering process.
/// This could include contacting external STUN and TURN servers. Events will
/// be fired as each ICE is identified and as the gathering state machine changes
/// state.
/// </summary>
public void StartGathering()
{
if (GatheringState == RTCIceGatheringState.@new)
{
GatheringState = RTCIceGatheringState.gathering;
OnIceGatheringStateChange?.Invoke(RTCIceGatheringState.gathering);
_candidates = GetHostCandidates();
if (_candidates == null || _candidates.Count == 0)
{
logger.LogWarning("ICE session did not discover any host candidates no point continuing.");
OnIceCandidateError?.Invoke();
OnIceConnectionStateChange?.Invoke(RTCIceConnectionState.failed);
OnIceConnectionStateChange(RTCIceConnectionState.failed);
}
else
{
logger.LogDebug($"ICE session discovered {_candidates.Count} local candidates.");
if (_iceServers != null)
{
InitialiseIceServers(_iceServers);
_processIceServersTimer = new Timer(CheckIceServers, null, 0, Ta);
}
_processChecklistTimer = new Timer(ProcessChecklist, null, 0, Ta);
}
}
}
/// <summary>
/// Set the ICE credentials that have been supplied by the remote peer. Once these
/// are set the connectivity checks should be able to commence.
/// </summary>
/// <param name="username">The remote peer's ICE username.</param>
/// <param name="password">The remote peer's ICE password.</param>
public void SetRemoteCredentials(string username, string password)
{
logger.LogDebug("ICE session remote credentials set.");
RemoteIceUser = username;
RemoteIcePassword = password;
// Once the remote party's ICE credentials are known connection checking can
// commence immediately as candidates trickle in.
ConnectionState = RTCIceConnectionState.checking;
OnIceConnectionStateChange?.Invoke(ConnectionState);
}
/// <summary>
/// Closes the ICE session and stops any further connectivity checks.
/// </summary>
/// <param name="reason">Reason for the close. Informational only.</param>
public void Close(string reason)
{
if (!_closed)
{
_closed = true;
_processChecklistTimer?.Dispose();
_processIceServersTimer?.Dispose();
}
}
/// <summary>
/// Adds a remote ICE candidate to the ICE session.
/// </summary>
/// <param name="candidate">An ICE candidate from the remote party.</param>
public async Task AddRemoteCandidate(RTCIceCandidate candidate)
{
if (candidate == null || string.IsNullOrWhiteSpace(candidate.address))
{
// Note that the way ICE signals the end of the gathering stage is to send
// an empty candidate or "end-of-candidates" SDP attribute.
logger.LogWarning($"ICE session omitting empty remote candidate.");
}
else if (candidate.component != Component)
{
// This occurs if the remote party made an offer and assumed we couldn't multiplex the audio and video streams.
// It will offer the same ICE candidates separately for the audio and video announcements.
logger.LogWarning($"ICE session omitting remote candidate with unsupported component: {candidate}.");
}
else if (candidate.protocol != RTCIceProtocol.udp)
{
// This implementation currently only supports UDP for RTP communications.
logger.LogWarning($"ICE session omitting remote candidate with unsupported transport protocol: {candidate.protocol}.");
}
else if (candidate.address.Trim().ToLower().EndsWith(MDNS_TLD))
{
// Supporting MDNS lookups means an additional nuget dependency. Hopefully
// support is coming to .Net Core soon (AC 12 Jun 2020).
logger.LogWarning($"ICE session omitting remote candidate with unsupported MDNS hostname: {candidate.address}");
}
else
{
// Have a remote candidate. Connectivity checks can start. Note because we support ICE trickle
// we may also still be gathering candidates. Connectivity checks and gathering can be done in parallel.
logger.LogDebug($"ICE session received remote candidate: {candidate}");
_remoteCandidates.Add(candidate);
await UpdateChecklist(candidate);
}
}
/// <summary>
/// Restarts the ICE gathering and connection checks for this ICE session.
/// </summary>
public void Restart()
{
// Reset the session state.
_processChecklistTimer?.Dispose();
_candidates.Clear();
_checklist.Clear();
GatheringState = RTCIceGatheringState.@new;
ConnectionState = RTCIceConnectionState.@new;
StartGathering();
}
/// <summary>
/// Acquires an ICE candidate for each IP address that this host has except for:
/// - Loopback addresses must not be included.
/// - Deprecated IPv4-compatible IPv6 addresses and IPv6 site-local unicast addresses
/// must not be included,
/// - IPv4-mapped IPv6 address should not be included.
/// - If a non-location tracking IPv6 address is available use it and do not included
/// location tracking enabled IPv6 addresses (i.e. prefer temporary IPv6 addresses over
/// permanent addresses), see RFC6724.
///
/// SECURITY NOTE: https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12#section-5.2
/// Makes recommendations about how host IP address information should be exposed.
/// Of particular relevance are:
///
/// Mode 1: Enumerate all addresses: WebRTC MUST use all network
/// interfaces to attempt communication with STUN servers, TURN
/// servers, or peers.This will converge on the best media
/// path, and is ideal when media performance is the highest
/// priority, but it discloses the most information.
///
/// Mode 2: Default route + associated local addresses: WebRTC MUST
/// follow the kernel routing table rules, which will typically
/// cause media packets to take the same route as the
/// application's HTTP traffic. If an enterprise TURN server is
/// present, the preferred route MUST be through this TURN
/// server.Once an interface has been chosen, the private IPv4
/// and IPv6 addresses associated with this interface MUST be
/// discovered and provided to the application as host
/// candidates.This ensures that direct connections can still
/// be established in this mode.
///
/// This implementation implements Mode 2.
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc8445#section-5.1.1.1</remarks>
/// <returns>A list of "host" ICE candidates for the local machine.</returns>
private List<RTCIceCandidate> GetHostCandidates()
{
List<RTCIceCandidate> hostCandidates = new List<RTCIceCandidate>();
RTCIceCandidateInit init = new RTCIceCandidateInit { usernameFragment = LocalIceUser };
IPAddress signallingDstAddress = _remoteSignallingAddress;
// RFC8445 states that loopback addresses should not be included in
// host candidates. If the provided signalling address is a loopback
// address it means no host candidates will be gathered. To avoid this
// set the desired interface address to the Internet facing address
// in the event a loopback address was specified.
if (signallingDstAddress != null &&
(IPAddress.IsLoopback(signallingDstAddress) ||
IPAddress.Any.Equals(signallingDstAddress) ||
IPAddress.IPv6Any.Equals(signallingDstAddress)))
{
// By setting to null means the default Internet facing interface will be used.
signallingDstAddress = null;
}
var rtpBindAddress = _rtpChannel.RTPLocalEndPoint.Address;
// We get a list of local addresses that can be used with the address the RTP socket is bound on.
List<IPAddress> localAddresses = null;
if (IPAddress.IPv6Any.Equals(rtpBindAddress))
{
if (_rtpChannel.RtpSocket.DualMode)
{
// IPv6 dual mode listening on [::] means we can use all valid local addresses.
localAddresses = NetServices.GetLocalAddressesOnInterface(signallingDstAddress)
.Where(x => !IPAddress.IsLoopback(x) && !x.IsIPv4MappedToIPv6 && !x.IsIPv6SiteLocal).ToList();
}
else
{
// IPv6 but not dual mode on [::] means can use all valid local IPv6 addresses.
localAddresses = NetServices.GetLocalAddressesOnInterface(signallingDstAddress)
.Where(x => x.AddressFamily == AddressFamily.InterNetworkV6
&& !IPAddress.IsLoopback(x) && !x.IsIPv4MappedToIPv6 && !x.IsIPv6SiteLocal).ToList();
}
}
else if (IPAddress.Any.Equals(rtpBindAddress))
{
// IPv4 on 0.0.0.0 means can use all valid local IPv4 addresses.
localAddresses = NetServices.GetLocalAddressesOnInterface(signallingDstAddress)
.Where(x => x.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(x)).ToList();
}
else
{
// If not bound on a [::] or 0.0.0.0 means we're only listening on a specific IP address
// and that's the only one that can be used for the host candidate.
localAddresses = new List<IPAddress> { rtpBindAddress };
}
foreach (var localAddress in localAddresses)
{
var hostCandidate = new RTCIceCandidate(init);
hostCandidate.SetAddressProperties(RTCIceProtocol.udp, localAddress, (ushort)_rtpChannel.RTPPort, RTCIceCandidateType.host, null, 0);
// We currently only support a single multiplexed connection for all data streams and RTCP.
if (hostCandidate.component == RTCIceComponent.rtp && hostCandidate.sdpMLineIndex == SDP_MLINE_INDEX)
{
hostCandidates.Add(hostCandidate);
OnIceCandidate?.Invoke(hostCandidate);
}
}
return hostCandidates;
}
/// <summary>
/// Initialises the ICE servers if any were provided in the initial configuration.
/// ICE servers are STUN and TURN servers and are used to gather "server reflexive"
/// and "relay" candidates.
/// </summary>
/// <remarks>See https://tools.ietf.org/html/rfc8445#section-5.1.1.2</remarks>
private void InitialiseIceServers(List<RTCIceServer> iceServers)
{
_iceServerConnections = new ConcurrentDictionary<STUNUri, IceServerConnectionState>();
// Send STUN binding requests to each of the STUN servers.
foreach (var iceServer in iceServers)
{
string[] urls = iceServer.urls.Split(',');
foreach (string url in urls)
{
if (!String.IsNullOrWhiteSpace(url))
{
if (STUNUri.TryParse(url, out var stunUri))
{
if (!_iceServerConnections.ContainsKey(stunUri))
{
logger.LogDebug($"Adding ICE server to connection checks {stunUri}.");
var iceServerState = new IceServerConnectionState(stunUri, iceServer.username, iceServer.credential);
_iceServerConnections.TryAdd(stunUri, iceServerState);
logger.LogDebug($"Attempting to resolve STUN server URI {stunUri}.");
STUNDns.Resolve(stunUri).ContinueWith(x =>
{
if (x.Result != null)
{
logger.LogDebug($"ICE server {stunUri} successfully resolved to {x.Result}.");
iceServerState.ServerEndPoint = x.Result;
}
else
{
logger.LogWarning($"Unable to resolve ICE server end point for {stunUri}.");
iceServerState.Error = SocketError.HostNotFound;
}
});
}
}
else
{
logger.LogWarning($"ICE session could not parse ICE server URL {url}.");
}
}
}
}
}
/// <summary>
/// Checks the list of ICE servers to perform STUN binding or TURN reservation requests.
/// </summary>
private void CheckIceServers(Object state)
{
// The lock is to ensure the timer callback doesn't run multiple instances in parallel.
if (Monitor.TryEnter(_iceServerConnections))
{
if (_iceServerConnections.Count(x => x.Value.Error == SocketError.Success && x.Value.Candidate == null) == 0)
{
logger.LogDebug("ICE session there are no ICE servers left to check, closing check ICE servers timer.");
_processIceServersTimer.Dispose();
}
else
{
// Only send one check gets sent per callback.
var entry = _iceServerConnections
.Where(x => x.Value.Error == SocketError.Success && x.Value.ServerEndPoint != null && x.Value.Candidate == null)
.OrderBy(x => x.Value.RequestsSent)
.FirstOrDefault();
if (!entry.Equals(default(KeyValuePair<STUNUri, IceServerConnectionState>)))
{
var iceServerState = entry.Value;
if (DateTime.Now.Subtract(iceServerState.LastRequestSentAt).TotalMilliseconds > Ta)
{
if (iceServerState.LastResponseReceivedAt == DateTime.MinValue &&
iceServerState.RequestsSent >= IceServerConnectionState.MAX_REQUESTS)
{
logger.LogWarning($"Connection attempt to ICE server {iceServerState._uri} timed out after {iceServerState.RequestsSent} requests.");
iceServerState.Error = SocketError.TimedOut;
}
else
{
iceServerState.RequestsSent += 1;
iceServerState.LastRequestSentAt = DateTime.Now;
// Send a STUN binding request.
STUNMessage stunRequest = new STUNMessage(STUNMessageTypesEnum.BindingRequest);
stunRequest.Header.TransactionId = Encoding.ASCII.GetBytes(iceServerState.TransactionID);
byte[] stunReqBytes = stunRequest.ToByteBuffer(null, false);
var sendResult = _rtpChannel.SendAsync(RTPChannelSocketsEnum.RTP, iceServerState.ServerEndPoint, stunReqBytes);
if (sendResult != SocketError.Success)
{
logger.LogWarning($"Error sending STUN server binding request {iceServerState.RequestsSent} for " +
$"{iceServerState._uri} to {iceServerState.ServerEndPoint}. {sendResult}.");
iceServerState.Error = sendResult;
}
}
}
}
}
Monitor.Exit(_iceServerConnections);
}
}
/// <summary>
/// Updates the checklist with new candidate pairs.
/// </summary>
/// <remarks>
/// From https://tools.ietf.org/html/rfc8445#section-6.1.2.2:
/// IPv6 link-local addresses MUST NOT be paired with other than link-local addresses.
/// </remarks>
private async Task UpdateChecklist(RTCIceCandidate remoteCandidate)
{
// Local server reflexive candidates don't get added to the checklist since they are just local
// "host" candidates with an extra NAT address mapping. The NAT address mapping is needed for the
// remote ICE peer but locally a server reflexive candidate is always going to be represented by
// a "host" candidate.
bool supportsIPv4 = _rtpChannel.RtpSocket.AddressFamily == AddressFamily.InterNetwork || _rtpChannel.IsDualMode;
bool supportsIPv6 = _rtpChannel.RtpSocket.AddressFamily == AddressFamily.InterNetworkV6 || _rtpChannel.IsDualMode;
string remoteAddress = (string.IsNullOrWhiteSpace(remoteCandidate.relatedAddress)) ? remoteCandidate.address : remoteCandidate.relatedAddress;
if (!IPAddress.TryParse(remoteAddress, out var remoteCandidateIPAddr))
{
// The candidate string can be a hostname or an IP address.
var lookupResult = await _dnsLookupClient.QueryAsync(remoteAddress, DnsClient.QueryType.A);
if (lookupResult.Answers.Count > 0)
{
remoteCandidateIPAddr = lookupResult.Answers.AddressRecords().FirstOrDefault()?.Address;
logger.LogDebug($"ICE session resolved remote candidate {remoteAddress} to {remoteCandidateIPAddr}.");
}
else
{
logger.LogDebug($"ICE session failed to resolve remote candidate {remoteAddress}.");
}
}
if (remoteCandidateIPAddr != null)
{
var port = (string.IsNullOrWhiteSpace(remoteCandidate.relatedAddress)) ? remoteCandidate.port : remoteCandidate.relatedPort;
var remoteEP = new IPEndPoint(remoteCandidateIPAddr, port);
remoteCandidate.SetDestinationEndPoint(remoteEP);
lock (_checklist)
{
if (remoteCandidateIPAddr.AddressFamily == AddressFamily.InterNetwork && supportsIPv4 ||
remoteCandidateIPAddr.AddressFamily == AddressFamily.InterNetworkV6 && supportsIPv6)
{
ChecklistEntry entry = new ChecklistEntry(_localChecklistCandidate, remoteCandidate, IsController);
// Because only ONE checklist is currently supported each candidate pair can be set to
// a "waiting" state. If an additional checklist is ever added then only one candidate
// pair with the same foundation should be set to waiting across all checklists.
// See https://tools.ietf.org/html/rfc8445#section-6.1.2.6 for a somewhat convoluted
// explanation and example.
entry.State = ChecklistEntryState.Waiting;
AddChecklistEntry(entry);
}
// Finally sort the checklist to put it in priority order and if necessary remove lower
// priority pairs.
_checklist.Sort();
while (_checklist.Count > MAX_CHECKLIST_ENTRIES)
{
_checklist.RemoveAt(_checklist.Count - 1);
}
}
}
}
/// <summary>
/// Attempts to add a checklist entry. If there is already an equivalent entry in the checklist
/// the entry may not be added or may replace an existing entry.
/// </summary>
/// <param name="entry">The new entry to attempt to add to the checklist.</param>
private void AddChecklistEntry(ChecklistEntry entry)
{
// Check if there is already an entry that matches the remote candidate.
// Note: The implementation in this class relies binding the socket used for all
// local candidates on a SINGLE address (typically 0.0.0.0 or [::]). Consequently
// there is no need to check the local candidate when determining duplicates. As long
// as there is one checklist entry with each remote candidate the connectivity check will
// work. To put it another way the local candidate information is not used on the
// "Nominated" pair.
var entryRemoteEP = entry.RemoteCandidate.DestinationEndPoint;
var existingEntry = _checklist.Where(x => x.RemoteCandidate.DestinationEndPoint != null
&& x.RemoteCandidate.DestinationEndPoint.Address.Equals(entryRemoteEP.Address)
&& x.RemoteCandidate.DestinationEndPoint.Port == entryRemoteEP.Port
&& x.RemoteCandidate.protocol == entry.RemoteCandidate.protocol).SingleOrDefault();
if (existingEntry != null)
{
if (entry.Priority > existingEntry.Priority)
{
logger.LogDebug($"Removing lower priority entry and adding candidate pair to checklist for: {entry.RemoteCandidate}");
_checklist.Remove(existingEntry);
_checklist.Add(entry);
}
else
{
logger.LogDebug($"Existing checklist entry has higher priority, NOT adding entry for: {entry.RemoteCandidate}");
}
}
else
{
// No existing entry.
logger.LogDebug($"Adding new candidate pair to checklist for: {entry.RemoteCandidate}");
_checklist.Add(entry);
}
}
/// <summary>
/// Processes the checklist and sends any required STUN requests to perform connectivity checks.
/// </summary>
/// <remarks>
/// The scheduling mechanism for ICE is specified in https://tools.ietf.org/html/rfc8445#section-6.1.4.
/// </remarks>
private void ProcessChecklist(Object stateInfo)
{
try
{
if (ConnectionState == RTCIceConnectionState.checking && _checklist != null && _checklist.Count > 0)
{
if (RemoteIceUser == null || RemoteIcePassword == null)
{
logger.LogWarning("ICE session checklist processing cannot occur as either the remote ICE user or password are not set.");
ConnectionState = RTCIceConnectionState.failed;
}
else
{
lock (_checklist)
{
// The checklist gets sorted into priority order whenever a remote candidate and its corresponding candidate pairs
// are added. At this point it can be relied upon that the checklist is correctly sorted by candidate pair priority.
// Do a check for any timed out entries.
var failedEntries = _checklist.Where(x => x.State == ChecklistEntryState.InProgress
&& DateTime.Now.Subtract(x.LastCheckSentAt).TotalMilliseconds > RTO
&& x.ChecksSent >= N).ToList();
foreach (var failedEntry in failedEntries)
{
logger.LogDebug($"Checks for checklist entry have timed out, state being set to failed: {failedEntry.LocalCandidate} -> {failedEntry.RemoteCandidate}.");
failedEntry.State = ChecklistEntryState.Failed;
}
// Move on to checking for checklist entries that need an initial check sent.
var nextEntry = _checklist.Where(x => x.State == ChecklistEntryState.Waiting).FirstOrDefault();
if (nextEntry != null)
{
SendConnectivityCheck(nextEntry, false);
return;
}
// No waiting entries so check for ones requiring a retransmit.
var retransmitEntry = _checklist.Where(x => x.State == ChecklistEntryState.InProgress
&& DateTime.Now.Subtract(x.LastCheckSentAt).TotalMilliseconds > RTO).FirstOrDefault();
if (retransmitEntry != null)
{
SendConnectivityCheck(retransmitEntry, false);
return;
}
// If this point is reached and all entries are in a failed state then the overall result
// of the ICE check is a failure.
if (_checklist.All(x => x.State == ChecklistEntryState.Failed))
{
_processChecklistTimer.Dispose();
_checklistState = ChecklistState.Failed;
ConnectionState = RTCIceConnectionState.failed;
OnIceConnectionStateChange?.Invoke(ConnectionState);
}
}
}
}
}
catch (Exception excp)
{
logger.LogError("Exception ProcessChecklist. " + excp);
}
}
/// <summary>
/// Sets the nominated checklist entry. This action completes the checklist processing and
/// indicates the connection checks were successful.
/// </summary>
/// <param name="entry">The checklist entry that was nominated.</param>
private void SetNominatedEntry(ChecklistEntry entry)
{
entry.Nominated = true;
_checklistState = ChecklistState.Completed;
NominatedCandidate = entry.RemoteCandidate;
ConnectionState = RTCIceConnectionState.connected;
OnIceConnectionStateChange?.Invoke(RTCIceConnectionState.connected);
}
/// <summary>
/// Performs a connectivity check for a single candidate pair entry.
/// </summary>
/// <param name="candidatePair">The candidate pair to perform a connectivity check for.</param>
/// <param name="setUseCandidate">If true indicates we are acting as the "controlling" ICE agent
/// and are nominating this candidate as the chosen one.</param>
/// <remarks>As specified in https://tools.ietf.org/html/rfc8445#section-7.2.4.</remarks>
private void SendConnectivityCheck(ChecklistEntry candidatePair, bool setUseCandidate)
{
candidatePair.State = ChecklistEntryState.InProgress;
candidatePair.LastCheckSentAt = DateTime.Now;
candidatePair.ChecksSent++;
candidatePair.RequestTransactionID = Crypto.GetRandomString(STUNHeader.TRANSACTION_ID_LENGTH);
IPEndPoint remoteEndPoint = candidatePair.RemoteCandidate.DestinationEndPoint;
logger.LogDebug($"Sending ICE connectivity check from {_rtpChannel.RTPLocalEndPoint} to {remoteEndPoint} (use candidate {setUseCandidate}).");
STUNMessage stunRequest = new STUNMessage(STUNMessageTypesEnum.BindingRequest);
stunRequest.Header.TransactionId = Encoding.ASCII.GetBytes(candidatePair.RequestTransactionID);
stunRequest.AddUsernameAttribute(RemoteIceUser + ":" + LocalIceUser);
stunRequest.Attributes.Add(new STUNAttribute(STUNAttributeTypesEnum.Priority, BitConverter.GetBytes(candidatePair.Priority)));
if (setUseCandidate)
{
stunRequest.Attributes.Add(new STUNAttribute(STUNAttributeTypesEnum.UseCandidate, null));
}
byte[] stunReqBytes = stunRequest.ToByteBufferStringKey(RemoteIcePassword, true);
_rtpChannel.SendAsync(RTPChannelSocketsEnum.RTP, remoteEndPoint, stunReqBytes);
}
/// <summary>
/// Processes a received STUN request or response.
/// </summary>
/// <param name="stunMessage">The STUN message received.</param>
/// <param name="remoteEndPoint">The remote end point the STUN packet was received from.</param>
public void ProcessStunMessage(STUNMessage stunMessage, IPEndPoint remoteEndPoint)
{
remoteEndPoint = (!remoteEndPoint.Address.IsIPv4MappedToIPv6) ? remoteEndPoint : new IPEndPoint(remoteEndPoint.Address.MapToIPv4(), remoteEndPoint.Port);
//logger.LogDebug($"STUN message received from remote {remoteEndPoint} {stunMessage.Header.MessageType}.");
bool isForIceServerCheck = false;
// Check if the STUN message is for an ICE server check.
if (_iceServerConnections != null)
{
string txID = Encoding.ASCII.GetString(stunMessage.Header.TransactionId);
var iceServerConnection = GetIceServerConnection(txID);
if (iceServerConnection != null)
{
isForIceServerCheck = true;
ProcessStunResponseForIceServer(iceServerConnection, stunMessage, remoteEndPoint);
}
}
// If the STUN message isn't for an ICE server then look for matching entries in the checklist.
if (!isForIceServerCheck)
{
if (stunMessage.Header.MessageType == STUNMessageTypesEnum.BindingRequest)
{
#region STUN Binding Requests.
// TODO: The integrity check method needs to be implemented (currently just returns true).
bool result = stunMessage.CheckIntegrity(System.Text.Encoding.UTF8.GetBytes(LocalIcePassword), LocalIceUser, RemoteIceUser);
if (!result)
{
// Send STUN error response.
STUNMessage stunErrResponse = new STUNMessage(STUNMessageTypesEnum.BindingErrorResponse);
stunErrResponse.Header.TransactionId = stunMessage.Header.TransactionId;
_rtpChannel.SendAsync(RTPChannelSocketsEnum.RTP, remoteEndPoint, stunErrResponse.ToByteBuffer(null, false));
}
else
{
var matchingCandidate = (_remoteCandidates != null) ? _remoteCandidates.Where(x => x.IsEquivalentEndPoint(RTCIceProtocol.udp, remoteEndPoint)).FirstOrDefault() : null;
if (matchingCandidate == null)
{
// This STUN request has come from a socket not in the remote ICE candidates list.
// Add a new remote peer reflexive candidate.
RTCIceCandidate peerRflxCandidate = new RTCIceCandidate(new RTCIceCandidateInit());
peerRflxCandidate.SetAddressProperties(RTCIceProtocol.udp, remoteEndPoint.Address, (ushort)remoteEndPoint.Port, RTCIceCandidateType.prflx, null, 0);
logger.LogDebug($"Adding peer reflex ICE candidate for {remoteEndPoint}.");
_remoteCandidates.Add(peerRflxCandidate);
_ = UpdateChecklist(peerRflxCandidate);
matchingCandidate = peerRflxCandidate;
}
// Find the checklist entry for this remote candidate and update its status.
ChecklistEntry matchingChecklistEntry = null;
lock (_checklist)
{
matchingChecklistEntry = _checklist.Where(x => x.RemoteCandidate.foundation == matchingCandidate.foundation).FirstOrDefault();
}
if (matchingChecklistEntry == null)
{
logger.LogWarning("ICE session STUN request matched a remote candidate but NOT a checklist entry.");
}
// The UseCandidate attribute is only meant to be set by the "Controller" peer. This implementation
// will accept it irrespective of the peer roles. If the remote peer wants us to use a certain remote
// end point then so be it.
if (stunMessage.Attributes.Any(x => x.AttributeType == STUNAttributeTypesEnum.UseCandidate))
{
if (ConnectionState != RTCIceConnectionState.connected)
{
// If we are the "controlled" agent and get a "use candidate" attribute that sets the matching candidate as nominated
// as per https://tools.ietf.org/html/rfc8445#section-7.3.1.5.
if (matchingChecklistEntry == null)
{
logger.LogWarning("ICE session STUN request had UseCandidate set but no matching checklist entry was found.");
}
else
{
logger.LogDebug($"ICE session remote peer nominated entry from binding request: {matchingChecklistEntry.RemoteCandidate}");
SetNominatedEntry(matchingChecklistEntry);
}
}
}
STUNMessage stunResponse = new STUNMessage(STUNMessageTypesEnum.BindingSuccessResponse);
stunResponse.Header.TransactionId = stunMessage.Header.TransactionId;
stunResponse.AddXORMappedAddressAttribute(remoteEndPoint.Address, remoteEndPoint.Port);
string localIcePassword = LocalIcePassword;
byte[] stunRespBytes = stunResponse.ToByteBufferStringKey(localIcePassword, true);
_rtpChannel.SendAsync(RTPChannelSocketsEnum.RTP, remoteEndPoint, stunRespBytes);
}
#endregion
}
else if (stunMessage.Header.MessageType == STUNMessageTypesEnum.BindingSuccessResponse)
{
#region STUN Binding Success Responses
// Correlate with request using transaction ID as per https://tools.ietf.org/html/rfc8445#section-7.2.5.
// Actions to take on a successful STUN response https://tools.ietf.org/html/rfc8445#section-7.2.5.3
// - Discover peer reflexive remote candidates
// (TODO: According to https://tools.ietf.org/html/rfc8445#section-7.2.5.3.1 peer reflexive get added to the local candidates list?)
// - Construct a valid pair which means match a candidate pair in the check list and mark it as valid (since a successful STUN exchange
// has now taken place on it). A new entry may need to be created for this pair since peer reflexive candidates are not added to the connectivity
// check checklist.
// - Update state of candidate pair that generated the check to Succeeded.
// - If the controlling candidate set the USE_CANDIDATE attribute then the ICE agent that receives the successful response sets the nominated
// flag of the pair to true. Once the nominated flag is set it concludes the ICE processing for that component.
if (_checklistState == ChecklistState.Running)
{
string txID = Encoding.ASCII.GetString(stunMessage.Header.TransactionId);
// Attempt to find the checklist entry for this transaction ID.
ChecklistEntry matchingChecklistEntry = null;
lock (_checklist)
{
matchingChecklistEntry = _checklist.Where(x => x.RequestTransactionID == txID).FirstOrDefault();
}
if (matchingChecklistEntry == null)
{
logger.LogWarning("ICE session STUN response transaction ID did not match a checklist entry.");
}
else
{
matchingChecklistEntry.State = ChecklistEntryState.Succeeded;
if (matchingChecklistEntry.Nominated)
{
logger.LogDebug($"ICE session remote peer nominated entry from binding response: {matchingChecklistEntry.RemoteCandidate}");
// This is the response to a connectivity check that had the "UseCandidate" attribute set.
SetNominatedEntry(matchingChecklistEntry);
}
else if (this.IsController && !_checklist.Any(x => x.Nominated))
{
// If we are the controlling ICE agent it's up to us to decide when to nominate a candidate pair to use for the connection.
// To start with we'll just use whichever pair gets the first successful STUN exchange. If needs be the selection algorithm can
// improve over time.
matchingChecklistEntry.ChecksSent = 0;
matchingChecklistEntry.LastCheckSentAt = DateTime.MinValue;
matchingChecklistEntry.Nominated = true;
SendConnectivityCheck(matchingChecklistEntry, true);
}
}
}
#endregion
}
else if (stunMessage.Header.MessageType == STUNMessageTypesEnum.BindingErrorResponse)
{
#region STUN Binding Error Responses
logger.LogWarning($"A STUN binding error response was received from {remoteEndPoint}.");
// Attempt to find the checklist entry for this transaction ID.
string txID = Encoding.ASCII.GetString(stunMessage.Header.TransactionId);
ChecklistEntry matchingChecklistEntry = null;
lock (_checklist)
{
_checklist.Where(x => x.RequestTransactionID == txID).FirstOrDefault();
}
if (matchingChecklistEntry == null)
{
logger.LogWarning("ICE session STUN error response transaction ID did not match a checklist entry.");
}
else
{
logger.LogWarning($"ICE session check list entry set to failed: {matchingChecklistEntry.RemoteCandidate}");
matchingChecklistEntry.State = ChecklistEntryState.Failed;
}
#endregion
}
else
{
logger.LogWarning($"An unrecognised STUN request was received from {remoteEndPoint}.");
}
}
}
/// <summary>
/// Checks a STUN response transaction ID to determine if it matches a check being carried
/// out for an ICE server.
/// </summary>
/// <param name="transactionID">The transaction ID from the STUN response.</param>
/// <returns>If found a matching state object or null if not.</returns>
private IceServerConnectionState GetIceServerConnection(string transactionID)
{
var entry = _iceServerConnections
.Where(x => x.Value.TransactionID == transactionID)
.SingleOrDefault();
if (!entry.Equals(default(KeyValuePair<STUNUri, IceServerConnectionState>)))
{
return entry.Value;
}
else
{
return null;
}
}
/// <summary>
/// Processes a STUN response for an ICE server check.
/// </summary>
/// <param name="iceServerConnection">The ICE server connection the STUN response was generated for.</param>
/// <param name="stunResponse">The STUN response received from the remote server.</param>
/// <param name="remoteEndPoint">The remote end point the STUN response originated from.</param>
private void ProcessStunResponseForIceServer(IceServerConnectionState iceServerConnection, STUNMessage stunResponse, IPEndPoint remoteEndPoint)
{
if (iceServerConnection == null)
{
throw new ArgumentNullException("iceServerConenction", "The ICE server connection parameter cannot be null.");
}
else if (stunResponse == null)
{
throw new ArgumentNullException("stunResponse", "The STUN response parameter cannot be null.");
}
if (stunResponse.Header.MessageType == STUNMessageTypesEnum.BindingSuccessResponse)
{
// The STUN response is for a check sent to an ICE server.
iceServerConnection.LastResponseReceivedAt = DateTime.Now;
// If the candidate is set then this connection check has already been completed.
if (iceServerConnection.Candidate == null)
{
logger.LogDebug($"STUN binding success response received for ICE server check to {iceServerConnection._uri}.");
var mappedAddr = stunResponse.Attributes.Where(x => x.AttributeType == STUNAttributeTypesEnum.XORMappedAddress).FirstOrDefault();
if (mappedAddr != null)
{
var mappedAddress = (mappedAddr as STUNXORAddressAttribute).Address;
int mappedPort = (mappedAddr as STUNXORAddressAttribute).Port;
// Mark the ICE server check as successful by setting the candidate property on it.
RTCIceCandidateInit init = new RTCIceCandidateInit { usernameFragment = LocalIceUser };
RTCIceCandidate svrRflxCandidate = new RTCIceCandidate(init);
svrRflxCandidate.SetAddressProperties(RTCIceProtocol.udp, NetServices.InternetDefaultAddress, (ushort)_rtpChannel.RTPPort,
RTCIceCandidateType.srflx, mappedAddress, (ushort)mappedPort);
svrRflxCandidate.IceServerUri = iceServerConnection._uri;
logger.LogDebug($"Adding server reflex ICE candidate for ICE server {iceServerConnection._uri}.");
// Note server reflexive candidates don't update the checklist pairs since it's merely an
// alternative way to represent an existing host candidate.
_candidates.Add(svrRflxCandidate);
iceServerConnection.Candidate = svrRflxCandidate;
OnIceCandidate?.Invoke(svrRflxCandidate);
}
}
}
else if (stunResponse.Header.MessageType == STUNMessageTypesEnum.BindingErrorResponse)
{
logger.LogWarning($"STUN binding error response received for ICE server check to {iceServerConnection._uri}.");
// The STUN response is for a check sent to an ICE server.
iceServerConnection.LastResponseReceivedAt = DateTime.Now;
iceServerConnection.Error = SocketError.ConnectionRefused;
}
else
{
logger.LogWarning($"An unrecognised STUN message for an ICE server check was received from {remoteEndPoint}.");
}
}
/// <summary>
/// Gets an allocate request for a TURN server.
/// </summary>
/// <param name="iceServerState">The TURN server configuration to get the request for.</param>
private STUNMessage GetTurnAllocateRequest(IceServerConnectionState iceServerState)
{
STUNMessage allocateRequest = new STUNMessage(STUNMessageTypesEnum.Allocate);
allocateRequest.Header.TransactionId = Encoding.ASCII.GetBytes(iceServerState.TransactionID);
allocateRequest.Attributes.Add(new STUNAttribute(STUNAttributeTypesEnum.Lifetime, 3600));
allocateRequest.Attributes.Add(new STUNAttribute(STUNAttributeTypesEnum.RequestedTransport, STUNAttributeConstants.UdpTransportType));
return allocateRequest;
}
private STUNMessage GetTurnPermissionsRequest(IceServerConnectionState iceServerState)
{
// Send create permission request
STUNMessage turnPermissionRequest = new STUNMessage(STUNMessageTypesEnum.CreatePermission);
turnPermissionRequest.Header.TransactionId = Encoding.ASCII.GetBytes(iceServerState.TransactionID);
//turnBindRequest.Attributes.Add(new STUNv2Attribute(STUNv2AttributeTypesEnum.ChannelNumber, (ushort)3000));
turnPermissionRequest.Attributes.Add(new STUNXORAddressAttribute(STUNAttributeTypesEnum.XORPeerAddress, iceServerState._uri.Port, iceServerState.ServerEndPoint.Address));
turnPermissionRequest.Attributes.Add(new STUNAttribute(STUNAttributeTypesEnum.Username, Encoding.UTF8.GetBytes(iceServerState._username)));
//turnPermissionRequest.Attributes.Add(new STUNAttribute(STUNAttributeTypesEnum.Nonce, Encoding.UTF8.GetBytes(localTurnIceCandidate.TurnServer.Nonce)));
//turnPermissionRequest.Attributes.Add(new STUNAttribute(STUNAttributeTypesEnum.Realm, Encoding.UTF8.GetBytes(localTurnIceCandidate.TurnServer.Realm)));
//MD5 md5 = new MD5CryptoServiceProvider();
//byte[] hmacKey = md5.ComputeHash(Encoding.UTF8.GetBytes(localTurnIceCandidate.TurnServer.Username + ":" + localTurnIceCandidate.TurnServer.Realm + ":" + localTurnIceCandidate.TurnServer.Password));
//byte[] turnPermissionReqBytes = turnPermissionRequest.ToByteBuffer(hmacKey, false);
return turnPermissionRequest;
}
}
}
| 51.010676 | 212 | 0.56795 | [
"BSD-3-Clause"
] | spFly/sipsorcery | src/net/ICE/IceSession.cs | 71,672 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.V2beta1.Snippets
{
using Google.Cloud.Dialogflow.V2beta1;
public sealed partial class GeneratedIntentsClientStandaloneSnippets
{
/// <summary>Snippet for GetIntent</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void GetIntent2()
{
// Create client
IntentsClient intentsClient = IntentsClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/agent/intents/[INTENT]";
string languageCode = "";
// Make the request
Intent response = intentsClient.GetIntent(name, languageCode);
}
}
}
| 36.85 | 89 | 0.675034 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/dialogflow/v2beta1/google-cloud-dialogflow-v2beta1-csharp/Google.Cloud.Dialogflow.V2beta1.StandaloneSnippets/IntentsClient.GetIntent2Snippet.g.cs | 1,474 | C# |
/*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Copyright (C) 2010 Michael Möller <mmoeller@openhardwaremonitor.org>
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO.Ports;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Win32;
namespace OpenHardwareMonitor.Hardware.Heatmaster {
internal class HeatmasterGroup : IGroup {
private readonly List<Heatmaster> hardware = new List<Heatmaster>();
private readonly StringBuilder report = new StringBuilder();
private static string ReadLine(SerialPort port, int timeout) {
int i = 0;
StringBuilder builder = new StringBuilder();
while (i < timeout) {
while (port.BytesToRead > 0) {
byte b = (byte)port.ReadByte();
switch (b) {
case 0xAA: return ((char)b).ToString();
case 0x0D: return builder.ToString();
default: builder.Append((char)b); break;
}
}
i++;
Thread.Sleep(1);
}
throw new TimeoutException();
}
private static string[] GetRegistryPortNames() {
List<string> result = new List<string>();
string[] paths = { "", "&MI_00" };
try {
foreach (string path in paths) {
RegistryKey key = Registry.LocalMachine.OpenSubKey(
@"SYSTEM\CurrentControlSet\Enum\USB\VID_10C4&PID_EA60" + path);
if (key != null) {
foreach (string subKeyName in key.GetSubKeyNames()) {
RegistryKey subKey =
key.OpenSubKey(subKeyName + "\\" + "Device Parameters");
if (subKey != null) {
string name = subKey.GetValue("PortName") as string;
if (name != null && !result.Contains(name))
result.Add(name);
}
}
}
}
} catch (SecurityException) { }
return result.ToArray();
}
public HeatmasterGroup(ISettings settings) {
// No implementation for Heatmaster on Unix systems
if (OperatingSystem.IsUnix)
return;
string[] portNames = GetRegistryPortNames();
for (int i = 0; i < portNames.Length; i++) {
bool isValid = false;
try {
using (SerialPort serialPort =
new SerialPort(portNames[i], 38400, Parity.None, 8, StopBits.One)) {
serialPort.NewLine = ((char)0x0D).ToString();
report.Append("Port Name: "); report.AppendLine(portNames[i]);
try {
serialPort.Open();
} catch (UnauthorizedAccessException) {
report.AppendLine("Exception: Access Denied");
}
if (serialPort.IsOpen) {
serialPort.DiscardInBuffer();
serialPort.DiscardOutBuffer();
serialPort.Write(new byte[] { 0xAA }, 0, 1);
int j = 0;
while (serialPort.BytesToRead == 0 && j < 10) {
Thread.Sleep(20);
j++;
}
if (serialPort.BytesToRead > 0) {
bool flag = false;
while (serialPort.BytesToRead > 0 && !flag) {
flag |= (serialPort.ReadByte() == 0xAA);
}
if (flag) {
serialPort.WriteLine("[0:0]RH");
try {
int k = 0;
int revision = 0;
while (k < 5) {
string line = ReadLine(serialPort, 100);
if (line.StartsWith("-[0:0]RH:",
StringComparison.Ordinal)) {
revision = int.Parse(line.Substring(9),
CultureInfo.InvariantCulture);
break;
}
k++;
}
isValid = (revision == 770);
if (!isValid) {
report.Append("Status: Wrong Hardware Revision " +
revision.ToString(CultureInfo.InvariantCulture));
}
} catch (TimeoutException) {
report.AppendLine("Status: Timeout Reading Revision");
}
} else {
report.AppendLine("Status: Wrong Startflag");
}
} else {
report.AppendLine("Status: No Response");
}
serialPort.DiscardInBuffer();
} else {
report.AppendLine("Status: Port not Open");
}
}
} catch (Exception e) {
report.AppendLine(e.ToString());
}
if (isValid) {
report.AppendLine("Status: OK");
hardware.Add(new Heatmaster(portNames[i], settings));
}
report.AppendLine();
}
}
public IReadOnlyList<IHardware> Hardware {
get {
return hardware.ToArray();
}
}
public string GetReport() {
if (report.Length > 0) {
StringBuilder r = new StringBuilder();
r.AppendLine("Serial Port Heatmaster");
r.AppendLine();
r.Append(report);
r.AppendLine();
return r.ToString();
} else
return null;
}
public void Close() {
foreach (Heatmaster heatmaster in hardware)
heatmaster.Dispose();
}
}
}
| 32.462428 | 80 | 0.508903 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Cereal-Killa/openhardwaremonitor | OpenHardwareMonitorLib/Hardware/Heatmaster/HeatmasterGroup.cs | 5,619 | C# |
/*********************************************************************
*
* Copyright (C) 2009 Andrew Khan
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***************************************************************************/
// Port to C#
// Chris Laforet
// Wachovia, a Wells-Fargo Company
// Feb 2010
using CSharpJExcel.Jxl.Biff;
namespace CSharpJExcel.Jxl.Read.Biff
{
/**
* A hideobj record
*/
class HideobjRecord : RecordData
{
/**
* The logger
*/
// private static Logger logger = Logger.getLogger(HideobjRecord.class);
/**
* The hide obj mode
*/
private int hidemode;
/**
* Constructor
*
* @param t the record
*/
public HideobjRecord(Record t)
: base(t)
{
byte[] data = t.getData();
hidemode = IntegerHelper.getInt(data[0],data[1]);
}
/**
* Accessor for the hide mode mode
*
* @return the hide mode
*/
public int getHideMode()
{
return hidemode;
}
}
}
| 23.797101 | 76 | 0.619367 | [
"Apache-2.0"
] | Tatetaylor/kbplumbapp | CSharpJExcel/CSharpJExcel/CSharpJExcel/Jxl/Read/Biff/HideobjRecord.cs | 1,642 | 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 GoodyAppDesktop.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GoodyAppDesktop.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 38.708333 | 181 | 0.604234 | [
"MIT"
] | KRDmitriy/GoodyAppDesktop | GoodyAppDesktop/Properties/Resources.Designer.cs | 2,789 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthOwner : MonoBehaviour {
[SerializeField] int health = 1;
public delegate void HealthEnded();
public event HealthEnded OnHealthEnded = delegate { };
public void DecreaseHealth(int amount) {
health -= amount;
if (health <= 0) {
OnHealthEnded();
}
}
}
| 21.578947 | 58 | 0.646341 | [
"Apache-2.0"
] | vadym-vasilyev/star-rage | Assets/Scripts/Enemies/HealthOwner.cs | 412 | C# |
// Copyright (c) Nathan Ellenfield. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using Microsoft.Extensions.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
namespace VariableConfig.Test
{
[TestClass]
public class VariableConfigurationExtensionsTests
{
[TestMethod]
public void AutomaticallyBuildSourceConfig()
{
var autoBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddXmlFile("variables.config")
.AddVariableConfiguration();
var autoConfiguration = autoBuilder.Build();
Assert.AreEqual("VarValueComp1", autoConfiguration["Composite"]);
}
[TestMethod]
public void ManuallyBuildSourceConfig()
{
var sourceBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddXmlFile("variables.config");
var sourceConfig = sourceBuilder.Build();
var manualBuilder = new ConfigurationBuilder()
.AddVariableConfiguration(sourceConfig);
var manualConfiguration = manualBuilder.Build();
Assert.AreEqual("VarValueComp1", manualConfiguration["Composite"]);
}
}
}
| 35.225 | 107 | 0.654365 | [
"Apache-2.0"
] | ellenfieldn/VariableConfig | test/VariableConfig.Test/VariableConfigurationExtensionsTests.cs | 1,411 | C# |
using System;
namespace CreativeCoders.Core.UnitTests.Reflection
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class DummyTestAttribute : Attribute
{
public int Value { get; set; }
}
} | 23.4 | 64 | 0.705128 | [
"Apache-2.0"
] | CreativeCodersTeam/Core | source/UnitTests/CreativeCoders.Core.UnitTests/Reflection/DummyTestAttribute.cs | 236 | C# |
/*
* THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.Json.Serialization;
namespace Plotly.Blazor.Traces.DensityMapBoxLib
{
/// <summary>
/// The Stream class.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")]
[Serializable]
public class Stream : IEquatable<Stream>
{
/// <summary>
/// The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings
/// for more details.
/// </summary>
[JsonPropertyName(@"token")]
public string Token { get; set;}
/// <summary>
/// Sets the maximum number of points to keep on the plots from an incoming
/// stream. If <c>maxpoints</c> is set to <c>50</c>, only the newest 50 points
/// will be displayed on the plot.
/// </summary>
[JsonPropertyName(@"maxpoints")]
public decimal? MaxPoints { get; set;}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (!(obj is Stream other)) return false;
return ReferenceEquals(this, obj) || Equals(other);
}
/// <inheritdoc />
public bool Equals([AllowNull] Stream other)
{
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
return
(
Token == other.Token ||
Token != null &&
Token.Equals(other.Token)
) &&
(
MaxPoints == other.MaxPoints ||
MaxPoints != null &&
MaxPoints.Equals(other.MaxPoints)
);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
var hashCode = 41;
if (Token != null) hashCode = hashCode * 59 + Token.GetHashCode();
if (MaxPoints != null) hashCode = hashCode * 59 + MaxPoints.GetHashCode();
return hashCode;
}
}
/// <summary>
/// Checks for equality of the left Stream and the right Stream.
/// </summary>
/// <param name="left">Left Stream.</param>
/// <param name="right">Right Stream.</param>
/// <returns>Boolean</returns>
public static bool operator == (Stream left, Stream right)
{
return Equals(left, right);
}
/// <summary>
/// Checks for inequality of the left Stream and the right Stream.
/// </summary>
/// <param name="left">Left Stream.</param>
/// <param name="right">Right Stream.</param>
/// <returns>Boolean</returns>
public static bool operator != (Stream left, Stream right)
{
return !Equals(left, right);
}
/// <summary>
/// Gets a deep copy of this instance.
/// </summary>
/// <returns>Stream</returns>
public Stream DeepClone()
{
return this.Copy();
}
}
} | 32.038095 | 125 | 0.520809 | [
"MIT"
] | valu8/Plotly.Blazor | Plotly.Blazor/Traces/DensityMapBoxLib/Stream.cs | 3,364 | C# |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Threading.Tasks;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Guids;
using Volo.Abp.Identity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.PermissionManagement;
using Volo.Abp.Uow;
namespace LINGYUN.Abp.PermissionManagement.Identity
{
[Dependency(ServiceLifetime.Singleton, ReplaceServices = true)]
[ExposeServices(typeof(IPermissionManager), typeof(PermissionManager), typeof(DefaultPermissionManager))]
public class IdentityPermissionManager : DefaultPermissionManager
{
protected IUnitOfWorkManager UnitOfWorkManager => LazyGetRequiredService(ref _unitOfWorkManager);
private IUnitOfWorkManager _unitOfWorkManager;
protected IUnitOfWork CurrentUnitOfWork => UnitOfWorkManager?.Current;
protected IUserRoleFinder UserRoleFinder { get; }
public IdentityPermissionManager(
IPermissionDefinitionManager permissionDefinitionManager,
IPermissionGrantRepository permissionGrantRepository,
IPermissionStore permissionStore,
IServiceProvider serviceProvider,
IGuidGenerator guidGenerator,
IOptions<PermissionManagementOptions> options,
ICurrentTenant currentTenant,
IUserRoleFinder userRoleFinder)
: base(permissionDefinitionManager, permissionGrantRepository, permissionStore, serviceProvider, guidGenerator, options, currentTenant)
{
UserRoleFinder = userRoleFinder;
}
protected override async Task<bool> IsGrantedAsync(string permissionName, string providerName, string providerKey)
{
if (!RolePermissionValueProvider.ProviderName.Equals(providerName))
{
// 如果查询的是用户权限,需要查询用户角色权限
if (providerName == UserPermissionValueProvider.ProviderName)
{
var userId = Guid.Parse(providerKey);
var roleNames = await GetUserRolesAsync(userId);
foreach (var roleName in roleNames)
{
var permissionGrant = await PermissionStore.IsGrantedAsync(permissionName, RolePermissionValueProvider.ProviderName, roleName);
if (permissionGrant)
{
return true;
}
}
}
}
return await base.IsGrantedAsync(permissionName, providerName, providerKey);
}
protected virtual async Task<string[]> GetUserRolesAsync(Guid userId)
{
// 通过工作单元来缓存用户角色,防止多次查询
if (CurrentUnitOfWork != null)
{
var userRoleItemKey = $"FindRolesByUser:{userId}";
return await CurrentUnitOfWork.GetOrAddItem(userRoleItemKey, (key) =>
{
// 取消同步调用
//var roles = AsyncHelper.RunSync(async ()=> await UserRoleFinder.GetRolesAsync(userId));
return UserRoleFinder.GetRolesAsync(userId);
});
}
return await UserRoleFinder.GetRolesAsync(userId);
}
}
}
| 41.936709 | 151 | 0.64262 | [
"MIT"
] | FanShiYou/abp-vue-admin-element-typescript | aspnet-core/modules/identity/LINGYUN.Abp.PermissionManagement.Domain.Identity/LINGYUN/Abp/PermissionManagement/Identity/IdentityPermissionManager.cs | 3,405 | C# |
using ShoppingListService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
namespace ShoppingListService.Helpers
{
public class ShoppingListHelper : IShoppingListHelper
{
/// <summary>
/// A a new item to the list
/// </summary>
/// <param name="list">The shopping list</param>
/// <param name="itemName">The item to add</param>
/// <param name="quantity">The initial quantity for the item</param>
/// <returns>null if successful. An Error if not successful.</returns>
public RequestError Add(ShoppingList list, string itemName, int quantity)
{
if (GetListItem(list, itemName) != null)
{
return new RequestError(HttpStatusCode.BadRequest);
}
list.Items.Add(new ShoppingListItem
{
Item = itemName,
Quantity = quantity
});
return null;
}
/// <summary>
/// Update an item that already exists in the list
/// </summary>
/// <param name="list">The shopping list</param>
/// <param name="itemName">The item to update</param>
/// <param name="quantity">The quantity to update</param>
/// <returns>null if successful. An Error if not successful.</returns>
public RequestError Update(ShoppingList list, string itemName, int quantity)
{
var listItem = GetListItem(list, itemName);
if (listItem == null)
{
return new RequestError(HttpStatusCode.NotFound);
}
listItem.Quantity = quantity;
return null;
}
/// <summary>
/// Delete an item that exists in the list
/// </summary>
/// <param name="list">The shopping list</param>
/// <param name="itemName">The item to delete</param>
/// <returns>null if successful. An Error if not successful.</returns>
public RequestError Delete(ShoppingList list, string itemName)
{
var listItem = GetListItem(list, itemName);
if (listItem == null)
{
return new RequestError(HttpStatusCode.NotFound);
}
list.Items.Remove(listItem);
return null;
}
/// <summary>
/// Get the existing list item from the list.
/// </summary>
/// <param name="itemName">The name of the item to get</param>
/// <param name="list">The shopping list</param>
/// <returns>The list item if it exists. Otherwise null.</returns>
public ShoppingListItem GetListItem(ShoppingList list, string itemName)
{
return list.Items.Where(items => items.Item.ToUpper() == itemName.ToUpper()).FirstOrDefault();
}
}
} | 34.176471 | 106 | 0.570052 | [
"MIT"
] | neilkennedy/coding-challenge-shopping-list | WebService/ShoppingListService/Helpers/ShoppingListHelper.cs | 2,907 | C# |
namespace Sakuno.ING.Game.Models
{
public enum FleetType
{
None = 0,
/// <summary>
/// 通常艦隊
/// </summary>
SingleFleet = 1,
/// <summary>
/// 空母機動部隊
/// </summary>
CarrierTaskForceFleet = 2,
/// <summary>
/// 水上打撃部隊
/// </summary>
SurfaceTaskForceFleet = 3,
/// <summary>
/// 輸送護衛部隊
/// </summary>
TransportEscortFleet = 4,
/// <summary>
/// 遊撃部隊
/// </summary>
StrikingForceFleet = 5,
}
}
| 20.392857 | 34 | 0.42732 | [
"MIT"
] | A-Kaga/ing | src/Game/Sakuno.ING.Game.Models.Raw/Models/FleetType.cs | 625 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BezierSpline))]
public class SplineSigil : BaseSigil {
//public SpellCircle spellPlane;
private BezierSpline sigil;
public int numPointsInSigil;
public bool manuallySetBoundingBox;
// Start is called before the first frame update
void Start() {
sigil = GetComponent<BezierSpline>();
CalculateBoundingBox();
}
// --------------------------------------------------------------------------------
// Sigil position
// --------------------------------------------------------------------------------
public Vector3 GetPointOnSpellPlane(float t, SpellCircle spellPlane) {
return TranslatePointToSpellPlane(sigil.GetPointLocalSpace(t), spellPlane);
}
// --------------------------------------------------------------------------------
// Sigil rendering
// --------------------------------------------------------------------------------
public override void DrawSigil(SpellCircle spellPlane, LineRenderer lineRenderer, bool transformToSpellPlane) {
if (numPointsInSigil < 1) {
Debug.LogError("Not enough points given to draw this spline!");
return;
}
lineRenderer.enabled = true;
lineRenderer.positionCount = numPointsInSigil;
Vector3 point = sigil.GetPointLocalSpace(0f);
if (transformToSpellPlane) {
lineRenderer.SetPosition(0, TranslatePointToSpellPlane(point, spellPlane));
} else {
lineRenderer.SetPosition(0, point);
}
for (int i = 1; i < numPointsInSigil; i++) {
float splineIndex = (float) i / (numPointsInSigil - 1);
point = sigil.GetPointLocalSpace(splineIndex);
if (transformToSpellPlane) {
lineRenderer.SetPosition(i, TranslatePointToSpellPlane(point, spellPlane));
} else {
lineRenderer.SetPosition(i, point);
}
}
}
// --------------------------------------------------------------------------------
// Sigil size
// --------------------------------------------------------------------------------
// Cheap hack to estimate the min/max x/y values:
// Query the spline at each control point for its x/y values.
// Also query the halfway points between control points
protected override void CalculateBoundingBox() {
if (manuallySetBoundingBox) return;
for (int cp = 0; cp < sigil.numControlPoints; cp++) {
float sigilIndex = (float)cp / (float)(sigil.numControlPoints - 1);
Vector3 point = sigil.GetPointLocalSpace(sigilIndex);
// Reset
if (cp == 0) {
boundingBox[0] = point;
boundingBox[1] = point;
} else {
UpdateBoundingBox(point);
// Test the halfway point between this control point, and the previous one
sigilIndex = ((float)cp - 0.5f) / (float)(sigil.numControlPoints - 1);
point = sigil.GetPointLocalSpace(sigilIndex);
UpdateBoundingBox(point);
}
}
}
}
| 38.674419 | 116 | 0.50451 | [
"MIT"
] | iamrequest/a-vr-game-about-magic-and-ducks-in-cosplay | Assets/Scripts/Spells/SplineSigil.cs | 3,328 | C# |
//
// System.Security.Permissions.UrlIdentityPermissionAttribute.cs
//
// Authors:
// Duncan Mak <duncan@ximian.com>
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2002 Ximian, Inc. http://www.ximian.com
// Portions (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.InteropServices;
namespace System.Security.Permissions {
#if NET_2_0
[ComVisible (true)]
#endif
[AttributeUsage (AttributeTargets.Assembly | AttributeTargets.Class |
AttributeTargets.Struct | AttributeTargets.Constructor |
AttributeTargets.Method, AllowMultiple=true, Inherited=false)]
[Serializable]
public sealed class UrlIdentityPermissionAttribute : CodeAccessSecurityAttribute {
// Fields
private string url;
// Constructor
public UrlIdentityPermissionAttribute (SecurityAction action)
: base (action)
{
}
// Properties
public string Url {
get { return url; }
set { url = value; }
}
// Methods
public override IPermission CreatePermission ()
{
if (this.Unrestricted)
return new UrlIdentityPermission (PermissionState.Unrestricted);
// Note: It is possible to create a permission with a
// null URL but not to create a UrlIdentityPermission (null)
else if (url == null)
return new UrlIdentityPermission (PermissionState.None);
else
return new UrlIdentityPermission (url);
}
}
}
| 34.027027 | 83 | 0.741461 | [
"MIT"
] | zlxy/Genesis-3D | Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/corlib/System.Security.Permissions/UrlIdentityPermissionAttribute.cs | 2,518 | C# |
using NBitcoin;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.CommandLine
{
internal class PasswordFinder
{
internal static Dictionary<string, string> Charsets = new Dictionary<string, string>
{
["en"] = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
["es"] = "aábcdeéfghiíjkmnñoópqrstuúüvwxyzAÁBCDEÉFGHIÍJKLMNNOÓPQRSTUÚÜVWXYZ",
["pt"] = "aáàâābcçdeéêfghiíjkmnoóôōpqrstuúvwxyzAÁÀÂĀBCÇDEÉÊFGHIÍJKMNOÓÔŌPQRSTUÚVWXYZ",
["it"] = "abcdefghimnopqrstuvxyzABCDEFGHILMNOPQRSTUVXYZ",
["fr"] = "aâàbcçdæeéèëœfghiîïjkmnoôpqrstuùüvwxyÿzAÂÀBCÇDÆEÉÈËŒFGHIÎÏJKMNOÔPQRSTUÙÜVWXYŸZ",
};
internal static void Find(string secret, string language, bool useNumbers, bool useSymbols)
{
BitcoinEncryptedSecretNoEC encryptedSecret;
try
{
encryptedSecret = new BitcoinEncryptedSecretNoEC(secret, NBitcoin.Altcoins.Groestlcoin.Instance.Mainnet);
}
catch (FormatException)
{
Logger.LogCritical("ERROR: The encrypted secret is invalid. Make sure you copied correctly from your wallet file.");
return;
}
Logger.LogWarning($"WARNING: This tool will display your password if it finds it.");
Logger.LogWarning($" You can cancel this by CTRL+C combination anytime.{Environment.NewLine}");
Console.Write("Enter a likely password: ");
var password = PasswordConsole.ReadPassword();
var charset = Charsets[language] + (useNumbers ? "0123456789" : "") + (useSymbols ? "|!¡@$¿?_-\"#$/%&()´+*=[]{},;:.^`<>" : "");
var found = false;
var lastpwd = "";
var attempts = 0;
var maxNumberAttempts = password.Length * charset.Length;
var stepSize = (maxNumberAttempts + 101) / 100;
Console.WriteLine();
Console.Write($"[{"",100}] 0%");
var sw = new Stopwatch();
sw.Start();
foreach (var pwd in GeneratePasswords(password, charset.ToArray()))
{
lastpwd = pwd;
try
{
encryptedSecret.GetKey(pwd);
found = true;
break;
}
catch (SecurityException)
{
}
Progress(++attempts, stepSize, maxNumberAttempts, sw.Elapsed);
}
sw.Stop();
Console.WriteLine();
Console.WriteLine();
Logger.LogInfo($"Completed in {sw.Elapsed}");
Console.WriteLine(found ? $"SUCCESS: Password found: >>> {lastpwd} <<<" : "FAILED: Password not found");
Console.WriteLine();
}
private static void Progress(int iter, int stepSize, int max, TimeSpan elapsed)
{
if (iter % stepSize == 0)
{
var percentage = (int)((float)iter / max * 100);
var estimatedTime = elapsed / percentage * (100 - percentage);
var bar = new string('#', percentage);
Console.CursorLeft = 0;
Console.Write($"[{bar,-100}] {percentage}% - ET: {estimatedTime}");
}
}
private static IEnumerable<string> GeneratePasswords(string password, char[] charset)
{
var pwChar = password.ToCharArray();
for (var i = 0; i < pwChar.Length; i++)
{
var original = pwChar[i];
foreach (var c in charset)
{
pwChar[i] = c;
yield return new string(pwChar);
}
pwChar[i] = original;
}
}
}
}
| 29.841121 | 130 | 0.678359 | [
"MIT"
] | Groestlcoin/WalletWasabi | WalletWasabi.Gui/CommandLine/PasswordFinder.cs | 3,261 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Xunit;
namespace Mundane.Tests.Tests_Validator;
[ExcludeFromCodeCoverage]
public static class Validate_Throws_ArgumentNullException
{
[Fact]
public static void When_The_Action_Parameter_Is_Null()
{
var exception =
Assert.ThrowsAny<ArgumentNullException>(() => Validator.Validate((null as ValidationOperation<object>)!));
Assert.Equal("validationOperation", exception.ParamName!);
}
[Fact]
public static async Task When_The_Async_Action_Parameter_Is_Null()
{
var exception = await Assert.ThrowsAnyAsync<ArgumentNullException>(
async () => await Validator.Validate((null as ValidationOperation<ValueTask<object>>)!));
Assert.Equal("validationOperation", exception.ParamName!);
}
}
| 27.413793 | 109 | 0.788679 | [
"MIT"
] | adambarclay/mundane | tests/Mundane.Tests/Tests_Validator/Validate_Throws_ArgumentNullException.cs | 795 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Description;
using OpenRiaServices.DomainServices.Server;
using System.Web;
using System.Web.Configuration;
namespace OpenRiaServices.DomainServices.Hosting
{
/// <summary>
/// Provides a host for domain services.
/// </summary>
public class DomainServiceHost : ServiceHost, IServiceProvider
{
private static readonly HashSet<string> _allowedSchemes = new HashSet<string>() { Uri.UriSchemeHttp, Uri.UriSchemeHttps };
private static readonly HashSet<string> _allowedSecureSchemes = new HashSet<string>() { Uri.UriSchemeHttps };
private DomainServiceDescription _domainServiceDescription;
/// <summary>
/// Initializes a new instance of the <see cref="DomainServiceHost"/> class with
/// the type of service and its base addresses specified.
/// </summary>
/// <param name="domainServiceType">The type of the <see cref="DomainService"/> to host.</param>
/// <param name="baseAddresses">
/// An array of type <see cref="System.Uri"/> that contains the base addresses for
/// the hosted service.
/// </param>
public DomainServiceHost(Type domainServiceType, params Uri[] baseAddresses)
{
if (domainServiceType == null)
{
throw new ArgumentNullException("domainServiceType");
}
if (baseAddresses == null)
{
throw new ArgumentNullException("baseAddresses");
}
EnableClientAccessAttribute att = (EnableClientAccessAttribute)TypeDescriptor.GetAttributes(domainServiceType)[typeof(EnableClientAccessAttribute)];
// Filter out all non-HTTP addresses.
HashSet<string> allowedSchemes = DomainServiceHost._allowedSchemes;
// Additionally filter out HTTP addresses if this DomainService requires a secure endpoint.
if (att != null && att.RequiresSecureEndpoint)
{
allowedSchemes = DomainServiceHost._allowedSecureSchemes;
}
// Apply the filter.
baseAddresses = baseAddresses.Where(addr => allowedSchemes.Contains(addr.Scheme)).ToArray();
this._domainServiceDescription = DomainServiceDescription.GetDescription(domainServiceType);
this.InitializeDescription(domainServiceType, new UriSchemeKeyedCollection(baseAddresses));
}
/// <summary>
/// Gets a service.
/// </summary>
/// <param name="serviceType">The type of service to get.</param>
/// <returns>The service.</returns>
public object GetService(Type serviceType)
{
if (serviceType == null)
{
throw new ArgumentNullException("serviceType");
}
if (serviceType == typeof(IPrincipal))
{
return HttpContext.Current.User;
}
if (serviceType == typeof(HttpContext))
{
return HttpContext.Current;
}
if (serviceType == typeof(HttpContextBase))
{
return new HttpContextWrapper(HttpContext.Current);
}
return null;
}
/// <summary>
/// Creates a description of the service hosted.
/// </summary>
/// <param name="implementedContracts">
/// The <see cref="IDictionary<TKey,TValue>"/> with key pairs of
/// type (string, <see cref="ContractDescription"/>) that contains the
/// keyed-contracts of the hosted service that have been implemented.
/// </param>
/// <returns>A <see cref="ServiceDescription"/> of the hosted service.</returns>
protected override ServiceDescription CreateDescription(out IDictionary<string, ContractDescription> implementedContracts)
{
try
{
Type domainServiceType = this._domainServiceDescription.DomainServiceType;
ServiceDescription serviceDesc = ServiceDescription.GetService(domainServiceType);
implementedContracts = new Dictionary<string, ContractDescription>();
DomainServicesSection config = (DomainServicesSection)WebConfigurationManager.GetSection("system.serviceModel/domainServices");
if (config == null)
{
// Make sure we have a config instance, as that's where we put our default configuration. If we don't do this, our
// binary endpoint won't be used when someone doesn't have a <domainServices/> section in their web.config.
config = new DomainServicesSection();
config.InitializeDefaultInternal();
}
foreach (ProviderSettings provider in config.Endpoints)
{
DomainServiceEndpointFactory endpointFactory = DomainServiceHost.CreateEndpointFactoryInstance(provider);
foreach (ServiceEndpoint endpoint in endpointFactory.CreateEndpoints(this._domainServiceDescription, this))
{
string contractName = endpoint.Contract.ConfigurationName;
ContractDescription contract;
if (implementedContracts.TryGetValue(contractName, out contract) && contract != endpoint.Contract)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resource.DomainServiceHost_DuplicateContractName, contract.ConfigurationName));
}
// Register the contract.
implementedContracts[endpoint.Contract.ConfigurationName] = endpoint.Contract;
// Register the endpoint.
serviceDesc.Endpoints.Add(endpoint);
}
}
return serviceDesc;
}
catch (Exception ex)
{
DiagnosticUtility.ServiceException(ex);
throw;
}
}
/// <summary>
/// Loads the service description information from the configuration file and
/// applies it to the runtime being constructed.
/// </summary>
protected override void ApplyConfiguration()
{
base.ApplyConfiguration();
this.AddDefaultBehaviors();
foreach (ServiceEndpoint endpoint in this.Description.Endpoints)
{
#if DEBUG
if (Debugger.IsAttached)
{
endpoint.Binding.OpenTimeout = TimeSpan.FromMinutes(5);
}
#endif
}
}
/// <summary>
/// Adds the default service and contract behaviors for a domain service.
/// </summary>
protected virtual void AddDefaultBehaviors()
{
// Force ASP.NET compat mode.
AspNetCompatibilityRequirementsAttribute aspNetCompatModeBehavior = ServiceUtility.EnsureBehavior<AspNetCompatibilityRequirementsAttribute>(this.Description);
aspNetCompatModeBehavior.RequirementsMode = AspNetCompatibilityRequirementsMode.Required;
// Force default service behavior.
ServiceBehaviorAttribute serviceBehavior = ServiceUtility.EnsureBehavior<ServiceBehaviorAttribute>(this.Description);
serviceBehavior.InstanceContextMode = InstanceContextMode.PerCall;
serviceBehavior.IncludeExceptionDetailInFaults = true;
serviceBehavior.AddressFilterMode = AddressFilterMode.Any;
// Force metadata to be available through HTTP GET.
ServiceMetadataBehavior serviceMetadataBehavior = ServiceUtility.EnsureBehavior<ServiceMetadataBehavior>(this.Description);
serviceMetadataBehavior.HttpGetEnabled = this.BaseAddresses.Any(a => a.Scheme.Equals(Uri.UriSchemeHttp));
serviceMetadataBehavior.HttpsGetEnabled = this.BaseAddresses.Any(a => a.Scheme.Equals(Uri.UriSchemeHttps));
}
/// <summary>
/// Creates a <see cref="DomainServiceEndpointFactory"/> from a <see cref="ProviderSettings"/> object.
/// </summary>
/// <param name="provider">The <see cref="ProviderSettings"/> object.</param>
/// <returns>A <see cref="DomainServiceEndpointFactory"/>.</returns>
private static DomainServiceEndpointFactory CreateEndpointFactoryInstance(ProviderSettings provider)
{
Type endpointFactoryType = Type.GetType(provider.Type, /* throwOnError */ true);
DomainServiceEndpointFactory endpointFactory = (DomainServiceEndpointFactory)Activator.CreateInstance(endpointFactoryType);
endpointFactory.Name = provider.Name;
endpointFactory.Parameters = provider.Parameters;
return endpointFactory;
}
}
}
| 44.287081 | 185 | 0.631158 | [
"Apache-2.0"
] | jeffhandley/OpenRiaServices | OpenRiaServices.DomainServices.Hosting/Framework/Services/DomainServiceHost.cs | 9,258 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\dxva2swdev.h(60,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct _DXVA2_VIDEOPROCESSBLT
{
public int TargetFrame;
public tagRECT TargetRect;
public tagSIZE ConstrictionSize;
public uint StreamingFlags;
public int BackgroundColor;
public int DestFormat;
public uint DestFlags;
public int ProcAmpValues;
public int Alpha;
public int NoiseFilterLuma;
public int NoiseFilterChroma;
public int DetailFilterLuma;
public int DetailFilterChroma;
public IntPtr pSrcSurfaces;
public uint NumSrcSurfaces;
}
}
| 29.185185 | 85 | 0.682741 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/_DXVA2_VIDEOPROCESSBLT.cs | 790 | C# |
//Copyright 2018 Samsung Electronics Co., Ltd
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using Weather.Config;
using Weather.Views;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace Weather
{
/// <summary>
/// Main App class - derives Xamarin.Forms application functionalities
/// </summary>
public class App : Application
{
#region properties
/// <summary>
/// Gets or sets value that indicates if weather and forecast for selected city is initialized.
/// </summary>
public bool IsInitialized { get; set; }
#endregion
#region methods
/// <summary>
/// App constructor.
/// Makes sure that API Key is defined.
/// </summary>
public App()
{
Page root;
if (ApiConfig.IsApiKeyDefined())
{
root = new MainPage();
}
else
{
root = new MissingKeyErrorPage();
}
MainPage = new NavigationPage(root);
}
#endregion
}
} | 27.716667 | 103 | 0.61816 | [
"Apache-2.0"
] | AchoWang/Tizen-CSharp-Samples | Wearable/Weather/Weather/App.cs | 1,665 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Baseline;
using Xunit;
using NSubstitute;
using Shouldly;
using StoryTeller.Engine;
using StoryTeller.Messages;
using StoryTeller.Model;
using StoryTeller.Model.Persistence;
using StoryTeller.Model.Persistence.Markdown;
using StoryTeller.Remotes.Messaging;
namespace StoryTeller.Testing.Engine
{
public class SpecExecutionRequestTester : IDisposable
{
private readonly Specification theSpec;
private readonly RuntimeErrorListener listener;
public SpecExecutionRequestTester()
{
var path = TestingContext.FindParallelDirectory("Storyteller.Samples")
.AppendPath("Specs", "General", "Check properties.md");
theSpec = MarkdownReader.ReadFromFile(path);
listener = new RuntimeErrorListener();
}
public void Dispose()
{
EventAggregator.Messaging.RemoveListener(listener);
}
[Fact]
public void finishing_a_spec()
{
var action = Substitute.For<IResultObserver>();
var request = new SpecExecutionRequest(theSpec, action);
request.CreatePlan(TestingContext.Library);
request.Plan.Attempts = 3;
var results = new SpecResults();
request.SpecExecutionFinished(results);
action.Received().SpecExecutionFinished(theSpec, results);
}
[Fact]
public void finishing_a_spec_finishes_the_completion()
{
var action = Substitute.For<IResultObserver>();
var request = new SpecExecutionRequest(theSpec, action);
request.CreatePlan(TestingContext.Library);
request.Plan.Attempts = 3;
var results = new SpecResults();
request.Completion.IsCompleted.ShouldBeFalse();
request.SpecExecutionFinished(results);
request.Completion.IsCompleted.ShouldBeTrue();
request.Completion.Result.ShouldBe(results);
}
[Fact]
public void read_xml_happy_path()
{
var request = SpecExecutionRequest.For(theSpec);
request.Specification.ShouldNotBeNull();
request.Specification.Children.Count.ShouldBeGreaterThan(0);
request.IsCancelled.ShouldBe(false);
}
[Fact]
public void cancel_cancels_the_request()
{
var request = SpecExecutionRequest.For(theSpec);
request.IsCancelled.ShouldBe(false);
request.Cancel();
request.IsCancelled.ShouldBe(true);
}
[Fact]
public void create_plan_happy_path_smoke_test()
{
var request = SpecExecutionRequest.For(theSpec);
request.CreatePlan(TestingContext.Library);
request.IsCancelled.ShouldBe(false);
request.Plan.ShouldNotBeNull();
}
public class RuntimeErrorListener : IListener<RuntimeError>
{
public readonly IList<RuntimeError> Errors = new List<RuntimeError>();
public void Receive(RuntimeError message)
{
Errors.Add(message);
}
}
}
} | 27.705882 | 82 | 0.618441 | [
"Apache-2.0"
] | SergeiGolos/Storyteller | src/StoryTeller.Testing/Engine/SpecExecutionRequestTester.cs | 3,297 | 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("BasicSample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BasicSample")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("2c74d8d3-f97e-41a9-8552-f0748fabb459")]
// 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.702703 | 84 | 0.744803 | [
"Unlicense"
] | kichristensen/zipkin-net | samples/BasicSample/Properties/AssemblyInfo.cs | 1,398 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace Koji
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 17.666667 | 42 | 0.698113 | [
"Apache-2.0"
] | Aviramk/koji | Koji/App.xaml.cs | 320 | C# |
using System;
using System.Windows;
namespace AdaptiveCards.Rendering.Wpf
{
public class MissingInputException : Exception
{
public MissingInputException(string message, AdaptiveInput input, FrameworkElement frameworkElement)
: base(message)
{
this.FrameworkElement = frameworkElement;
this.AdaptiveInput = input;
}
public FrameworkElement FrameworkElement { get; set; }
public AdaptiveInput AdaptiveInput { get; set; }
}
} | 27.105263 | 108 | 0.669903 | [
"MIT"
] | Clancey/AdaptiveCards | source/dotnet/Library/AdaptiveCards.Rendering.Wpf/MissingInputException.cs | 517 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("ZMap.GNGDataGenerator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ZMap.GNGDataGenerator")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
| 41.125 | 97 | 0.737733 | [
"Apache-2.0"
] | hanzhou/ZenithMap | ZMap.GNGDataGenerator/Properties/AssemblyInfo.cs | 2,306 | C# |
using System;
namespace SwiftClient
{
public partial class Client : ISwiftClient, IDisposable
{
/// <summary>
/// Set credentials (username, password, list of proxy endpoints)
/// </summary>
/// <param name="credentials"></param>
/// <returns></returns>
public Client WithCredentials(SwiftCredentials credentials)
{
if (RetryManager == null)
{
var authManager = new SwiftAuthManager(credentials);
authManager.Authenticate = Authenticate;
authManager.Credentials = credentials;
RetryManager = new SwiftRetryManager(authManager);
}
return this;
}
/// <summary>
/// Log authentication errors, reauthorization events and request errors
/// </summary>
/// <param name="logger"></param>
/// <returns></returns>
public Client SetLogger(ISwiftLogger logger)
{
_logger = logger;
RetryManager.SetLogger(logger);
return this;
}
/// <summary>
/// Set retries count for all proxy nodes
/// </summary>
/// <param name="retryCount">Default value 1</param>
/// <returns></returns>
public Client SetRetryCount(int retryCount)
{
RetryManager.SetRetryCount(retryCount);
return this;
}
/// <summary>
/// Set retries count per proxy node request
/// </summary>
/// <param name="retryPerEndpointCount">Default value 1</param>
/// <returns></returns>
public Client SetRetryPerEndpointCount(int retryPerEndpointCount)
{
RetryManager.SetRetryPerEndpointCount(retryPerEndpointCount);
return this;
}
}
}
| 27.671642 | 80 | 0.556095 | [
"MIT"
] | amangallon/SwiftClient.NetStandard | src/SwiftClient/SwiftClientConfig.cs | 1,856 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
namespace Microsoft.Data.Tools.VSXmlDesignerBase.VirtualTreeGrid
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using Microsoft.Data.Entity.Design.VisualStudio;
using Microsoft.Data.Tools.VSXmlDesignerBase.Common;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.Win32;
/// <summary>
/// Values passed to TypeEditorHost.Create to indicate the style of the edit
/// box to show in the text area.
/// </summary>
internal enum TypeEditorHostEditControlStyle
{
/// <summary>
/// Displays a live edit box for the given value.
/// </summary>
Editable = 0,
/// <summary>
/// Leaves the region where a live edit box would normally be transparent
/// to let the backend control draw the text region.
/// </summary>
TransparentEditRegion = 1,
/// <summary>
/// Places an instruction label with GrayText in the area the text region would
/// normally be.
/// </summary>
InstructionLabel = 2,
/// <summary>
/// Displays a read-only edit box for the given value.
/// </summary>
ReadOnlyEdit = 3,
}
/// <summary>
/// Class used to drop down an arbitrary Control, or display a modal dialog editor
/// akin to what's being done by the property browser
/// </summary>
[SuppressMessage("Whitehorse.CustomRules", "WH03:WinFormControlCatchUnhandledExceptions",
Justification = "All but critical exceptions are caught.")]
internal class TypeEditorHost : Control, IWindowsFormsEditorService, ITypeDescriptorContext, IVirtualTreeInPlaceControl
{
private TypeEditorHostTextBox _edit;
private Control _instructionLabel;
private Control _dropDown;
private DropDownButton _button;
private DropDownHolder _dropDownHolder;
private object _instance; // instance object currently being edited
private PropertyDescriptor _propertyDescriptor; // property descriptor describing instance object property being edited
private readonly UITypeEditor _uiTypeEditor; // cached uiTypeEditor
private bool _inShowDialog; // flag set to true if we are showing a dialog.
private DialogResult _dialogResult;
// cached DialogResult from ShowDialog call. Used in OpenDropDown to determine whether to dismiss the label edit control if commitOnClose is set.
// cache these because we won't use them until handle creation.
private TypeEditorHostEditControlStyle _editControlStyle;
private readonly UITypeEditorEditStyle _editStyle;
private const int DROP_DOWN_DEFAULT_HEIGHT = 100;
/// <summary>
/// Fired after the dropdown closes
/// </summary>
public event EventHandler DropDownClosed;
/// <summary>
/// Creates a new TypeEditorHost to display the given UITypeEditor
/// </summary>
/// <param name="editor">The UITypeEditor instance to host</param>
/// <param name="propertyDescriptor">Property descriptor used to get/set values in the drop-down.</param>
/// <param name="instance">Instance object used to get/set values in the drop-down.</param>
protected TypeEditorHost(UITypeEditor editor, PropertyDescriptor propertyDescriptor, object instance)
:
this(UITypeEditorEditStyle.DropDown, propertyDescriptor, instance, TypeEditorHostEditControlStyle.Editable)
{
_uiTypeEditor = editor;
if (editor != null)
{
_editStyle = editor.GetEditStyle(this);
}
}
/// <summary>
/// Creates a new TypeEditorHost to display the given UITypeEditor
/// </summary>
/// <param name="editor">The UITypeEditor instance to host</param>
/// <param name="editControlStyle">The type of control to show in the edit area.</param>
/// <param name="propertyDescriptor">Property descriptor used to get/set values in the drop-down.</param>
/// <param name="instance">Instance object used to get/set values in the drop-down.</param>
protected TypeEditorHost(
UITypeEditor editor, PropertyDescriptor propertyDescriptor, object instance, TypeEditorHostEditControlStyle editControlStyle)
:
this(UITypeEditorEditStyle.DropDown, propertyDescriptor, instance, editControlStyle)
{
_uiTypeEditor = editor;
if (editor != null)
{
_editStyle = editor.GetEditStyle(this);
}
}
/// <summary>
/// Creates a new TypeEditorHost with the given editStyle.
/// </summary>
/// <param name="editStyle">Style of editor to create.</param>
/// ///
/// <param name="propertyDescriptor">Property descriptor used to get/set values in the drop-down.</param>
/// <param name="instance">Instance object used to get/set values in the drop-down.</param>
/// <param name="editControlStyle">Style of text box to create.</param>
protected TypeEditorHost(
UITypeEditorEditStyle editStyle, PropertyDescriptor propertyDescriptor, object instance,
TypeEditorHostEditControlStyle editControlStyle)
{
if (m_inPlaceHelper != null)
{
return; // only allow initialization once
}
_editStyle = editStyle;
_editControlStyle = editControlStyle;
CurrentPropertyDescriptor = propertyDescriptor;
CurrentInstance = instance;
// initialize VirtualTree in-place edit stuff
m_inPlaceHelper = VirtualTreeControl.CreateInPlaceControlHelper(this);
m_inPlaceHelper.Flags &= ~VirtualTreeInPlaceControls.SizeToText; // size to full item width by default
// set accessible role of the parent control of the text box/button to combo box,
// so accessibility clients have a clue they're dealing with a combo box-like control.
AccessibleRole = AccessibleRole.ComboBox;
TabStop = false;
}
/// <summary>
/// Factory method for creating the appropriate drop-down control based on the given property descriptor
/// </summary>
/// <param name="propertyDescriptor">A property descriptor describing the property being set</param>
/// <param name="instance">The object instance being edited</param>
/// <returns>A TypeEditorHost instance if the given property descriptor supports it, null otherwise.</returns>
public static TypeEditorHost Create(PropertyDescriptor propertyDescriptor, object instance)
{
TypeEditorHost dropDown = null;
if (propertyDescriptor != null)
{
var uiTypeEditor = propertyDescriptor.GetEditor(typeof(UITypeEditor)) as UITypeEditor;
if (uiTypeEditor != null) // UITypeEditor case
{
dropDown = new TypeEditorHost(uiTypeEditor, propertyDescriptor, instance);
}
else
{
var converter = propertyDescriptor.Converter;
if (converter != null
&& converter.GetStandardValuesSupported(null)) // converter case
{
dropDown = new TypeEditorHostListBox(converter, propertyDescriptor, instance);
}
}
}
return dropDown;
}
/// <summary>
/// Factory method for creating the appropriate drop-down control based on the given property descriptor.
/// If the property descriptor supports a UITypeEditor, a TypeEditorHost will be created with that editor.
/// If not, and the TypeConverver attached to the PropertyDescriptor supports standard values, a
/// TypeEditorHostListBox will be created with this TypeConverter.
/// </summary>
/// <param name="propertyDescriptor">A property descriptor describing the property being set</param>
/// <param name="instance">The object instance being edited</param>
/// <param name="editControlStyle">The type of control to show in the edit area.</param>
/// <returns>A TypeEditorHost instance if the given property descriptor supports it, null otherwise.</returns>
public static TypeEditorHost Create(
PropertyDescriptor propertyDescriptor, object instance, TypeEditorHostEditControlStyle editControlStyle)
{
TypeEditorHost dropDown = null;
if (propertyDescriptor != null)
{
var uiTypeEditor = propertyDescriptor.GetEditor(typeof(UITypeEditor)) as UITypeEditor;
if (uiTypeEditor != null) // UITypeEditor case
{
dropDown = new TypeEditorHost(uiTypeEditor, propertyDescriptor, instance, editControlStyle);
}
else
{
var converter = propertyDescriptor.Converter;
if (converter != null
&& converter.GetStandardValuesSupported(null)) // converter case
{
dropDown = new TypeEditorHostListBox(converter, propertyDescriptor, instance, editControlStyle);
}
}
}
return dropDown;
}
/// <summary>
/// Create the edit/drop-down controls when our handle is created.
/// </summary>
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
// create the edit box. done before creating the button because
// DockStyle.Right controls should be added first.
switch (_editControlStyle)
{
case TypeEditorHostEditControlStyle.Editable:
InitializeEdit();
break;
case TypeEditorHostEditControlStyle.ReadOnlyEdit:
InitializeEdit();
_edit.ReadOnly = true;
break;
case TypeEditorHostEditControlStyle.InstructionLabel:
InitializeInstructionLabel();
UpdateInstructionLabelText();
break;
}
// create the drop-down button
if (EditStyle != UITypeEditorEditStyle.None)
{
_button = new DropDownButton();
_button.Dock = DockStyle.Right;
_button.FlatStyle = FlatStyle.Flat;
_button.FlatAppearance.BorderSize = 0;
_button.FlatAppearance.MouseDownBackColor
= VSColorTheme.GetThemedColor(EnvironmentColors.ComboBoxButtonMouseDownBackgroundColorKey);
_button.FlatAppearance.MouseOverBackColor
= VSColorTheme.GetThemedColor(EnvironmentColors.ComboBoxButtonMouseOverBackgroundColorKey);
// only allow focus to go to the drop-down button if we don't have an edit control.
// if we have an edit control, we want this to act like a combo box, where only the edit control
// is focusable. If there's no edit control, though, we need to make sure the button can be
// focused, to prevent WinForms from forwarding focus somewhere else.
_button.TabStop = _edit == null;
if (_editStyle == UITypeEditorEditStyle.DropDown)
{
_button.Image = CreateArrowBitmap();
// set button name for accessibility purposes.
_button.AccessibleName = VirtualTreeStrings.GetString(VirtualTreeStrings.DropDownButtonAccessibleName);
}
else if (_editStyle == UITypeEditorEditStyle.Modal)
{
_button.Image = CreateDotDotDotBitmap();
// set button name for accessibility purposes.
_button.AccessibleName = VirtualTreeStrings.GetString(VirtualTreeStrings.BrowseButtonAccessibleName);
}
// Bug 17449 (Currituck). Use the system prescribed one, property grid uses this approach in
// ndp\fx\src\winforms\managed\system\winforms\propertygridinternal\propertygridview.cs
_button.Size = new Size(SystemInformation.VerticalScrollBarArrowHeight, Font.Height);
_button.BackColor = VSColorTheme.GetThemedColor(EnvironmentColors.ComboBoxBackgroundColorKey);
Controls.Add(_button);
_button.Click += OnDropDownButtonClick;
_button.LostFocus += OnContainedControlLostFocus;
}
// Create the drop down control container. Check for null here because this
// may have already been created via a call to SetComponent.
if (_dropDownHolder == null
&& EditStyle == UITypeEditorEditStyle.DropDown)
{
_dropDownHolder = new DropDownHolder(this);
_dropDownHolder.Font = Font;
}
}
private void InitializeEdit()
{
_edit = CreateTextBox();
_edit.BorderStyle = BorderStyle.None;
_edit.AutoSize = false; // with no border, AutoSize causes some overlap with the grid lines on the tree control, so we remove it.
_edit.Dock = DockStyle.Fill;
_edit.Text = base.Text; // we store text locally prior to handle creation, so we set it here.
_edit.KeyDown += OnEditKeyDown;
_edit.KeyPress += OnEditKeyPress;
_edit.LostFocus += OnContainedControlLostFocus;
_edit.TextChanged += OnEditTextChanged;
Controls.Add(_edit);
}
/// <summary>
/// Create the edit control. Derived classes may override to customize the edit control.
/// </summary>
protected virtual TypeEditorHostTextBox CreateTextBox()
{
return new TypeEditorHostTextBox(this);
}
private void InitializeInstructionLabel()
{
_instructionLabel = CreateInstructionLabel();
_instructionLabel.Dock = DockStyle.Fill;
Controls.Add(_instructionLabel);
}
/// <summary>
/// Create the instruction label control. Derived classes may override this to customize the instruction label.
/// </summary>
/// <returns>A new instruction label</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
protected virtual Label CreateInstructionLabel()
{
var label = new Label();
label.UseMnemonic = false;
return label;
}
/// <summary>
/// Determine the TypeEditorHostEditControlStyle settings for this control
/// </summary>
public TypeEditorHostEditControlStyle EditControlStyle
{
get { return _editControlStyle; }
set
{
if (value != _editControlStyle)
{
_editControlStyle = value;
// Whatever control is currently visible has to go.
if (_edit != null)
{
_edit.Dispose();
_edit = null;
}
if (_instructionLabel != null)
{
_instructionLabel.Dispose();
_instructionLabel = null;
}
switch (value)
{
case TypeEditorHostEditControlStyle.Editable:
InitializeEdit();
break;
case TypeEditorHostEditControlStyle.ReadOnlyEdit:
InitializeEdit();
_edit.ReadOnly = true;
break;
case TypeEditorHostEditControlStyle.InstructionLabel:
InitializeInstructionLabel();
break;
}
}
}
}
/// <summary>
/// UITypeEditorEditStyle used by this TypeEditorHost.
/// </summary>
public UITypeEditorEditStyle EditStyle
{
get { return _editStyle; }
}
/// <summary>
/// Get/set the current property descriptor
/// </summary>
public PropertyDescriptor CurrentPropertyDescriptor
{
get { return _propertyDescriptor; }
set
{
_propertyDescriptor = value;
UpdateInstructionLabelText();
}
}
/// <summary>
/// Get/set the current instance object
/// </summary>
public object CurrentInstance
{
get { return _instance; }
set
{
_instance = value;
UpdateInstructionLabelText();
}
}
/// <summary>
/// Specifies whether the label edit control should remain active when the drop-down closes.
/// Note that this only applies to cases where the value changes, if the value does not change
/// or the user cancels the edit, the edit control will remain active regardless of the value of
/// this property.
/// The default value is false, which means that the label edit conrol remains active.
/// </summary>
/// <value></value>
public bool DismissLabelEditOnDropDownClose { get; set; }
/// <summary>
/// The instruction label text is based on the value returned from the current
/// property descriptor. This function should be called when the CurrentPropertyDescriptor
/// and Instance properties change to update the text.
/// </summary>
protected void UpdateInstructionLabelText()
{
if (_instructionLabel != null
&& _propertyDescriptor != null
&& _instance != null)
{
_instructionLabel.Text = Text;
}
}
/// <summary>
/// Specifies window creation flags.
/// </summary>
protected override CreateParams CreateParams
{
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[SecurityPermission(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
var cp = base.CreateParams;
// remove WS_CLIPCHILDREN. Presence of this style causes update regions of our child controls
// not to be invalidated when the parent control is resized, which causes painting issues.
cp.Style &= ~NativeMethods.WS_CLIPCHILDREN;
return cp;
}
}
/// <summary>
/// Control.WndProc override
/// </summary>
/// <param name="m">Message</param>
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[SecurityPermission(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Data.Entity.Design.VisualStudio.NativeMethods.ValidateRect(System.IntPtr,Microsoft.Data.Entity.Design.VisualStudio.NativeMethods+Rectangle@)")]
protected override void WndProc(ref Message m)
{
try
{
// Do special processing if the control is simply in pass through mode
if (_edit == null)
{
switch (m.Msg)
{
case NativeMethods.WM_PAINT:
if (_instructionLabel == null
&& m.WParam == IntPtr.Zero)
{
var rect = new NativeMethods.Rectangle(ClientRectangle);
if (_button != null)
{
rect.Right = _button.Left;
}
NativeMethods.ValidateRect(m.HWnd, ref rect);
if (!NativeMethods.GetUpdateRect(m.HWnd, IntPtr.Zero, false))
{
return;
}
}
break;
default:
if (m.Msg >= NativeMethods.WM_MOUSEFIRST
&& m.Msg <= NativeMethods.WM_MOUSELAST)
{
if (m_inPlaceHelper.OnMouseMessage(ref m) || IsDisposed)
{
return;
}
}
break;
}
}
else
{
// if we have an edit control, forward clipboard commands to it.
if (m.Msg == NativeMethods.WM_CUT
|| m.Msg == NativeMethods.WM_COPY
|| m.Msg == NativeMethods.WM_PASTE)
{
// forward these to the underlying edit control
m.Result = NativeMethods.SendMessage(_edit.Handle, m.Msg, (int)m.WParam, (int)m.LParam);
return;
}
}
base.WndProc(ref m);
}
catch (Exception e)
{
if (CriticalException.IsCriticalException(e))
{
throw;
}
m_inPlaceHelper.DisplayException(e);
}
}
/// <summary>
/// Control.IsInputKey override
/// </summary>
/// <param name="keyData"></param>
/// <returns>true if the parent control will need the keys for navigation</returns>
protected override bool IsInputKey(Keys keyData)
{
if (_edit == null)
{
switch (keyData & Keys.KeyCode)
{
case Keys.Left:
case Keys.Right:
case Keys.Up:
case Keys.Down:
// Key these to the message loop, where we can forward them to the parent control
return true;
}
}
return base.IsInputKey(keyData);
}
/// <summary>
/// Control.OnKeyDown override. First tries to open dropdown, then defers
/// to the helper, and finally the control
/// </summary>
/// <param name="e">KeyEventArgs</param>
protected override void OnKeyDown(KeyEventArgs e)
{
if (!e.Handled)
{
switch (e.KeyCode)
{
case Keys.Down:
if (e.Alt
&& !e.Control)
{
OpenDropDown();
e.Handled = true;
return;
}
break;
}
}
// pass on to the outer control, for further handling
if (!m_inPlaceHelper.OnKeyDown(e))
{
base.OnKeyDown(e);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_edit != null)
{
_edit.Dispose();
}
if (_instructionLabel != null)
{
_instructionLabel.Dispose();
}
if (_button != null)
{
_button.Dispose();
}
if (_dropDown != null)
{
_dropDown.Dispose();
}
if (_dropDownHolder != null)
{
_dropDownHolder.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// Specify the control to display in the drop-down
/// </summary>
/// <param name="control">control to display</param>
public void SetComponent(Control control)
{
if (control == null)
{
throw new ArgumentNullException("control");
}
// create the drop-down holder, if necessary
if (_dropDownHolder == null)
{
_dropDownHolder = new DropDownHolder(this);
_dropDownHolder.Font = Font;
}
if (_dropDown != null)
{
_dropDown.KeyDown -= OnDropDownKeyDown;
_dropDown.Dispose();
}
_dropDown = control;
if (_dropDown != null)
{
// site the control, to allow it access to services from our container
control.Site = Site;
control.KeyDown += OnDropDownKeyDown;
_dropDownHolder.SetComponent(_dropDown, (_uiTypeEditor == null) ? Resizable : _uiTypeEditor.IsDropDownResizable);
}
}
/// <summary>
/// Override to make the dropdown resizable. This property is ignored if a UITypeEditor is
/// provided.
/// </summary>
protected virtual bool Resizable
{
get { return false; }
}
protected TextBox Edit
{
get { return _edit; }
}
/// <summary>
/// Allow clients to customize the edit control accessible name.
/// </summary>
public string EditAccessibleName
{
get { return _edit.AccessibleName; }
set { _edit.AccessibleName = value; }
}
/// <summary>
/// Allow clients to customize the edit control accessible description.
/// </summary>
public string EditAccessibleDescription
{
get { return _edit.AccessibleDescription; }
set { _edit.AccessibleDescription = value; }
}
protected override void OnLayout(LayoutEventArgs e)
{
// size button
if (_button != null)
{
_button.Height = Height;
// Part of Bug 17449 (Currituck). Button width setting removed here to match VS guidelines, use SystemInformation.VerticalScrollBarArrowHeight instead.
}
base.OnLayout(e);
/*if(edit != null)
{
// center text box vertically
edit.Top += ((Height - edit.Height) / 2);
}*/
}
/// <summary>
/// Update the drop-down container font when our font changes.
/// </summary>
/// <param name="e"></param>
protected override void OnFontChanged(EventArgs e)
{
// update the font of the drop down container
if (_dropDownHolder != null)
{
_dropDownHolder.Font = Font;
}
base.OnFontChanged(e);
}
/// <summary>
/// Returns true iff the drop down currently contains the focus
/// </summary>
public bool DropDownContainsFocus
{
get { return _dropDownHolder != null && _dropDownHolder.ContainsFocus; }
}
protected Control DropDown
{
get { return _dropDown; }
}
public override string Text
{
get
{
if (_edit != null)
{
return _edit.Text;
}
else if (!IsHandleCreated
&& (EditControlStyle == TypeEditorHostEditControlStyle.Editable
|| EditControlStyle == TypeEditorHostEditControlStyle.ReadOnlyEdit))
{
// prior to handle creation, the edit control will not be created, so we store text
// locally in this control.
return base.Text;
}
else if (_instance != null
&& _propertyDescriptor != null)
{
var converter = _propertyDescriptor.Converter;
var value = _propertyDescriptor.GetValue(_instance);
if (converter != null
&& converter.CanConvertTo(this, typeof(string)))
{
return converter.ConvertToString(this, CultureInfo.CurrentUICulture, value);
}
return value.ToString();
}
return String.Empty;
}
set
{
if (_edit != null)
{
_edit.Text = value;
OnTextChanged(EventArgs.Empty);
}
else if (!IsHandleCreated
&& (EditControlStyle == TypeEditorHostEditControlStyle.Editable
|| EditControlStyle == TypeEditorHostEditControlStyle.ReadOnlyEdit))
{
base.Text = value;
}
}
}
/// <summary>
/// Return the height of the control contained in the drop down control.
/// The default implementation returns the width of the contained drop down control.
/// </summary>
protected virtual int DropDownHeight
{
get { return (_dropDownHolder != null) ? _dropDownHolder.Component.Height : DROP_DOWN_DEFAULT_HEIGHT; }
}
/// <summary>
/// Returns the width of the control contained in the dropdown. The default implementation
/// returns the width of the drop down control, if one is provided.
/// This override is not used if IgnoreDropDownWidth returns true.
/// </summary>
protected virtual int DropDownWidth
{
get { return (_dropDownHolder != null) ? _dropDownHolder.Component.Width : Width; }
}
/// <summary>
/// Override this property and return true to always give the dropdown
/// the same initial size as the dropdown host control. If this property
/// is set, the DropDownWidth property will not be called.
/// </summary>
protected virtual bool IgnoreDropDownWidth
{
get { return false; }
}
/// <summary>
/// Fired before the drop down is opened. Clients may sink this event if they need to perform
/// some initialization before the drop-down control is shown.
/// </summary>
public event EventHandler OpeningDropDown;
/// <summary>
/// Fired after the property descriptor's SetValue method is called and before
/// the OnTextChanged method is called to (potentially) resize the control. Responding to
/// this event allows the use the change the EditControlStyle property for different values
/// </summary>
public event EventHandler PropertyDescriptorValueChanged;
/// <summary>
/// Notify derived classes that the drop-down is opening
/// </summary>
protected virtual void OnOpeningDropDown(EventArgs e)
{
// inform listeners that the drop-down is about to open
if (OpeningDropDown != null)
{
OpeningDropDown(this, EventArgs.Empty);
}
}
/// <summary>
/// Notify derived classes that CurrentPropertyDescriptor.SetValue has been called.
/// </summary>
protected virtual void OnPropertyDescriptorValueChanged(EventArgs e)
{
// inform listeners that the value is changing
if (PropertyDescriptorValueChanged != null)
{
PropertyDescriptorValueChanged(this, EventArgs.Empty);
}
}
private void DisplayDropDown()
{
Debug.Assert(_dropDownHolder != null, "OpenDropDown called with no control to drop down");
OnOpeningDropDown(EventArgs.Empty);
// Get drop down height
var dropHeight = DropDownHeight + 2 * DropDownHolder.DropDownHolderBorder;
var dropWidth = IgnoreDropDownWidth ? Width : DropDownWidth + 2 * DropDownHolder.DropDownHolderBorder;
// position drop-down under the arrow
var location = new Point(Width - dropWidth, Height);
location = PointToScreen(location);
var bounds = new Rectangle(location, new Size(dropWidth, dropHeight));
var currentScreen = Screen.FromControl(this);
if (currentScreen != null
&& bounds.Bottom > currentScreen.WorkingArea.Bottom)
{
// open the drop-down upwards if it will go off the bottom of the screen
bounds.Y -= (dropHeight + Height);
_dropDownHolder.ResizeUp = true;
}
else
{
_dropDownHolder.ResizeUp = false;
}
_dropDownHolder.Bounds = bounds;
// display drop-down
_dropDownHolder.Visible = true;
_dropDownHolder.Focus();
_dropDownHolder.HookMouseDown = true;
_dropDownHolder.DoModalLoop();
_dropDownHolder.HookMouseDown = false;
}
internal void CloseDropDown(bool accept)
{
Debug.Assert(_dropDownHolder != null, "CloseDropDown called with no drop-down");
_dropDownHolder.Visible = false;
_dropDownHolder.HookMouseDown = false;
if (accept && (0 != String.Compare(Text, _dropDown.Text, false, CultureInfo.CurrentCulture)))
{
Text = _dropDown.Text;
}
if (_edit != null)
{
_edit.Focus();
}
else
{
Focus();
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private static Bitmap CreateArrowBitmap()
{
Bitmap bitmap = null;
Icon icon = null;
try
{
icon = new Icon(typeof(TypeEditorHost), "arrow.ico");
using (var original = icon.ToBitmap())
{
bitmap = BitmapFromImageReplaceColor(original);
}
}
catch
{
bitmap = new Bitmap(16, 16);
throw;
}
finally
{
if (icon != null)
{
icon.Dispose();
}
}
return bitmap;
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private static Bitmap CreateDotDotDotBitmap()
{
Bitmap bitmap = null;
Icon icon = null;
try
{
icon = new Icon(typeof(TypeEditorHost), "dotdotdot.ico");
using (var original = icon.ToBitmap())
{
bitmap = BitmapFromImageReplaceColor(original);
}
}
catch
{
bitmap = new Bitmap(16, 16);
throw;
}
finally
{
if (icon != null)
{
icon.Dispose();
}
}
return bitmap;
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private static Bitmap BitmapFromImageReplaceColor(Image original)
{
var newBitmap = new Bitmap(original.Width, original.Height, original.PixelFormat);
using (var g = Graphics.FromImage(newBitmap))
{
using (var attrs = new ImageAttributes())
{
var cm = new ColorMap();
cm.OldColor = Color.Black;
// Bug 17449 (Currituck). Use the system prescribed one, property grid uses this approach in
// ndp\fx\src\winforms\managed\system\winforms\propertygridinternal\propertygridview.cs
cm.NewColor = VSColorTheme.GetThemedColor(EnvironmentColors.ComboBoxGlyphColorKey);
attrs.SetRemapTable(new[] { cm }, ColorAdjustType.Bitmap);
g.DrawImage(
original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height,
GraphicsUnit.Pixel, attrs, null, IntPtr.Zero);
}
}
return newBitmap;
}
private void OnDropDownButtonClick(object sender, EventArgs e)
{
OpenDropDown();
}
/// <summary>
/// Open the dropdown
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
public void OpenDropDown()
{
if (_dropDown == null
|| !_dropDown.Visible)
{
try
{
if (m_inPlaceHelper.Dirty)
{
// Handle currently dirty editor. Follow the property grid here and commit the dirty value before
// displaying the drop-down. Note that this is one case where we take a label edit and convert it
// before calling SetValue. Don't really have much choice, though, since we can't force a CommitLabelEdit
// here.
Debug.Assert(Edit != null, "how did we become dirty without an in-place edit control?");
m_inPlaceHelper.Dirty = false;
_propertyDescriptor.SetValue(_instance, ConvertFromString(Text));
if (m_inPlaceHelper.Parent == null
|| m_inPlaceHelper.Parent.LabelEditControl != this)
{
return; // bail out if we're no longer editing
}
}
// Get the value directly from the property descriptor so that the
// EditValue call deals with a raw value, not one that has gone through
// type converters, etc.
var value = _propertyDescriptor.GetValue(_instance);
if (_uiTypeEditor != null)
{
_dialogResult = DialogResult.None;
// we have a UITypeEditor, use it. UITypeEditor usually calls back on ShowDialog or OpenDropDown
// via the IWindowsFormsEditorService, so in most cases this pushes a modal loop.
var newValue = _uiTypeEditor.EditValue(this, this, value);
if (m_inPlaceHelper.Parent == null
|| m_inPlaceHelper.Parent.LabelEditControl != this)
{
// when control is dismissed, one need to call setvalue to prevent loss of user data
// See bug VSW 328713
// when control is dismissed, one must *not* call setvalue if the new value is the same as the old one
// See bug VSW 383162
if (value != newValue)
{
m_inPlaceHelper.Dirty = false;
_propertyDescriptor.SetValue(_instance, newValue);
OnPropertyDescriptorValueChanged(EventArgs.Empty);
}
}
else
{
if (value != newValue)
{
m_inPlaceHelper.OnTextChanged();
if (DismissLabelEditOnDropDownClose)
{
// dismiss the edit control if DismissLabelEditOnDropDownClose is set.
m_inPlaceHelper.Parent.EndLabelEdit(true /* cancel */);
}
else
{
// user has made an edit, update the text displayed
Text = ConvertToString(newValue);
SelectAllText();
// inform the VirtualTreeControl that the edit should not dirty the in-place edit window.
// All required data store changes should be made as part of the SetValue call, so
// we do not want to generate a CommitLabelEdit call when the in-place edit is committed.
// we make this call prior to the call to SetValue in case that call triggers the commit.
m_inPlaceHelper.Dirty = false;
}
_propertyDescriptor.SetValue(_instance, newValue);
OnPropertyDescriptorValueChanged(EventArgs.Empty);
}
else
{
if (DismissLabelEditOnDropDownClose)
{
// dismiss the edit control if DismissLabelEditOnDropDownClose is set.
// if a dialog editor was used and OK was pressed, we do this even if
// value == newValue. This enables editors that want to internally handle
// updates in EditValue rather than through a separate SetValue call.
m_inPlaceHelper.Parent.EndLabelEdit(true /* cancel */);
}
else
{
// the property browser refreshes after EditValue returns, no matter what the return value is.
// To mimic this, we'll update the value from the property descriptor if no edit is made.
// This enables editors that want to internally handle updates in EditValue rather than through
// a separate SetValue call.
var refreshValue = _propertyDescriptor.GetValue(_instance);
if (refreshValue != null)
{
Text = ConvertToString(refreshValue);
SelectAllText();
m_inPlaceHelper.Dirty = false;
}
}
}
}
}
else
{
// non-UITypeEditor case. May be a TypeEditorHostListBox that uses a TypeConverter,
// or a derived class that doesn't use a UITypeEditor.
// Open the drop down. This pushes a modal loop.
DisplayDropDown();
if (m_inPlaceHelper.Parent == null
|| m_inPlaceHelper.Parent.LabelEditControl != this
|| !Dirty)
{
return; // bail out if we're no longer editing
}
// use our text to determine the new value. This will be set
// in CloseDropDown, if the user makes an edit
var newValue = (Edit != null) ? ConvertFromString(Text) : null;
if ((value != null && !value.Equals(newValue))
|| (value == null && newValue != null))
{
m_inPlaceHelper.OnTextChanged();
if (DismissLabelEditOnDropDownClose)
{
// dismiss the edit control if DismissLabelEditOnDropDownClose is set.
m_inPlaceHelper.Parent.EndLabelEdit(true /* cancel */);
}
else
{
m_inPlaceHelper.Dirty = false; // see comment above
}
_propertyDescriptor.SetValue(_instance, newValue);
OnPropertyDescriptorValueChanged(EventArgs.Empty);
}
}
OnDropDownClosed(EventArgs.Empty);
}
catch (Exception e)
{
if (CriticalException.IsCriticalException(e))
{
throw;
}
// display exceptions thrown during drop-down open to the user
if (!m_inPlaceHelper.DisplayException(e))
{
throw;
}
}
}
else
{
CloseDropDown(false);
}
}
private object ConvertFromString(string value)
{
if (_propertyDescriptor.PropertyType == typeof(string))
{
return value;
}
var converter = _propertyDescriptor.Converter;
if (converter != null
&& converter.CanConvertFrom(this, typeof(string)))
{
try
{
return converter.ConvertFromString(this, CultureInfo.CurrentCulture, value);
}
catch (Exception e)
{
if (CriticalException.IsCriticalException(e))
{
// We throw if this is a critical exception.
throw;
}
// If the string cannot be converted by the TypeConverter, we return null.
// This change was made for VSW Bug # 448059. When a boolean value had
// not been initialized to true or false, and the user hit the drop-down
// control and dismissed it without selecting an item, we got an empty
// string that we tried to convert to a boolean. Ideally we would be passed
// a different type-converter for a boolean that can exist in uninitialized
// state, but that would have been a bigger code change towards the end of Beta2.
// We put this fix in instead so that if the client passes us a string that
// their TypeConverter cannot handle, then we return null. We hope that if
// the client passed us a string and a TypeConverter that are incompatible,
// then their PropertyDescriptor can handle setting a value to null.
return null;
}
}
return null;
}
private string ConvertToString(object value)
{
var stringValue = value as string;
if (stringValue != null)
{
return stringValue;
}
var converter = _propertyDescriptor.Converter;
if (converter != null
&& converter.CanConvertTo(this, typeof(string)))
{
return converter.ConvertToString(this, CultureInfo.CurrentCulture, value);
}
return null;
}
/// <summary>
/// The dropdown has been closed
/// </summary>
protected virtual void OnDropDownClosed(EventArgs e)
{
if (DropDownClosed != null)
{
DropDownClosed(this, e);
}
}
private void OnEditKeyDown(object sender, KeyEventArgs e)
{
OnEditKeyDown(e);
}
/// <summary>
/// </summary>
/// <param name="e"></param>
protected virtual void OnEditKeyDown(KeyEventArgs e)
{
OnKeyDown(e);
}
private void OnEditKeyPress(object sender, KeyPressEventArgs e)
{
OnEditKeyPress(e);
}
/// <summary>
/// </summary>
/// <param name="e"></param>
protected virtual void OnEditKeyPress(KeyPressEventArgs e)
{
// pass on to the outer control, for further handling
OnKeyPress(e);
}
private void OnContainedControlLostFocus(object sender, EventArgs e)
{
// pass on to the outer control, for further handling
OnLostFocus(e);
}
private void OnEditTextChanged(object sender, EventArgs e)
{
// this causes the Text property of this control to
// change as well, so treat it as such
OnTextChanged(e);
}
/// <summary>
/// Update drop-down button image when the system colors change.
/// Required for high-contrast mode support.
/// </summary>
protected override void OnSystemColorsChanged(EventArgs e)
{
// colors actually haven't been updated at this point.
// wait for the System event to let us know they have
SystemEvents.UserPreferenceChanged += OnUserPreferenceChanged;
}
private void OnUserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
{
if (e.Category == UserPreferenceCategory.Color)
{
SystemEvents.UserPreferenceChanged -= OnUserPreferenceChanged;
// recreate button image, required to support high contrast
var editStyle = UITypeEditorEditStyle.DropDown;
if (_uiTypeEditor != null)
{
editStyle = _uiTypeEditor.GetEditStyle();
}
var oldImage = _button.Image;
if (oldImage != null)
{
try
{
if (editStyle == UITypeEditorEditStyle.DropDown)
{
_button.Image = CreateArrowBitmap();
}
else if (editStyle == UITypeEditorEditStyle.Modal)
{
_button.Image = CreateDotDotDotBitmap();
}
}
finally
{
oldImage.Dispose();
}
}
}
}
private void OnDropDownKeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Escape:
CloseDropDown(false);
e.Handled = true;
break;
case Keys.Enter:
CloseDropDown(true);
e.Handled = true;
break;
}
if (!e.Handled)
{
// pass this on to the outer control, for further handling
OnKeyDown(e);
}
}
internal static bool HandleContains(IntPtr parentHandle, IntPtr childHandle)
{
if (parentHandle == IntPtr.Zero)
{
return false;
}
while (childHandle != IntPtr.Zero)
{
if (childHandle == parentHandle)
{
return true;
}
childHandle = NativeMethods.GetParent(childHandle);
}
return false;
}
#region ITypeDescriptorContext Members
/// <summary>
/// ITypeDescriptorContext.OnComponentChanged
/// </summary>
public void /*ITypeDescriptorContext*/ OnComponentChanged()
{
// don't support IComponentChangeService
}
IContainer ITypeDescriptorContext.Container
{
get { return TypeDescriptorContextContainer; }
}
/// <summary>
/// Gets the IContainer that contains the Component.
/// </summary>
/// <value></value>
protected static IContainer TypeDescriptorContextContainer
{
get
{
// we don't support containers
return null;
}
}
/// <summary>
/// ITypeDescriptorContext.OnComponentChanging implementation.
/// </summary>
/// <returns>true</returns>
public bool /*ITypeDescriptorContext*/ OnComponentChanging()
{
// Don't really support IComponentChangeService
// but must return true to allow component update.
// However, framework will not fire ComponentChanged event.
return true;
}
/// <summary>
/// ITypeDescriptorContext.Instance implementation
/// </summary>
public object /*ITypeDescriptorContext*/ Instance
{
get { return _instance; }
}
/// <summary>
/// ITypeDescriptorContext.PropertyDescriptor implementation
/// </summary>
public PropertyDescriptor /*ITypeDescriptorContext*/ PropertyDescriptor
{
get { return _propertyDescriptor; }
}
#endregion
#region IServiceProvider Members
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProviderGetService(serviceType);
}
/// <summary>
/// Gets the service provided by this TypeEditorHost.
/// </summary>
/// <param name="serviceType">type of service being requested.</param>
/// <returns></returns>
protected object ServiceProviderGetService(Type serviceType)
{
// services we support
if (serviceType == typeof(IWindowsFormsEditorService)
|| serviceType == typeof(ITypeDescriptorContext))
{
return this;
}
// delegate to our site for other services
if (Site != null)
{
return Site.GetService(serviceType);
}
return null;
}
#endregion
#region IWindowsFormsEditorService Members
void IWindowsFormsEditorService.DropDownControl(Control control)
{
DropDownControl(control);
}
/// <summary>
/// Display the given control in a dropdown. Implements IWindowsFormsEditorService.DropDownControl
/// </summary>
/// <param name="control">The control to display</param>
protected void DropDownControl(Control control)
{
if (_dropDown != control)
{
SetComponent(control);
}
DisplayDropDown();
}
void IWindowsFormsEditorService.CloseDropDown()
{
CloseDropDown();
}
/// <summary>
/// Implements IWindowsFormsEditorService.CloseDropDown
/// </summary>
protected void CloseDropDown()
{
CloseDropDown(false);
}
DialogResult IWindowsFormsEditorService.ShowDialog(Form dialog)
{
return ShowDialog(dialog);
}
/// <summary>
/// Show the type editor dialog. Implements IWindowsFormsEditorService.ShowDialog.
/// </summary>
/// <param name="dialog"></param>
/// <returns></returns>
protected DialogResult ShowDialog(Form dialog)
{
_dialogResult = DialogResult.None;
// try to shift down if sitting right on top of existing owner.
if (dialog.StartPosition == FormStartPosition.CenterScreen)
{
Control topControl = this;
if (topControl != null)
{
while (topControl.Parent != null)
{
topControl = topControl.Parent;
}
if (topControl.Size.Equals(dialog.Size))
{
dialog.StartPosition = FormStartPosition.Manual;
var location = topControl.Location;
// CONSIDER what constant to get here?
location.Offset(25, 25);
dialog.Location = location;
}
}
}
var service = (IUIService)((IServiceProvider)this).GetService(typeof(IUIService));
try
{
_inShowDialog = true;
if (service != null)
{
_dialogResult = service.ShowDialog(dialog);
}
else
{
_dialogResult = dialog.ShowDialog(this);
}
}
finally
{
_inShowDialog = false;
}
// give focus back to the text box
if (_edit != null)
{
_edit.Focus();
}
else
{
Focus();
}
return _dialogResult;
}
#endregion
#region Implementation of IInPlaceControl
/// <summary>
/// Select all text in the edit area
/// </summary>
public void SelectAllText()
{
// force handle creation here, because we need the edit control.
if (!IsHandleCreated)
{
CreateHandle();
}
// Note that m_edit.SelectAll() is not quite the same as the following code
if (Edit != null)
{
Edit.Focus();
var hwndEdit = Edit.Handle;
NativeMethods.SendMessage(hwndEdit, NativeMethods.EM_SETSEL, -1, -1); // move to the end
NativeMethods.SendMessage(hwndEdit, NativeMethods.EM_SETSEL, 0, -1); // select all text
}
}
/// <summary>
/// Return the position of the current selection start
/// </summary>
public int SelectionStart
{
get { return (Edit == null) ? 0 : Edit.SelectionStart; }
set
{
// force handle creation here, because we need the edit control.
if (!IsHandleCreated)
{
CreateHandle();
}
if (Edit != null)
{
Edit.SelectionStart = value;
}
}
}
/// <summary>
/// Return maximum length of text in the edit field
/// </summary>
public int MaxTextLength
{
get { return (Edit == null) ? 0 : Edit.MaxLength; }
set
{
// force handle creation here, because we need the edit control.
if (!IsHandleCreated)
{
CreateHandle();
}
if (Edit != null)
{
Edit.MaxLength = value;
}
}
}
/// <summary>
/// </summary>
public Rectangle FormattingRectangle
{
get
{
// UNDONE: Untrue statement
// not necessary since we're always sizing this
// based on cell size, not text size
return Rectangle.Empty;
}
}
/// <summary>
/// </summary>
int IVirtualTreeInPlaceControl.ExtraEditWidth
{
get { return ExtraEditWidth; }
}
/// <summary>
/// Implementation of IVirtualTreeInPlaceControl.ExtraEditWidth
/// </summary>
protected int ExtraEditWidth
{
get
{
var retVal = 0;
if (EditControlStyle == TypeEditorHostEditControlStyle.Editable
|| EditControlStyle == TypeEditorHostEditControlStyle.ReadOnlyEdit)
{
retVal += VirtualTreeInPlaceControlHelper.DefaultExtraEditWidth;
}
if (EditStyle != UITypeEditorEditStyle.None)
{
retVal += 16; // bitmap size for button
}
return retVal;
}
}
#endregion
#region Boilerplate InPlaceControl code
private readonly VirtualTreeInPlaceControlHelper m_inPlaceHelper;
/// <summary>
/// Parent VirtualTreeControl
/// </summary>
VirtualTreeControl IVirtualTreeInPlaceControlDefer.Parent
{
get { return VirtualTreeInPlaceControlDeferParent; }
set { VirtualTreeInPlaceControlDeferParent = value; }
}
/// <summary>
/// The tree control that activates this object.
/// </summary>
protected VirtualTreeControl VirtualTreeInPlaceControlDeferParent
{
get { return m_inPlaceHelper.Parent; }
set { m_inPlaceHelper.Parent = value; }
}
/// <summary>
/// Windows message used to launch the control. Defers to helper.
/// </summary>
int IVirtualTreeInPlaceControlDefer.LaunchedByMessage
{
get { return LaunchedByMessage; }
set { LaunchedByMessage = value; }
}
/// <summary>
/// The windows message (WM_LBUTTONDOWN) that launched the edit
/// control. Use 0 for for a timer, selection change, or explicit
/// launch. Used to support mouse behavior while a control is in-place
/// activating in response to a mouse click.
/// </summary>
protected int LaunchedByMessage
{
get { return m_inPlaceHelper.LaunchedByMessage; }
set { m_inPlaceHelper.LaunchedByMessage = value; }
}
bool IVirtualTreeInPlaceControlDefer.Dirty
{
get { return Dirty; }
set { Dirty = value; }
}
/// <summary>
/// Dirty state of the in-place control. Defers to helper.
/// </summary>
protected bool Dirty
{
get { return m_inPlaceHelper.Dirty; }
set { m_inPlaceHelper.Dirty = value; }
}
/// <summary>
/// Returns the in-place control itself (this)
/// </summary>
public Control InPlaceControl
{
get { return m_inPlaceHelper.InPlaceControl; }
}
/// <summary>
/// Settings indicating how the inplace control interacts with the tree control. Defaults
/// to SizeToText | DisposeControl.
/// </summary>
public VirtualTreeInPlaceControls Flags
{
get { return m_inPlaceHelper.Flags; }
set { m_inPlaceHelper.Flags = value; }
}
/// <summary>
/// Pass KeyPress events on to the parent control for special handling
/// </summary>
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (!e.Handled)
{
e.Handled = m_inPlaceHelper.OnKeyPress(e);
}
}
protected override void OnTextChanged(EventArgs e)
{
m_inPlaceHelper.OnTextChanged();
base.OnTextChanged(e);
}
protected override void OnLostFocus(EventArgs e)
{
if (!_inShowDialog
&& !ContainsFocus
&& !DropDownContainsFocus)
{
m_inPlaceHelper.OnLostFocus();
}
base.OnLostFocus(e);
}
#endregion // Boilerplace InPlaceControl code
/// <summary>
/// Derived class so we can customize the accessibility keyboard shortcut
/// </summary>
[SuppressMessage("Whitehorse.CustomRules", "WH03:WinFormControlCatchUnhandledExceptions",
Justification = "All but critical exceptions are caught.")]
private class DropDownButton : Button
{
protected override AccessibleObject CreateAccessibilityInstance()
{
return new DropDownButtonAccessibleObject(this);
}
/// <summary>
/// Control.WndProc override
/// </summary>
/// <param name="m">Message</param>
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[SecurityPermission(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
try
{
base.WndProc(ref m);
}
catch (Exception e)
{
if (CriticalException.IsCriticalException(e))
{
throw;
}
VirtualTreeControl.DisplayException(Parent.Site, e);
}
}
}
private class DropDownButtonAccessibleObject : ControlAccessibleObject
{
public DropDownButtonAccessibleObject(Control inner)
: base(inner)
{
}
/// <summary>
/// return Alt+Down as our keyboard shortcut
/// </summary>
public override string KeyboardShortcut
{
get { return VirtualTreeStrings.GetString(VirtualTreeStrings.DropDownAccessibleShortcut); }
}
}
}
internal interface IMouseHookClient
{
// return true if the click is handled, false
// to pass it on
bool OnClickHooked();
}
/// <summary>
/// Borrowed from property browser. Installs a mouse hook so we can close the drop down if the
/// user clicks the mouse while it's open
/// </summary>
internal class MouseHooker : IDisposable
{
private readonly Control _control;
private readonly IMouseHookClient _client;
internal int ThisProcessId = 0;
private GCHandle _mouseHookRoot;
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
private IntPtr _mouseHookHandle = IntPtr.Zero;
private const bool HookDisable = false;
private bool _processing;
public MouseHooker(Control control, IMouseHookClient client)
{
_control = control;
_client = client;
}
public virtual bool HookMouseDown
{
get { return _mouseHookHandle != IntPtr.Zero; }
set
{
if (value && !HookDisable)
{
HookMouse();
}
else
{
UnhookMouse();
}
}
}
#region IDisposable
~MouseHooker()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
UnhookMouse();
}
}
#endregion
/// <devdoc>
/// Sets up the needed windows hooks to catch messages.
/// </devdoc>
/// <internalonly />
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Data.Entity.Design.VisualStudio.NativeMethods.GetWindowThreadProcessId(System.Runtime.InteropServices.HandleRef,System.Int32@)")]
private void HookMouse()
{
lock (this)
{
if (_mouseHookHandle != IntPtr.Zero)
{
return;
}
if (ThisProcessId == 0)
{
NativeMethods.GetWindowThreadProcessId(new HandleRef(_control, _control.Handle), out ThisProcessId);
}
NativeMethods.HookProc hook = new MouseHookObject(this).Callback;
_mouseHookRoot = GCHandle.Alloc(hook);
_mouseHookHandle = NativeMethods.SetWindowsHookEx(
NativeMethods.WH_MOUSE,
hook,
NativeMethods.NullHandleRef,
NativeMethods.GetCurrentThreadId());
Debug.Assert(_mouseHookHandle != IntPtr.Zero, "Failed to install mouse hook");
}
}
/// <devdoc>
/// HookProc used for catch mouse messages.
/// </devdoc>
/// <internalonly />
private IntPtr MouseHookProc(int nCode, IntPtr wparam, IntPtr lparam)
{
if (nCode == NativeMethods.HC_ACTION)
{
var mhs = (NativeMethods.MouseHookStruct)Marshal.PtrToStructure(lparam, typeof(NativeMethods.MouseHookStruct));
if (mhs != null)
{
switch ((int)wparam)
{
case NativeMethods.WM_LBUTTONDOWN:
case NativeMethods.WM_MBUTTONDOWN:
case NativeMethods.WM_RBUTTONDOWN:
case NativeMethods.WM_NCLBUTTONDOWN:
case NativeMethods.WM_NCMBUTTONDOWN:
case NativeMethods.WM_NCRBUTTONDOWN:
case NativeMethods.WM_MOUSEACTIVATE:
if (ProcessMouseDown(mhs.handle))
{
return (IntPtr)1;
}
break;
}
}
}
return NativeMethods.CallNextHookEx(new HandleRef(this, _mouseHookHandle), nCode, wparam, lparam);
}
/// <devdoc>
/// Removes the windowshook that was installed.
/// </devdoc>
/// <internalonly />
private void UnhookMouse()
{
lock (this)
{
if (_mouseHookHandle != IntPtr.Zero)
{
NativeMethods.UnhookWindowsHookEx(new HandleRef(this, _mouseHookHandle));
_mouseHookRoot.Free();
_mouseHookHandle = IntPtr.Zero;
}
}
}
private static MouseButtons GetAsyncMouseState()
{
MouseButtons buttons = 0;
// SECURITYNOTE : only let state of MouseButtons out...
//
if (NativeMethods.GetKeyState((int)Keys.LButton) < 0)
{
buttons |= MouseButtons.Left;
}
if (NativeMethods.GetKeyState((int)Keys.RButton) < 0)
{
buttons |= MouseButtons.Right;
}
if (NativeMethods.GetKeyState((int)Keys.MButton) < 0)
{
buttons |= MouseButtons.Middle;
}
if (NativeMethods.GetKeyState((int)Keys.XButton1) < 0)
{
buttons |= MouseButtons.XButton1;
}
if (NativeMethods.GetKeyState((int)Keys.XButton2) < 0)
{
buttons |= MouseButtons.XButton2;
}
return buttons;
}
//
// Here is where we force validation on any clicks outside the control
//
private bool ProcessMouseDown(IntPtr hWnd)
{
// com+ 12678
// if we put up the "invalid" message box, it appears this
// method is getting called re-entrantly when it shouldn't be.
// this prevents us from recursing.
//
if (_processing)
{
return false;
}
var hWndAtPoint = hWnd;
var handle = _control.Handle;
var ctrlAtPoint = Control.FromHandle(hWndAtPoint);
// if it's us or one of our children, just process as normal
//
if (hWndAtPoint != handle
&& !_control.Contains(ctrlAtPoint)
&& !TypeEditorHost.HandleContains(_control.Handle, handle))
{
Debug.Assert(ThisProcessId != 0, "Didn't get our process id!");
// make sure the window is in our process
int pid;
var hr = NativeMethods.GetWindowThreadProcessId(new HandleRef(null, hWndAtPoint), out pid);
// if this isn't our process, unhook the mouse.
if (!NativeMethods.Succeeded(hr) || pid != ThisProcessId)
{
HookMouseDown = false;
return false;
}
// if this a sibling control (e.g. the drop down or buttons), just forward the message and skip the commit
var needCommit = ctrlAtPoint == null || !IsSiblingControl(_control, ctrlAtPoint);
try
{
_processing = true;
if (needCommit)
{
if (_client.OnClickHooked())
{
return true; // there was an error, so eat the mouse
}
else
{
// Returning false lets the message go to its destination. Only
// return false if there is still a mouse button down. That might not be the
// case if committing the entry opened a modal dialog.
var state = GetAsyncMouseState();
return (int)state == 0;
}
}
}
finally
{
_processing = false;
}
// cancel our hook at this point
HookMouseDown = false;
}
return false;
}
private static bool IsSiblingControl(Control c1, Control c2)
{
var parent1 = c1.Parent;
var parent2 = c2.Parent;
while (parent2 != null)
{
if (parent1 == parent2)
{
return true;
}
parent2 = parent2.Parent;
}
return false;
}
/// <devdoc>
/// Forwards messageHook calls to ToolTip.messageHookProc
/// </devdoc>
/// <internalonly />
private class MouseHookObject
{
internal readonly WeakReference reference;
public MouseHookObject(MouseHooker parent)
{
reference = new WeakReference(parent, false);
}
public virtual IntPtr Callback(int nCode, IntPtr wparam, IntPtr lparam)
{
var ret = IntPtr.Zero;
// try
// {
var control = (MouseHooker)reference.Target;
if (control != null)
{
ret = control.MouseHookProc(nCode, wparam, lparam);
}
// }
// catch (Exception)
// {
// ignore
// }
return ret;
}
}
}
/// <summary>
/// Borrowed from the property browser. Control to contain a child control which can be used
/// to do editing
/// </summary>
[SuppressMessage("Whitehorse.CustomRules", "WH03:WinFormControlCatchUnhandledExceptions",
Justification = "All but critical exceptions are caught.")]
internal class DropDownHolder : Form, IMouseHookClient
{
internal Control CurrentControl = null;
internal const int Border = 1;
private readonly TypeEditorHost _dropDownParent;
// we use this to hook mouse downs, etc. to know when to close the dropdown.
private readonly MouseHooker _mouseHooker;
// all the resizing goo...
private bool _resizable = true; // true if we're showing the resize widget.
private bool _resizing; // true if we're in the middle of a resize operation.
private bool _resizeUp; // true if the dropdown is above the grid row, which means the resize widget is at the top.
private Point _dragStart = Point.Empty; // the point at which the drag started to compute the delta
private Rectangle _dragBaseRect = Rectangle.Empty; // the original bounds of our control.
private int _currentMoveType = MoveTypeNone; // what type of move are we processing? left, bottom, or both?
// the width of the vertical resize area at the bottom
private static readonly int _resizeBorderSize = SystemInformation.HorizontalScrollBarHeight / 2;
// the minimum size for the control
private static readonly Size _minDropDownSize =
new Size(SystemInformation.VerticalScrollBarWidth * 4, SystemInformation.HorizontalScrollBarHeight * 4);
// our cached size grip glyph. Control paint only does right bottom glyphs, so we cache a mirrored one.
// See GetSizeGripGlyph
private Bitmap _sizeGripGlyph;
internal const int DropDownHolderBorder = 1;
private const int MoveTypeNone = 0x0;
private const int MoveTypeBottom = 0x1;
private const int MoveTypeLeft = 0x2;
private const int MoveTypeTop = 0x4;
internal DropDownHolder(TypeEditorHost dropDownParent)
{
ShowInTaskbar = false;
ControlBox = false;
MinimizeBox = false;
MaximizeBox = false;
Text = String.Empty;
FormBorderStyle = FormBorderStyle.None;
StartPosition = FormStartPosition.Manual; // set this to avoid being moved when our handle is created.
_mouseHooker = new MouseHooker(this, this);
Visible = false;
BackColor = VSColorTheme.GetThemedColor(EnvironmentColors.ComboBoxBackgroundColorKey);
_dropDownParent = dropDownParent;
}
protected override CreateParams CreateParams
{
get
{
var cp = base.CreateParams;
cp.ExStyle |= NativeMethods.WS_EX_TOOLWINDOW;
cp.Style |= NativeMethods.WS_POPUP | NativeMethods.WS_BORDER;
if (OSFeature.IsPresent(SystemParameter.DropShadow))
{
cp.ClassStyle |= NativeMethods.CS_DROPSHADOW;
}
if (_dropDownParent != null)
{
cp.Parent = _dropDownParent.Handle;
}
return cp;
}
}
public virtual bool HookMouseDown
{
get { return _mouseHooker.HookMouseDown; }
set { _mouseHooker.HookMouseDown = value; }
}
/// <devdoc>
/// This gets set to true if there isn't enough space below the currently selected
/// row for the drop down, so it appears above the row. In this case, we make the resize
/// grip appear at the top left.
/// </devdoc>
public bool ResizeUp
{
get { return _resizeUp; }
set
{
if (_resizeUp != value)
{
// clear the glyph so we regenerate it.
//
_sizeGripGlyph = null;
_resizeUp = value;
if (_resizable)
{
DockPadding.Bottom = 0;
DockPadding.Top = 0;
if (value)
{
DockPadding.Top = SystemInformation.HorizontalScrollBarHeight;
}
else
{
DockPadding.Bottom = SystemInformation.HorizontalScrollBarHeight;
}
}
}
}
}
protected override void DestroyHandle()
{
_mouseHooker.Dispose();
base.DestroyHandle();
}
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Data.Entity.Design.VisualStudio.NativeMethods.MsgWaitForMultipleObjects(System.Int32,System.Int32,System.Boolean,System.Int32,System.Int32)")]
public void DoModalLoop()
{
// Push a modal loop. This kind of stinks, but I think it is a
// better user model than returning from DropDownControl immediately.
//
while (Visible)
{
Application.DoEvents();
NativeMethods.MsgWaitForMultipleObjects(1, 0, true, 250, NativeMethods.QS_ALLINPUT);
}
}
public virtual Control Component
{
get { return CurrentControl; }
}
/// <devdoc>
/// Get a glyph for sizing the lower left hand grip. The code in ControlPaint only does lower-right glyphs
/// so we do some GDI+ magic to take that glyph and mirror it. That way we can still share the code (in case it changes for theming, etc),
/// not have any special cases, and possibly solve world hunger.
/// </devdoc>
private Bitmap GetSizeGripGlyph(Graphics g)
{
if (_sizeGripGlyph != null)
{
return _sizeGripGlyph;
}
var scrollBarWidth = SystemInformation.VerticalScrollBarWidth;
var scrollBarHeight = SystemInformation.HorizontalScrollBarHeight;
// create our drawing surface based on the current graphics context.
//
_sizeGripGlyph = new Bitmap(scrollBarWidth, scrollBarHeight, g);
using (var glyphGraphics = Graphics.FromImage(_sizeGripGlyph))
{
// mirror the image around the x-axis to get a gripper handle that works
// for the lower left.
using (var m = new Matrix())
{
// basically, mirroring is just scaling by -1 on the X-axis. So any point that's like (10, 10) goes to (-10, 10).
// that mirrors it, but also moves everything to the negative axis, so we just bump the whole thing over by it's width.
//
// the +1 is because things at (0,0) stay at (0,0) since [0 * -1 = 0] so we want to get them over to the other side too.
//
// resizeUp causes the image to also be mirrored vertically so the grip can be used as a top-left grip instead of bottom-left.
//
m.Translate(scrollBarWidth + 1, (_resizeUp ? scrollBarHeight + 1 : 0));
m.Scale(-1, (ResizeUp ? -1 : 1));
glyphGraphics.Transform = m;
ControlPaint.DrawSizeGrip(glyphGraphics, BackColor, 0, 0, scrollBarWidth, scrollBarHeight);
glyphGraphics.ResetTransform();
}
}
_sizeGripGlyph.MakeTransparent(BackColor);
return _sizeGripGlyph;
}
public virtual bool GetUsed()
{
return (CurrentControl != null);
}
public virtual void FocusComponent()
{
if (CurrentControl != null && Visible)
{
CurrentControl.Focus();
}
}
bool IMouseHookClient.OnClickHooked()
{
_dropDownParent.CloseDropDown(true);
return false;
}
private void OnCurrentControlResize(object o, EventArgs e)
{
if (CurrentControl != null
&& !_resizing
&& !CurrentControl.Disposing)
{
var oldWidth = Width;
var newSize = new Size(2 * DropDownHolderBorder + CurrentControl.Width, 2 * DropDownHolderBorder + CurrentControl.Height);
if (_resizable)
{
newSize.Height += SystemInformation.HorizontalScrollBarHeight;
}
try
{
_resizing = true;
SuspendLayout();
Size = newSize;
}
finally
{
_resizing = false;
ResumeLayout(false);
}
Left -= (Width - oldWidth);
}
}
protected override void OnLayout(LayoutEventArgs levent)
{
try
{
_resizing = true;
base.OnLayout(levent);
}
finally
{
_resizing = false;
}
}
/// <devdoc>
/// Just figure out what kind of sizing we would do at a given drag location.
/// </devdoc>
private int MoveTypeFromPoint(int x, int y)
{
var scrollBarWidth = SystemInformation.VerticalScrollBarWidth;
var scrollBarHeight = SystemInformation.HorizontalScrollBarHeight;
var bRect = new Rectangle(0, Height - scrollBarHeight, scrollBarWidth, scrollBarHeight);
var tRect = new Rectangle(0, 0, scrollBarWidth, scrollBarHeight);
if (!ResizeUp
&& bRect.Contains(x, y))
{
return MoveTypeLeft | MoveTypeBottom;
}
else if (ResizeUp && tRect.Contains(x, y))
{
return MoveTypeLeft | MoveTypeTop;
}
else if (!ResizeUp
&& Math.Abs(Height - y) < _resizeBorderSize)
{
return MoveTypeBottom;
}
else if (ResizeUp && Math.Abs(y) < _resizeBorderSize)
{
return MoveTypeTop;
}
return MoveTypeNone;
}
/// <devdoc>
/// Decide if we're going to be sizing at the given point, and if so, Capture and safe our current state.
/// </devdoc>
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_currentMoveType = MoveTypeFromPoint(e.X, e.Y);
if (_currentMoveType != MoveTypeNone)
{
_dragStart = PointToScreen(new Point(e.X, e.Y));
_dragBaseRect = Bounds;
Capture = true;
}
else
{
_dropDownParent.CloseDropDown(true);
}
}
base.OnMouseDown(e);
}
/// <devdoc>
/// Either set the cursor or do a move, depending on what our currentMoveType is/
/// </devdoc>
protected override void OnMouseMove(MouseEventArgs e)
{
if (! _resizable)
{
// don't do any resizing ops
}
else
// not moving so just set the cursor.
//
if (_currentMoveType == MoveTypeNone)
{
var cursorMoveType = MoveTypeFromPoint(e.X, e.Y);
switch (cursorMoveType)
{
case (MoveTypeLeft | MoveTypeBottom):
Cursor = Cursors.SizeNESW;
break;
case MoveTypeBottom:
case MoveTypeTop:
Cursor = Cursors.SizeNS;
break;
case MoveTypeTop | MoveTypeLeft:
Cursor = Cursors.SizeNWSE;
break;
default:
Cursor = null;
break;
}
}
else
{
var dragPoint = PointToScreen(new Point(e.X, e.Y));
var newBounds = Bounds;
// we're in a move operation, so do the resize.
//
if ((_currentMoveType & MoveTypeBottom) == MoveTypeBottom)
{
newBounds.Height = Math.Max(_minDropDownSize.Height, _dragBaseRect.Height + (dragPoint.Y - _dragStart.Y));
}
// for left and top moves, we actually have to resize and move the form simultaneously.
// do to that, we compute the xdelta, and apply that to the base rectangle if it's not going to
// make the form smaller than the minimum.
//
if ((_currentMoveType & MoveTypeTop) == MoveTypeTop)
{
var delta = dragPoint.Y - _dragStart.Y;
if ((_dragBaseRect.Height - delta) > _minDropDownSize.Height)
{
newBounds.Y = _dragBaseRect.Top + delta;
newBounds.Height = _dragBaseRect.Height - delta;
}
}
if ((_currentMoveType & MoveTypeLeft) == MoveTypeLeft)
{
var delta = dragPoint.X - _dragStart.X;
if ((_dragBaseRect.Width - delta) > _minDropDownSize.Width)
{
newBounds.X = _dragBaseRect.Left + delta;
newBounds.Width = _dragBaseRect.Width - delta;
}
}
if (newBounds != Bounds)
{
try
{
_resizing = true;
Bounds = newBounds;
}
finally
{
_resizing = false;
}
}
// Redraw!
//
var scrollBarHeight = SystemInformation.HorizontalScrollBarHeight;
Invalidate(new Rectangle(0, Height - scrollBarHeight, Width, scrollBarHeight));
}
base.OnMouseMove(e);
}
protected override void OnMouseLeave(EventArgs e)
{
// just clear the cursor back to the default.
//
Cursor = null;
base.OnMouseLeave(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button == MouseButtons.Left)
{
// reset the world.
//
_currentMoveType = MoveTypeNone;
_dragStart = Point.Empty;
_dragBaseRect = Rectangle.Empty;
Capture = false;
}
}
/// <devdoc>
/// Just paint and draw our glyph.
/// </devdoc>
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (_resizable)
{
var scrollBarWidth = SystemInformation.VerticalScrollBarWidth;
var scrollBarHeight = SystemInformation.HorizontalScrollBarHeight;
var lRect = new Rectangle(0, ResizeUp ? 0 : Height - scrollBarHeight, scrollBarWidth, scrollBarHeight);
pe.Graphics.DrawImage(GetSizeGripGlyph(pe.Graphics), lRect);
}
}
protected override bool ProcessDialogKey(Keys keyData)
{
try
{
if ((keyData & (Keys.Shift | Keys.Control | Keys.Alt)) == 0)
{
var accept = false;
var doClose = false;
switch (keyData & Keys.KeyCode)
{
case Keys.Escape:
doClose = true;
//accept = false; // default value
break;
case Keys.Enter:
doClose = accept = true;
break;
}
if (doClose)
{
_dropDownParent.CloseDropDown(accept);
return true;
}
}
return base.ProcessDialogKey(keyData);
}
catch (Exception e)
{
if (CriticalException.IsCriticalException(e))
{
throw;
}
VirtualTreeControl.DisplayException(_dropDownParent.Site, e);
return false;
}
}
public void SetComponent(Control ctl, bool resizable)
{
_resizable = resizable;
// clear any existing control we have
//
if (CurrentControl != null)
{
CurrentControl.Resize -= OnCurrentControlResize;
Controls.Remove(CurrentControl);
CurrentControl = null;
}
// now set up the new control, top to bottom
//
if (ctl != null)
{
var sz = new Size(2 * DropDownHolderBorder + ctl.Width, 2 * DropDownHolderBorder + ctl.Height);
// set the size stuff.
//
try
{
SuspendLayout();
// if we're resizable, add the space for the widget. Make sure
// this happens with layout off or you get the side effect of shrinking
// the contained control.
if (resizable)
{
var hscrollHeight = SystemInformation.HorizontalScrollBarHeight;
sz.Height += hscrollHeight + hscrollHeight;
// UNDONE: This is bizarre. But if we don't double the height adjustment, we lose that much each time the control is shown
// we use dockpadding to save space to draw the widget.
//
if (ResizeUp)
{
DockPadding.Top = hscrollHeight;
}
else
{
DockPadding.Bottom = hscrollHeight;
}
}
Size = sz;
ctl.Dock = DockStyle.Fill;
ctl.Visible = true;
Controls.Add(ctl);
}
finally
{
ResumeLayout(true);
}
CurrentControl = ctl;
// hook the resize event.
//
CurrentControl.Resize += OnCurrentControlResize;
}
Enabled = CurrentControl != null;
}
/// <summary>
/// Control.WndProc override
/// </summary>
protected override void WndProc(ref Message m)
{
try
{
if (m.Msg == NativeMethods.WM_ACTIVATE)
{
// SetState(STATE_MODAL, true);
var activatedControl = FromHandle(m.LParam);
if (Visible
&& NativeMethods.UnsignedLOWORD(m.WParam) == NativeMethods.WA_INACTIVE
&& (activatedControl == null || (!Contains(activatedControl) && !TypeEditorHost.HandleContains(Handle, m.LParam))))
{
// Notification occurs when the drop-down holder
// is de-activated via a click outside the drop-down area.
// call CloseDropDown(true) to commit any changes.
_dropDownParent.CloseDropDown(true);
return;
}
}
else if (m.Msg == NativeMethods.WM_CLOSE)
{
// don't let an ALT-F4 get you down
//
if (Visible)
{
_dropDownParent.CloseDropDown(false);
}
return;
}
base.WndProc(ref m);
}
catch (Exception e)
{
if (CriticalException.IsCriticalException(e))
{
throw;
}
VirtualTreeControl.DisplayException(_dropDownParent.Site, e);
}
}
}
/// <summary>
/// Edit control displayed in the TypeEditorHost. Just a TextBox with some addtional
/// key message processing for opening the drop down.
/// </summary>
[SuppressMessage("Whitehorse.CustomRules", "WH03:WinFormControlCatchUnhandledExceptions",
Justification = "All but critical exceptions are caught.")]
internal class TypeEditorHostTextBox : TextBox
{
private readonly TypeEditorHost _dropDownParent;
/// <summary>
/// Edit control displayed in the TypeEditorHost. Just a TextBox with some addtional
/// key message processing for opening the drop down.
/// </summary>
public TypeEditorHostTextBox(TypeEditorHost dropDownParent)
{
_dropDownParent = dropDownParent;
BackColor = VSColorTheme.GetThemedColor(EnvironmentColors.ComboBoxBackgroundColorKey);
ForeColor = VSColorTheme.GetThemedColor(EnvironmentColors.ComboBoxTextColorKey);
}
/// <summary>
/// Key processing.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase",
Justification =
"[rakeshna] Because the rest of our Whitehorse code is only run in a full-trusted environment in Whidbey, we do not gain any security benefit from applying the LinkDemand attribute."
)]
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch (keyData & Keys.KeyCode)
{
case Keys.Z: // ensure that the edit control handles undo if the text box is dirty.
if (((IVirtualTreeInPlaceControlDefer)_dropDownParent).Dirty
&& ((keyData & Keys.Control) != 0)
&& ((keyData & Keys.Shift) == 0)
&& ((keyData & Keys.Alt) == 0))
{
Undo();
return true;
}
break;
case Keys.A: // ensure that the edit control handles select all.
if (((keyData & Keys.Control) != 0)
&& ((keyData & Keys.Shift) == 0)
&& ((keyData & Keys.Alt) == 0))
{
SelectAll();
return true;
}
break;
case Keys.F4: // F4 opens the drop down
if ((keyData & (Keys.Shift | Keys.Control | Keys.Alt)) == 0)
{
_dropDownParent.OpenDropDown();
return true;
}
break;
case Keys.Down: // Alt-Down opens the drop down
if (((keyData & Keys.Alt) != 0)
&& ((keyData & Keys.Control) == 0))
{
_dropDownParent.OpenDropDown();
return true;
}
break;
case Keys.Delete:
NativeMethods.SendMessage(Handle, msg.Msg, msg.WParam.ToInt32(), msg.LParam.ToInt32());
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
/// <summary>
/// Key processing.
/// </summary>
protected override void OnKeyDown(KeyEventArgs e)
{
// for some reason when the Alt key is pressed,
// WM_KEYDOWN messages aren't going through the
// TranslateAccelerator/PreProcessMessage loop.
// So we handle Alt-Down here.
switch (e.KeyCode)
{
case Keys.Down: // Alt-Down opens the drop down
if (((e.KeyData & Keys.Alt) != 0)
&& ((e.KeyData & Keys.Control) == 0))
{
_dropDownParent.OpenDropDown();
e.Handled = true;
return;
}
break;
}
base.OnKeyDown(e);
}
/// <summary>
/// Control.WndProc override
/// </summary>
/// <param name="m">Message</param>
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
[SecurityPermission(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
try
{
base.WndProc(ref m);
}
catch (Exception e)
{
if (CriticalException.IsCriticalException(e))
{
throw;
}
VirtualTreeControl.DisplayException(_dropDownParent.Site, e);
}
}
}
/// <summary>
/// Specializes the TypeEditorHost to use a ListBox as the control to drop down,
/// making this essentially a ComboBox.
/// </summary>
internal class TypeEditorHostListBox : TypeEditorHost
{
private readonly ListBox _listBox;
private TypeConverter _typeConverter;
/// <summary>
/// Creates a new drop-down control to display the given TypeConverter
/// </summary>
/// <param name="typeConverter">The TypeConverter instance to retrieve drop-down values from</param>
/// <param name="propertyDescriptor">Property descriptor used to get/set values in the drop-down.</param>
/// <param name="instance">Instance object used to get/set values in the drop-down.</param>
protected internal TypeEditorHostListBox(TypeConverter typeConverter, PropertyDescriptor propertyDescriptor, object instance)
:
this(
typeConverter, propertyDescriptor, instance,
(typeConverter != null && typeConverter.GetStandardValuesExclusive())
? TypeEditorHostEditControlStyle.ReadOnlyEdit
: TypeEditorHostEditControlStyle.Editable)
{
}
/// <summary>
/// Creates a new drop-down list to display the given type converter.
/// The type converter must support a standard values collection.
/// </summary>
/// <param name="typeConverter">The TypeConverter instance to retrieve drop-down values from</param>
/// <param name="propertyDescriptor">Property descriptor used to get/set values in the drop-down.</param>
/// <param name="instance">Instance object used to get/set values in the drop-down.</param>
/// <param name="editControlStyle">Edit control style.</param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
protected internal TypeEditorHostListBox(
TypeConverter typeConverter, PropertyDescriptor propertyDescriptor, object instance,
TypeEditorHostEditControlStyle editControlStyle)
:
base(UITypeEditorEditStyle.DropDown, propertyDescriptor, instance, editControlStyle)
{
_typeConverter = typeConverter;
// UNDONE: currently, this class only supports exclusive values.
// create the list box
_listBox = new ListBox { BorderStyle = BorderStyle.None };
_listBox.MouseUp += OnDropDownMouseUp;
_listBox.BackColor = VSColorTheme.GetThemedColor(EnvironmentColors.ComboBoxBackgroundColorKey);
_listBox.ForeColor = VSColorTheme.GetThemedColor(EnvironmentColors.ComboBoxTextColorKey);
if (_typeConverter != null
&& _typeConverter.GetStandardValuesSupported(this))
{
// populate it with values from the type converter
foreach (var value in _typeConverter.GetStandardValues())
{
_listBox.Items.Add(value);
}
}
// set list box as the drop control
SetComponent(_listBox);
}
private void OnDropDownMouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
CloseDropDown(true);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_listBox != null)
{
_listBox.MouseUp -= OnDropDownMouseUp;
_listBox.Dispose();
}
}
base.Dispose(disposing);
}
protected override int DropDownHeight
{
get
{
var itemCount = _listBox.Items.Count;
return itemCount < 8 ? (itemCount * _listBox.ItemHeight) + (_listBox.ItemHeight / 2) : 8 * _listBox.ItemHeight;
}
}
/// <summary>
/// Do not call the DropDownWidth override
/// </summary>
protected override bool IgnoreDropDownWidth
{
get { return true; }
}
protected override void OnEditKeyDown(KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
if (_listBox.SelectedIndex > 0)
{
_listBox.SelectedIndex--;
Text = _listBox.Text;
if (Edit != null)
{
Edit.SelectionStart = 0;
Edit.SelectionLength = Edit.Text.Length;
}
}
e.Handled = true;
break;
case Keys.Down:
if (_listBox.SelectedIndex < _listBox.Items.Count - 1)
{
_listBox.SelectedIndex++;
Text = _listBox.Text;
if (Edit != null)
{
Edit.SelectionStart = 0;
Edit.SelectionLength = Edit.Text.Length;
}
}
e.Handled = true;
break;
}
base.OnEditKeyDown(e);
}
protected override void OnEditKeyPress(KeyPressEventArgs e)
{
base.OnEditKeyPress(e);
if (!e.Handled)
{
var caret = (Edit == null) ? 0 : Edit.SelectionStart;
string currentString = null;
if (caret == 0)
{
currentString = new string(e.KeyChar, 1);
}
else if (caret > 0)
{
currentString = Edit.Lines[0].Substring(0, caret) + e.KeyChar;
}
if (currentString != null
&& currentString.Length > 0)
{
var index = _listBox.SelectedIndex;
if (index == -1)
{
index = 0;
}
var endIndex = index;
var foundMatch = false;
while (true)
{
// TODO : refine this algorithm. Should we assume the
// list is sorted?
var itemText = _listBox.Items[index].ToString();
if (currentString.Length <= itemText.Length
&& String.Compare(itemText, 0, currentString, 0, currentString.Length, true, CultureInfo.CurrentUICulture) == 0)
{
foundMatch = true;
break;
}
index++;
if (index == _listBox.Items.Count)
{
index = 0;
}
if (index == endIndex)
{
break;
}
}
if (foundMatch)
{
_listBox.SelectedIndex = index;
Text = _listBox.Text;
if (Edit != null)
{
Edit.SelectionStart = currentString.Length;
}
e.Handled = true;
}
}
}
}
/// <summary>
/// Overriden to set up the list index based on current text
/// </summary>
protected override void OnOpeningDropDown(EventArgs e)
{
// make sure list box is hardened appropriately against exceptions.
if (!(_listBox.WindowTarget is SafeWindowTarget))
{
_listBox.WindowTarget = new SafeWindowTarget(Site, _listBox.WindowTarget);
}
// if we have a type converter, populate with values
if (_listBox.Items.Count > 0)
{
SetListBoxIndexForCurrentText();
}
base.OnOpeningDropDown(e);
}
/// <summary>
/// Overriden to set up the list index based on current text
/// </summary>
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
// ensure that list box index is set appropriately
if (_listBox.Items.Count > 0
&& (_listBox.SelectedIndex == -1
|| String.Compare(_listBox.Items[_listBox.SelectedIndex].ToString(), Text, true, CultureInfo.CurrentUICulture) != 0))
{
SetListBoxIndexForCurrentText();
}
}
private void SetListBoxIndexForCurrentText()
{
var selectedIndex = 0;
var found = false;
for (var i = 0; i < _listBox.Items.Count; i++)
{
var itemText = _listBox.Items[i].ToString();
if (String.Compare(itemText, Text, true, CultureInfo.CurrentUICulture) == 0)
{
selectedIndex = i;
found = true;
break;
}
}
if (found)
{
_listBox.SelectedIndex = selectedIndex;
}
}
public ListBox.ObjectCollection Items
{
get { return _listBox.Items; }
}
}
}
| 37.170006 | 245 | 0.49813 | [
"MIT"
] | dotnet/ef6tools | src/EFTools/DesignXmlCore/VirtualTreeGrid/DropDownControl.cs | 115,004 | C# |
namespace Inoxie.Tools.KeyWarehouse.Client.Configuration;
public class WarehouseClientConfiguration
{
public const string Key = "WarehouseConfiguration";
public string Username { get; set; }
public string Password { get; set; }
public string BaseAddress { get; set; }
}
| 26.272727 | 58 | 0.737024 | [
"MIT"
] | Strosx/Inoxie.Tools | src/Inoxie.Tools.KeyWarehouse.Client/Configuration/WarehouseClientConfiguration.cs | 291 | C# |
using AppKit;
using Foundation;
namespace LMDB
{
[Register("AppDelegate")]
public class AppDelegate : NSApplicationDelegate
{
public AppDelegate()
{
}
public override void DidFinishLaunching(NSNotification notification)
{
// Insert code here to initialize your application
}
public override void WillTerminate(NSNotification notification)
{
// Insert code here to tear down your application
}
}
}
| 21.375 | 76 | 0.617934 | [
"MIT"
] | PiPinecone/Library | AppDelegate.cs | 515 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Liuliu.Demo.Web.Migrations
{
public partial class Init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Auth_EntityInfo",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: false),
TypeName = table.Column<string>(nullable: false),
AuditEnabled = table.Column<bool>(nullable: false),
PropertyJson = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Auth_EntityInfo", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Auth_Function",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: true),
Area = table.Column<string>(nullable: true),
Controller = table.Column<string>(nullable: true),
Action = table.Column<string>(nullable: true),
IsController = table.Column<bool>(nullable: false),
IsAjax = table.Column<bool>(nullable: false),
AccessType = table.Column<int>(nullable: false),
IsAccessTypeChanged = table.Column<bool>(nullable: false),
AuditOperationEnabled = table.Column<bool>(nullable: false),
AuditEntityEnabled = table.Column<bool>(nullable: false),
CacheExpirationSeconds = table.Column<int>(nullable: false),
IsCacheSliding = table.Column<bool>(nullable: false),
IsLocked = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Auth_Function", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Auth_Module",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false),
Remark = table.Column<string>(nullable: true),
Code = table.Column<string>(nullable: false),
OrderCode = table.Column<double>(nullable: false),
TreePathString = table.Column<string>(nullable: true),
ParentId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Auth_Module", x => x.Id);
table.ForeignKey(
name: "FK_Auth_Module_Auth_Module_ParentId",
column: x => x.ParentId,
principalTable: "Auth_Module",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Identity_Organization",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false),
Remark = table.Column<string>(nullable: true),
ParentId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Identity_Organization", x => x.Id);
table.ForeignKey(
name: "FK_Identity_Organization_Identity_Organization_ParentId",
column: x => x.ParentId,
principalTable: "Identity_Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Systems_AuditOperation",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
FunctionName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: true),
UserName = table.Column<string>(nullable: true),
NickName = table.Column<string>(nullable: true),
Ip = table.Column<string>(nullable: true),
OperationSystem = table.Column<string>(nullable: true),
Browser = table.Column<string>(nullable: true),
UserAgent = table.Column<string>(nullable: true),
ResultType = table.Column<int>(nullable: false),
Message = table.Column<string>(nullable: true),
Elapsed = table.Column<int>(nullable: false),
CreatedTime = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Systems_AuditOperation", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Systems_KeyValue",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
ValueJson = table.Column<string>(nullable: true),
ValueType = table.Column<string>(nullable: true),
Key = table.Column<string>(nullable: false),
IsLocked = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Systems_KeyValue", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Auth_ModuleFunction",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
ModuleId = table.Column<int>(nullable: false),
FunctionId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Auth_ModuleFunction", x => x.Id);
table.ForeignKey(
name: "FK_Auth_ModuleFunction_Auth_Function_FunctionId",
column: x => x.FunctionId,
principalTable: "Auth_Function",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Auth_ModuleFunction_Auth_Module_ModuleId",
column: x => x.ModuleId,
principalTable: "Auth_Module",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Systems_AuditEntity",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: true),
TypeName = table.Column<string>(nullable: true),
EntityKey = table.Column<string>(nullable: true),
OperateType = table.Column<int>(nullable: false),
OperationId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Systems_AuditEntity", x => x.Id);
table.ForeignKey(
name: "FK_Systems_AuditEntity_Systems_AuditOperation_OperationId",
column: x => x.OperationId,
principalTable: "Systems_AuditOperation",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Systems_AuditProperty",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
DisplayName = table.Column<string>(nullable: true),
FieldName = table.Column<string>(nullable: true),
OriginalValue = table.Column<string>(nullable: true),
NewValue = table.Column<string>(nullable: true),
DataType = table.Column<string>(nullable: true),
AuditEntityId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Systems_AuditProperty", x => x.Id);
table.ForeignKey(
name: "FK_Systems_AuditProperty_Systems_AuditEntity_AuditEntityId",
column: x => x.AuditEntityId,
principalTable: "Systems_AuditEntity",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Auth_EntityRole",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
RoleId = table.Column<int>(nullable: false),
EntityId = table.Column<Guid>(nullable: false),
Operation = table.Column<int>(nullable: false),
FilterGroupJson = table.Column<string>(nullable: true),
IsLocked = table.Column<bool>(nullable: false),
CreatedTime = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Auth_EntityRole", x => x.Id);
table.ForeignKey(
name: "FK_Auth_EntityRole_Auth_EntityInfo_EntityId",
column: x => x.EntityId,
principalTable: "Auth_EntityInfo",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Auth_EntityUser",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
UserId = table.Column<int>(nullable: false),
EntityId = table.Column<Guid>(nullable: false),
FilterGroupJson = table.Column<string>(nullable: true),
IsLocked = table.Column<bool>(nullable: false),
CreatedTime = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Auth_EntityUser", x => x.Id);
table.ForeignKey(
name: "FK_Auth_EntityUser_Auth_EntityInfo_EntityId",
column: x => x.EntityId,
principalTable: "Auth_EntityInfo",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Auth_ModuleRole",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
ModuleId = table.Column<int>(nullable: false),
RoleId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Auth_ModuleRole", x => x.Id);
table.ForeignKey(
name: "FK_Auth_ModuleRole_Auth_Module_ModuleId",
column: x => x.ModuleId,
principalTable: "Auth_Module",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Auth_ModuleUser",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
ModuleId = table.Column<int>(nullable: false),
UserId = table.Column<int>(nullable: false),
Disabled = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Auth_ModuleUser", x => x.Id);
table.ForeignKey(
name: "FK_Auth_ModuleUser_Auth_Module_ModuleId",
column: x => x.ModuleId,
principalTable: "Auth_Module",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Identity_RoleClaim",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
RoleId = table.Column<int>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Identity_RoleClaim", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Identity_UserRole",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
UserId = table.Column<int>(nullable: false),
RoleId = table.Column<int>(nullable: false),
CreatedTime = table.Column<DateTime>(nullable: false),
IsLocked = table.Column<bool>(nullable: false),
DeletedTime = table.Column<DateTime>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Identity_UserRole", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Identity_LoginLog",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Ip = table.Column<string>(nullable: true),
UserAgent = table.Column<string>(nullable: true),
LogoutTime = table.Column<DateTime>(nullable: true),
CreatedTime = table.Column<DateTime>(nullable: false),
UserId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Identity_LoginLog", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Identity_UserClaim",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<int>(nullable: false),
ClaimType = table.Column<string>(nullable: false),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Identity_UserClaim", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Identity_UserDetail",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
RegisterIp = table.Column<string>(nullable: true),
UserId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Identity_UserDetail", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Identity_UserLogin",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
LoginProvider = table.Column<string>(nullable: true),
ProviderKey = table.Column<string>(nullable: true),
ProviderDisplayName = table.Column<string>(nullable: true),
Avatar = table.Column<string>(nullable: true),
UserId = table.Column<int>(nullable: false),
CreatedTime = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Identity_UserLogin", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Identity_UserToken",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
UserId = table.Column<int>(nullable: false),
LoginProvider = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Identity_UserToken", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Infos_Message",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Title = table.Column<string>(nullable: false),
Content = table.Column<string>(nullable: false),
MessageType = table.Column<int>(nullable: false),
NewReplyCount = table.Column<int>(nullable: false),
IsSended = table.Column<bool>(nullable: false),
CanReply = table.Column<bool>(nullable: false),
BeginDate = table.Column<DateTime>(nullable: true),
EndDate = table.Column<DateTime>(nullable: true),
IsLocked = table.Column<bool>(nullable: false),
DeletedTime = table.Column<DateTime>(nullable: true),
CreatedTime = table.Column<DateTime>(nullable: false),
SenderId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Infos_Message", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Identity_Role",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false),
NormalizedName = table.Column<string>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Remark = table.Column<string>(maxLength: 512, nullable: true),
IsAdmin = table.Column<bool>(nullable: false),
IsDefault = table.Column<bool>(nullable: false),
IsSystem = table.Column<bool>(nullable: false),
IsLocked = table.Column<bool>(nullable: false),
CreatedTime = table.Column<DateTime>(nullable: false),
DeletedTime = table.Column<DateTime>(nullable: true),
MessageId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Identity_Role", x => x.Id);
table.ForeignKey(
name: "FK_Identity_Role_Infos_Message_MessageId",
column: x => x.MessageId,
principalTable: "Infos_Message",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Identity_User",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserName = table.Column<string>(nullable: false),
NormalizedUserName = table.Column<string>(nullable: false),
NickName = table.Column<string>(nullable: true),
TrueName = table.Column<string>(nullable: true),
Gender = table.Column<int>(nullable: false),
Email = table.Column<string>(nullable: true),
NormalizeEmail = table.Column<string>(nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
Avatar = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
IsSystem = table.Column<bool>(nullable: false),
IsLocked = table.Column<bool>(nullable: false),
CreatedTime = table.Column<DateTime>(nullable: false),
DeletedTime = table.Column<DateTime>(nullable: true),
Remark = table.Column<string>(nullable: true),
MessageId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Identity_User", x => x.Id);
table.ForeignKey(
name: "FK_Identity_User_Infos_Message_MessageId",
column: x => x.MessageId,
principalTable: "Infos_Message",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Infos_MessageReceive",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
ReadDate = table.Column<DateTime>(nullable: false),
NewReplyCount = table.Column<int>(nullable: false),
CreatedTime = table.Column<DateTime>(nullable: false),
MessageId = table.Column<Guid>(nullable: false),
UserId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Infos_MessageReceive", x => x.Id);
table.ForeignKey(
name: "FK_Infos_MessageReceive_Infos_Message_MessageId",
column: x => x.MessageId,
principalTable: "Infos_Message",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Infos_MessageReceive_Identity_User_UserId",
column: x => x.UserId,
principalTable: "Identity_User",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Infos_MessageReply",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Content = table.Column<string>(nullable: false),
IsRead = table.Column<bool>(nullable: false),
ParentMessageId = table.Column<Guid>(nullable: false),
ParentReplyId = table.Column<Guid>(nullable: false),
IsLocked = table.Column<bool>(nullable: false),
DeletedTime = table.Column<DateTime>(nullable: true),
CreatedTime = table.Column<DateTime>(nullable: false),
UserId = table.Column<int>(nullable: false),
BelongMessageId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Infos_MessageReply", x => x.Id);
table.ForeignKey(
name: "FK_Infos_MessageReply_Infos_Message_BelongMessageId",
column: x => x.BelongMessageId,
principalTable: "Infos_Message",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Infos_MessageReply_Infos_Message_ParentMessageId",
column: x => x.ParentMessageId,
principalTable: "Infos_Message",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Infos_MessageReply_Infos_MessageReply_ParentReplyId",
column: x => x.ParentReplyId,
principalTable: "Infos_MessageReply",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Infos_MessageReply_Identity_User_UserId",
column: x => x.UserId,
principalTable: "Identity_User",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "ClassFullNameIndex",
table: "Auth_EntityInfo",
column: "TypeName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Auth_EntityRole_RoleId",
table: "Auth_EntityRole",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EntityRoleIndex",
table: "Auth_EntityRole",
columns: new[] { "EntityId", "RoleId", "Operation" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Auth_EntityUser_UserId",
table: "Auth_EntityUser",
column: "UserId");
migrationBuilder.CreateIndex(
name: "EntityUserIndex",
table: "Auth_EntityUser",
columns: new[] { "EntityId", "UserId" });
migrationBuilder.CreateIndex(
name: "AreaControllerActionIndex",
table: "Auth_Function",
columns: new[] { "Area", "Controller", "Action" },
unique: true,
filter: "[Area] IS NOT NULL AND [Controller] IS NOT NULL AND [Action] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Auth_Module_ParentId",
table: "Auth_Module",
column: "ParentId");
migrationBuilder.CreateIndex(
name: "IX_Auth_ModuleFunction_FunctionId",
table: "Auth_ModuleFunction",
column: "FunctionId");
migrationBuilder.CreateIndex(
name: "ModuleFunctionIndex",
table: "Auth_ModuleFunction",
columns: new[] { "ModuleId", "FunctionId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Auth_ModuleRole_RoleId",
table: "Auth_ModuleRole",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "ModuleRoleIndex",
table: "Auth_ModuleRole",
columns: new[] { "ModuleId", "RoleId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Auth_ModuleUser_UserId",
table: "Auth_ModuleUser",
column: "UserId");
migrationBuilder.CreateIndex(
name: "ModuleUserIndex",
table: "Auth_ModuleUser",
columns: new[] { "ModuleId", "UserId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Identity_LoginLog_UserId",
table: "Identity_LoginLog",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Identity_Organization_ParentId",
table: "Identity_Organization",
column: "ParentId");
migrationBuilder.CreateIndex(
name: "IX_Identity_Role_MessageId",
table: "Identity_Role",
column: "MessageId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "Identity_Role",
columns: new[] { "NormalizedName", "DeletedTime" },
unique: true,
filter: "[DeletedTime] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Identity_RoleClaim_RoleId",
table: "Identity_RoleClaim",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_Identity_User_MessageId",
table: "Identity_User",
column: "MessageId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "Identity_User",
columns: new[] { "NormalizeEmail", "DeletedTime" });
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "Identity_User",
columns: new[] { "NormalizedUserName", "DeletedTime" },
unique: true,
filter: "[DeletedTime] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Identity_UserClaim_UserId",
table: "Identity_UserClaim",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Identity_UserDetail_UserId",
table: "Identity_UserDetail",
column: "UserId",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Identity_UserLogin_UserId",
table: "Identity_UserLogin",
column: "UserId");
migrationBuilder.CreateIndex(
name: "UserLoginIndex",
table: "Identity_UserLogin",
columns: new[] { "LoginProvider", "ProviderKey" },
unique: true,
filter: "[LoginProvider] IS NOT NULL AND [ProviderKey] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Identity_UserRole_RoleId",
table: "Identity_UserRole",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "UserRoleIndex",
table: "Identity_UserRole",
columns: new[] { "UserId", "RoleId", "DeletedTime" },
unique: true,
filter: "[DeletedTime] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "UserTokenIndex",
table: "Identity_UserToken",
columns: new[] { "UserId", "LoginProvider", "Name" },
unique: true,
filter: "[LoginProvider] IS NOT NULL AND [Name] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_Infos_Message_SenderId",
table: "Infos_Message",
column: "SenderId");
migrationBuilder.CreateIndex(
name: "IX_Infos_MessageReceive_MessageId",
table: "Infos_MessageReceive",
column: "MessageId");
migrationBuilder.CreateIndex(
name: "IX_Infos_MessageReceive_UserId",
table: "Infos_MessageReceive",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Infos_MessageReply_BelongMessageId",
table: "Infos_MessageReply",
column: "BelongMessageId");
migrationBuilder.CreateIndex(
name: "IX_Infos_MessageReply_ParentMessageId",
table: "Infos_MessageReply",
column: "ParentMessageId");
migrationBuilder.CreateIndex(
name: "IX_Infos_MessageReply_ParentReplyId",
table: "Infos_MessageReply",
column: "ParentReplyId");
migrationBuilder.CreateIndex(
name: "IX_Infos_MessageReply_UserId",
table: "Infos_MessageReply",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Systems_AuditEntity_OperationId",
table: "Systems_AuditEntity",
column: "OperationId");
migrationBuilder.CreateIndex(
name: "IX_Systems_AuditProperty_AuditEntityId",
table: "Systems_AuditProperty",
column: "AuditEntityId");
migrationBuilder.AddForeignKey(
name: "FK_Auth_EntityRole_Identity_Role_RoleId",
table: "Auth_EntityRole",
column: "RoleId",
principalTable: "Identity_Role",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Auth_EntityUser_Identity_User_UserId",
table: "Auth_EntityUser",
column: "UserId",
principalTable: "Identity_User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Auth_ModuleRole_Identity_Role_RoleId",
table: "Auth_ModuleRole",
column: "RoleId",
principalTable: "Identity_Role",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Auth_ModuleUser_Identity_User_UserId",
table: "Auth_ModuleUser",
column: "UserId",
principalTable: "Identity_User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Identity_RoleClaim_Identity_Role_RoleId",
table: "Identity_RoleClaim",
column: "RoleId",
principalTable: "Identity_Role",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Identity_UserRole_Identity_Role_RoleId",
table: "Identity_UserRole",
column: "RoleId",
principalTable: "Identity_Role",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Identity_UserRole_Identity_User_UserId",
table: "Identity_UserRole",
column: "UserId",
principalTable: "Identity_User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Identity_LoginLog_Identity_User_UserId",
table: "Identity_LoginLog",
column: "UserId",
principalTable: "Identity_User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Identity_UserClaim_Identity_User_UserId",
table: "Identity_UserClaim",
column: "UserId",
principalTable: "Identity_User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Identity_UserDetail_Identity_User_UserId",
table: "Identity_UserDetail",
column: "UserId",
principalTable: "Identity_User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Identity_UserLogin_Identity_User_UserId",
table: "Identity_UserLogin",
column: "UserId",
principalTable: "Identity_User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Identity_UserToken_Identity_User_UserId",
table: "Identity_UserToken",
column: "UserId",
principalTable: "Identity_User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Infos_Message_Identity_User_SenderId",
table: "Infos_Message",
column: "SenderId",
principalTable: "Identity_User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Infos_Message_Identity_User_SenderId",
table: "Infos_Message");
migrationBuilder.DropTable(
name: "Auth_EntityRole");
migrationBuilder.DropTable(
name: "Auth_EntityUser");
migrationBuilder.DropTable(
name: "Auth_ModuleFunction");
migrationBuilder.DropTable(
name: "Auth_ModuleRole");
migrationBuilder.DropTable(
name: "Auth_ModuleUser");
migrationBuilder.DropTable(
name: "Identity_LoginLog");
migrationBuilder.DropTable(
name: "Identity_Organization");
migrationBuilder.DropTable(
name: "Identity_RoleClaim");
migrationBuilder.DropTable(
name: "Identity_UserClaim");
migrationBuilder.DropTable(
name: "Identity_UserDetail");
migrationBuilder.DropTable(
name: "Identity_UserLogin");
migrationBuilder.DropTable(
name: "Identity_UserRole");
migrationBuilder.DropTable(
name: "Identity_UserToken");
migrationBuilder.DropTable(
name: "Infos_MessageReceive");
migrationBuilder.DropTable(
name: "Infos_MessageReply");
migrationBuilder.DropTable(
name: "Systems_AuditProperty");
migrationBuilder.DropTable(
name: "Systems_KeyValue");
migrationBuilder.DropTable(
name: "Auth_EntityInfo");
migrationBuilder.DropTable(
name: "Auth_Function");
migrationBuilder.DropTable(
name: "Auth_Module");
migrationBuilder.DropTable(
name: "Identity_Role");
migrationBuilder.DropTable(
name: "Systems_AuditEntity");
migrationBuilder.DropTable(
name: "Systems_AuditOperation");
migrationBuilder.DropTable(
name: "Identity_User");
migrationBuilder.DropTable(
name: "Infos_Message");
}
}
}
| 43.658254 | 100 | 0.497917 | [
"Apache-2.0"
] | ArcherTrister/ESoftor | samples/web/Identity/Liuliu.Demo.Web/Migrations/20200404064604_Init.cs | 41,521 | C# |
namespace PropertyAds.WebApp.Services.PropertyAggregateServices
{
using PropertyAds.WebApp.Services.DistrictServices;
using PropertyAds.WebApp.Services.PropertyServices;
public class PropertyAggregateServiceModel
{
public DistrictServiceModel District { get; set; }
public PropertyTypeServiceModel PropertyType { get; set; }
public int AveragePrice { get; set; }
public int AveragePricePerSqM { get; set; }
}
}
| 27.529412 | 66 | 0.724359 | [
"MIT"
] | IvanS1991/SoftUni-AspNet-Core-Project | PropertyAds/PropertyAds.WebApp/Services/PropertyAggregateServices/PropertyAggregateServiceModel.cs | 470 | C# |
using Mass_BTC_Balance_Checker.Static_Class.SSH;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mass_BTC_Balance_Checker.HomeModules
{
public class InfoRequired
{
public List<SshDetail> listSsh { get; set; }
public List<BtcKeys> keys { get; set; }
public int Thread { get; set; }
public int Port { get; set; }
public int Timeout { get; set; }
public string SshFileSelected { get; set; }
}
}
| 26.6 | 52 | 0.676692 | [
"MIT"
] | tranphucuk/BTC-Balance-Check | Mass BTC Balance Checker/HomeModules/InfoRequired.cs | 534 | C# |
using NHibernate;
namespace TrueOrFalse.Updates
{
public class UpdateToVs081
{
public static void Run()
{
Sl.Resolve<ISession>()
.CreateSQLQuery(
@"ALTER TABLE `membership`
ADD COLUMN `BillingName` VARCHAR(255) NULL DEFAULT NULL AFTER `Id`;"
).ExecuteUpdate();
}
}
} | 24.4375 | 86 | 0.514066 | [
"MIT"
] | memucho/webapp | src/TrueOrFalse/Tools/Update/Steps.Archive/UpdateToVs081.cs | 393 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// <auto-generated />
using System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
namespace Identity.DefaultUI.WebSite.Data.Migrations
{
[DbContext(typeof(IdentityDbContext))]
partial class IdentityDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.0-preview2-30103")
.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();
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();
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");
b.Property<string>("ProviderKey");
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");
b.Property<string>("Name");
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
}
}
}
| 34.191304 | 117 | 0.483215 | [
"MIT"
] | 3ejki/aspnetcore | src/Identity/testassets/Identity.DefaultUI.WebSite/Data/Migrations/IdentityDbContextModelSnapshot.cs | 7,866 | C# |
// https://docs.microsoft.com/en-us/visualstudio/modeling/t4-include-directive?view=vs-2017
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.Bot.Solutions.Responses;
namespace Microsoft.Bot.Solutions.Tests.Skills.Fakes.FakeSkill.Dialogs.Main.Resources
{
/// <summary>
/// Contains bot responses.
/// </summary>
public class MainResponses : IResponseIdCollection
{
// Generated accessors
public const string WelcomeMessage = "WelcomeMessage";
public const string HelpMessage = "HelpMessage";
public const string GreetingMessage = "GreetingMessage";
public const string GoodbyeMessage = "GoodbyeMessage";
public const string LogOut = "LogOut";
public const string FeatureNotAvailable = "FeatureNotAvailable";
public const string CancelMessage = "CancelMessage";
}
} | 36.5 | 92 | 0.748858 | [
"MIT"
] | ElizabethGreene/AI | solutions/Virtual-Assistant/src/csharp/tests/Microsoft.Bot.Solutions.Tests/Skills/Fakes/FakeSkill/Dialogs/Main/Resources/MainResponses.cs | 878 | C# |
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Factory.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Engineers",
columns: table => new
{
EngineerId = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Engineers", x => x.EngineerId);
});
migrationBuilder.CreateTable(
name: "Machines",
columns: table => new
{
MachineId = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Type = table.Column<string>(type: "longtext CHARACTER SET utf8mb4", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Machines", x => x.MachineId);
});
migrationBuilder.CreateTable(
name: "MachineEngineer",
columns: table => new
{
MachineEngineerId = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
EngineerId = table.Column<int>(type: "int", nullable: false),
MachineId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_MachineEngineer", x => x.MachineEngineerId);
table.ForeignKey(
name: "FK_MachineEngineer_Engineers_EngineerId",
column: x => x.EngineerId,
principalTable: "Engineers",
principalColumn: "EngineerId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_MachineEngineer_Machines_MachineId",
column: x => x.MachineId,
principalTable: "Machines",
principalColumn: "MachineId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_MachineEngineer_EngineerId",
table: "MachineEngineer",
column: "EngineerId");
migrationBuilder.CreateIndex(
name: "IX_MachineEngineer_MachineId",
table: "MachineEngineer",
column: "MachineId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "MachineEngineer");
migrationBuilder.DropTable(
name: "Engineers");
migrationBuilder.DropTable(
name: "Machines");
}
}
}
| 40.744186 | 114 | 0.516838 | [
"ISC"
] | hmcvay/Factory.Solution | Factory/Migrations/20220318165732_Initial.cs | 3,506 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace MediatRSample.Controllers
{
[Route("[controller]")]
[ApiController]
public class MediatRController : ControllerBase
{
IMediator _mediator;
public MediatRController(IMediator mediator)
{
_mediator = mediator;
}
[Route("cal")]
[HttpGet]
public async Task<double> Calculator([FromQuery]Calculator calculator)
{
return await _mediator.Send(calculator);
}
[Route("ping")]
[HttpGet]
public async Task<string> Ping()
{
await _mediator.Publish(new Ping());
return "success";
}
}
} | 23.432432 | 78 | 0.618224 | [
"MIT"
] | zhaobingwang/sample | Demo/MediatRSample/MediatRSample/Controllers/MediatRController.cs | 869 | 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.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Metadata.Conventions
{
/// <summary>
/// <para>
/// A convention that configures the foreign key properties associated with a navigation property
/// based on the <see cref="ForeignKeyAttribute" /> specified on the properties or the navigation properties.
/// </para>
/// <para>
/// For one-to-one relationships the attribute has to be specified on the navigation property pointing to the principal.
/// </para>
/// </summary>
public class ForeignKeyAttributeConvention : IForeignKeyAddedConvention, INavigationAddedConvention, IModelFinalizingConvention
{
/// <summary>
/// Creates a new instance of <see cref="ForeignKeyAttributeConvention" />.
/// </summary>
/// <param name="dependencies"> Parameter object containing dependencies for this convention. </param>
public ForeignKeyAttributeConvention([NotNull] ProviderConventionSetBuilderDependencies dependencies)
{
Dependencies = dependencies;
}
/// <summary>
/// Parameter object containing service dependencies.
/// </summary>
protected virtual ProviderConventionSetBuilderDependencies Dependencies { get; }
/// <summary>
/// Called after a foreign key is added to the entity type.
/// </summary>
/// <param name="relationshipBuilder"> The builder for the foreign key. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
public virtual void ProcessForeignKeyAdded(
IConventionForeignKeyBuilder relationshipBuilder, IConventionContext<IConventionForeignKeyBuilder> context)
{
Check.NotNull(relationshipBuilder, nameof(relationshipBuilder));
var newRelationshipBuilder = UpdateRelationshipBuilder(relationshipBuilder, context);
if (newRelationshipBuilder != null)
{
context.StopProcessingIfChanged(newRelationshipBuilder);
}
}
/// <summary>
/// Called after a navigation is added to the entity type.
/// </summary>
/// <param name="navigationBuilder"> The builder for the navigation. </param>
/// <param name="context"> Additional information associated with convention execution. </param>
public virtual void ProcessNavigationAdded(
IConventionNavigationBuilder navigationBuilder, IConventionContext<IConventionNavigationBuilder> context)
{
Check.NotNull(navigationBuilder, nameof(navigationBuilder));
var onDependent = navigationBuilder.Metadata.IsOnDependent;
var newRelationshipBuilder =
UpdateRelationshipBuilder(navigationBuilder.Metadata.ForeignKey.Builder, context);
if (newRelationshipBuilder != null)
{
var newNavigationBuilder = onDependent
? newRelationshipBuilder.Metadata.DependentToPrincipal.Builder
: newRelationshipBuilder.Metadata.PrincipalToDependent.Builder;
context.StopProcessingIfChanged(newNavigationBuilder);
}
}
private IConventionForeignKeyBuilder UpdateRelationshipBuilder(
IConventionForeignKeyBuilder relationshipBuilder, IConventionContext context)
{
var foreignKey = relationshipBuilder.Metadata;
var fkPropertyOnPrincipal
= FindForeignKeyAttributeOnProperty(foreignKey.PrincipalEntityType, foreignKey.PrincipalToDependent?.Name);
var fkPropertyOnDependent
= FindForeignKeyAttributeOnProperty(foreignKey.DeclaringEntityType, foreignKey.DependentToPrincipal?.Name);
if (fkPropertyOnDependent != null
&& fkPropertyOnPrincipal != null)
{
Dependencies.Logger.ForeignKeyAttributesOnBothPropertiesWarning(
foreignKey.PrincipalToDependent,
foreignKey.DependentToPrincipal,
fkPropertyOnPrincipal,
fkPropertyOnDependent);
relationshipBuilder = SplitNavigationsToSeparateRelationships(relationshipBuilder);
if (relationshipBuilder == null)
{
context.StopProcessing();
return null;
}
fkPropertyOnPrincipal = null;
}
var fkPropertiesOnPrincipalToDependent
= FindCandidateDependentPropertiesThroughNavigation(relationshipBuilder, pointsToPrincipal: false);
var fkPropertiesOnDependentToPrincipal
= FindCandidateDependentPropertiesThroughNavigation(relationshipBuilder, pointsToPrincipal: true);
if (fkPropertiesOnDependentToPrincipal != null
&& fkPropertiesOnPrincipalToDependent != null)
{
Dependencies.Logger.ForeignKeyAttributesOnBothNavigationsWarning(
relationshipBuilder.Metadata.DependentToPrincipal, relationshipBuilder.Metadata.PrincipalToDependent);
relationshipBuilder = SplitNavigationsToSeparateRelationships(relationshipBuilder);
if (relationshipBuilder == null)
{
context.StopProcessing();
return null;
}
fkPropertiesOnPrincipalToDependent = null;
}
var fkPropertiesOnNavigation = fkPropertiesOnDependentToPrincipal ?? fkPropertiesOnPrincipalToDependent;
var upgradePrincipalToDependentNavigationSource = fkPropertiesOnPrincipalToDependent != null;
var upgradeDependentToPrincipalNavigationSource = fkPropertiesOnDependentToPrincipal != null;
var shouldInvert = false;
IReadOnlyList<string> fkPropertiesToSet;
if (fkPropertiesOnNavigation == null
|| fkPropertiesOnNavigation.Count == 0)
{
if (fkPropertyOnDependent == null
&& fkPropertyOnPrincipal == null)
{
return null;
}
if (fkPropertyOnDependent != null)
{
fkPropertiesToSet = new List<string> { fkPropertyOnDependent.GetSimpleMemberName() };
upgradeDependentToPrincipalNavigationSource = true;
}
else
{
if (foreignKey.PrincipalToDependent.IsCollection)
{
context.StopProcessing();
return null;
}
shouldInvert = true;
fkPropertiesToSet = new List<string> { fkPropertyOnPrincipal.GetSimpleMemberName() };
upgradePrincipalToDependentNavigationSource = true;
}
}
else
{
fkPropertiesToSet = fkPropertiesOnNavigation;
if (fkPropertyOnDependent == null
&& fkPropertyOnPrincipal == null)
{
if (fkPropertiesOnPrincipalToDependent != null
&& foreignKey.IsUnique)
{
shouldInvert = true;
}
}
else
{
var fkProperty = fkPropertyOnDependent ?? fkPropertyOnPrincipal;
if (fkPropertiesOnNavigation.Count != 1
|| !Equals(fkPropertiesOnNavigation.First(), fkProperty.GetSimpleMemberName()))
{
Dependencies.Logger.ConflictingForeignKeyAttributesOnNavigationAndPropertyWarning(
fkPropertiesOnDependentToPrincipal != null
? relationshipBuilder.Metadata.DependentToPrincipal
: relationshipBuilder.Metadata.PrincipalToDependent,
fkProperty);
relationshipBuilder = SplitNavigationsToSeparateRelationships(relationshipBuilder);
if (relationshipBuilder == null)
{
context.StopProcessing();
return null;
}
upgradePrincipalToDependentNavigationSource = false;
fkPropertiesToSet = fkPropertiesOnDependentToPrincipal
?? new List<string> { fkPropertyOnDependent.GetSimpleMemberName() };
}
if (fkPropertyOnDependent != null)
{
upgradeDependentToPrincipalNavigationSource = true;
}
else
{
shouldInvert = true;
}
}
}
var newRelationshipBuilder = relationshipBuilder;
if (upgradeDependentToPrincipalNavigationSource)
{
newRelationshipBuilder = newRelationshipBuilder.HasNavigation(
newRelationshipBuilder.Metadata.DependentToPrincipal.Name, pointsToPrincipal: true, fromDataAnnotation: true);
}
if (upgradePrincipalToDependentNavigationSource)
{
newRelationshipBuilder = newRelationshipBuilder.HasNavigation(
newRelationshipBuilder.Metadata.PrincipalToDependent.Name, pointsToPrincipal: false, fromDataAnnotation: true);
}
if (shouldInvert)
{
newRelationshipBuilder = newRelationshipBuilder.HasEntityTypes(
foreignKey.DeclaringEntityType, foreignKey.PrincipalEntityType, fromDataAnnotation: true);
}
else
{
var existingProperties = foreignKey.DeclaringEntityType.FindProperties(fkPropertiesToSet);
if (existingProperties != null)
{
var conflictingFk = foreignKey.DeclaringEntityType.FindForeignKeys(existingProperties)
.FirstOrDefault(
fk => fk != foreignKey
&& fk.PrincipalEntityType == foreignKey.PrincipalEntityType
&& fk.GetConfigurationSource() == ConfigurationSource.DataAnnotation
&& fk.GetPropertiesConfigurationSource() == ConfigurationSource.DataAnnotation);
if (conflictingFk != null)
{
throw new InvalidOperationException(
CoreStrings.ConflictingForeignKeyAttributes(
existingProperties.Format(),
foreignKey.DeclaringEntityType.DisplayName()));
}
}
}
newRelationshipBuilder = newRelationshipBuilder?.HasForeignKey(fkPropertiesToSet, fromDataAnnotation: true);
return newRelationshipBuilder;
}
private static IConventionForeignKeyBuilder SplitNavigationsToSeparateRelationships(
IConventionForeignKeyBuilder relationshipBuilder)
{
var foreignKey = relationshipBuilder.Metadata;
var dependentToPrincipalNavigationName = foreignKey.DependentToPrincipal.Name;
var principalToDependentNavigationName = foreignKey.PrincipalToDependent.Name;
if (GetInversePropertyAttribute(foreignKey.PrincipalToDependent) != null
|| GetInversePropertyAttribute(foreignKey.DependentToPrincipal) != null)
{
// Relationship is joined by InversePropertyAttribute
throw new InvalidOperationException(
CoreStrings.InvalidRelationshipUsingDataAnnotations(
dependentToPrincipalNavigationName,
foreignKey.DeclaringEntityType.DisplayName(),
principalToDependentNavigationName,
foreignKey.PrincipalEntityType.DisplayName()));
}
relationshipBuilder = relationshipBuilder.HasNavigation(
(string)null,
pointsToPrincipal: false,
fromDataAnnotation: true);
return relationshipBuilder == null
? null
: foreignKey.PrincipalEntityType.Builder.HasRelationship(
foreignKey.DeclaringEntityType,
principalToDependentNavigationName,
null,
fromDataAnnotation: true)
== null
? null
: relationshipBuilder;
}
private static ForeignKeyAttribute GetForeignKeyAttribute(IConventionTypeBase entityType, string propertyName)
=> entityType.GetRuntimeProperties()?.Values
.FirstOrDefault(
p => string.Equals(p.GetSimpleMemberName(), propertyName, StringComparison.OrdinalIgnoreCase)
&& Attribute.IsDefined(p, typeof(ForeignKeyAttribute), inherit: true))
?.GetCustomAttribute<ForeignKeyAttribute>(inherit: true);
private static ForeignKeyAttribute GetForeignKeyAttribute(IConventionNavigation navigation)
=> GetAttribute<ForeignKeyAttribute>(navigation.GetIdentifyingMemberInfo());
private static InversePropertyAttribute GetInversePropertyAttribute(IConventionNavigation navigation)
=> GetAttribute<InversePropertyAttribute>(navigation.GetIdentifyingMemberInfo());
private static TAttribute GetAttribute<TAttribute>(MemberInfo memberInfo)
where TAttribute : Attribute
{
if (memberInfo == null
|| !Attribute.IsDefined(memberInfo, typeof(TAttribute), inherit: true))
{
return null;
}
return memberInfo.GetCustomAttribute<TAttribute>(inherit: true);
}
[ContractAnnotation("navigationName:null => null")]
private MemberInfo FindForeignKeyAttributeOnProperty(IConventionEntityType entityType, string navigationName)
{
if (string.IsNullOrWhiteSpace(navigationName)
|| !entityType.HasClrType())
{
return null;
}
MemberInfo candidateProperty = null;
foreach (var memberInfo in entityType.GetRuntimeProperties().Values.Cast<MemberInfo>()
.Concat(entityType.GetRuntimeFields().Values))
{
if (entityType.Builder.IsIgnored(memberInfo.GetSimpleMemberName())
|| !Attribute.IsDefined(memberInfo, typeof(ForeignKeyAttribute), inherit: true))
{
continue;
}
var attribute = memberInfo.GetCustomAttribute<ForeignKeyAttribute>(inherit: true);
if (attribute.Name != navigationName
|| (memberInfo is PropertyInfo propertyInfo
&& FindCandidateNavigationPropertyType(propertyInfo) != null))
{
continue;
}
if (candidateProperty != null)
{
throw new InvalidOperationException(
CoreStrings.CompositeFkOnProperty(navigationName, entityType.DisplayName()));
}
candidateProperty = memberInfo;
}
if (candidateProperty != null)
{
var fkAttributeOnNavigation = GetForeignKeyAttribute(entityType, navigationName);
if (fkAttributeOnNavigation != null
&& fkAttributeOnNavigation.Name != candidateProperty.GetSimpleMemberName())
{
throw new InvalidOperationException(
CoreStrings.FkAttributeOnPropertyNavigationMismatch(
candidateProperty.Name, navigationName, entityType.DisplayName()));
}
}
return candidateProperty;
}
private Type FindCandidateNavigationPropertyType([NotNull] PropertyInfo propertyInfo)
=> Dependencies.MemberClassifier.FindCandidateNavigationPropertyType(propertyInfo);
private static IReadOnlyList<string> FindCandidateDependentPropertiesThroughNavigation(
IConventionForeignKeyBuilder relationshipBuilder,
bool pointsToPrincipal)
{
var navigation = pointsToPrincipal
? relationshipBuilder.Metadata.DependentToPrincipal
: relationshipBuilder.Metadata.PrincipalToDependent;
var navigationFkAttribute = navigation != null
? GetForeignKeyAttribute(navigation)
: null;
if (navigationFkAttribute != null)
{
var properties = navigationFkAttribute.Name.Split(',').Select(p => p.Trim()).ToList();
if (properties.Any(string.IsNullOrWhiteSpace))
{
throw new InvalidOperationException(
CoreStrings.InvalidPropertyListOnNavigation(navigation.Name, navigation.DeclaringEntityType.DisplayName()));
}
var navigationPropertyTargetType =
navigation.DeclaringEntityType.GetRuntimeProperties()[navigation.Name].PropertyType;
var otherNavigations = navigation.DeclaringEntityType.GetRuntimeProperties().Values
.Where(p => p.PropertyType == navigationPropertyTargetType && p.GetSimpleMemberName() != navigation.Name)
.OrderBy(p => p.GetSimpleMemberName());
foreach (var propertyInfo in otherNavigations)
{
var attribute = GetAttribute<ForeignKeyAttribute>(propertyInfo);
if (attribute?.Name == navigationFkAttribute.Name)
{
throw new InvalidOperationException(
CoreStrings.MultipleNavigationsSameFk(navigation.DeclaringEntityType.DisplayName(), attribute.Name));
}
}
return properties;
}
return null;
}
/// <inheritdoc />
public virtual void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext<IConventionModelBuilder> context)
{
foreach (var entityType in modelBuilder.Metadata.GetEntityTypes())
{
foreach (var declaredNavigation in entityType.GetDeclaredNavigations())
{
if (declaredNavigation.IsCollection)
{
var foreignKey = declaredNavigation.ForeignKey;
var fkPropertyOnPrincipal
= FindForeignKeyAttributeOnProperty(foreignKey.PrincipalEntityType, declaredNavigation.Name);
if (fkPropertyOnPrincipal != null)
{
throw new InvalidOperationException(
CoreStrings.FkAttributeOnNonUniquePrincipal(
declaredNavigation.Name,
foreignKey.PrincipalEntityType.DisplayName(),
foreignKey.DeclaringEntityType.DisplayName()));
}
}
}
}
}
}
}
| 45.660714 | 141 | 0.593664 | [
"Apache-2.0"
] | 1iveowl/efcore | src/EFCore/Metadata/Conventions/ForeignKeyAttributeConvention.cs | 20,456 | C# |
using System;
using System.Collections.Generic;
using RogueEssence.Dungeon;
using RogueEssence.Content;
using RogueElements;
using RogueEssence;
using RogueEssence.Data;
using PMDC.Dungeon;
using PMDC;
using PMDC.Data;
using System.IO;
using PMDC.Dev;
namespace DataGenerator.Data
{
public static class DataInfo
{
public const int N_E = PreTypeEvent.N_E;
public const int NVE = PreTypeEvent.NVE;
public const int NRM = PreTypeEvent.NRM;
public const int S_E = PreTypeEvent.S_E;
public static void AddUniversalEvent()
{
File.Delete(PathMod.ModPath(DataManager.DATA_PATH + "Universal.bin"));
ActiveEffect universalEvent = new ActiveEffect();
universalEvent.OnHits.Add(5, new HitPostEvent(31, 30, 25, 127));
universalEvent.OnHitTiles.Add(5, new TilePostEvent());
universalEvent.OnActions.Add(-10, new PreActionEvent());
universalEvent.AfterActions.Add(5, new UsePostEvent(26, 27, 28, 29, 126));
universalEvent.OnRefresh.Add(-5, new RefreshPreEvent());
universalEvent.InitActionData.Add(-10, new PreSkillEvent());
universalEvent.InitActionData.Add(-10, new PreItemEvent());
universalEvent.InitActionData.Add(-10, new PreThrowEvent());
universalEvent.BeforeHits.Add(-10, new PreHitEvent());
universalEvent.BeforeHits.Add(10, new AttemptHitEvent());
universalEvent.ElementEffects.Add(-10, new PreTypeEvent());
universalEvent.OnDeaths.Add(0, new ImpostorReviveEvent(150));
universalEvent.OnDeaths.Add(10, new HandoutRelativeExpEvent(1, 5, 10));
universalEvent.OnMapStarts.Add(-10, new FadeInEvent());
universalEvent.OnMapStarts.Add(-5, new SpecialIntroEvent());
universalEvent.OnMapStarts.Add(-5, new ReactivateItemsEvent());
//UniversalEvent.OnWalks.Add(-5, new RevealFrontTrapEvent());
HitRateLevelTableState hitRateTable = new HitRateLevelTableState(-6, 6, -6, 6);
hitRateTable.AccuracyLevels = new int[13] { 105, 120, 140, 168, 210, 280, 420, 630, 840, 1050, 1260, 1470, 1680 };
hitRateTable.EvasionLevels = new int[13] { 1680, 1470, 1260, 1050, 840, 630, 420, 280, 210, 168, 140, 120, 105 };
universalEvent.UniversalStates.Set(hitRateTable);
CritRateLevelTableState critRateTable = new CritRateLevelTableState();
critRateTable.CritLevels = new int[5] { 0, 3, 4, 6, 12 };
universalEvent.UniversalStates.Set(critRateTable);
AtkDefLevelTableState dmgModTable = new AtkDefLevelTableState(-6, 6, -6, 6, 4, 4);
universalEvent.UniversalStates.Set(dmgModTable);
ElementTableState elementTable = new ElementTableState();
elementTable.TypeMatchup = new int[19][];
elementTable.TypeMatchup[00] = new int[19] { NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM};
elementTable.TypeMatchup[01] = new int[19] { NRM,NRM,S_E,NRM,NRM,NVE,NVE,NVE,NVE,NVE,S_E,NRM,NRM,NRM,NVE,S_E,NRM,NVE,NRM};
elementTable.TypeMatchup[02] = new int[19] { NRM,NRM,NVE,NRM,NRM,NVE,NVE,NRM,NRM,S_E,NRM,NRM,NRM,NRM,NRM,S_E,NRM,NRM,NRM};
elementTable.TypeMatchup[03] = new int[19] { NRM,NRM,NRM,S_E,NRM,N_E,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NVE,NRM};
elementTable.TypeMatchup[04] = new int[19] { NRM,NRM,NRM,NVE,NVE,NRM,NRM,NRM,S_E,NRM,NVE,N_E,NRM,NRM,NRM,NRM,NRM,NRM,S_E};
elementTable.TypeMatchup[05] = new int[19] { NRM,NRM,S_E,S_E,NRM,NRM,S_E,NVE,NRM,NRM,NRM,NRM,NRM,NRM,NVE,NRM,NRM,NVE,NRM};
elementTable.TypeMatchup[06] = new int[19] { NRM,NVE,S_E,NRM,NRM,NVE,NRM,NRM,NVE,N_E,NRM,NRM,S_E,S_E,NVE,NVE,S_E,S_E,NRM};
elementTable.TypeMatchup[07] = new int[19] { NRM,S_E,NRM,NVE,NRM,NRM,NRM,NVE,NRM,NRM,S_E,NRM,S_E,NRM,NRM,NRM,NVE,S_E,NVE};
elementTable.TypeMatchup[08] = new int[19] { NRM,S_E,NRM,NRM,NVE,NRM,S_E,NRM,NRM,NRM,S_E,NRM,NRM,NRM,NRM,NRM,NVE,NVE,NRM};
elementTable.TypeMatchup[09] = new int[19] { NRM,NRM,NVE,NRM,NRM,NRM,NRM,NRM,NRM,S_E,NRM,NRM,NRM,N_E,NRM,S_E,NRM,NRM,NRM};
elementTable.TypeMatchup[10] = new int[19] { NRM,NVE,NRM,NVE,NRM,NRM,NRM,NVE,NVE,NRM,NVE,S_E,NRM,NRM,NVE,NRM,S_E,NVE,S_E};
elementTable.TypeMatchup[11] = new int[19] { NRM,NVE,NRM,NRM,S_E,NRM,NRM,S_E,N_E,NRM,NVE,NRM,NRM,NRM,S_E,NRM,S_E,S_E,NRM};
elementTable.TypeMatchup[12] = new int[19] { NRM,NRM,NRM,S_E,NRM,NRM,NRM,NVE,S_E,NRM,S_E,S_E,NVE,NRM,NRM,NRM,NRM,NVE,NVE};
elementTable.TypeMatchup[13] = new int[19] { NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,NRM,N_E,NRM,NRM,NRM,NRM,NRM,NRM,NVE,NVE,NRM};
elementTable.TypeMatchup[14] = new int[19] { NRM,NRM,NRM,NRM,NRM,S_E,NRM,NRM,NRM,NVE,S_E,NVE,NRM,NRM,NVE,NRM,NVE,N_E,NRM};
elementTable.TypeMatchup[15] = new int[19] { NRM,NRM,N_E,NRM,NRM,NRM,S_E,NRM,NRM,NRM,NRM,NRM,NRM,NRM,S_E,NVE,NRM,NVE,NRM};
elementTable.TypeMatchup[16] = new int[19] { NRM,S_E,NRM,NRM,NRM,NRM,NVE,S_E,S_E,NRM,NRM,NVE,S_E,NRM,NRM,NRM,NRM,NVE,NRM};
elementTable.TypeMatchup[17] = new int[19] { NRM,NRM,NRM,NRM,NVE,S_E,NRM,NVE,NRM,NRM,NRM,NRM,S_E,NRM,NRM,NRM,S_E,NVE,NVE};
elementTable.TypeMatchup[18] = new int[19] { NRM,NRM,NRM,NVE,NRM,NRM,NRM,S_E,NRM,NRM,NVE,S_E,NRM,NRM,NRM,NRM,S_E,NRM,NVE};
elementTable.Effectiveness = new int[11] { 0, 0, 0, 0, 0, 0, 1, 2, 4, 6, 8 };
universalEvent.UniversalStates.Set(elementTable);
universalEvent.UniversalStates.Set(new SkinTableState(1024));
DataManager.SaveData(PathMod.ModPath(DataManager.DATA_PATH + "Universal.bin"), universalEvent);
}
public static void AddUniversalData()
{
File.Delete(PathMod.ModPath(DataManager.MISC_PATH + "Index.bin"));
TypeDict<BaseData> baseData = new TypeDict<BaseData>();
baseData.Set(new RarityData());
baseData.Set(new MonsterFeatureData());
DataManager.SaveData(PathMod.ModPath(DataManager.MISC_PATH + "Index.bin"), baseData);
}
public static void AddEditorOps()
{
DeleteData(Path.Combine(PathMod.RESOURCE_PATH, "Extensions"));
{
CharSheetGenAnimOp op = new CharSheetGenAnimOp();
DataManager.SaveData(Path.Combine(PathMod.RESOURCE_PATH, "Extensions", "GenAnim.op"), op);
}
{
CharSheetAlignOp op = new CharSheetAlignOp();
DataManager.SaveData(Path.Combine(PathMod.RESOURCE_PATH, "Extensions", "Align.op"), op);
}
{
CharSheetMirrorOp op = new CharSheetMirrorOp();
DataManager.SaveData(Path.Combine(PathMod.RESOURCE_PATH, "Extensions", "MirrorLR.op"), op);
}
{
CharSheetMirrorOp op = new CharSheetMirrorOp();
op.StartRight = true;
DataManager.SaveData(Path.Combine(PathMod.RESOURCE_PATH, "Extensions", "MirrorRL.op"), op);
}
{
CharSheetCollapseOffsetsOp op = new CharSheetCollapseOffsetsOp();
DataManager.SaveData(Path.Combine(PathMod.RESOURCE_PATH, "Extensions", "CollapseOffsets.op"), op);
}
}
public static void AddSystemFX()
{
DeleteData(PathMod.ModPath(DataManager.FX_PATH));
{
BattleFX fx = new BattleFX();
fx.Sound = "DUN_Heal";
RepeatEmitter lowEmit = new RepeatEmitter(new AnimData("Stat_White_Ring", 3));
lowEmit.Bursts = 4;
lowEmit.BurstTime = 9;
lowEmit.LocHeight = -6;
lowEmit.Layer = DrawLayer.Bottom;
FiniteSprinkleEmitter emitter = new FiniteSprinkleEmitter(new AnimData("Event_Gather_Sparkle", 8));
emitter.Range = 18;
emitter.Speed = 36;
emitter.TotalParticles = 8;
emitter.StartHeight = 4;
emitter.HeightSpeed = 36;
emitter.SpeedDiff = 12;
ListEmitter listEmitter = new ListEmitter();
listEmitter.Layer = DrawLayer.NoDraw;
listEmitter.Anim.Add(lowEmit);
listEmitter.Anim.Add(emitter);
fx.Emitter = listEmitter;
fx.Delay = 20;
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "Heal.fx"), fx);
}
{
BattleFX fx = new BattleFX();
fx.Sound = "DUN_PP_Up";
SingleEmitter lowEmit = new SingleEmitter(new AnimData("Stat_Red_Ring", 3));
lowEmit.LocHeight = -6;
lowEmit.Layer = DrawLayer.Bottom;
SqueezedAreaEmitter emitter = new SqueezedAreaEmitter(new AnimData("Stat_Red_Line", 2, Dir8.Up));
emitter.Bursts = 3;
emitter.ParticlesPerBurst = 2;
emitter.BurstTime = 6;
emitter.Range = GraphicsManager.TileSize;
emitter.HeightSpeed = 6;
ListEmitter listEmitter = new ListEmitter();
listEmitter.Layer = DrawLayer.NoDraw;
listEmitter.Anim.Add(lowEmit);
listEmitter.Anim.Add(emitter);
fx.Emitter = listEmitter;
fx.Delay = 30;
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "RestoreCharge.fx"), fx);
}
{
BattleFX fx = new BattleFX();
fx.Sound = "DUN_PP_Down";
SqueezedAreaEmitter emitter = new SqueezedAreaEmitter(new AnimData("Stat_Red_Line", 2, Dir8.Down));
emitter.Bursts = 3;
emitter.ParticlesPerBurst = 2;
emitter.BurstTime = 6;
emitter.Range = GraphicsManager.TileSize;
emitter.StartHeight = 0;
emitter.HeightSpeed = 6;
fx.Emitter = emitter;
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "LoseCharge.fx"), fx);
}
{
EmoteFX fx = new EmoteFX();
fx.Sound = "EVT_Emote_Sweating";
fx.Anim = new AnimData("Emote_Sweating", 2);
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "NoCharge.fx"), fx);
}
{
BattleFX fx = new BattleFX();
fx.Sound = "DUN_Trace";
FiniteReleaseEmitter emitter = new FiniteReleaseEmitter(new AnimData("Puff_Green", 3), new AnimData("Puff_Yellow", 3), new AnimData("Puff_Blue", 3), new AnimData("Puff_Red", 3));
emitter.BurstTime = 4;
emitter.ParticlesPerBurst = 1;
emitter.Bursts = 4;
emitter.Speed = 48;
emitter.StartDistance = 4;
fx.Emitter = emitter;
fx.Delay = 20;
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "Element.fx"), fx);
}
{
BattleFX fx = new BattleFX();
fx.Sound = "DUN_Trace";
FiniteReleaseEmitter emitter = new FiniteReleaseEmitter(new AnimData("Puff_Green", 3), new AnimData("Puff_Yellow", 3), new AnimData("Puff_Blue", 3), new AnimData("Puff_Red", 3));
emitter.BurstTime = 4;
emitter.ParticlesPerBurst = 1;
emitter.Bursts = 4;
emitter.Speed = 48;
emitter.StartDistance = 4;
fx.Emitter = emitter;
fx.Delay = 20;
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "Intrinsic.fx"), fx);
}
{
BattleFX fx = new BattleFX();
fx.Sound = "DUN_Send_Home";
SingleEmitter emitter = new SingleEmitter(new BeamAnimData("Column_Yellow", 3));
emitter.Layer = DrawLayer.Front;
fx.Emitter = emitter;
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "SendHome.fx"), fx);
}
{
BattleFX fx = new BattleFX();
fx.Sound = "DUN_Ember";
fx.Emitter = new SingleEmitter(new AnimData("Circle_Small_Blue_Out", 2));
fx.Delay = 20;
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "ItemLost.fx"), fx);
}
{
BattleFX fx = new BattleFX();
fx.Sound = "DUN_Warp";
SingleEmitter emitter = new SingleEmitter(new AnimData("Circle_Red_Out", 3));
emitter.Layer = DrawLayer.Front;
fx.Emitter = emitter;
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "Warp.fx"), fx);
}
{
BattleFX fx = new BattleFX();
fx.Sound = "DUN_Throw_Spike";
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "Knockback.fx"), fx);
}
{
BattleFX fx = new BattleFX();
fx.Sound = "DUN_Pound";
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "Jump.fx"), fx);
}
{
BattleFX fx = new BattleFX();
fx.Sound = "DUN_Throw_Spike";
DataManager.SaveData(PathMod.ModPath(DataManager.FX_PATH + "Throw.fx"), fx);
}
}
public static void DeleteIndexedData(string subPath)
{
DeleteData(PathMod.ModPath(DataManager.DATA_PATH + subPath));
}
public static void DeleteData(string path)
{
string[] filePaths = Directory.GetFiles(path);
foreach (string filePath in filePaths)
File.Delete(filePath);
}
}
}
| 48.28866 | 194 | 0.586322 | [
"MIT"
] | audinowho/PMDODump | DataGenerator/Data/DataInfo.cs | 14,054 | C# |
using System;
using System.Collections.Generic;
using MaxLib.WebServer.Post;
#nullable enable
namespace MaxLib.WebServer
{
[Serializable]
public class HttpPost
{
[Obsolete]
public string CompletePost { get; private set; }
public string? MimeType { get; private set; }
protected Lazy<IPostData>? LazyData { get; set; }
public IPostData? Data => LazyData?.Value;
[Obsolete("this will be removed in a future release. Use HttpPost.Data instead.")]
public Dictionary<string, string> PostParameter
=> Data is UrlEncodedData data ? data.Parameter : new Dictionary<string, string>();
public static Dictionary<string, Func<IPostData>> DataHandler { get; }
= new Dictionary<string, Func<IPostData>>();
static HttpPost()
{
DataHandler[WebServer.MimeType.ApplicationXWwwFromUrlencoded] =
() => new UrlEncodedData();
DataHandler[WebServer.MimeType.MultipartFormData] =
() => new MultipartFormData();
}
public virtual void SetPost(ReadOnlyMemory<byte> post, string? mime)
{
string args = "";
if (mime != null)
{
var ind = mime.IndexOf(';');
if (ind >= 0)
{
args = mime.Substring(ind + 1);
mime = mime.Remove(ind);
}
}
if ((MimeType = mime) != null &&
DataHandler.TryGetValue(mime!, out Func<IPostData> constructor)
)
LazyData = new Lazy<IPostData>(() =>
{
var data = constructor();
data.Set(post, args);
return data;
}, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
else LazyData = new Lazy<IPostData>(new UnknownPostData(post, mime));
}
[Obsolete]
public virtual void SetPost(string post, string? mime)
{
CompletePost = post ?? throw new ArgumentNullException("Post");
string args = "";
if (mime != null)
{
var ind = mime.IndexOf(';');
if (ind >= 0)
{
args = mime.Substring(ind + 1);
mime = mime.Remove(ind);
}
}
if ((MimeType = mime) != null &&
DataHandler.TryGetValue(mime!, out Func<IPostData> constructor)
)
LazyData = new Lazy<IPostData>(() =>
{
var data = constructor();
data.Set(post, args);
return data;
}, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
else LazyData = null;
}
public HttpPost()
{
#pragma warning disable CS0612 // 'HttpPost.CompletePost' is obsolete
CompletePost = "";
#pragma warning restore CS0612
}
public HttpPost(ReadOnlyMemory<byte> post, string? mime)
: this()
=> SetPost(post, mime);
[Obsolete]
public HttpPost(string post, string? mime)
{
CompletePost = post ?? throw new ArgumentNullException(nameof(post));
SetPost(post, mime);
}
public override string ToString()
{
return $"{MimeType}: {Data}";
}
}
}
| 31.327434 | 95 | 0.507627 | [
"MIT"
] | Garados007/MaxLib.WebServer | MaxLib.WebServer/HttpPost.cs | 3,542 | C# |
using RimWorld;
using System;
using System.Collections.Generic;
using Verse;
namespace RimThreaded
{
class TaleManager_Patch
{
public static void RunDestructivePatches()
{
Type original = typeof(TaleManager);
Type patched = typeof(TaleManager_Patch);
RimThreadedHarmony.Prefix(original, patched, "Add");
RimThreadedHarmony.Prefix(original, patched, "RemoveTale");
}
public static bool Add(TaleManager __instance, Tale tale)
{
lock (__instance)
{
__instance.tales.Add(tale);
}
__instance.CheckCullTales(tale);
return false;
}
public static bool RemoveTale(TaleManager __instance, Tale tale)
{
if (!tale.Unused)
{
Log.Warning("Tried to remove used tale " + tale);
}
else
{
lock (__instance)
{
List<Tale> newTales = new List<Tale>(__instance.tales);
newTales.Remove(tale);
__instance.tales = newTales;
}
}
return false;
}
}
}
| 25.408163 | 75 | 0.508434 | [
"MIT"
] | BlackJack1155/RimThreaded | Source/TaleManager_Patch.cs | 1,247 | C# |
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
#if NUNIT
using NUnit.Framework;
using TestClassAttribute = NUnit.Framework.TestFixtureAttribute;
using TestMethodAttribute = NUnit.Framework.TestAttribute;
using TestContext = System.Version; //dummy
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Bluetooth.BlueSoleil;
using InTheHand.Net.Bluetooth.AttributeIds;
using System.Runtime.InteropServices;
using NMock2;
using System.Diagnostics;
namespace BlueSoleilTests.AlanJMcF.BlueSoleil.Tests
{
/// <summary>
/// Summary description for BlueSoleilServiceRecordTests
/// </summary>
[TestClass]
public class BlueSoleilServiceRecordTests
{
public BlueSoleilServiceRecordTests()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion
#region Manual mock native interface
[TestMethod]
public void OneNoExtAttr_ManualMock()
{
var hackApi = new TestSdBluesoleilApi();
byte[] setSvcName = Encoding.UTF8.GetBytes("aabbccdd");
var attrs = new Structs.BtSdkRemoteServiceAttrStru(0, 0x1112, setSvcName, IntPtr.Zero);
ServiceRecord sr = BluesoleilDeviceInfo.CreateServiceRecord(ref attrs, hackApi);
//
const string NewLine = "\r\n";
const string expectedDump = "AttrId: 0x0001 -- ServiceClassIdList" + NewLine
+ "ElementSequence" + NewLine
+ " Uuid16: 0x1112 -- HeadsetAudioGateway" + NewLine
+ NewLine
+ "AttrId: 0x0006 -- LanguageBaseAttributeIdList" + NewLine
+ "ElementSequence" + NewLine
+ " UInt16: 0x656E" + NewLine
+ " UInt16: 0x6A" + NewLine
+ " UInt16: 0x100" + NewLine
+ NewLine
+ "AttrId: 0x0100 -- ServiceName" + NewLine
+ "TextString: [en] 'aabbccdd'" + NewLine
+ NewLine
+ "AttrId: 0xFFFF" + NewLine
+ "TextString (guessing UTF-8): '<partial BlueSoleil decode>'" + NewLine
;
string dump = ServiceRecordUtilities.Dump(sr);
Assert.AreEqual(expectedDump, dump, "dump");
//
ServiceElement e;
//
e = sr.GetAttributeById(UniversalAttributeId.ServiceClassIdList).Value;
ServiceElement eSvcClass = e.GetValueAsElementArray()[0];
UInt16 svcC = (UInt16)eSvcClass.Value;
Assert.AreEqual(0x1112, svcC, "svcC");
//
string sn = sr.GetPrimaryMultiLanguageStringAttributeById(UniversalAttributeId.ServiceName);
Assert.AreEqual("aabbccdd", sn, "sn");
//----
hackApi.AssertActionsNoMore();
}
[TestMethod]
public void OneSppExtAttr_ManualMock()
{
var hackApi = new TestSdBluesoleilApi();
//
const byte Port = 23;
var ext = new Structs.BtSdkRmtSPPSvcExtAttrStru(Port);
IntPtr pExt = Marshal.AllocHGlobal(Marshal.SizeOf(ext));
Marshal.StructureToPtr(ext, pExt, false);
//
byte[] setSvcName = Encoding.UTF8.GetBytes("aabbccdd");
var attrs = new Structs.BtSdkRemoteServiceAttrStru(0, 0x1112, setSvcName, pExt);
ServiceRecord sr = BluesoleilDeviceInfo.CreateServiceRecord(ref attrs, hackApi);
//
const string NewLine = "\r\n";
const string expectedDump = "AttrId: 0x0001 -- ServiceClassIdList" + NewLine
+ "ElementSequence" + NewLine
+ " Uuid16: 0x1112 -- HeadsetAudioGateway" + NewLine
+ NewLine
+ "AttrId: 0x0004 -- ProtocolDescriptorList" + NewLine
+ "ElementSequence" + NewLine
+ " ElementSequence" + NewLine
+ " Uuid16: 0x100 -- L2CapProtocol" + NewLine
+ " ElementSequence" + NewLine
+ " Uuid16: 0x3 -- RFCommProtocol" + NewLine
+ " UInt8: 0x17" + NewLine
+ "( ( L2Cap ), ( Rfcomm, ChannelNumber=23 ) )" + NewLine
+ NewLine
+ "AttrId: 0x0006 -- LanguageBaseAttributeIdList" + NewLine
+ "ElementSequence" + NewLine
+ " UInt16: 0x656E" + NewLine
+ " UInt16: 0x6A" + NewLine
+ " UInt16: 0x100" + NewLine
+ NewLine
+ "AttrId: 0x0100 -- ServiceName" + NewLine
+ "TextString: [en] 'aabbccdd'" + NewLine
+ NewLine
+ "AttrId: 0xFFFF" + NewLine
+ "TextString (guessing UTF-8): '<partial BlueSoleil decode>'" + NewLine
;
string dump = ServiceRecordUtilities.Dump(sr);
Assert.AreEqual(expectedDump, dump, "dump");
//
ServiceElement e;
//
e = sr.GetAttributeById(UniversalAttributeId.ServiceClassIdList).Value;
ServiceElement eSvcClass = e.GetValueAsElementArray()[0];
UInt16 svcC = (UInt16)eSvcClass.Value;
Assert.AreEqual(0x1112, svcC, "svcC");
//
e = sr.GetAttributeById(UniversalAttributeId.ProtocolDescriptorList).Value;
ServiceElement listRfcomm = e.GetValueAsElementArray()[1];
ServiceElement eScn = listRfcomm.GetValueAsElementArray()[1];
byte scn = (byte)eScn.Value;
Assert.AreEqual(Port, scn, "scn");
//
string sn = sr.GetPrimaryMultiLanguageStringAttributeById(UniversalAttributeId.ServiceName);
Assert.AreEqual("aabbccdd", sn, "sn");
//----
hackApi.AssertActionsInOrder("Btsdk_FreeMemory", pExt);
hackApi.AssertActionsNoMore();
}
#endregion
#region Using Mockery
private void SetupNoSearchAppExtSPPService(IBluesoleilApi hackApi)
{
Expect.Once.On(hackApi).Method("Btsdk_SearchAppExtSPPService")
.WithAnyArguments().Will(Return.Value(BtSdkError.NO_SERVICE));
}
[TestMethod]
public void OneNoExtAttr()
{
var mocks = new Mockery();
var hackApi = mocks.NewMock<IBluesoleilApi>();
SetupNoSearchAppExtSPPService(hackApi);
Expect.Never.On(hackApi).Method("Btsdk_FreeMemory");
//
byte[] setSvcName = { (byte)'a', /* \u00E4 */ 0xC3, 0xA4, (byte)'b', (byte)'b', (byte)'c', (byte)'c', (byte)'d', (byte)'d' };
var attrs = new Structs.BtSdkRemoteServiceAttrStru(0, 0x1112, setSvcName, IntPtr.Zero);
ServiceRecord sr = BluesoleilDeviceInfo.CreateServiceRecord(ref attrs, hackApi);
//
const string NewLine = "\r\n";
const string expectedDump = "AttrId: 0x0001 -- ServiceClassIdList" + NewLine
+ "ElementSequence" + NewLine
+ " Uuid16: 0x1112 -- HeadsetAudioGateway" + NewLine
+ NewLine
+ "AttrId: 0x0006 -- LanguageBaseAttributeIdList" + NewLine
+ "ElementSequence" + NewLine
+ " UInt16: 0x656E" + NewLine
+ " UInt16: 0x6A" + NewLine
+ " UInt16: 0x100" + NewLine
+ NewLine
+ "AttrId: 0x0100 -- ServiceName" + NewLine
+ "TextString: [en] 'a\u00E4bbccdd'" + NewLine
+ NewLine
+ "AttrId: 0xFFFF" + NewLine
+ "TextString (guessing UTF-8): '<partial BlueSoleil decode>'" + NewLine
;
string dump = ServiceRecordUtilities.Dump(sr);
Assert.AreEqual(expectedDump, dump, "dump");
//
ServiceElement e;
//
e = sr.GetAttributeById(UniversalAttributeId.ServiceClassIdList).Value;
ServiceElement eSvcClass = e.GetValueAsElementArray()[0];
UInt16 svcC = (UInt16)eSvcClass.Value;
Assert.AreEqual(0x1112, svcC, "svcC");
//
string sn = sr.GetPrimaryMultiLanguageStringAttributeById(UniversalAttributeId.ServiceName);
Assert.AreEqual("a\u00E4bbccdd", sn, "sn");
//----
mocks.VerifyAllExpectationsHaveBeenMet();
}
[TestMethod]
public void OneSppExtAttr_FullLenServiceName()
{
var mocks = new Mockery();
var hackApi = mocks.NewMock<IBluesoleilApi>();
SetupNoSearchAppExtSPPService(hackApi);
//
const byte Port = 23;
var ext = new Structs.BtSdkRmtSPPSvcExtAttrStru(Port);
IntPtr pExt = Marshal.AllocHGlobal(Marshal.SizeOf(ext));
Marshal.StructureToPtr(ext, pExt, false);
Expect.Once.On(hackApi).Method("Btsdk_FreeMemory").With(pExt);
//
Debug.Assert(80 == StackConsts.BTSDK_SERVICENAME_MAXLENGTH, "BTSDK_SERVICENAME_MAXLENGTH: " + StackConsts.BTSDK_SERVICENAME_MAXLENGTH);
byte[] setSvcName = new byte[StackConsts.BTSDK_SERVICENAME_MAXLENGTH];
for (int i = 0; i < (setSvcName.Length - 1); ++i) setSvcName[i] = (byte)'a';
setSvcName[setSvcName.Length - 1] = (byte)'b';
var attrs = new Structs.BtSdkRemoteServiceAttrStru(0, 0x1112,
setSvcName, pExt);
ServiceRecord sr = BluesoleilDeviceInfo.CreateServiceRecord(ref attrs, hackApi);
//
const string NewLine = "\r\n";
const string expectedDump = "AttrId: 0x0001 -- ServiceClassIdList" + NewLine
+ "ElementSequence" + NewLine
+ " Uuid16: 0x1112 -- HeadsetAudioGateway" + NewLine
+ NewLine
+ "AttrId: 0x0004 -- ProtocolDescriptorList" + NewLine
+ "ElementSequence" + NewLine
+ " ElementSequence" + NewLine
+ " Uuid16: 0x100 -- L2CapProtocol" + NewLine
+ " ElementSequence" + NewLine
+ " Uuid16: 0x3 -- RFCommProtocol" + NewLine
+ " UInt8: 0x17" + NewLine
+ "( ( L2Cap ), ( Rfcomm, ChannelNumber=23 ) )" + NewLine
+ NewLine
+ "AttrId: 0x0006 -- LanguageBaseAttributeIdList" + NewLine
+ "ElementSequence" + NewLine
+ " UInt16: 0x656E" + NewLine
+ " UInt16: 0x6A" + NewLine
+ " UInt16: 0x100" + NewLine
+ NewLine
+ "AttrId: 0x0100 -- ServiceName" + NewLine
+ "TextString: [en] 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab'" + NewLine
+ NewLine
+ "AttrId: 0xFFFF" + NewLine
+ "TextString (guessing UTF-8): '<partial BlueSoleil decode>'" + NewLine
;
string dump = ServiceRecordUtilities.Dump(sr);
Assert.AreEqual(expectedDump, dump, "dump");
//
ServiceElement e;
//
e = sr.GetAttributeById(UniversalAttributeId.ServiceClassIdList).Value;
ServiceElement eSvcClass = e.GetValueAsElementArray()[0];
UInt16 svcC = (UInt16)eSvcClass.Value;
Assert.AreEqual(0x1112, svcC, "svcC");
//
e = sr.GetAttributeById(UniversalAttributeId.ProtocolDescriptorList).Value;
ServiceElement listRfcomm = e.GetValueAsElementArray()[1];
ServiceElement eScn = listRfcomm.GetValueAsElementArray()[1];
byte scn = (byte)eScn.Value;
Assert.AreEqual(Port, scn, "scn");
//
string sn = sr.GetPrimaryMultiLanguageStringAttributeById(UniversalAttributeId.ServiceName);
Assert.AreEqual("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", sn, "sn");
//----
mocks.VerifyAllExpectationsHaveBeenMet();
}
[TestMethod]
public void OneNoExtAttr_PanuLeUnicodeSvcName()
{
var mocks = new Mockery();
var hackApi = mocks.NewMock<IBluesoleilApi>();
SetupNoSearchAppExtSPPService(hackApi);
Expect.Never.On(hackApi).Method("Btsdk_FreeMemory");
//
byte[] setSvcName = {
0x50, 0x00, 0x65, 0x00, 0x72, 0x00, 0x73, 0x00,
0x6F, 0x00, 0x6E, 0x00, 0x61, 0x00, 0x6C, 0x00,
0x20, 0x00, 0x41, 0x00, 0x64, 0x00, 0x2D, 0x00,
0x68, 0x00, 0x6F, 0x00, 0x63, 0x00, 0x20, 0x00,
0x55, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00,
0x20, 0x00, 0x53, 0x00, 0x65, 0x00, 0x72, 0x00,
0x76, 0x00, 0x69, 0x00, 0x63, 0x00, 0x65, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
ushort SvcClassPanu = 0x1115;
var attrs = new Structs.BtSdkRemoteServiceAttrStru(0, SvcClassPanu, setSvcName, IntPtr.Zero);
ServiceRecord sr = BluesoleilDeviceInfo.CreateServiceRecord(ref attrs, hackApi);
//
const string NewLine = "\r\n";
const string expectedDump = "AttrId: 0x0001 -- ServiceClassIdList" + NewLine
+ "ElementSequence" + NewLine
+ " Uuid16: 0x1115 -- Panu" + NewLine
+ NewLine
+ "AttrId: 0x0006 -- LanguageBaseAttributeIdList" + NewLine
+ "ElementSequence" + NewLine
+ " UInt16: 0x656E" + NewLine
+ " UInt16: 0x6A" + NewLine
+ " UInt16: 0x100" + NewLine
+ NewLine
+ "AttrId: 0x0100 -- ServiceName" + NewLine
+ "TextString: [en] 'Personal Ad-hoc User Service'" + NewLine
+ NewLine
+ "AttrId: 0xFFFF" + NewLine
+ "TextString (guessing UTF-8): '<partial BlueSoleil decode>'" + NewLine
;
string dump = ServiceRecordUtilities.Dump(sr);
Assert.AreEqual(expectedDump, dump, "dump");
//
ServiceElement e;
//
e = sr.GetAttributeById(UniversalAttributeId.ServiceClassIdList).Value;
ServiceElement eSvcClass = e.GetValueAsElementArray()[0];
UInt16 svcC = (UInt16)eSvcClass.Value;
Assert.AreEqual(0x1115, svcC, "svcC");
//
string sn = sr.GetPrimaryMultiLanguageStringAttributeById(UniversalAttributeId.ServiceName);
Assert.AreEqual("Personal Ad-hoc User Service", sn, "sn");
//----
mocks.VerifyAllExpectationsHaveBeenMet();
}
//Not supported! Can't tell between little-endian and big-endian Unicode!
//[TestMethod]
public void OneNoExtAttr_PanuBeUnicodeSvcName()
{
var mocks = new Mockery();
var hackApi = mocks.NewMock<IBluesoleilApi>();
SetupNoSearchAppExtSPPService(hackApi);
Expect.Never.On(hackApi).Method("Btsdk_FreeMemory");
//
byte[] setSvcName = {
0x00, 0x50, 0x00, 0x65, 0x00, 0x72, 0x00, 0x73, 0x00,
0x6F, 0x00, 0x6E, 0x00, 0x61, 0x00, 0x6C, 0x00,
0x20, 0x00, 0x41, 0x00, 0x64, 0x00, 0x2D, 0x00,
0x68, 0x00, 0x6F, 0x00, 0x63, 0x00, 0x20, 0x00,
0x55, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00,
0x20, 0x00, 0x53, 0x00, 0x65, 0x00, 0x72, 0x00,
0x76, 0x00, 0x69, 0x00, 0x63, 0x00, 0x65, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
ushort SvcClassPanu = 0x1115;
var attrs = new Structs.BtSdkRemoteServiceAttrStru(0, SvcClassPanu, setSvcName, IntPtr.Zero);
ServiceRecord sr = BluesoleilDeviceInfo.CreateServiceRecord(ref attrs, hackApi);
//
const string NewLine = "\r\n";
const string expectedDump = "AttrId: 0x0001 -- ServiceClassIdList" + NewLine
+ "ElementSequence" + NewLine
+ " Uuid16: 0x1115 -- Panu" + NewLine
+ NewLine
+ "AttrId: 0x0006 -- LanguageBaseAttributeIdList" + NewLine
+ "ElementSequence" + NewLine
+ " UInt16: 0x656E" + NewLine
+ " UInt16: 0x6A" + NewLine
+ " UInt16: 0x100" + NewLine
+ NewLine
+ "AttrId: 0x0100 -- ServiceName" + NewLine
+ "TextString: [en] 'Personal Ad-hoc User Service'" + NewLine
+ NewLine
+ "AttrId: 0xFFFF" + NewLine
+ "TextString (guessing UTF-8): '<partial BlueSoleil decode>'" + NewLine
;
string dump = ServiceRecordUtilities.Dump(sr);
Assert.AreEqual(expectedDump, dump, "dump");
//
ServiceElement e;
//
e = sr.GetAttributeById(UniversalAttributeId.ServiceClassIdList).Value;
ServiceElement eSvcClass = e.GetValueAsElementArray()[0];
UInt16 svcC = (UInt16)eSvcClass.Value;
Assert.AreEqual(0x1115, svcC, "svcC");
//
string sn = sr.GetPrimaryMultiLanguageStringAttributeById(UniversalAttributeId.ServiceName);
Assert.AreEqual("Personal Ad-hoc User Service", sn, "sn");
//----
mocks.VerifyAllExpectationsHaveBeenMet();
}
[TestMethod]
public void DeviceIdExtAttr_NoServiceName()
{
var mocks = new Mockery();
var hackApi = mocks.NewMock<IBluesoleilApi>();
SetupNoSearchAppExtSPPService(hackApi);
//
var ext = new Structs.BtSdkRmtDISvcExtAttrStru(1, 2, 3, 4, true, 6, 0);
IntPtr pExt = Marshal.AllocHGlobal(Marshal.SizeOf(ext));
Marshal.StructureToPtr(ext, pExt, false);
Expect.Once.On(hackApi).Method("Btsdk_FreeMemory").With(pExt);
//
byte[] setSvcName = new byte[0];
const int SvcClassPnp = 0x1200;
var attrs = new Structs.BtSdkRemoteServiceAttrStru(0, SvcClassPnp,
setSvcName, pExt);
ServiceRecord sr = BluesoleilDeviceInfo.CreateServiceRecord(ref attrs, hackApi);
//
const string NewLine = "\r\n";
const string expectedDump
= "AttrId: 0x0001 -- ServiceClassIdList" + NewLine
+ "ElementSequence" + NewLine
+ " Uuid16: 0x1200 -- PnPInformation" + NewLine
+ NewLine
//
+ "AttrId: 0x0200 -- SpecificationId" + NewLine
+ "UInt16: 0x1" + NewLine
+ NewLine
+ "AttrId: 0x0201 -- VendorId" + NewLine
+ "UInt16: 0x2" + NewLine
+ NewLine
+ "AttrId: 0x0202 -- ProductId" + NewLine
+ "UInt16: 0x3" + NewLine
+ NewLine
+ "AttrId: 0x0203 -- Version" + NewLine
+ "UInt16: 0x4" + NewLine
+ NewLine
+ "AttrId: 0x0204 -- PrimaryRecord" + NewLine
+ "Boolean: True" + NewLine
+ NewLine
+ "AttrId: 0x0205 -- VendorIdSource" + NewLine
+ "UInt16: 0x6" + NewLine
+ NewLine
//
+ "AttrId: 0xFFFF" + NewLine
+ "TextString (guessing UTF-8): '<partial BlueSoleil decode>'" + NewLine
;
string dump = ServiceRecordUtilities.Dump(sr, typeof(DeviceIdProfileAttributeId));
Assert.AreEqual(expectedDump, dump, "dump");
//
ServiceElement e;
//
e = sr.GetAttributeById(UniversalAttributeId.ServiceClassIdList).Value;
ServiceElement eSvcClass = e.GetValueAsElementArray()[0];
UInt16 svcC = (UInt16)eSvcClass.Value;
Assert.AreEqual(0x1200, svcC, "svcC");
//
//----
mocks.VerifyAllExpectationsHaveBeenMet();
}
#endregion
}
}
| 45.445135 | 147 | 0.550524 | [
"MIT"
] | 3wayHimself/32feet | Widcomm/BlueSoleilTests/BlueSoleilServiceRecordTests.cs | 21,952 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Le informazioni generali relative a un assembly sono controllate dal seguente
// set di attributi. Modificare i valori di questi attributi per modificare le informazioni
// associate a un assembly.
[assembly: AssemblyTitle("VisualChatServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("VisualChatServer")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili
// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da
// COM, impostare su true l'attributo ComVisible per tale tipo.
[assembly: ComVisible(false)]
// Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi
[assembly: Guid("af6a372b-cc95-4e69-a796-b2c9af8a7b49")]
// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
//
// Versione principale
// Versione secondaria
// Numero di build
// Revisione
//
// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
// usando l'asterisco '*' come illustrato di seguito:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 41.837838 | 127 | 0.76292 | [
"MIT"
] | Destewie/LAN-PizzaChat | LAN Chat (First version)/Visuale/VisualChatServer/VisualChatServer/Properties/AssemblyInfo.cs | 1,554 | 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.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Protocols.WsFederation;
using Microsoft.IdentityModel.Tokens;
namespace Microsoft.AspNetCore.Authentication.WsFederation
{
/// <summary>
/// A per-request authentication handler for the WsFederation.
/// </summary>
public class WsFederationHandler : RemoteAuthenticationHandler<WsFederationOptions>, IAuthenticationSignOutHandler
{
private const string CorrelationProperty = ".xsrf";
private WsFederationConfiguration _configuration;
/// <summary>
/// Creates a new WsFederationAuthenticationHandler
/// </summary>
/// <param name="options"></param>
/// <param name="encoder"></param>
/// <param name="clock"></param>
/// <param name="logger"></param>
public WsFederationHandler(IOptionsMonitor<WsFederationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
/// <summary>
/// The handler calls methods on the events which give the application control at certain points where processing is occurring.
/// If it is not provided a default instance is supplied which does nothing when the methods are called.
/// </summary>
protected new WsFederationEvents Events
{
get { return (WsFederationEvents)base.Events; }
set { base.Events = value; }
}
/// <summary>
/// Creates a new instance of the events instance.
/// </summary>
/// <returns>A new instance of the events instance.</returns>
protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new WsFederationEvents());
/// <summary>
/// Overridden to handle remote signout requests
/// </summary>
/// <returns><see langword="true" /> if request processing should stop.</returns>
public override Task<bool> HandleRequestAsync()
{
// RemoteSignOutPath and CallbackPath may be the same, fall through if the message doesn't match.
if (Options.RemoteSignOutPath.HasValue && Options.RemoteSignOutPath == Request.Path && HttpMethods.IsGet(Request.Method)
&& string.Equals(Request.Query[WsFederationConstants.WsFederationParameterNames.Wa],
WsFederationConstants.WsFederationActions.SignOutCleanup, StringComparison.OrdinalIgnoreCase))
{
// We've received a remote sign-out request
return HandleRemoteSignOutAsync();
}
return base.HandleRequestAsync();
}
/// <summary>
/// Handles Challenge
/// </summary>
/// <returns></returns>
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
if (_configuration == null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
}
// Save the original challenge URI so we can redirect back to it when we're done.
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = OriginalPathBase + OriginalPath + Request.QueryString;
}
var wsFederationMessage = new WsFederationMessage()
{
IssuerAddress = _configuration.TokenEndpoint ?? string.Empty,
Wtrealm = Options.Wtrealm,
Wa = WsFederationConstants.WsFederationActions.SignIn,
};
if (!string.IsNullOrEmpty(Options.Wreply))
{
wsFederationMessage.Wreply = Options.Wreply;
}
else
{
wsFederationMessage.Wreply = BuildRedirectUri(Options.CallbackPath);
}
GenerateCorrelationId(properties);
var redirectContext = new RedirectContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.RedirectToIdentityProvider(redirectContext);
if (redirectContext.Handled)
{
return;
}
wsFederationMessage = redirectContext.ProtocolMessage;
if (!string.IsNullOrEmpty(wsFederationMessage.Wctx))
{
properties.Items[WsFederationDefaults.UserstatePropertiesKey] = wsFederationMessage.Wctx;
}
wsFederationMessage.Wctx = Uri.EscapeDataString(Options.StateDataFormat.Protect(properties));
var redirectUri = wsFederationMessage.CreateSignInUrl();
if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
{
Logger.MalformedRedirectUri(redirectUri);
}
Response.Redirect(redirectUri);
}
/// <summary>
/// Invoked to process incoming authentication messages.
/// </summary>
/// <returns></returns>
protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync()
{
WsFederationMessage wsFederationMessage = null;
AuthenticationProperties properties = null;
// assumption: if the ContentType is "application/x-www-form-urlencoded" it should be safe to read as it is small.
if (HttpMethods.IsPost(Request.Method)
&& !string.IsNullOrEmpty(Request.ContentType)
// May have media/type; charset=utf-8, allow partial match.
&& Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)
&& Request.Body.CanRead)
{
var form = await Request.ReadFormAsync();
wsFederationMessage = new WsFederationMessage(form.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value)));
}
if (wsFederationMessage == null || !wsFederationMessage.IsSignInMessage)
{
if (Options.SkipUnrecognizedRequests)
{
// Not for us?
return HandleRequestResult.SkipHandler();
}
return HandleRequestResult.Fail("No message.");
}
try
{
// Retrieve our cached redirect uri
var state = wsFederationMessage.Wctx;
// WsFed allows for uninitiated logins, state may be missing. See AllowUnsolicitedLogins.
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
{
if (!Options.AllowUnsolicitedLogins)
{
return HandleRequestResult.Fail("Unsolicited logins are not allowed.");
}
}
else
{
// Extract the user state from properties and reset.
properties.Items.TryGetValue(WsFederationDefaults.UserstatePropertiesKey, out var userState);
wsFederationMessage.Wctx = userState;
}
var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.MessageReceived(messageReceivedContext);
if (messageReceivedContext.Result != null)
{
return messageReceivedContext.Result;
}
wsFederationMessage = messageReceivedContext.ProtocolMessage;
properties = messageReceivedContext.Properties; // Provides a new instance if not set.
// If state did flow from the challenge then validate it. See AllowUnsolicitedLogins above.
if (properties.Items.TryGetValue(CorrelationProperty, out string correlationId)
&& !ValidateCorrelationId(properties))
{
return HandleRequestResult.Fail("Correlation failed.", properties);
}
if (wsFederationMessage.Wresult == null)
{
Logger.SignInWithoutWResult();
return HandleRequestResult.Fail(Resources.SignInMessageWresultIsMissing, properties);
}
var token = wsFederationMessage.GetToken();
if (string.IsNullOrEmpty(token))
{
Logger.SignInWithoutToken();
return HandleRequestResult.Fail(Resources.SignInMessageTokenIsMissing, properties);
}
var securityTokenReceivedContext = new SecurityTokenReceivedContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.SecurityTokenReceived(securityTokenReceivedContext);
if (securityTokenReceivedContext.Result != null)
{
return securityTokenReceivedContext.Result;
}
wsFederationMessage = securityTokenReceivedContext.ProtocolMessage;
properties = messageReceivedContext.Properties;
if (_configuration == null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
}
// Copy and augment to avoid cross request race conditions for updated configurations.
var tvp = Options.TokenValidationParameters.Clone();
var issuers = new[] { _configuration.Issuer };
tvp.ValidIssuers = (tvp.ValidIssuers == null ? issuers : tvp.ValidIssuers.Concat(issuers));
tvp.IssuerSigningKeys = (tvp.IssuerSigningKeys == null ? _configuration.SigningKeys : tvp.IssuerSigningKeys.Concat(_configuration.SigningKeys));
ClaimsPrincipal principal = null;
SecurityToken parsedToken = null;
foreach (var validator in Options.SecurityTokenHandlers)
{
if (validator.CanReadToken(token))
{
principal = validator.ValidateToken(token, tvp, out parsedToken);
break;
}
}
if (principal == null)
{
throw new SecurityTokenException(Resources.Exception_NoTokenValidatorFound);
}
if (Options.UseTokenLifetime && parsedToken != null)
{
// Override any session persistence to match the token lifetime.
var issued = parsedToken.ValidFrom;
if (issued != DateTime.MinValue)
{
properties.IssuedUtc = issued.ToUniversalTime();
}
var expires = parsedToken.ValidTo;
if (expires != DateTime.MinValue)
{
properties.ExpiresUtc = expires.ToUniversalTime();
}
properties.AllowRefresh = false;
}
var securityTokenValidatedContext = new SecurityTokenValidatedContext(Context, Scheme, Options, principal, properties)
{
ProtocolMessage = wsFederationMessage,
SecurityToken = parsedToken,
};
await Events.SecurityTokenValidated(securityTokenValidatedContext);
if (securityTokenValidatedContext.Result != null)
{
return securityTokenValidatedContext.Result;
}
// Flow possible changes
principal = securityTokenValidatedContext.Principal;
properties = securityTokenValidatedContext.Properties;
return HandleRequestResult.Success(new AuthenticationTicket(principal, properties, Scheme.Name));
}
catch (Exception exception)
{
Logger.ExceptionProcessingMessage(exception);
// Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the notification.
if (Options.RefreshOnIssuerKeyNotFound && exception is SecurityTokenSignatureKeyNotFoundException)
{
Options.ConfigurationManager.RequestRefresh();
}
var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
{
ProtocolMessage = wsFederationMessage,
Exception = exception
};
await Events.AuthenticationFailed(authenticationFailedContext);
if (authenticationFailedContext.Result != null)
{
return authenticationFailedContext.Result;
}
return HandleRequestResult.Fail(exception, properties);
}
}
/// <summary>
/// Handles Signout
/// </summary>
/// <returns></returns>
public async virtual Task SignOutAsync(AuthenticationProperties properties)
{
var target = ResolveTarget(Options.ForwardSignOut);
if (target != null)
{
await Context.SignOutAsync(target, properties);
return;
}
if (_configuration == null)
{
_configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
}
var wsFederationMessage = new WsFederationMessage()
{
IssuerAddress = _configuration.TokenEndpoint ?? string.Empty,
Wtrealm = Options.Wtrealm,
Wa = WsFederationConstants.WsFederationActions.SignOut,
};
// Set Wreply in order:
// 1. properties.Redirect
// 2. Options.SignOutWreply
// 3. Options.Wreply
if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri))
{
wsFederationMessage.Wreply = BuildRedirectUriIfRelative(properties.RedirectUri);
}
else if (!string.IsNullOrEmpty(Options.SignOutWreply))
{
wsFederationMessage.Wreply = BuildRedirectUriIfRelative(Options.SignOutWreply);
}
else if (!string.IsNullOrEmpty(Options.Wreply))
{
wsFederationMessage.Wreply = BuildRedirectUriIfRelative(Options.Wreply);
}
var redirectContext = new RedirectContext(Context, Scheme, Options, properties)
{
ProtocolMessage = wsFederationMessage
};
await Events.RedirectToIdentityProvider(redirectContext);
if (!redirectContext.Handled)
{
var redirectUri = redirectContext.ProtocolMessage.CreateSignOutUrl();
if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute))
{
Logger.MalformedRedirectUri(redirectUri);
}
Response.Redirect(redirectUri);
}
}
/// <summary>
/// Handles wsignoutcleanup1.0 messages sent to the RemoteSignOutPath
/// </summary>
/// <returns></returns>
protected virtual async Task<bool> HandleRemoteSignOutAsync()
{
var message = new WsFederationMessage(Request.Query.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value)));
var remoteSignOutContext = new RemoteSignOutContext(Context, Scheme, Options, message);
await Events.RemoteSignOut(remoteSignOutContext);
if (remoteSignOutContext.Result != null)
{
if (remoteSignOutContext.Result.Handled)
{
Logger.RemoteSignOutHandledResponse();
return true;
}
if (remoteSignOutContext.Result.Skipped)
{
Logger.RemoteSignOutSkipped();
return false;
}
}
Logger.RemoteSignOut();
await Context.SignOutAsync(Options.SignOutScheme);
return true;
}
/// <summary>
/// Build a redirect path if the given path is a relative path.
/// </summary>
private string BuildRedirectUriIfRelative(string uri)
{
if (string.IsNullOrEmpty(uri))
{
return uri;
}
if (!uri.StartsWith("/", StringComparison.Ordinal))
{
return uri;
}
return BuildRedirectUri(uri);
}
}
}
| 41.361502 | 160 | 0.577696 | [
"Apache-2.0"
] | 1kevgriff/aspnetcore | src/Security/Authentication/WsFederation/src/WsFederationHandler.cs | 17,620 | C# |
using NUnit.Framework;
using Publicity.Tests.Cases;
using Publicity.Tests.Constraints;
namespace Publicity.Tests
{
public class ArrayTests
{
[Test]
public void RootArrayShouldOpenAllItems()
{
object sample = ArrayFixture.Root();
dynamic instance = sample.Open();
Assert.That(instance.Count, Is.EqualTo(2));
Assert.That(instance.Length, Is.EqualTo(2));
Assert.That(instance.Rank, Is.EqualTo(1));
Assert.That(instance, Enumerates.To(2));
Assert.That(instance, Has.All.InstanceOf<OpenTarget>());
Assert.That(instance, Is.InstanceOf<OpenTarget>());
Assert.That(instance[0].value, Is.EqualTo(1));
Assert.That(instance[1].value, Is.EqualTo(2));
}
[Test]
public void NestedArrayShouldOpenAllItems()
{
object sample = ArrayFixture.Nested();
dynamic instance = sample.Open();
Assert.That(instance.items.Count, Is.EqualTo(2));
Assert.That(instance.items.Length, Is.EqualTo(2));
Assert.That(instance.items.Rank, Is.EqualTo(1));
Assert.That(instance.items, Enumerates.To(2));
Assert.That(instance.items, Has.All.InstanceOf<OpenTarget>());
Assert.That(instance.items, Is.InstanceOf<OpenTarget>());
Assert.That(instance.items[0].value, Is.EqualTo(1));
Assert.That(instance.items[1].value, Is.EqualTo(2));
}
[Test]
public void JaggedArrayShouldOpenAllItems()
{
object sample = ArrayFixture.Jagged();
dynamic instance = sample.Open();
Assert.That(instance.Count, Is.EqualTo(2));
Assert.That(instance.Length, Is.EqualTo(2));
Assert.That(instance.Rank, Is.EqualTo(1));
Assert.That(instance, Enumerates.To(2));
Assert.That(instance, Has.All.InstanceOf<OpenTarget>());
Assert.That(instance, Is.InstanceOf<OpenTarget>());
Assert.That(instance[0], Enumerates.To(1));
Assert.That(instance[0], Is.InstanceOf<OpenTarget>());
Assert.That(instance[0][0].value, Is.EqualTo(1));
Assert.That(instance[1], Enumerates.To(1));
Assert.That(instance[1], Is.InstanceOf<OpenTarget>());
Assert.That(instance[1][0].value, Is.EqualTo(2));
}
[Test]
public void MultiArrayShouldOpenAllItems()
{
object sample = ArrayFixture.Multi();
dynamic instance = sample.Open();
Assert.That(instance.Count, Is.EqualTo(4));
Assert.That(instance.Length, Is.EqualTo(4));
Assert.That(instance.Rank, Is.EqualTo(2));
Assert.That(instance, Enumerates.To(4));
Assert.That(instance, Has.All.InstanceOf<OpenTarget>());
Assert.That(instance, Is.InstanceOf<OpenTarget>());
Assert.That(instance[0, 0].value, Is.EqualTo(1));
Assert.That(instance[0, 1].value, Is.EqualTo(3));
Assert.That(instance[1, 0].value, Is.EqualTo(2));
Assert.That(instance[1, 1].value, Is.EqualTo(4));
}
}
} | 35.065217 | 74 | 0.586175 | [
"MIT"
] | amacal/publicity | sources/Publicity.Tests/ArrayTests.cs | 3,228 | C# |
using Monaco;
using Newtonsoft.Json;
namespace Monaco.Languages
{
public interface WorkspaceFileEdit
{
[JsonProperty("metadata", NullValueHandling = NullValueHandling.Ignore)]
WorkspaceEditMetadata Metadata { get; set; }
[JsonProperty("newUri", NullValueHandling = NullValueHandling.Ignore)]
Uri NewUri { get; set; }
[JsonProperty("oldUri", NullValueHandling = NullValueHandling.Ignore)]
Uri OldUri { get; set; }
[JsonProperty("options", NullValueHandling = NullValueHandling.Ignore)]
WorkspaceFileEditOptions Options { get; set; }
}
}
| 29.380952 | 80 | 0.685575 | [
"MIT"
] | hawkerm/monaco-editor-uwp | MonacoEditorComponent/Monaco/Languages/WorkspaceFileEdit.cs | 619 | C# |
namespace System.Windows.Forms
{
public partial class InterpolationForm : Form
{
public InterpolationEditor _interpolationEditor;
public InterpolationForm(ModelEditorBase mainWindow)
{
InitializeComponent();
_interpolationEditor = new InterpolationEditor(mainWindow);
TopMost = true;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Controls.Add(_interpolationEditor);
_interpolationEditor.Dock = DockStyle.Fill;
}
}
}
| 26.227273 | 71 | 0.618718 | [
"MIT"
] | Birdthulu/Legacy-Costume-Manager | brawltools/BrawlLib/System/Windows/Forms/InterpolationForm.cs | 579 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using MIMWebClient.Core.Events;
namespace MIMWebClient.Core.Mob.Events
{
public class Shop
{
public static void listItems(PlayerSetup.Player player, Room.Room room)
{
var itemsForSell = "<table><thead><tr><td>Item</td><td>Price</td></tr></thead><tbody>";
var mob = room.mobs.FirstOrDefault(x => x.Shop.Equals(true));
if (mob != null)
{
if (mob.itemsToSell.Count > 0)
{
Regex rgx = new Regex(@"\s[a-z][0-9]*$");
foreach (var item in ItemContainer.List(mob.itemsToSell))
{
var cleanItemName = rgx.Replace(item, string.Empty);
var goldAmount = mob.itemsToSell.FirstOrDefault(x => x.name.Equals(cleanItemName)).Gold;
if (goldAmount <= 0)
{
goldAmount = 10;
}
itemsForSell += "<tr><td>" + item + "</td> <td>" + (int)(goldAmount + (goldAmount * 0.15)) + " GP</td></tr>";
}
itemsForSell += "</tbody></table>";
}
else
{
HubContext.Instance.SendToClient("<span class='sayColor'>" + mob.Name + "says, \"Sorry I have nothing to sell you.\"</span>", player.HubGuid);
return;
}
//e.g Yes sure here are my wares.
HubContext.Instance.SendToClient("<span class='sayColor'>" + mob.Name + " says to you \"" + mob.sellerMessage + "\"</span>", player.HubGuid);
//show player items
HubContext.Instance.SendToClient(itemsForSell, player.HubGuid);
}
else
{
HubContext.Instance.SendToClient("There is no merchant here", player.HubGuid);
}
}
public static void buyItems(PlayerSetup.Player player, Room.Room room, string itemName)
{
var mob = room.mobs.FirstOrDefault(x => x.Shop.Equals(true));
if (mob != null)
{
if (mob.Shop)
{
if (string.IsNullOrEmpty(itemName))
{
HubContext.Instance.SendToClient("Buy? Buy what?", player.HubGuid);
return;
}
var itemToBuy = mob.itemsToSell.FirstOrDefault(x => x.name.ToLower().Contains(itemName.ToLower()));
if (itemToBuy != null)
{
var result = AvsAnLib.AvsAn.Query(itemToBuy.name);
string article = result.Article;
//Can afford
var cost = itemToBuy.Gold + itemToBuy.Gold * 0.15;
if (player.Gold >= cost)
{
itemToBuy.location = Item.Item.ItemLocation.Inventory;
PlayerSetup.Player.AddItem(player,itemToBuy);
HubContext.Instance.SendToClient(
"You buy " + article + " " + itemToBuy.name + " from " + mob.Name + " for " + cost + " gold.",
player.HubGuid);
foreach (var character in room.players)
{
if (player != character)
{
var hisOrHer = Helpers.ReturnHisOrHers(player, character);
var roomMessage = $"{ Helpers.ReturnName(player, character, string.Empty)} buys {article} {itemToBuy.name} from {mob.Name}";
HubContext.Instance.SendToClient(roomMessage, character.HubGuid);
}
}
if (!itemToBuy.infinite)
{
mob.itemsToSell.Remove(itemToBuy);
}
foreach (var item in mob.itemsToSell.Where(x => x.name.Equals(itemToBuy.name)))
{
item.Gold = itemToBuy.Gold > 0 ? itemToBuy.Gold : 10;
}
Score.UpdateUiInventory(player);
//deduct gold
var value = itemToBuy.Gold > 0 ? itemToBuy.Gold : 10;
player.Gold -= value;
Score.ReturnScoreUI(player);
}
else
{
HubContext.Instance.SendToClient("You can't afford " + article + " " + itemToBuy.name, player.HubGuid);
}
}
else
{
HubContext.Instance.SendToClient("I don't have that item.", player.HubGuid);
}
}
else
{
HubContext.Instance.SendToClient("<span class='sayColor'>" + mob.Name + " says to you \"Sorry I don't sell that\"", player.HubGuid);
}
}
}
public static void sellItems(PlayerSetup.Player player, Room.Room room, string itemName)
{
var mob = room.mobs.FirstOrDefault(x => x.Shop.Equals(true));
if (mob != null)
{
if (mob.Shop)
{
if (string.IsNullOrEmpty(itemName))
{
HubContext.Instance.SendToClient("Sell? Sell what?", player.HubGuid);
return;
}
var itemToSell = player.Inventory.FirstOrDefault(x => x.name.ToLower().Contains(itemName.ToLower()));
if (itemToSell != null)
{
var oldPlayerInfo = player;
var result = AvsAnLib.AvsAn.Query(itemToSell.name);
string article = result.Article;
//Can afford
itemToSell.location = Item.Item.ItemLocation.Inventory;
mob.itemsToSell.Add(itemToSell);
var value = itemToSell.Gold > 0 ? itemToSell.Gold : 1;
player.Gold += value;
foreach (var character in room.players)
{
if (player != character)
{
var hisOrHer = Helpers.ReturnHisOrHers(player, character);
var roomMessage = $"{ Helpers.ReturnName(player, character, string.Empty)} sells {article} {itemToSell.name} to {mob.Name}.";
HubContext.Instance.SendToClient(roomMessage, character.HubGuid);
}
}
HubContext.Instance.SendToClient(
"You sell " + article + " " + itemToSell.name + " to " + mob.Name + " for " + value + " gold.",
player.HubGuid);
PlayerSetup.Player.RemoveItem(player, itemToSell, Item.Item.ItemLocation.Inventory);
Cache.updatePlayer(oldPlayerInfo, player);
Score.UpdateUiInventory(player);
}
else
{
HubContext.Instance.SendToClient("You don't have that item.", player.HubGuid);
}
}
else
{
HubContext.Instance.SendToClient("<span class='sayColor'>" + mob.Name + " says to you \"Sorry I don't want to buy anything.\"", player.HubGuid);
}
}
}
}
} | 36.808511 | 165 | 0.413295 | [
"MIT"
] | LiamKenneth/ArchaicQuest | MIMWebClient/Core/Mob/Events/Shop.cs | 8,652 | C# |
[ComVisibleAttribute] // RVA: 0xAE1D0 Offset: 0xAE2D1 VA: 0xAE1D0
[Serializable]
public class CustomAttributeFormatException : FormatException // TypeDefIndex: 574
{
// Methods
// RVA: 0x195D7C0 Offset: 0x195D8C1 VA: 0x195D7C0
public void .ctor() { }
// RVA: 0x195D820 Offset: 0x195D921 VA: 0x195D820
public void .ctor(string message) { }
// RVA: 0x195D830 Offset: 0x195D931 VA: 0x195D830
protected void .ctor(SerializationInfo info, StreamingContext context) { }
}
| 28.058824 | 82 | 0.748428 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | System/Reflection/CustomAttributeFormatException.cs | 477 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BlazorProducts.Server.ChartDataProvider;
using BlazorProducts.Server.Context;
using BlazorProducts.Server.HubConfig;
using BlazorProducts.Server.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace BlazorProducts.Server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(policy =>
{
policy.AddPolicy("CorsPolicy", opt => opt
.WithOrigins("https://localhost:5001")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
});
services.AddDbContext<ProductContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("sqlConnection")));
services.AddScoped<IProductRepository, ProductRepository>();
services.AddSignalR();
services.AddSingleton<TimerManager>();
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ChartHub>("/chart");
});
}
}
}
| 30.197368 | 127 | 0.644009 | [
"MIT"
] | CodeMazeBlog/blazor-wasm-signalr-charts | End/BlazorProducts.Server/BlazorProducts.Server/Startup.cs | 2,295 | 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("SortArrayOfNumbersUsingSelectionSort")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SortArrayOfNumbersUsingSelectionSort")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d1740d64-21e9-4db5-a621-bfecc83bd495")]
// 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")]
| 39.054054 | 84 | 0.753633 | [
"MIT"
] | LPetrova/CSharpAdvance | ArraysListsStacksQueuesHomework/SortArrayOfNumbersUsingSelectionSort/Properties/AssemblyInfo.cs | 1,448 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the frauddetector-2019-11-15.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.FraudDetector.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.FraudDetector.Model.Internal.MarshallTransformations
{
/// <summary>
/// CreateRule Request Marshaller
/// </summary>
public class CreateRuleRequestMarshaller : IMarshaller<IRequest, CreateRuleRequest> , 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((CreateRuleRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(CreateRuleRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.FraudDetector");
string target = "AWSHawksNestServiceFacade.CreateRule";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-11-15";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetDescription())
{
context.Writer.WritePropertyName("description");
context.Writer.Write(publicRequest.Description);
}
if(publicRequest.IsSetDetectorId())
{
context.Writer.WritePropertyName("detectorId");
context.Writer.Write(publicRequest.DetectorId);
}
if(publicRequest.IsSetExpression())
{
context.Writer.WritePropertyName("expression");
context.Writer.Write(publicRequest.Expression);
}
if(publicRequest.IsSetLanguage())
{
context.Writer.WritePropertyName("language");
context.Writer.Write(publicRequest.Language);
}
if(publicRequest.IsSetOutcomes())
{
context.Writer.WritePropertyName("outcomes");
context.Writer.WriteArrayStart();
foreach(var publicRequestOutcomesListValue in publicRequest.Outcomes)
{
context.Writer.Write(publicRequestOutcomesListValue);
}
context.Writer.WriteArrayEnd();
}
if(publicRequest.IsSetRuleId())
{
context.Writer.WritePropertyName("ruleId");
context.Writer.Write(publicRequest.RuleId);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static CreateRuleRequestMarshaller _instance = new CreateRuleRequestMarshaller();
internal static CreateRuleRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CreateRuleRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.957143 | 135 | 0.589392 | [
"Apache-2.0"
] | JeffAshton/aws-sdk-net | sdk/src/Services/FraudDetector/Generated/Model/Internal/MarshallTransformations/CreateRuleRequestMarshaller.cs | 5,034 | 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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.CommandLineUtils;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
{
public class StaticWebAssetsIntegrationTest : MSBuildIntegrationTestBase, IClassFixture<BuildServerTestFixture>
{
public StaticWebAssetsIntegrationTest(
BuildServerTestFixture buildServer,
ITestOutputHelper output)
: base(buildServer)
{
Output = output;
}
public ITestOutputHelper Output { get; private set; }
[Fact]
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/22049")]
[InitializeTestProject("AppWithPackageAndP2PReference", language: "C#", additionalProjects: new[] { "ClassLibrary", "ClassLibrary2" })]
public async Task Build_GeneratesStaticWebAssetsManifest_Success_CreatesManifest()
{
var result = await DotnetMSBuild("Build");
var expectedManifest = GetExpectedManifest();
Assert.BuildPassed(result);
// GenerateStaticWebAssetsManifest should generate the manifest and the cache.
Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "AppWithPackageAndP2PReference.StaticWebAssets.xml");
Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "AppWithPackageAndP2PReference.StaticWebAssets.Manifest.cache");
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// Skip this check on mac as the CI seems to use a somewhat different path on OSX.
// This check works just fine on a local OSX instance, but the CI path seems to require prepending /private.
// There is nothing OS specific about publishing this file, so the chances of this breaking are infinitesimal.
Assert.FileExists(result, OutputPath, "AppWithPackageAndP2PReference.StaticWebAssets.xml");
}
var path = Assert.FileExists(result, OutputPath, "AppWithPackageAndP2PReference.dll");
var manifest = Assert.FileExists(result, OutputPath, "AppWithPackageAndP2PReference.StaticWebAssets.xml");
var data = File.ReadAllText(manifest);
Assert.Equal(expectedManifest, data);
}
[Fact]
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/22049")]
[InitializeTestProject("AppWithPackageAndP2PReference", additionalProjects: new[] { "ClassLibrary", "ClassLibrary2" })]
public async Task Publish_CopiesStaticWebAssetsToDestinationFolder()
{
var result = await DotnetMSBuild("Publish");
Assert.BuildPassed(result);
Assert.FileExists(result, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary", "js", "project-transitive-dep.js"));
Assert.FileExists(result, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary", "js", "project-transitive-dep.v4.js"));
Assert.FileExists(result, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary2", "css", "site.css"));
Assert.FileExists(result, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary2", "js", "project-direct-dep.js"));
Assert.FileExists(result, PublishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryDirectDependency", "css", "site.css"));
Assert.FileExists(result, PublishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryDirectDependency", "js", "pkg-direct-dep.js"));
Assert.FileExists(result, PublishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryTransitiveDependency", "js", "pkg-transitive-dep.js"));
// Validate that static web assets don't get published as content too on their regular path
Assert.FileDoesNotExist(result, PublishOutputPath, Path.Combine("wwwroot", "js", "project-transitive-dep.js"));
Assert.FileDoesNotExist(result, PublishOutputPath, Path.Combine("wwwroot", "js", "project-transitive-dep.v4.js"));
// Validate that the manifest never gets copied
Assert.FileDoesNotExist(result, PublishOutputPath, "AppWithPackageAndP2PReference.StaticWebAssets.xml");
}
[ConditionalFact]
[OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
[InitializeTestProject("AppWithPackageAndP2PReferenceAndRID", additionalProjects: new[] { "ClassLibrary", "ClassLibrary2" })]
public async Task Publish_CopiesStaticWebAssetsToDestinationFolder_PublishSingleFile()
{
var result = await DotnetMSBuild("Publish", $"/restore /p:PublishSingleFile=true /p:ReferenceLocallyBuiltPackages=true");
Assert.BuildPassed(result);
var publishOutputPath = GetRidSpecificPublishOutputPath("win-x64");
Assert.FileExists(result, publishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary", "js", "project-transitive-dep.js"));
Assert.FileExists(result, publishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary", "js", "project-transitive-dep.v4.js"));
Assert.FileExists(result, publishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary2", "css", "site.css"));
Assert.FileExists(result, publishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary2", "js", "project-direct-dep.js"));
Assert.FileExists(result, publishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryDirectDependency", "css", "site.css"));
Assert.FileExists(result, publishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryDirectDependency", "js", "pkg-direct-dep.js"));
Assert.FileExists(result, publishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryTransitiveDependency", "js", "pkg-transitive-dep.js"));
// Validate that static web assets don't get published as content too on their regular path
Assert.FileDoesNotExist(result, publishOutputPath, Path.Combine("wwwroot", "js", "project-transitive-dep.js"));
Assert.FileDoesNotExist(result, publishOutputPath, Path.Combine("wwwroot", "js", "project-transitive-dep.v4.js"));
// Validate that the manifest never gets copied
Assert.FileDoesNotExist(result, publishOutputPath, "AppWithPackageAndP2PReference.StaticWebAssets.xml");
}
[Fact]
[QuarantinedTest]
[InitializeTestProject("AppWithPackageAndP2PReference", additionalProjects: new[] { "ClassLibrary", "ClassLibrary2" })]
public async Task Publish_WithBuildReferencesDisabled_CopiesStaticWebAssetsToDestinationFolder()
{
var build = await DotnetMSBuild("Build");
Assert.BuildPassed(build);
var publish = await DotnetMSBuild("Publish", "/p:BuildProjectReferences=false");
Assert.BuildPassed(publish);
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary", "js", "project-transitive-dep.js"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary", "js", "project-transitive-dep.v4.js"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary2", "css", "site.css"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary2", "js", "project-direct-dep.js"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryDirectDependency", "css", "site.css"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryDirectDependency", "js", "pkg-direct-dep.js"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryTransitiveDependency", "js", "pkg-transitive-dep.js"));
}
[Fact]
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/22049")]
[InitializeTestProject("AppWithPackageAndP2PReference", additionalProjects: new[] { "ClassLibrary", "ClassLibrary2" })]
public async Task Publish_NoBuild_CopiesStaticWebAssetsToDestinationFolder()
{
var build = await DotnetMSBuild("Build");
Assert.BuildPassed(build);
var publish = await DotnetMSBuild("Publish", "/p:NoBuild=true");
Assert.BuildPassed(publish);
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary", "js", "project-transitive-dep.js"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary", "js", "project-transitive-dep.v4.js"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary2", "css", "site.css"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "ClassLibrary2", "js", "project-direct-dep.js"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryDirectDependency", "css", "site.css"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryDirectDependency", "js", "pkg-direct-dep.js"));
Assert.FileExists(publish, PublishOutputPath, Path.Combine("wwwroot", "_content", "PackageLibraryTransitiveDependency", "js", "pkg-transitive-dep.js"));
}
[Fact]
[InitializeTestProject("SimpleMvc")]
public async Task Build_DoesNotEmbedManifestWhen_NoStaticResourcesAvailable()
{
var result = await DotnetMSBuild("Build");
Assert.BuildPassed(result);
// GenerateStaticWebAssetsManifest should generate the manifest and the cache.
Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "SimpleMvc.StaticWebAssets.xml");
Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "SimpleMvc.StaticWebAssets.Manifest.cache");
Assert.FileDoesNotExist(result, OutputPath, "SimpleMvc.StaticWebAssets.xml");
var path = Assert.FileExists(result, OutputPath, "SimpleMvc.dll");
}
[Fact]
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/23756")]
[InitializeTestProject("AppWithPackageAndP2PReference", language: "C#", additionalProjects: new[] { "ClassLibrary", "ClassLibrary2" })]
public async Task Clean_Success_RemovesManifestAndCache()
{
var result = await DotnetMSBuild("Build");
Assert.BuildPassed(result);
// GenerateStaticWebAssetsManifest should generate the manifest and the cache.
Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "AppWithPackageAndP2PReference.StaticWebAssets.xml");
Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "AppWithPackageAndP2PReference.StaticWebAssets.Manifest.cache");
var cleanResult = await DotnetMSBuild("Clean");
Assert.BuildPassed(cleanResult);
// Clean should delete the manifest and the cache.
Assert.FileDoesNotExist(result, IntermediateOutputPath, "staticwebassets", "AppWithPackageAndP2PReference.StaticWebAssets.Manifest.cache");
Assert.FileDoesNotExist(result, IntermediateOutputPath, "staticwebassets", "AppWithPackageAndP2PReference.StaticWebAssets.xml");
}
[Fact]
[QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/22049")]
[InitializeTestProject("AppWithPackageAndP2PReference", language: "C#", additionalProjects: new[] { "ClassLibrary", "ClassLibrary2" })]
public async Task Rebuild_Success_RecreatesManifestAndCache()
{
// Arrange
var result = await DotnetMSBuild("Build");
var expectedManifest = GetExpectedManifest();
Assert.BuildPassed(result);
// GenerateStaticWebAssetsManifest should generate the manifest and the cache.
Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "AppWithPackageAndP2PReference.StaticWebAssets.xml");
Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "AppWithPackageAndP2PReference.StaticWebAssets.Manifest.cache");
var directoryPath = Path.Combine(result.Project.DirectoryPath, IntermediateOutputPath, "staticwebassets");
var thumbPrints = new Dictionary<string, FileThumbPrint>();
var thumbPrintFiles = new[]
{
Path.Combine(directoryPath, "AppWithPackageAndP2PReference.StaticWebAssets.xml"),
Path.Combine(directoryPath, "AppWithPackageAndP2PReference.StaticWebAssets.Manifest.cache"),
};
foreach (var file in thumbPrintFiles)
{
var thumbprint = GetThumbPrint(file);
thumbPrints[file] = thumbprint;
}
// Act
var rebuild = await DotnetMSBuild("Rebuild");
// Assert
Assert.BuildPassed(rebuild);
foreach (var file in thumbPrintFiles)
{
var thumbprint = GetThumbPrint(file);
Assert.NotEqual(thumbPrints[file], thumbprint);
}
var path = Assert.FileExists(result, OutputPath, "AppWithPackageAndP2PReference.dll");
var manifest = Assert.FileExists(result, OutputPath, "AppWithPackageAndP2PReference.StaticWebAssets.xml");
var data = File.ReadAllText(manifest);
Assert.Equal(expectedManifest, data);
}
[Fact]
[InitializeTestProject("AppWithPackageAndP2PReference", language: "C#", additionalProjects: new[] { "ClassLibrary", "ClassLibrary2" })]
public async Task GenerateStaticWebAssetsManifest_IncrementalBuild_ReusesManifest()
{
var result = await DotnetMSBuild("GenerateStaticWebAssetsManifest");
Assert.BuildPassed(result);
// GenerateStaticWebAssetsManifest should generate the manifest and the cache.
Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "AppWithPackageAndP2PReference.StaticWebAssets.xml");
Assert.FileExists(result, IntermediateOutputPath, "staticwebassets", "AppWithPackageAndP2PReference.StaticWebAssets.Manifest.cache");
var directoryPath = Path.Combine(result.Project.DirectoryPath, IntermediateOutputPath, "staticwebassets");
var thumbPrints = new Dictionary<string, FileThumbPrint>();
var thumbPrintFiles = new[]
{
Path.Combine(directoryPath, "AppWithPackageAndP2PReference.StaticWebAssets.xml"),
Path.Combine(directoryPath, "AppWithPackageAndP2PReference.StaticWebAssets.Manifest.cache"),
};
foreach (var file in thumbPrintFiles)
{
var thumbprint = GetThumbPrint(file);
thumbPrints[file] = thumbprint;
}
// Act
var incremental = await DotnetMSBuild("GenerateStaticWebAssetsManifest");
// Assert
Assert.BuildPassed(incremental);
foreach (var file in thumbPrintFiles)
{
var thumbprint = GetThumbPrint(file);
Assert.Equal(thumbPrints[file], thumbprint);
}
}
private string GetExpectedManifest()
{
// We need to do this for Mac as apparently the temp folder in mac is prepended by /private by the os, even though the current user
// can refer to it without the /private prefix. We don't care a lot about the specific path in this test as we will have tests that
// validate the behavior at runtime.
var source = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? $"/private{Project.SolutionPath}" : Project.SolutionPath;
var nugetPackages = Environment.GetEnvironmentVariable("NUGET_PACKAGES");
var restorePath = !string.IsNullOrEmpty(nugetPackages) ?
nugetPackages :
Path.Combine(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Environment.GetEnvironmentVariable("USERPROFILE") : Environment.GetEnvironmentVariable("HOME"),
".nuget",
"packages");
var projects = new[]
{
Path.Combine(restorePath, "packagelibrarytransitivedependency", "1.0.0", "build", "..", "staticwebassets") + Path.DirectorySeparatorChar,
Path.Combine(restorePath, "packagelibrarydirectdependency", "1.0.0", "build", "..", "staticwebassets") + Path.DirectorySeparatorChar,
Path.GetFullPath(Path.Combine(source, "ClassLibrary", "wwwroot")) + Path.DirectorySeparatorChar,
Path.GetFullPath(Path.Combine(source, "ClassLibrary2", "wwwroot")) + Path.DirectorySeparatorChar
};
return $@"<StaticWebAssets Version=""1.0"">
<ContentRoot BasePath=""_content/ClassLibrary"" Path=""{projects[2]}"" />
<ContentRoot BasePath=""_content/ClassLibrary2"" Path=""{projects[3]}"" />
<ContentRoot BasePath=""_content/PackageLibraryDirectDependency"" Path=""{projects[1]}"" />
<ContentRoot BasePath=""_content/PackageLibraryTransitiveDependency"" Path=""{projects[0]}"" />
</StaticWebAssets>";
}
}
}
| 58.187097 | 169 | 0.680397 | [
"Apache-2.0"
] | Blubern/AspNetCore | src/Razor/Microsoft.NET.Sdk.Razor/integrationtests/StaticWebAssetsIntegrationTest.cs | 18,040 | C# |
using System.ComponentModel.DataAnnotations.Schema;
namespace Silk.Core.Data.Entities
{
public enum ExemptionType
{
Role,
User,
Channel
}
public sealed class ExemptionEntity
{
/// <summary>
/// The Id of this exemption.
/// </summary>
public int Id { get; set; }
/// <summary>
/// What this exemtpion covers.
/// </summary>
[Column("exempt_from")]
public string Exemption { get; set; }
/// <summary>
/// What type of exemption this is.
/// </summary>
[Column("type")]
public ExemptionType Type { get; set; }
/// <summary>
/// The target of the exemption.
/// </summary>
[Column("target_id")]
public ulong Target { get; set; }
/// <summary>
/// The guild this exemption applies to.
/// </summary>
[Column("guild_id")]
public ulong Guild { get; set; }
}
} | 19.27907 | 52 | 0.615199 | [
"Apache-2.0"
] | VelvetThePanda/Silk | src/Silk.Core.Data/Entities/ExemptionEntity.cs | 831 | 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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Commands;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Frameworks;
using NuGet.PackageManagement.Utility;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.Packaging.Signing;
using NuGet.ProjectManagement;
using NuGet.ProjectManagement.Projects;
using NuGet.ProjectModel;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using NuGet.Resolver;
using NuGet.Versioning;
namespace NuGet.PackageManagement
{
/// <summary>
/// NuGetPackageManager orchestrates a nuget package operation such as an install or uninstall
/// It is to be called by various NuGet Clients including the custom third-party ones
/// </summary>
public class NuGetPackageManager
{
private IReadOnlyList<SourceRepository> _globalPackageFolderRepositories;
private ISourceRepositoryProvider SourceRepositoryProvider { get; }
private ISolutionManager SolutionManager { get; }
private Configuration.ISettings Settings { get; }
private HashSet<string> _buildIntegratedProjectsUpdateSet;
private DependencyGraphSpec _buildIntegratedProjectsCache;
private RestoreCommandProvidersCache _restoreProviderCache;
public IDeleteOnRestartManager DeleteOnRestartManager { get; }
public FolderNuGetProject PackagesFolderNuGetProject { get; set; }
public SourceRepository PackagesFolderSourceRepository { get; set; }
public IInstallationCompatibility InstallationCompatibility { get; set; }
/// <summary>
/// Event to be raised when batch processing of install/ uninstall packages starts at a project level
/// </summary>
public event EventHandler<PackageProjectEventArgs> BatchStart;
/// <summary>
/// Event to be raised when batch processing of install/ uninstall packages ends at a project level
/// </summary>
public event EventHandler<PackageProjectEventArgs> BatchEnd;
/// <summary>
/// To construct a NuGetPackageManager that does not need a SolutionManager like NuGet.exe
/// </summary>
public NuGetPackageManager(
ISourceRepositoryProvider sourceRepositoryProvider,
ISettings settings,
string packagesFolderPath)
: this(sourceRepositoryProvider, settings, packagesFolderPath, excludeVersion: false)
{
}
public NuGetPackageManager(
ISourceRepositoryProvider sourceRepositoryProvider,
ISettings settings,
string packagesFolderPath,
bool excludeVersion)
{
if (packagesFolderPath == null)
{
throw new ArgumentNullException(nameof(packagesFolderPath));
}
SourceRepositoryProvider = sourceRepositoryProvider ?? throw new ArgumentNullException(nameof(sourceRepositoryProvider));
Settings = settings ?? throw new ArgumentNullException(nameof(settings));
InstallationCompatibility = PackageManagement.InstallationCompatibility.Instance;
InitializePackagesFolderInfo(packagesFolderPath, excludeVersion);
}
/// <summary>
/// To construct a NuGetPackageManager with a mandatory SolutionManager lke VS
/// </summary>
public NuGetPackageManager(
ISourceRepositoryProvider sourceRepositoryProvider,
ISettings settings,
ISolutionManager solutionManager,
IDeleteOnRestartManager deleteOnRestartManager)
: this(sourceRepositoryProvider, settings, solutionManager, deleteOnRestartManager, excludeVersion: false)
{
}
public NuGetPackageManager(
ISourceRepositoryProvider sourceRepositoryProvider,
ISettings settings,
ISolutionManager solutionManager,
IDeleteOnRestartManager deleteOnRestartManager,
bool excludeVersion)
{
SourceRepositoryProvider = sourceRepositoryProvider ?? throw new ArgumentNullException(nameof(sourceRepositoryProvider));
Settings = settings ?? throw new ArgumentNullException(nameof(settings));
SolutionManager = solutionManager ?? throw new ArgumentNullException(nameof(solutionManager));
InstallationCompatibility = PackageManagement.InstallationCompatibility.Instance;
InitializePackagesFolderInfo(PackagesFolderPathUtility.GetPackagesFolderPath(SolutionManager, Settings), excludeVersion);
DeleteOnRestartManager = deleteOnRestartManager ?? throw new ArgumentNullException(nameof(deleteOnRestartManager));
}
/// <summary>
/// SourceRepositories for the user global package folder and all fallback package folders.
/// </summary>
public IReadOnlyList<SourceRepository> GlobalPackageFolderRepositories
{
get
{
if (_globalPackageFolderRepositories == null)
{
var sources = new List<SourceRepository>();
// Read package folders from settings
var pathContext = NuGetPathContext.Create(Settings);
// count = FallbackPackageFolders.Count + 1 for UserPackageFolder
var count = (pathContext.FallbackPackageFolders?.Count() ?? 0) + 1;
var folders = new List<string>(count)
{
pathContext.UserPackageFolder
};
folders.AddRange(pathContext.FallbackPackageFolders);
foreach (var folder in folders)
{
// Create a repo for each folder
var source = SourceRepositoryProvider.CreateRepository(
new PackageSource(folder),
FeedType.FileSystemV3);
sources.Add(source);
}
_globalPackageFolderRepositories = sources;
}
return _globalPackageFolderRepositories;
}
}
private void InitializePackagesFolderInfo(string packagesFolderPath, bool excludeVersion = false)
{
// FileSystemPackagesConfig supports id.version formats, if the version is excluded use the normal v2 format
var feedType = excludeVersion ? FeedType.FileSystemV2 : FeedType.FileSystemPackagesConfig;
var resolver = new PackagePathResolver(packagesFolderPath, !excludeVersion);
PackagesFolderNuGetProject = new FolderNuGetProject(packagesFolderPath, resolver);
// Capturing it locally is important since it allows for the instance to cache packages for the lifetime
// of the closure \ NuGetPackageManager.
PackagesFolderSourceRepository = SourceRepositoryProvider.CreateRepository(
new PackageSource(packagesFolderPath),
feedType);
}
/// <summary>
/// Installs the latest version of the given <paramref name="packageId" /> to NuGetProject
/// <paramref name="nuGetProject" /> <paramref name="resolutionContext" /> and
/// <paramref name="nuGetProjectContext" /> are used in the process.
/// </summary>
public Task InstallPackageAsync(
NuGetProject nuGetProject,
string packageId,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
SourceRepository primarySourceRepository,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
var logger = new LoggerAdapter(nuGetProjectContext);
var downloadContext = new PackageDownloadContext(resolutionContext.SourceCacheContext)
{
ParentId = nuGetProjectContext.OperationId,
ClientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, logger)
};
return InstallPackageAsync(
nuGetProject,
packageId,
resolutionContext,
nuGetProjectContext,
downloadContext,
new List<SourceRepository> { primarySourceRepository },
secondarySources,
token);
}
/// <summary>
/// Installs the latest version of the given <paramref name="packageId" /> to NuGetProject
/// <paramref name="nuGetProject" /> <paramref name="resolutionContext" /> and
/// <paramref name="nuGetProjectContext" /> are used in the process.
/// </summary>
public Task InstallPackageAsync(
NuGetProject nuGetProject,
string packageId,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
PackageDownloadContext downloadContext,
SourceRepository primarySourceRepository,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
return InstallPackageAsync(
nuGetProject,
packageId,
resolutionContext,
nuGetProjectContext,
downloadContext,
new List<SourceRepository> { primarySourceRepository },
secondarySources,
token);
}
/// <summary>
/// Installs the latest version of the given
/// <paramref name="packageId" /> to NuGetProject <paramref name="nuGetProject" />
/// <paramref name="resolutionContext" /> and <paramref name="nuGetProjectContext" /> are used in the process.
/// </summary>
public async Task InstallPackageAsync(NuGetProject nuGetProject, string packageId, ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext, IEnumerable<SourceRepository> primarySources,
IEnumerable<SourceRepository> secondarySources, CancellationToken token)
{
var logger = new LoggerAdapter(nuGetProjectContext);
var downloadContext = new PackageDownloadContext(resolutionContext.SourceCacheContext)
{
ParentId = nuGetProjectContext.OperationId,
ClientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, logger)
};
await InstallPackageAsync(
nuGetProject,
packageId,
resolutionContext,
nuGetProjectContext,
downloadContext,
primarySources,
secondarySources, token);
}
/// <summary>
/// Installs the latest version of the given
/// <paramref name="packageId" /> to NuGetProject <paramref name="nuGetProject" />
/// <paramref name="resolutionContext" /> and <paramref name="nuGetProjectContext" /> are used in the process.
/// </summary>
public async Task InstallPackageAsync(
NuGetProject nuGetProject,
string packageId,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
PackageDownloadContext downloadContext,
IEnumerable<SourceRepository> primarySources,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
var log = new LoggerAdapter(nuGetProjectContext);
// Step-1 : Get latest version for packageId
var resolvedPackage = await GetLatestVersionAsync(
packageId,
nuGetProject,
resolutionContext,
primarySources,
log,
token);
if (resolvedPackage == null || resolvedPackage.LatestVersion == null)
{
throw new InvalidOperationException(string.Format(Strings.NoLatestVersionFound, packageId));
}
// Step-2 : Call InstallPackageAsync(project, packageIdentity)
await InstallPackageAsync(
nuGetProject,
new PackageIdentity(packageId, resolvedPackage.LatestVersion),
resolutionContext,
nuGetProjectContext,
downloadContext,
primarySources,
secondarySources,
token);
}
/// <summary>
/// Installs given <paramref name="packageIdentity" /> to NuGetProject <paramref name="nuGetProject" />
/// <paramref name="resolutionContext" /> and <paramref name="nuGetProjectContext" /> are used in the process.
/// </summary>
public Task InstallPackageAsync(
NuGetProject nuGetProject,
PackageIdentity packageIdentity,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
SourceRepository primarySourceRepository,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
var logger = new LoggerAdapter(nuGetProjectContext);
var downloadContext = new PackageDownloadContext(resolutionContext.SourceCacheContext)
{
ParentId = nuGetProjectContext.OperationId,
ClientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, logger)
};
return InstallPackageAsync(
nuGetProject,
packageIdentity,
resolutionContext,
nuGetProjectContext,
downloadContext,
new List<SourceRepository> { primarySourceRepository },
secondarySources,
token);
}
/// <summary>
/// Installs given <paramref name="packageIdentity" /> to NuGetProject <paramref name="nuGetProject" />
/// <paramref name="resolutionContext" /> and <paramref name="nuGetProjectContext" /> are used in the process.
/// </summary>
public Task InstallPackageAsync(
NuGetProject nuGetProject,
PackageIdentity packageIdentity,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
PackageDownloadContext downloadContext,
SourceRepository primarySourceRepository,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
return InstallPackageAsync(
nuGetProject,
packageIdentity,
resolutionContext,
nuGetProjectContext,
downloadContext,
new List<SourceRepository> { primarySourceRepository },
secondarySources,
token);
}
/// <summary>
/// Installs given <paramref name="packageIdentity" /> to NuGetProject <paramref name="nuGetProject" />
/// <paramref name="resolutionContext" /> and <paramref name="nuGetProjectContext" /> are used in the process.
/// </summary>
public async Task InstallPackageAsync(
NuGetProject nuGetProject,
PackageIdentity packageIdentity,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
IEnumerable<SourceRepository> primarySources,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
var logger = new LoggerAdapter(nuGetProjectContext);
var downloadContext = new PackageDownloadContext(resolutionContext.SourceCacheContext)
{
ParentId = nuGetProjectContext.OperationId,
ClientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, logger)
};
await InstallPackageAsync(
nuGetProject,
packageIdentity,
resolutionContext,
nuGetProjectContext,
downloadContext,
primarySources,
secondarySources,
token);
}
/// <summary>
/// Installs given <paramref name="packageIdentity" /> to NuGetProject <paramref name="nuGetProject" />
/// <paramref name="resolutionContext" /> and <paramref name="nuGetProjectContext" /> are used in the process.
/// </summary>
public async Task InstallPackageAsync(
NuGetProject nuGetProject,
PackageIdentity packageIdentity,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
PackageDownloadContext downloadContext,
IEnumerable<SourceRepository> primarySources,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
ActivityCorrelationId.StartNew();
// Step-1 : Call PreviewInstallPackageAsync to get all the nuGetProjectActions
var nuGetProjectActions = await PreviewInstallPackageAsync(nuGetProject, packageIdentity, resolutionContext,
nuGetProjectContext, primarySources, secondarySources, token);
SetDirectInstall(packageIdentity, nuGetProjectContext);
// Step-2 : Execute all the nuGetProjectActions
await ExecuteNuGetProjectActionsAsync(
nuGetProject,
nuGetProjectActions,
nuGetProjectContext,
downloadContext,
token);
ClearDirectInstall(nuGetProjectContext);
}
public async Task UninstallPackageAsync(NuGetProject nuGetProject, string packageId, UninstallationContext uninstallationContext,
INuGetProjectContext nuGetProjectContext, CancellationToken token)
{
ActivityCorrelationId.StartNew();
// Step-1 : Call PreviewUninstallPackagesAsync to get all the nuGetProjectActions
var nuGetProjectActions = await PreviewUninstallPackageAsync(nuGetProject, packageId, uninstallationContext, nuGetProjectContext, token);
// Step-2 : Execute all the nuGetProjectActions
await ExecuteNuGetProjectActionsAsync(nuGetProject, nuGetProjectActions, nuGetProjectContext, NullSourceCacheContext.Instance, token);
}
/// <summary>
/// Gives the preview as a list of NuGetProjectActions that will be performed to install
/// <paramref name="packageId" /> into <paramref name="nuGetProject" /> <paramref name="resolutionContext" />
/// and <paramref name="nuGetProjectContext" /> are used in the process.
/// </summary>
public Task<IEnumerable<NuGetProjectAction>> PreviewInstallPackageAsync(
NuGetProject nuGetProject,
string packageId,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
SourceRepository primarySourceRepository,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
return PreviewInstallPackageAsync(nuGetProject, packageId, resolutionContext, nuGetProjectContext, new[] { primarySourceRepository }, secondarySources, token);
}
/// <summary>
/// Gives the preview as a list of NuGetProjectActions that will be performed to install
/// <paramref name="packageId" /> into <paramref name="nuGetProject" /> <paramref name="resolutionContext" />
/// and <paramref name="nuGetProjectContext" /> are used in the process.
/// </summary>
public async Task<IEnumerable<NuGetProjectAction>> PreviewInstallPackageAsync(
NuGetProject nuGetProject,
string packageId,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
IEnumerable<SourceRepository> primarySources,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
if (nuGetProject == null)
{
throw new ArgumentNullException(nameof(nuGetProject));
}
if (packageId == null)
{
throw new ArgumentNullException(nameof(packageId));
}
if (resolutionContext == null)
{
throw new ArgumentNullException(nameof(resolutionContext));
}
if (nuGetProjectContext == null)
{
throw new ArgumentNullException(nameof(nuGetProjectContext));
}
var log = new LoggerAdapter(nuGetProjectContext);
// Step-1 : Get latest version for packageId
var resolvedPackage = await GetLatestVersionAsync(
packageId,
nuGetProject,
resolutionContext,
primarySources,
log,
token);
if (resolvedPackage == null || resolvedPackage.LatestVersion == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.UnknownPackage, packageId));
}
var projectInstalledPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token);
var installedPackageReference = projectInstalledPackageReferences.Where(pr => StringComparer.OrdinalIgnoreCase.Equals(pr.PackageIdentity.Id, packageId)).FirstOrDefault();
if (installedPackageReference != null
&& installedPackageReference.PackageIdentity.Version > resolvedPackage.LatestVersion)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.NewerVersionAlreadyReferenced, packageId));
}
// Step-2 : Call InstallPackage(project, packageIdentity)
return await PreviewInstallPackageAsync(nuGetProject, new PackageIdentity(packageId, resolvedPackage.LatestVersion), resolutionContext,
nuGetProjectContext, primarySources, secondarySources, token);
}
public Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesAsync(
IEnumerable<NuGetProject> nuGetProjects,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
IEnumerable<SourceRepository> primarySources,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
return PreviewUpdatePackagesAsync(
packageId: null,
packageIdentities: new List<PackageIdentity>(),
nuGetProjects: nuGetProjects,
resolutionContext: resolutionContext,
nuGetProjectContext: nuGetProjectContext,
primarySources: primarySources,
secondarySources: secondarySources,
token: token);
}
public Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesAsync(
string packageId,
IEnumerable<NuGetProject> nuGetProjects,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
IEnumerable<SourceRepository> primarySources,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
return PreviewUpdatePackagesAsync(
packageId: packageId,
packageIdentities: new List<PackageIdentity>(),
nuGetProjects: nuGetProjects,
resolutionContext: resolutionContext,
nuGetProjectContext: nuGetProjectContext,
primarySources: primarySources,
secondarySources: secondarySources,
token: token);
}
public Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesAsync(
PackageIdentity packageIdentity,
IEnumerable<NuGetProject> nuGetProjects,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
IEnumerable<SourceRepository> primarySources,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
return PreviewUpdatePackagesAsync(
packageId: null,
packageIdentities: new List<PackageIdentity> { packageIdentity },
nuGetProjects: nuGetProjects,
resolutionContext: resolutionContext,
nuGetProjectContext: nuGetProjectContext,
primarySources: primarySources,
secondarySources: secondarySources,
token: token);
}
public Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesAsync(
List<PackageIdentity> packageIdentities,
IEnumerable<NuGetProject> nuGetProjects,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
IEnumerable<SourceRepository> primarySources,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
return PreviewUpdatePackagesAsync(
packageId: null,
packageIdentities: packageIdentities,
nuGetProjects: nuGetProjects,
resolutionContext: resolutionContext,
nuGetProjectContext: nuGetProjectContext,
primarySources: primarySources,
secondarySources: secondarySources,
token: token);
}
private async Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesAsync(
string packageId,
List<PackageIdentity> packageIdentities,
IEnumerable<NuGetProject> nuGetProjects,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
IEnumerable<SourceRepository> primarySources,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
if (nuGetProjects == null)
{
throw new ArgumentNullException(nameof(nuGetProjects));
}
if (resolutionContext == null)
{
throw new ArgumentNullException(nameof(resolutionContext));
}
if (nuGetProjectContext == null)
{
throw new ArgumentNullException(nameof(nuGetProjectContext));
}
if (primarySources == null)
{
throw new ArgumentNullException(nameof(primarySources));
}
if (secondarySources == null)
{
throw new ArgumentNullException(nameof(secondarySources));
}
var maxTasks = 4;
var tasks = new List<Task<IEnumerable<NuGetProjectAction>>>(maxTasks);
var nugetActions = new List<NuGetProjectAction>();
var nuGetProjectList = nuGetProjects.ToList();
var buildIntegratedProjects = nuGetProjectList.OfType<BuildIntegratedNuGetProject>().ToList();
var nonBuildIntegratedProjects = nuGetProjectList.Except(buildIntegratedProjects).ToList();
var shouldFilterProjectsForUpdate = false;
if (packageIdentities.Count > 0)
{
shouldFilterProjectsForUpdate = true;
}
// Update http source cache context MaxAge so that it can always go online to fetch
// latest version of packages.
resolutionContext.SourceCacheContext.MaxAge = DateTimeOffset.UtcNow;
// add tasks for all build integrated projects
foreach (var project in buildIntegratedProjects)
{
var packagesToUpdateInProject = packageIdentities;
var updatedResolutionContext = resolutionContext;
if (shouldFilterProjectsForUpdate)
{
packagesToUpdateInProject = await GetPackagesToUpdateInProjectAsync(project, packageIdentities, token);
if (packagesToUpdateInProject.Count > 0)
{
var includePrerelease = packagesToUpdateInProject.Any(
package => package.Version.IsPrerelease) || resolutionContext.IncludePrerelease;
updatedResolutionContext = new ResolutionContext(
dependencyBehavior: resolutionContext.DependencyBehavior,
includePrelease: includePrerelease,
includeUnlisted: resolutionContext.IncludeUnlisted,
versionConstraints: resolutionContext.VersionConstraints,
gatherCache: resolutionContext.GatherCache,
sourceCacheContext: resolutionContext.SourceCacheContext);
}
else
{
// skip running update preview for this project, since it doesn't have any package installed
// which is being updated.
continue;
}
}
// if tasks count reachs max then wait until an existing task is completed
if (tasks.Count >= maxTasks)
{
var actions = await CompleteTaskAsync(tasks);
nugetActions.AddRange(actions);
}
// project.json based projects are handled here
tasks.Add(Task.Run(async ()
=> await PreviewUpdatePackagesForBuildIntegratedAsync(
packageId,
packagesToUpdateInProject,
project,
updatedResolutionContext,
nuGetProjectContext,
primarySources,
token)));
}
// Wait for all restores to finish
var allActions = await Task.WhenAll(tasks);
nugetActions.AddRange(allActions.SelectMany(action => action));
foreach (var project in nonBuildIntegratedProjects)
{
var packagesToUpdateInProject = packageIdentities;
var updatedResolutionContext = resolutionContext;
if (shouldFilterProjectsForUpdate)
{
packagesToUpdateInProject = await GetPackagesToUpdateInProjectAsync(project, packageIdentities, token);
if (packagesToUpdateInProject.Count > 0)
{
var includePrerelease = packagesToUpdateInProject.Any(
package => package.HasVersion && package.Version.IsPrerelease) || resolutionContext.IncludePrerelease;
updatedResolutionContext = new ResolutionContext(
dependencyBehavior: resolutionContext.DependencyBehavior,
includePrelease: includePrerelease,
includeUnlisted: resolutionContext.IncludeUnlisted,
versionConstraints: resolutionContext.VersionConstraints,
gatherCache: resolutionContext.GatherCache,
sourceCacheContext: resolutionContext.SourceCacheContext);
}
else
{
// skip running update preview for this project, since it doesn't have any package installed
// which is being updated.
continue;
}
}
// packages.config based projects are handled here
nugetActions.AddRange(await PreviewUpdatePackagesForClassicAsync(
packageId,
packagesToUpdateInProject,
project,
updatedResolutionContext,
nuGetProjectContext,
primarySources,
secondarySources,
token));
}
return nugetActions;
}
private async Task<List<PackageIdentity>> GetPackagesToUpdateInProjectAsync(
NuGetProject project,
List<PackageIdentity> packages,
CancellationToken token)
{
var installedPackages = await project.GetInstalledPackagesAsync(token);
var packageIds = new HashSet<string>(
installedPackages.Select(p => p.PackageIdentity.Id), StringComparer.OrdinalIgnoreCase);
// We need to filter out packages from packagesToUpdate that are not installed
// in the current project. Otherwise, we'll incorrectly install a
// package that is not installed before.
var packagesToUpdateInProject = packages.Where(
package => packageIds.Contains(package.Id)).ToList();
return packagesToUpdateInProject;
}
private async Task<IEnumerable<T>> CompleteTaskAsync<T>(
List<Task<IEnumerable<T>>> updateTasks)
{
var doneTask = await Task.WhenAny(updateTasks);
updateTasks.Remove(doneTask);
return await doneTask;
}
/// <summary>
/// Update Package logic specific to build integrated style NuGet projects
/// </summary>
private async Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesForBuildIntegratedAsync(
string packageId,
IReadOnlyList<PackageIdentity> packageIdentities,
NuGetProject nuGetProject,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
IEnumerable<SourceRepository> primarySources,
CancellationToken token)
{
var projectInstalledPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token);
if (!nuGetProject.TryGetMetadata(NuGetProjectMetadataKeys.TargetFramework, out NuGetFramework framework))
{
// Default to the any framework if the project does not specify a framework.
framework = NuGetFramework.AnyFramework;
}
var log = new LoggerAdapter(nuGetProjectContext);
var actions = new List<NuGetProjectAction>();
if (packageIdentities.Count == 0 && packageId == null)
{
// Update-Package all
//TODO: need to consider whether Update ALL simply does nothing for Build Integrated projects
var lowLevelActions = new List<NuGetProjectAction>();
foreach (var installedPackage in projectInstalledPackageReferences)
{
// Skip auto referenced packages during update all.
var autoReferenced = IsPackageReferenceAutoReferenced(installedPackage);
if (!autoReferenced)
{
var resolvedPackage = await GetLatestVersionAsync(
installedPackage,
framework,
resolutionContext,
primarySources,
log,
token);
if (resolvedPackage != null && resolvedPackage.LatestVersion != null && resolvedPackage.LatestVersion > installedPackage.PackageIdentity.Version)
{
lowLevelActions.Add(NuGetProjectAction.CreateInstallProjectAction(
new PackageIdentity(installedPackage.PackageIdentity.Id, resolvedPackage.LatestVersion),
primarySources.FirstOrDefault(),
nuGetProject));
}
}
}
// If the update operation is a no-op there will be no project actions.
if (lowLevelActions.Any())
{
var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;
if (buildIntegratedProject != null)
{
// Create a build integrated action
var buildIntegratedAction =
await PreviewBuildIntegratedProjectActionsAsync(buildIntegratedProject, lowLevelActions, nuGetProjectContext, token);
actions.Add(buildIntegratedAction);
}
else
{
// Use the low level actions for projectK
actions = lowLevelActions;
}
}
}
else
{
// either we have a packageId or a list of specific PackageIdentities to work with
// first lets normalize this input so we are just dealing with a list
if (packageIdentities.Count == 0)
{
var installedPackageReference = projectInstalledPackageReferences
.FirstOrDefault(pr => StringComparer.OrdinalIgnoreCase.Equals(pr.PackageIdentity.Id, packageId));
// Skip autoreferenced update when we have only a package ID.
var autoReferenced = IsPackageReferenceAutoReferenced(installedPackageReference);
if (installedPackageReference != null && !autoReferenced)
{
var resolvedPackage = await GetLatestVersionAsync(
installedPackageReference,
framework,
resolutionContext,
primarySources,
log,
token);
if (resolvedPackage == null || !resolvedPackage.Exists)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.UnknownPackage, packageId));
}
else if (resolvedPackage.LatestVersion != null)
{
if (installedPackageReference.PackageIdentity.Version > resolvedPackage.LatestVersion)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
Strings.NewerVersionAlreadyReferenced, packageId));
}
else if (installedPackageReference.PackageIdentity.Version < resolvedPackage.LatestVersion)
{
// The same instance of packageIdentities might be used by multiple tasks in parallel,
// so it's unsafe to modify, hence which it's IReadOnlyList and not just List.
// Therefore, treat the list as immutable (need a new instance with changes).
packageIdentities = packageIdentities.Concat(new[] { new PackageIdentity(packageId, resolvedPackage.LatestVersion) }).ToList();
}
}
}
}
// process the list of PackageIdentities
var lowLevelActions = new List<NuGetProjectAction>();
foreach (var packageIdentity in packageIdentities)
{
var installed = projectInstalledPackageReferences
.Where(pr => StringComparer.OrdinalIgnoreCase.Equals(pr.PackageIdentity.Id, packageIdentity.Id))
.FirstOrDefault();
var autoReferenced = IsPackageReferenceAutoReferenced(installed);
// if the package is not currently installed, or the installed one is auto referenced ignore it
if (installed != null && !autoReferenced)
{
lowLevelActions.Add(NuGetProjectAction.CreateInstallProjectAction(packageIdentity,
primarySources.FirstOrDefault(), nuGetProject));
}
}
if (lowLevelActions.Count > 0)
{
var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;
if (buildIntegratedProject != null)
{
// Create a build integrated action
var buildIntegratedAction = await PreviewBuildIntegratedProjectActionsAsync(
buildIntegratedProject,
lowLevelActions,
nuGetProjectContext,
token);
actions.Add(buildIntegratedAction);
}
else
{
// Use the low level actions for projectK
actions.AddRange(lowLevelActions);
}
}
}
if (actions.Count == 0)
{
var projectName = NuGetProject.GetUniqueNameOrName(nuGetProject);
nuGetProjectContext.Log(MessageLevel.Info, Strings.NoPackageUpdates, projectName);
}
return actions;
}
private static bool IsPackageReferenceAutoReferenced(PackageReference package)
{
var buildPackageReference = package as BuildIntegratedPackageReference;
return buildPackageReference?.Dependency?.AutoReferenced == true;
}
/// <summary>
/// Update Package logic specific to classic style NuGet projects
/// </summary>
private async Task<IEnumerable<NuGetProjectAction>> PreviewUpdatePackagesForClassicAsync(
string packageId,
IReadOnlyList<PackageIdentity> packageIdentities,
NuGetProject nuGetProject,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
IEnumerable<SourceRepository> primarySources,
IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
var log = new LoggerAdapter(nuGetProjectContext);
var stopWatch = Stopwatch.StartNew();
var projectInstalledPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token);
var oldListOfInstalledPackages = projectInstalledPackageReferences.Select(p => p.PackageIdentity);
var isUpdateAll = (packageId == null && packageIdentities.Count == 0);
var preferredVersions = new Dictionary<string, PackageIdentity>(StringComparer.OrdinalIgnoreCase);
// By default we start by preferring everything we already have installed
foreach (var installedPackage in oldListOfInstalledPackages)
{
preferredVersions[installedPackage.Id] = installedPackage;
}
var primaryTargetIds = new List<string>();
var primaryTargets = new List<PackageIdentity>();
// We have been given the exact PackageIdentities (id and version) to update to e.g. from PMC update-package -Id <id> -Version <version>
if (packageIdentities.Count > 0)
{
// If we have been given explicit PackageIdentities to install then we will naturally prefer that
foreach (var packageIdentity in packageIdentities)
{
// Just a check to make sure the preferredVersions created from the existing package list actually contains the target
if (preferredVersions.ContainsKey(packageIdentity.Id))
{
primaryTargetIds.Add(packageIdentity.Id);
// If there was a version specified we will prefer that version
if (packageIdentity.HasVersion)
{
preferredVersions[packageIdentity.Id] = packageIdentity;
((List<PackageIdentity>)primaryTargets).Add(packageIdentity);
}
// Otherwise we just have the Id and so we wil explicitly not prefer the one currently installed
else
{
preferredVersions.Remove(packageIdentity.Id);
}
}
}
}
// We have just been given the package id, in which case we will look for the highest version and attempt to move to that
else if (packageId != null)
{
if (preferredVersions.ContainsKey(packageId))
{
if (PrunePackageTree.IsExactVersion(resolutionContext.VersionConstraints))
{
primaryTargets = new List<PackageIdentity> { preferredVersions[packageId] };
}
else
{
primaryTargetIds = new List<string> { packageId };
// If we have been given just a package Id we certainly don't want the one installed - pruning will be significant
preferredVersions.Remove(packageId);
}
}
else
{
// This is the scenario where a specific package is being updated in a project with a -reinstall flag and the -projectname has not been specified.
// In this case, NuGet should bail out if the package does not exist in this project instead of re-installing all packages of the project.
// Bug: https://github.com/NuGet/Home/issues/737
return Enumerable.Empty<NuGetProjectAction>();
}
}
// We are apply update logic to the complete project - attempting to resolver all updates together
else
{
primaryTargetIds = projectInstalledPackageReferences.Select(p => p.PackageIdentity.Id).ToList();
// We are performing a global project-wide update - nothing is preferred - again pruning will be significant
preferredVersions.Clear();
}
// Note: resolver needs all the installed packages as targets too. And, metadata should be gathered for the installed packages as well
var packageTargetIdsForResolver = new HashSet<string>(oldListOfInstalledPackages.Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
foreach (var packageIdToInstall in primaryTargetIds)
{
packageTargetIdsForResolver.Add(packageIdToInstall);
}
var projectName = NuGetProject.GetUniqueNameOrName(nuGetProject);
var nuGetProjectActions = new List<NuGetProjectAction>();
if (!packageTargetIdsForResolver.Any())
{
nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Strings.NoPackagesInProject, projectName);
return nuGetProjectActions;
}
try
{
// If any targets are prerelease we should gather with prerelease on and filter afterwards
var includePrereleaseInGather = resolutionContext.IncludePrerelease || (projectInstalledPackageReferences.Any(p => (p.PackageIdentity.HasVersion && p.PackageIdentity.Version.IsPrerelease)));
// Create a modified resolution cache. This should include the same gather cache for multi-project
// operations.
var contextForGather = new ResolutionContext(
resolutionContext.DependencyBehavior,
includePrereleaseInGather,
resolutionContext.IncludeUnlisted,
VersionConstraints.None,
resolutionContext.GatherCache,
resolutionContext.SourceCacheContext);
// Step-1 : Get metadata resources using gatherer
var targetFramework = nuGetProject.GetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework);
nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Environment.NewLine);
nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Strings.AttemptingToGatherDependencyInfoForMultiplePackages, projectName, targetFramework);
var allSources = new List<SourceRepository>(primarySources);
var primarySourcesSet = new HashSet<string>(primarySources.Select(s => s.PackageSource.Source));
foreach (var secondarySource in secondarySources)
{
if (!primarySourcesSet.Contains(secondarySource.PackageSource.Source))
{
allSources.Add(secondarySource);
}
}
// Unless the packageIdentity was explicitly asked for we should remove any potential downgrades
var allowDowngrades = false;
if (packageIdentities.Count == 1)
{
// Get installed package version
var packageTargetsForResolver = new HashSet<PackageIdentity>(oldListOfInstalledPackages, PackageIdentity.Comparer);
var installedPackageWithSameId = packageTargetsForResolver.Where(p => p.Id.Equals(packageIdentities[0].Id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (installedPackageWithSameId != null)
{
if (installedPackageWithSameId.Version > packageIdentities[0].Version)
{
// Looks like the installed package is of higher version than one being installed. So, we take it that downgrade is allowed
allowDowngrades = true;
}
}
}
var gatherContext = new GatherContext()
{
InstalledPackages = oldListOfInstalledPackages.ToList(),
PrimaryTargetIds = primaryTargetIds.ToList(),
PrimaryTargets = primaryTargets.ToList(),
TargetFramework = targetFramework,
PrimarySources = primarySources.ToList(),
AllSources = allSources.ToList(),
PackagesFolderSource = PackagesFolderSourceRepository,
ResolutionContext = resolutionContext,
AllowDowngrades = allowDowngrades,
ProjectContext = nuGetProjectContext,
IsUpdateAll = isUpdateAll
};
var availablePackageDependencyInfoWithSourceSet = await ResolverGather.GatherAsync(gatherContext, token);
// emit gather dependency telemetry event and restart timer
stopWatch.Stop();
var gatherTelemetryEvent = new ActionTelemetryStepEvent(
nuGetProjectContext.OperationId.ToString(),
TelemetryConstants.GatherDependencyStepName,
stopWatch.Elapsed.TotalSeconds);
TelemetryActivity.EmitTelemetryEvent(gatherTelemetryEvent);
stopWatch.Restart();
if (!availablePackageDependencyInfoWithSourceSet.Any())
{
throw new InvalidOperationException(Strings.UnableToGatherDependencyInfoForMultiplePackages);
}
// Update-Package ALL packages scenarios must always include the packages in the current project
// Scenarios include: (1) a package havign been deleted from a feed (2) a source being removed from nuget config (3) an explicitly specified source
if (isUpdateAll)
{
// BUG #1181 VS2015 : Updating from one feed fails for packages from different feed.
var packagesFolderResource = await PackagesFolderSourceRepository.GetResourceAsync<DependencyInfoResource>(token);
var packages = new List<SourcePackageDependencyInfo>();
foreach (var installedPackage in projectInstalledPackageReferences)
{
var packageInfo = await packagesFolderResource.ResolvePackage(installedPackage.PackageIdentity, targetFramework, resolutionContext.SourceCacheContext, log, token);
if (packageInfo != null)
{
availablePackageDependencyInfoWithSourceSet.Add(packageInfo);
}
}
}
// Prune the results down to only what we would allow to be installed
IEnumerable<SourcePackageDependencyInfo> prunedAvailablePackages = availablePackageDependencyInfoWithSourceSet;
if (!resolutionContext.IncludePrerelease)
{
prunedAvailablePackages = PrunePackageTree.PrunePrereleaseExceptAllowed(
prunedAvailablePackages,
oldListOfInstalledPackages,
isUpdateAll);
}
// Prune unlisted versions if IncludeUnlisted flag is not set.
if (!resolutionContext.IncludeUnlisted)
{
prunedAvailablePackages = prunedAvailablePackages.Where(p => p.Listed);
}
// Remove packages that do not meet the constraints specified in the UpdateConstrainst
prunedAvailablePackages = PrunePackageTree.PruneByUpdateConstraints(prunedAvailablePackages, projectInstalledPackageReferences, resolutionContext.VersionConstraints);
// Verify that the target is allowed by packages.config
GatherExceptionHelpers.ThrowIfVersionIsDisallowedByPackagesConfig(primaryTargetIds, projectInstalledPackageReferences, prunedAvailablePackages, log);
// Remove versions that do not satisfy 'allowedVersions' attribute in packages.config, if any
prunedAvailablePackages = PrunePackageTree.PruneDisallowedVersions(prunedAvailablePackages, projectInstalledPackageReferences);
// Remove all but the highest packages that are of the same Id as a specified packageId
if (packageId != null)
{
prunedAvailablePackages = PrunePackageTree.PruneAllButHighest(prunedAvailablePackages, packageId);
// And then verify that the installed package is not already of a higher version - this check here ensures the user get's the right error message
GatherExceptionHelpers.ThrowIfNewerVersionAlreadyReferenced(packageId, projectInstalledPackageReferences, prunedAvailablePackages);
}
// Remove packages that are of the same Id but different version than the primartTargets
prunedAvailablePackages = PrunePackageTree.PruneByPrimaryTargets(prunedAvailablePackages, primaryTargets);
// Unless the packageIdentity was explicitly asked for we should remove any potential downgrades
if (!allowDowngrades)
{
prunedAvailablePackages = PrunePackageTree.PruneDowngrades(prunedAvailablePackages, projectInstalledPackageReferences);
}
// Step-2 : Call PackageResolver.Resolve to get new list of installed packages
var packageResolver = new PackageResolver();
var packageResolverContext = new PackageResolverContext(
resolutionContext.DependencyBehavior,
primaryTargetIds,
packageTargetIdsForResolver,
projectInstalledPackageReferences,
preferredVersions.Values,
prunedAvailablePackages,
SourceRepositoryProvider.GetRepositories().Select(s => s.PackageSource),
log);
nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Strings.AttemptingToResolveDependenciesForMultiplePackages);
var newListOfInstalledPackages = packageResolver.Resolve(packageResolverContext, token);
// emit resolve dependency telemetry event and restart timer
stopWatch.Stop();
var resolveTelemetryEvent = new ActionTelemetryStepEvent(
nuGetProjectContext.OperationId.ToString(),
TelemetryConstants.ResolveDependencyStepName,
stopWatch.Elapsed.TotalSeconds);
TelemetryActivity.EmitTelemetryEvent(resolveTelemetryEvent);
stopWatch.Restart();
if (newListOfInstalledPackages == null)
{
throw new InvalidOperationException(Strings.UnableToResolveDependencyInfoForMultiplePackages);
}
// if we have been asked for exact versions of packages then we should also force the uninstall/install of those packages (this corresponds to a -Reinstall)
var isReinstall = PrunePackageTree.IsExactVersion(resolutionContext.VersionConstraints);
var targetIds = Enumerable.Empty<string>();
if (!isUpdateAll)
{
targetIds = (isReinstall ? primaryTargets.Select(p => p.Id) : primaryTargetIds);
}
var installedPackagesInDependencyOrder = await GetInstalledPackagesInDependencyOrder(nuGetProject, token);
var isDependencyBehaviorIgnore = resolutionContext.DependencyBehavior == DependencyBehavior.Ignore;
nuGetProjectActions = GetProjectActionsForUpdate(
nuGetProject,
newListOfInstalledPackages,
installedPackagesInDependencyOrder,
prunedAvailablePackages,
nuGetProjectContext,
isReinstall,
targetIds,
isDependencyBehaviorIgnore);
// emit resolve actions telemetry event
stopWatch.Stop();
var actionTelemetryEvent = new ActionTelemetryStepEvent(
nuGetProjectContext.OperationId.ToString(),
TelemetryConstants.ResolvedActionsStepName,
stopWatch.Elapsed.TotalSeconds);
TelemetryActivity.EmitTelemetryEvent(actionTelemetryEvent);
if (nuGetProjectActions.Count == 0)
{
nuGetProjectContext.Log(MessageLevel.Info, Strings.ResolutionSuccessfulNoAction);
nuGetProjectContext.Log(MessageLevel.Info, Strings.NoUpdatesAvailable);
}
}
catch (InvalidOperationException)
{
throw;
}
catch (AggregateException aggregateEx)
{
throw new InvalidOperationException(aggregateEx.Message, aggregateEx);
}
catch (Exception ex)
{
if (string.IsNullOrEmpty(ex.Message))
{
throw new InvalidOperationException(Strings.PackagesCouldNotBeInstalled, ex);
}
throw new InvalidOperationException(ex.Message, ex);
}
if (nuGetProjectActions.Count == 0)
{
nuGetProjectContext.Log(MessageLevel.Info, Strings.NoPackageUpdates, projectName);
}
return nuGetProjectActions;
}
/// <summary>
/// The package dependency info for the given project. The project needs to be packages.config, otherwise returns an empty list.
/// </summary>
/// <param name="nuGetProject">The project is question</param>
/// <param name="token">cancellation token</param>
/// <param name="includeUnresolved">Whether to include the unresolved packages. The unresolved packages include packages that are not restored and cannot be found on disk.</param>
/// <returns></returns>
public async Task<IEnumerable<PackageDependencyInfo>> GetInstalledPackagesDependencyInfo(NuGetProject nuGetProject, CancellationToken token, bool includeUnresolved = false)
{
if (nuGetProject is MSBuildNuGetProject)
{
var targetFramework = nuGetProject.GetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework);
var installedPackageIdentities = (await nuGetProject.GetInstalledPackagesAsync(token)).Select(pr => pr.PackageIdentity);
return await GetDependencyInfoFromPackagesFolderAsync(installedPackageIdentities, targetFramework, includeUnresolved);
}
else
{
return Enumerable.Empty<PackageDependencyInfo>();
}
}
/// <summary>
/// Returns all installed packages in order of dependency. Packages with no dependencies come first.
/// </summary>
/// <remarks>Packages with unresolved dependencies are NOT returned since they are not valid.</remarks>
public async Task<IEnumerable<PackageIdentity>> GetInstalledPackagesInDependencyOrder(NuGetProject nuGetProject,
CancellationToken token)
{
var targetFramework = nuGetProject.GetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework);
var installedPackages = await nuGetProject.GetInstalledPackagesAsync(token);
var installedPackageIdentities = installedPackages.Select(pr => pr.PackageIdentity);
var dependencyInfoFromPackagesFolder = await GetDependencyInfoFromPackagesFolderAsync(installedPackageIdentities,
targetFramework);
// dependencyInfoFromPackagesFolder can be null when NuGetProtocolException is thrown
var resolverPackages = dependencyInfoFromPackagesFolder?.Select(package =>
new ResolverPackage(package.Id, package.Version, package.Dependencies, true, false));
// Use the resolver sort to find the order. Packages with no dependencies
// come first, then each package that has satisfied dependencies.
// Packages with missing dependencies will not be returned.
if (resolverPackages != null)
{
return ResolverUtility.TopologicalSort(resolverPackages);
}
return Enumerable.Empty<PackageIdentity>();
}
private static List<NuGetProjectAction> GetProjectActionsForUpdate(
NuGetProject project,
IEnumerable<PackageIdentity> newListOfInstalledPackages,
IEnumerable<PackageIdentity> oldListOfInstalledPackages,
IEnumerable<SourcePackageDependencyInfo> availablePackageDependencyInfoWithSourceSet,
INuGetProjectContext nuGetProjectContext,
bool isReinstall,
IEnumerable<string> targetIds,
bool isDependencyBehaviorIgnore)
{
// Step-3 : Get the list of nuGetProjectActions to perform, install/uninstall on the nugetproject
// based on newPackages obtained in Step-2 and project.GetInstalledPackages
var nuGetProjectActions = new List<NuGetProjectAction>();
nuGetProjectContext.Log(MessageLevel.Info, Strings.ResolvingActionsToInstallOrUpdateMultiplePackages);
// we are reinstalling everything so we just take the ordering directly from the Resolver
var newPackagesToUninstall = oldListOfInstalledPackages;
var newPackagesToInstall = newListOfInstalledPackages;
// we are doing a reinstall of a specific package - we will also want to generate Project Actions for the dependencies
if (isReinstall && targetIds.Any())
{
var packageIdsToReinstall = new HashSet<string>(targetIds, StringComparer.OrdinalIgnoreCase);
// Avoid getting dependencies if dependencyBehavior is set to ignore
if (!isDependencyBehaviorIgnore)
{
packageIdsToReinstall = GetDependencies(targetIds, newListOfInstalledPackages, availablePackageDependencyInfoWithSourceSet);
}
newPackagesToUninstall = oldListOfInstalledPackages.Where(p => packageIdsToReinstall.Contains(p.Id));
newPackagesToInstall = newListOfInstalledPackages.Where(p => packageIdsToReinstall.Contains(p.Id));
}
if (!isReinstall)
{
if (targetIds.Any())
{
// we are targeting a particular package - there is no need therefore to alter other aspects of the project
// specifically an unrelated package may have been force removed in which case we should be happy to leave things that way
// It will get the list of packages which are being uninstalled to get a new version
newPackagesToUninstall = oldListOfInstalledPackages.Where(oldPackage =>
newListOfInstalledPackages.Any(newPackage =>
StringComparer.OrdinalIgnoreCase.Equals(oldPackage.Id, newPackage.Id) && !oldPackage.Version.Equals(newPackage.Version)));
// this will be the new set of target ids which includes current target ids as well as packages which are being updated
//It fixes the issue where we were only getting dependencies for target ids ignoring other packages which are also being updated. #2724
var newTargetIds = new HashSet<string>(newPackagesToUninstall.Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
newTargetIds.AddRange(targetIds);
var allowed = newTargetIds;
// Avoid getting dependencies if dependencyBehavior is set to ignore
if (!isDependencyBehaviorIgnore)
{
// first, we will allow all the dependencies of the package(s) beging targeted
allowed = GetDependencies(newTargetIds, newListOfInstalledPackages, availablePackageDependencyInfoWithSourceSet);
}
// second, any package that is currently in the solution will also be allowed to change
// (note this logically doesn't include packages that have been force uninstalled from the project
// because we wouldn't want to just add those back in)
foreach (var p in oldListOfInstalledPackages)
{
allowed.Add(p.Id);
}
newListOfInstalledPackages = newListOfInstalledPackages.Where(p => allowed.Contains(p.Id));
newPackagesToInstall = newListOfInstalledPackages.Where(p => !oldListOfInstalledPackages.Contains(p));
}
else
{
newPackagesToUninstall = oldListOfInstalledPackages.Where(p => !newListOfInstalledPackages.Contains(p));
newPackagesToInstall = newListOfInstalledPackages.Where(p => !oldListOfInstalledPackages.Contains(p));
}
}
foreach (var newPackageToUninstall in newPackagesToUninstall.Reverse())
{
nuGetProjectActions.Add(NuGetProjectAction.CreateUninstallProjectAction(newPackageToUninstall, project));
}
foreach (var newPackageToInstall in newPackagesToInstall)
{
// find the package match based on identity
var sourceDepInfo = availablePackageDependencyInfoWithSourceSet.Where(p => PackageIdentity.Comparer.Equals(p, newPackageToInstall)).SingleOrDefault();
if (sourceDepInfo == null)
{
// this really should never happen
throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, Strings.PackageNotFound, newPackageToInstall));
}
nuGetProjectActions.Add(NuGetProjectAction.CreateInstallProjectAction(newPackageToInstall, sourceDepInfo.Source, project));
}
return nuGetProjectActions;
}
/// <summary>
/// Filter down the reinstall list to just the ones we need to reinstall (i.e. the dependencies)
/// </summary>
private static HashSet<string> GetDependencies(IEnumerable<string> targetIds, IEnumerable<PackageIdentity> newListOfInstalledPackages, IEnumerable<SourcePackageDependencyInfo> available)
{
var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var targetId in targetIds)
{
CollectDependencies(result, targetId, newListOfInstalledPackages, available, 0);
}
return result;
}
/// <summary>
/// A walk through the dependencies to collect the additional package identities that are involved in the current set of packages to be installed
/// </summary>
private static void CollectDependencies(HashSet<string> result,
string id,
IEnumerable<PackageIdentity> packages,
IEnumerable<SourcePackageDependencyInfo> available, int depth)
{
// check if we've already added dependencies for current id
if (!result.Add(id))
{
return;
}
// we want the exact PackageIdentity for this id
var packageIdentity = packages.FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
if (packageIdentity == null)
{
throw new ArgumentException("packages");
}
// now look up the dependencies of this exact package identity
var sourceDepInfo = available.SingleOrDefault(p => packageIdentity.Equals(p));
if (sourceDepInfo == null)
{
throw new ArgumentException("available");
}
// iterate through all the dependencies and call recursively to collect dependencies
foreach (var dependency in sourceDepInfo.Dependencies)
{
// check we don't fall into an infinite loop caused by bad dependency data in the packages
if (depth < packages.Count())
{
CollectDependencies(result, dependency.Id, packages, available, depth + 1);
}
}
}
/// <summary>
/// Gives the preview as a list of NuGetProjectActions that will be performed to install
/// <paramref name="packageIdentity" /> into <paramref name="nuGetProject" />
/// <paramref name="resolutionContext" /> and <paramref name="nuGetProjectContext" /> are used in the process.
/// </summary>
public async Task<IEnumerable<NuGetProjectAction>> PreviewInstallPackageAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity,
ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext,
SourceRepository primarySourceRepository, IEnumerable<SourceRepository> secondarySources, CancellationToken token)
{
if (nuGetProject is INuGetIntegratedProject)
{
var action = NuGetProjectAction.CreateInstallProjectAction(packageIdentity, primarySourceRepository, nuGetProject);
var actions = new[] { action };
var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;
if (buildIntegratedProject != null)
{
actions = new[] {
await PreviewBuildIntegratedProjectActionsAsync(buildIntegratedProject, actions, nuGetProjectContext, token)
};
}
return actions;
}
var primarySources = new List<SourceRepository> { primarySourceRepository };
return await PreviewInstallPackageAsync(nuGetProject, packageIdentity, resolutionContext,
nuGetProjectContext, primarySources, secondarySources, token);
}
// Preview and return ResolvedActions for many NuGetProjects.
public async Task<IEnumerable<ResolvedAction>> PreviewProjectsInstallPackageAsync(
IReadOnlyCollection<NuGetProject> nuGetProjects,
PackageIdentity packageIdentity,
ResolutionContext resolutionContext,
INuGetProjectContext nuGetProjectContext,
IReadOnlyCollection<SourceRepository> activeSources,
CancellationToken token)
{
if (nuGetProjects == null)
{
throw new ArgumentNullException(nameof(nuGetProjects));
}
if (packageIdentity == null)
{
throw new ArgumentNullException(nameof(packageIdentity));
}
if (resolutionContext == null)
{
throw new ArgumentNullException(nameof(resolutionContext));
}
if (nuGetProjectContext == null)
{
throw new ArgumentNullException(nameof(nuGetProjectContext));
}
if (activeSources == null)
{
throw new ArgumentNullException(nameof(activeSources));
}
if (activeSources.Count == 0)
{
throw new ArgumentException("At least 1 item expected for " + nameof(activeSources));
}
if (packageIdentity.Version == null)
{
throw new ArgumentNullException(nameof(packageIdentity));
}
var results = new List<ResolvedAction>();
// BuildIntegratedNuGetProject type projects are now supports parallel preview action for faster performance.
var buildIntegratedProjectsToUpdate = new List<BuildIntegratedNuGetProject>();
// Currently packages.config projects are not supported are supports parallel previews.
// Here is follow up issue to address it https://github.com/NuGet/Home/issues/9906
var otherTargetProjectsToUpdate = new List<NuGetProject>();
foreach (var proj in nuGetProjects)
{
if (proj is BuildIntegratedNuGetProject buildIntegratedNuGetProject)
{
buildIntegratedProjectsToUpdate.Add(buildIntegratedNuGetProject);
}
else
{
otherTargetProjectsToUpdate.Add(proj);
}
}
if (buildIntegratedProjectsToUpdate.Count != 0)
{
// Run build integrated project preview for all projects at the same time
var resolvedActions = await PreviewBuildIntegratedProjectsActionsAsync(
buildIntegratedProjectsToUpdate,
nugetProjectActionsLookup: null, // no nugetProjectActionsLookup so it'll be derived from packageIdentity and activeSources
packageIdentity,
activeSources,
nuGetProjectContext,
token);
results.AddRange(resolvedActions);
}
foreach (var target in otherTargetProjectsToUpdate)
{
var actions = await PreviewInstallPackageAsync(
target,
packageIdentity,
resolutionContext,
nuGetProjectContext,
activeSources,
null,
token);
results.AddRange(actions.Select(a => new ResolvedAction(target, a)));
}
return results;
}
public async Task<IEnumerable<NuGetProjectAction>> PreviewInstallPackageAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity,
ResolutionContext resolutionContext, INuGetProjectContext nuGetProjectContext,
IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources,
CancellationToken token)
{
if (nuGetProject == null)
{
throw new ArgumentNullException(nameof(nuGetProject));
}
if (packageIdentity == null)
{
throw new ArgumentNullException(nameof(packageIdentity));
}
if (resolutionContext == null)
{
throw new ArgumentNullException(nameof(resolutionContext));
}
if (nuGetProjectContext == null)
{
throw new ArgumentNullException(nameof(nuGetProjectContext));
}
if (primarySources == null)
{
throw new ArgumentNullException(nameof(primarySources));
}
if (secondarySources == null)
{
secondarySources = SourceRepositoryProvider.GetRepositories().Where(e => e.PackageSource.IsEnabled);
}
if (!primarySources.Any())
{
throw new ArgumentException(nameof(primarySources));
}
if (packageIdentity.Version == null)
{
throw new ArgumentNullException("packageIdentity.Version");
}
if (nuGetProject is INuGetIntegratedProject)
{
var action = NuGetProjectAction.CreateInstallProjectAction(packageIdentity, primarySources.First(), nuGetProject);
var actions = new[] { action };
var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;
if (buildIntegratedProject != null)
{
actions = new[] {
await PreviewBuildIntegratedProjectActionsAsync(buildIntegratedProject, actions, nuGetProjectContext, token)
};
}
return actions;
}
var projectName = NuGetProject.GetUniqueNameOrName(nuGetProject);
var stopWatch = Stopwatch.StartNew();
var projectInstalledPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token);
var oldListOfInstalledPackages = projectInstalledPackageReferences.Select(p => p.PackageIdentity);
if (oldListOfInstalledPackages.Any(p => p.Equals(packageIdentity)))
{
var alreadyInstalledMessage = string.Format(Strings.PackageAlreadyExistsInProject, packageIdentity, projectName ?? string.Empty);
throw new InvalidOperationException(alreadyInstalledMessage, new PackageAlreadyInstalledException(alreadyInstalledMessage));
}
var nuGetProjectActions = new List<NuGetProjectAction>();
var effectiveSources = GetEffectiveSources(primarySources, secondarySources);
if (resolutionContext.DependencyBehavior != DependencyBehavior.Ignore)
{
try
{
var downgradeAllowed = false;
var packageTargetsForResolver = new HashSet<PackageIdentity>(oldListOfInstalledPackages, PackageIdentity.Comparer);
// Note: resolver needs all the installed packages as targets too. And, metadata should be gathered for the installed packages as well
var installedPackageWithSameId = packageTargetsForResolver.Where(p => p.Id.Equals(packageIdentity.Id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (installedPackageWithSameId != null)
{
packageTargetsForResolver.Remove(installedPackageWithSameId);
if (installedPackageWithSameId.Version > packageIdentity.Version)
{
// Looks like the installed package is of higher version than one being installed. So, we take it that downgrade is allowed
downgradeAllowed = true;
}
}
packageTargetsForResolver.Add(packageIdentity);
// Step-1 : Get metadata resources using gatherer
var targetFramework = nuGetProject.GetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework);
nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Environment.NewLine);
nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.AttemptingToGatherDependencyInfo, packageIdentity, projectName, targetFramework);
var primaryPackages = new List<PackageIdentity> { packageIdentity };
HashSet<SourcePackageDependencyInfo> availablePackageDependencyInfoWithSourceSet = null;
var gatherContext = new GatherContext()
{
InstalledPackages = oldListOfInstalledPackages.ToList(),
PrimaryTargets = primaryPackages,
TargetFramework = targetFramework,
PrimarySources = primarySources.ToList(),
AllSources = effectiveSources.ToList(),
PackagesFolderSource = PackagesFolderSourceRepository,
ResolutionContext = resolutionContext,
AllowDowngrades = downgradeAllowed,
ProjectContext = nuGetProjectContext
};
availablePackageDependencyInfoWithSourceSet = await ResolverGather.GatherAsync(gatherContext, token);
// emit gather dependency telemetry event and restart timer
stopWatch.Stop();
var gatherTelemetryEvent = new ActionTelemetryStepEvent(
nuGetProjectContext.OperationId.ToString(),
TelemetryConstants.GatherDependencyStepName,
stopWatch.Elapsed.TotalSeconds);
TelemetryActivity.EmitTelemetryEvent(gatherTelemetryEvent);
stopWatch.Restart();
if (!availablePackageDependencyInfoWithSourceSet.Any())
{
throw new InvalidOperationException(string.Format(Strings.UnableToGatherDependencyInfo, packageIdentity));
}
// Prune the results down to only what we would allow to be installed
// Keep only the target package we are trying to install for that Id
var prunedAvailablePackages = PrunePackageTree.RemoveAllVersionsForIdExcept(availablePackageDependencyInfoWithSourceSet, packageIdentity);
if (!downgradeAllowed)
{
prunedAvailablePackages = PrunePackageTree.PruneDowngrades(prunedAvailablePackages, projectInstalledPackageReferences);
}
if (!resolutionContext.IncludePrerelease)
{
prunedAvailablePackages = PrunePackageTree.PrunePreleaseForStableTargets(
prunedAvailablePackages,
packageTargetsForResolver,
new[] { packageIdentity });
}
var log = new LoggerAdapter(nuGetProjectContext);
// Verify that the target is allowed by packages.config
GatherExceptionHelpers.ThrowIfVersionIsDisallowedByPackagesConfig(packageIdentity.Id, projectInstalledPackageReferences, prunedAvailablePackages, log);
// Remove versions that do not satisfy 'allowedVersions' attribute in packages.config, if any
prunedAvailablePackages = PrunePackageTree.PruneDisallowedVersions(prunedAvailablePackages, projectInstalledPackageReferences);
// Step-2 : Call PackageResolver.Resolve to get new list of installed packages
// Note: resolver prefers installed package versions if the satisfy the dependency version constraints
// So, since we want an exact version of a package, create a new list of installed packages where the packageIdentity being installed
// is present after removing the one with the same id
var preferredPackageReferences = new List<PackageReference>(projectInstalledPackageReferences.Where(pr =>
!pr.PackageIdentity.Id.Equals(packageIdentity.Id, StringComparison.OrdinalIgnoreCase)))
{
new PackageReference(packageIdentity, targetFramework)
};
var packageResolverContext = new PackageResolverContext(resolutionContext.DependencyBehavior,
new string[] { packageIdentity.Id },
oldListOfInstalledPackages.Select(package => package.Id),
projectInstalledPackageReferences,
preferredPackageReferences.Select(package => package.PackageIdentity),
prunedAvailablePackages,
SourceRepositoryProvider.GetRepositories().Select(s => s.PackageSource),
log);
nuGetProjectContext.Log(MessageLevel.Info, Strings.AttemptingToResolveDependencies, packageIdentity, resolutionContext.DependencyBehavior);
var packageResolver = new PackageResolver();
var newListOfInstalledPackages = packageResolver.Resolve(packageResolverContext, token);
// emit resolve dependency telemetry event and restart timer
stopWatch.Stop();
var resolveTelemetryEvent = new ActionTelemetryStepEvent(
nuGetProjectContext.OperationId.ToString(),
TelemetryConstants.ResolveDependencyStepName,
stopWatch.Elapsed.TotalSeconds);
TelemetryActivity.EmitTelemetryEvent(resolveTelemetryEvent);
stopWatch.Restart();
if (newListOfInstalledPackages == null)
{
throw new InvalidOperationException(string.Format(Strings.UnableToResolveDependencyInfo, packageIdentity, resolutionContext.DependencyBehavior));
}
// Step-3 : Get the list of nuGetProjectActions to perform, install/uninstall on the nugetproject
// based on newPackages obtained in Step-2 and project.GetInstalledPackages
nuGetProjectContext.Log(MessageLevel.Info, Strings.ResolvingActionsToInstallPackage, packageIdentity);
var newPackagesToUninstall = new List<PackageIdentity>();
foreach (var oldInstalledPackage in oldListOfInstalledPackages)
{
var newPackageWithSameId = newListOfInstalledPackages
.FirstOrDefault(np =>
oldInstalledPackage.Id.Equals(np.Id, StringComparison.OrdinalIgnoreCase) &&
!oldInstalledPackage.Version.Equals(np.Version));
if (newPackageWithSameId != null)
{
newPackagesToUninstall.Add(oldInstalledPackage);
}
}
var newPackagesToInstall = newListOfInstalledPackages.Where(p => !oldListOfInstalledPackages.Contains(p));
foreach (var newPackageToUninstall in newPackagesToUninstall)
{
nuGetProjectActions.Add(NuGetProjectAction.CreateUninstallProjectAction(newPackageToUninstall, nuGetProject));
}
// created hashset of packageIds we are OK with touching
// the scenario here is that the user might have done an uninstall-package -Force on a particular package
// this will be the new set of target ids which includes current target ids as well as packages which are being updated
//It fixes the issue where we were only getting dependencies for target ids ignoring other packages which are also being updated. #2724
var newTargetIds = new HashSet<string>(newPackagesToUninstall.Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
newTargetIds.Add(packageIdentity.Id);
// get all dependencies of new target ids so that we can have all the required install actions.
var allowed = GetDependencies(newTargetIds, newListOfInstalledPackages, prunedAvailablePackages);
foreach (var newPackageToInstall in newPackagesToInstall)
{
// we should limit actions to just packages that are in the dependency set of the target we are installing
if (allowed.Contains(newPackageToInstall.Id))
{
// find the package match based on identity
var sourceDepInfo = prunedAvailablePackages.SingleOrDefault(p => PackageIdentity.Comparer.Equals(p, newPackageToInstall));
if (sourceDepInfo == null)
{
// this really should never happen
throw new InvalidOperationException(string.Format(Strings.PackageNotFound, packageIdentity));
}
nuGetProjectActions.Add(NuGetProjectAction.CreateInstallProjectAction(sourceDepInfo, sourceDepInfo.Source, nuGetProject));
}
}
}
catch (InvalidOperationException)
{
throw;
}
catch (AggregateException aggregateEx)
{
throw new InvalidOperationException(aggregateEx.Message, aggregateEx);
}
catch (Exception ex)
{
if (string.IsNullOrEmpty(ex.Message))
{
throw new InvalidOperationException(string.Format(Strings.PackageCouldNotBeInstalled, packageIdentity), ex);
}
throw new InvalidOperationException(ex.Message, ex);
}
}
else
{
var logger = new ProjectContextLogger(nuGetProjectContext);
var sourceRepository = await GetSourceRepository(packageIdentity, effectiveSources, resolutionContext.SourceCacheContext, logger);
nuGetProjectActions.Add(NuGetProjectAction.CreateInstallProjectAction(packageIdentity, sourceRepository, nuGetProject));
}
// emit resolve actions telemetry event
stopWatch.Stop();
var actionTelemetryEvent = new ActionTelemetryStepEvent(
nuGetProjectContext.OperationId.ToString(),
TelemetryConstants.ResolvedActionsStepName,
stopWatch.Elapsed.TotalSeconds);
TelemetryActivity.EmitTelemetryEvent(actionTelemetryEvent);
nuGetProjectContext.Log(MessageLevel.Info, Strings.ResolvedActionsToInstallPackage, packageIdentity);
return nuGetProjectActions;
}
/// <summary>
/// Check all sources in parallel to see if the package exists while respecting the order of the list.
/// This is only used by PreviewInstall with DependencyBehavior.Ignore.
/// Since, resolver gather is not used when dependencies are not used,
/// we simply get the source repository using MetadataResource.Exists
/// </summary>
private static async Task<SourceRepository> GetSourceRepository(PackageIdentity packageIdentity,
IEnumerable<SourceRepository> sourceRepositories,
SourceCacheContext sourceCacheContext,
ILogger logger)
{
SourceRepository source = null;
// TODO: move this timeout to a better place
// TODO: what should the timeout be?
// Give up after 5 minutes
var tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(5));
var results = new Queue<KeyValuePair<SourceRepository, Task<bool>>>();
foreach (var sourceRepository in sourceRepositories)
{
// TODO: fetch the resource in parallel also
var metadataResource = await sourceRepository.GetResourceAsync<MetadataResource>();
if (metadataResource != null)
{
var task = Task.Run(() => metadataResource.Exists(packageIdentity, sourceCacheContext, logger, tokenSource.Token), tokenSource.Token);
results.Enqueue(new KeyValuePair<SourceRepository, Task<bool>>(sourceRepository, task));
}
}
while (results.Count > 0)
{
var pair = results.Dequeue();
try
{
var exists = await pair.Value;
// take only the first true result, but continue waiting for the remaining cancelled
// tasks to keep things from getting out of control.
if (source == null && exists)
{
source = pair.Key;
// there is no need to finish trying the others
tokenSource.Cancel();
}
}
catch (OperationCanceledException)
{
// ignore these
}
catch (Exception ex)
{
logger.LogWarning(
string.Format(Strings.Warning_ErrorFindingRepository,
pair.Key.PackageSource.Source,
ExceptionUtilities.DisplayMessage(ex)));
}
}
if (source == null)
{
// no matches were found
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
Strings.UnknownPackageSpecificVersion, packageIdentity.Id, packageIdentity.Version));
}
return source;
}
/// <summary>
/// Gives the preview as a list of NuGetProjectActions that will be performed to uninstall
/// <paramref name="packageId" /> into <paramref name="nuGetProject" />
/// <paramref name="uninstallationContext" /> and <paramref name="nuGetProjectContext" /> are used in the
/// process.
/// </summary>
public async Task<IEnumerable<NuGetProjectAction>> PreviewUninstallPackageAsync(NuGetProject nuGetProject, string packageId,
UninstallationContext uninstallationContext, INuGetProjectContext nuGetProjectContext, CancellationToken token)
{
if (nuGetProject == null)
{
throw new ArgumentNullException(nameof(nuGetProject));
}
if (packageId == null)
{
throw new ArgumentNullException(nameof(packageId));
}
if (uninstallationContext == null)
{
throw new ArgumentNullException(nameof(uninstallationContext));
}
if (nuGetProjectContext == null)
{
throw new ArgumentNullException(nameof(nuGetProjectContext));
}
// Step-1: Get the packageIdentity corresponding to packageId and check if it exists to be uninstalled
var installedPackages = await nuGetProject.GetInstalledPackagesAsync(token);
var packageReference = installedPackages.FirstOrDefault(pr => pr.PackageIdentity.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase));
if (packageReference?.PackageIdentity == null)
{
throw new ArgumentException(string.Format(Strings.PackageToBeUninstalledCouldNotBeFound,
packageId, nuGetProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name)));
}
return await PreviewUninstallPackageInternalAsync(nuGetProject, packageReference, uninstallationContext, nuGetProjectContext, token);
}
/// <summary>
/// Gives the preview as a list of <see cref="NuGetProjectAction" /> that will be performed to uninstall
/// <paramref name="packageIdentity" /> into <paramref name="nuGetProject" />
/// <paramref name="uninstallationContext" /> and <paramref name="nuGetProjectContext" /> are used in the
/// process.
/// </summary>
public async Task<IEnumerable<NuGetProjectAction>> PreviewUninstallPackageAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity,
UninstallationContext uninstallationContext, INuGetProjectContext nuGetProjectContext, CancellationToken token)
{
if (nuGetProject == null)
{
throw new ArgumentNullException(nameof(nuGetProject));
}
if (packageIdentity == null)
{
throw new ArgumentNullException(nameof(packageIdentity));
}
if (uninstallationContext == null)
{
throw new ArgumentNullException(nameof(uninstallationContext));
}
if (nuGetProjectContext == null)
{
throw new ArgumentNullException(nameof(nuGetProjectContext));
}
// Step-1: Get the packageIdentity corresponding to packageId and check if it exists to be uninstalled
var installedPackages = await nuGetProject.GetInstalledPackagesAsync(token);
var packageReference = installedPackages.FirstOrDefault(pr => pr.PackageIdentity.Equals(packageIdentity));
if (packageReference?.PackageIdentity == null)
{
throw new ArgumentException(string.Format(Strings.PackageToBeUninstalledCouldNotBeFound,
packageIdentity.Id, nuGetProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name)));
}
return await PreviewUninstallPackageInternalAsync(nuGetProject, packageReference, uninstallationContext, nuGetProjectContext, token);
}
private async Task<IEnumerable<NuGetProjectAction>> PreviewUninstallPackageInternalAsync(NuGetProject nuGetProject, Packaging.PackageReference packageReference,
UninstallationContext uninstallationContext, INuGetProjectContext nuGetProjectContext, CancellationToken token)
{
if (SolutionManager == null)
{
throw new InvalidOperationException(Strings.SolutionManagerNotAvailableForUninstall);
}
if (nuGetProject is INuGetIntegratedProject)
{
var action = NuGetProjectAction.CreateUninstallProjectAction(packageReference.PackageIdentity, nuGetProject);
var actions = new[] { action };
var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;
if (buildIntegratedProject != null)
{
actions = new[] {
await PreviewBuildIntegratedProjectActionsAsync(buildIntegratedProject, actions, nuGetProjectContext, token)
};
}
return actions;
}
// Step-1 : Get the metadata resources from "packages" folder or custom repository path
var packageIdentity = packageReference.PackageIdentity;
var projectName = NuGetProject.GetUniqueNameOrName(nuGetProject);
var packageReferenceTargetFramework = packageReference.TargetFramework;
nuGetProjectContext.Log(NuGet.ProjectManagement.MessageLevel.Info, Environment.NewLine);
nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.AttemptingToGatherDependencyInfo, packageIdentity, projectName, packageReferenceTargetFramework);
// TODO: IncludePrerelease is a big question mark
var log = new LoggerAdapter(nuGetProjectContext);
var installedPackageIdentities = (await nuGetProject.GetInstalledPackagesAsync(token)).Select(pr => pr.PackageIdentity);
var dependencyInfoFromPackagesFolder = await GetDependencyInfoFromPackagesFolderAsync(installedPackageIdentities,
packageReferenceTargetFramework);
nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.ResolvingActionsToUninstallPackage, packageIdentity);
// Step-2 : Determine if the package can be uninstalled based on the metadata resources
var packagesToBeUninstalled = UninstallResolver.GetPackagesToBeUninstalled(packageIdentity, dependencyInfoFromPackagesFolder, installedPackageIdentities, uninstallationContext);
var nuGetProjectActions =
packagesToBeUninstalled.Select(
package => NuGetProjectAction.CreateUninstallProjectAction(package, nuGetProject));
nuGetProjectContext.Log(MessageLevel.Info, Strings.ResolvedActionsToUninstallPackage, packageIdentity);
return nuGetProjectActions;
}
private async Task<IEnumerable<PackageDependencyInfo>> GetDependencyInfoFromPackagesFolderAsync(IEnumerable<PackageIdentity> packageIdentities,
NuGetFramework nuGetFramework,
bool includeUnresolved = false)
{
var dependencyInfoResource = await PackagesFolderSourceRepository.GetResourceAsync<DependencyInfoResource>();
return await PackageGraphAnalysisUtilities.GetDependencyInfoForPackageIdentitiesAsync(packageIdentities, nuGetFramework, dependencyInfoResource, NullSourceCacheContext.Instance, includeUnresolved, NullLogger.Instance, CancellationToken.None);
}
/// <summary>
/// Executes the list of <paramref name="nuGetProjectActions" /> on list of <paramref name="nuGetProjects" /> , which is
/// likely obtained by calling into
/// <see
/// cref="PreviewInstallPackageAsync(IEnumerable{NuGetProject},string,ResolutionContext,INuGetProjectContext,SourceRepository,IEnumerable{SourceRepository},CancellationToken)" />
/// <paramref name="nuGetProjectContext" /> is used in the process.
/// </summary>
public async Task ExecuteNuGetProjectActionsAsync(IEnumerable<NuGetProject> nuGetProjects,
IEnumerable<NuGetProjectAction> nuGetProjectActions,
INuGetProjectContext nuGetProjectContext,
SourceCacheContext sourceCacheContext,
CancellationToken token)
{
var projects = nuGetProjects.ToList();
// find out build integrated projects so that we can arrange them in reverse dependency order
var buildIntegratedProjectsToUpdate = projects.OfType<BuildIntegratedNuGetProject>().ToList();
// order won't matter for other type of projects so just add rest of the projects in result
var sortedProjectsToUpdate = projects.Except(buildIntegratedProjectsToUpdate).ToList();
if (buildIntegratedProjectsToUpdate.Count > 0)
{
var logger = new ProjectContextLogger(nuGetProjectContext);
var referenceContext = new DependencyGraphCacheContext(logger, Settings);
_buildIntegratedProjectsUpdateSet = new HashSet<string>(PathUtility.GetStringComparerBasedOnOS());
var projectUniqueNamesForBuildIntToUpdate
= buildIntegratedProjectsToUpdate.ToDictionary((project) => project.MSBuildProjectPath);
var dgFile = await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(SolutionManager, referenceContext);
_buildIntegratedProjectsCache = dgFile;
var allSortedProjects = DependencyGraphSpec.SortPackagesByDependencyOrder(dgFile.Projects);
// cache these already evaluated(without commit) buildIntegratedProjects project ids which will be used to avoid duplicate restore as part of parent projects
_buildIntegratedProjectsUpdateSet.AddRange(
buildIntegratedProjectsToUpdate.Select(child => child.MSBuildProjectPath));
foreach (var projectUniqueName in allSortedProjects.Select(e => e.RestoreMetadata.ProjectUniqueName))
{
BuildIntegratedNuGetProject project;
if (projectUniqueNamesForBuildIntToUpdate.TryGetValue(projectUniqueName, out project))
{
sortedProjectsToUpdate.Add(project);
}
}
}
// execute all nuget project actions
foreach (var project in sortedProjectsToUpdate)
{
var nugetActions = nuGetProjectActions.Where(action => action.Project.Equals(project));
await ExecuteNuGetProjectActionsAsync(project, nugetActions, nuGetProjectContext, sourceCacheContext, token);
}
// clear cache which could temper with other updates
_buildIntegratedProjectsUpdateSet?.Clear();
_buildIntegratedProjectsCache = null;
_restoreProviderCache = null;
}
/// <summary>
/// Executes the list of <paramref name="nuGetProjectActions" /> on <paramref name="nuGetProject" /> , which is
/// likely obtained by calling into
/// <see
/// cref="PreviewInstallPackageAsync(NuGetProject,string,ResolutionContext,INuGetProjectContext,SourceRepository,IEnumerable{SourceRepository},CancellationToken)" />
/// <paramref name="nuGetProjectContext" /> is used in the process.
/// </summary>
public async Task ExecuteNuGetProjectActionsAsync(NuGetProject nuGetProject,
IEnumerable<NuGetProjectAction> nuGetProjectActions,
INuGetProjectContext nuGetProjectContext,
SourceCacheContext sourceCacheContext,
CancellationToken token)
{
var logger = new LoggerAdapter(nuGetProjectContext);
var downloadContext = new PackageDownloadContext(sourceCacheContext)
{
ParentId = nuGetProjectContext.OperationId,
ClientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, logger)
};
await ExecuteNuGetProjectActionsAsync(nuGetProject,
nuGetProjectActions,
nuGetProjectContext,
downloadContext,
token);
}
/// <summary>
/// Executes the list of <paramref name="nuGetProjectActions" /> on <paramref name="nuGetProject" /> , which is
/// likely obtained by calling into
/// <see
/// cref="PreviewInstallPackageAsync(NuGetProject,string,ResolutionContext,INuGetProjectContext,SourceRepository,IEnumerable{SourceRepository},CancellationToken)" />
/// <paramref name="nuGetProjectContext" /> is used in the process.
/// </summary>
public async Task ExecuteNuGetProjectActionsAsync(NuGetProject nuGetProject,
IEnumerable<NuGetProjectAction> nuGetProjectActions,
INuGetProjectContext nuGetProjectContext,
PackageDownloadContext downloadContext,
CancellationToken token)
{
if (nuGetProject == null)
{
throw new ArgumentNullException(nameof(nuGetProject));
}
if (nuGetProjectActions == null)
{
throw new ArgumentNullException(nameof(nuGetProjectActions));
}
if (nuGetProjectContext == null)
{
throw new ArgumentNullException(nameof(nuGetProjectContext));
}
var stopWatch = Stopwatch.StartNew();
ExceptionDispatchInfo exceptionInfo = null;
// DNU: Find the closure before executing the actions
var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;
if (buildIntegratedProject != null)
{
await ExecuteBuildIntegratedProjectActionsAsync(buildIntegratedProject,
nuGetProjectActions,
nuGetProjectContext,
token);
}
else
{
// Set the original packages config if it exists
var msbuildProject = nuGetProject as MSBuildNuGetProject;
if (msbuildProject != null)
{
nuGetProjectContext.OriginalPackagesConfig =
msbuildProject.PackagesConfigNuGetProject?.GetPackagesConfig();
}
var executedNuGetProjectActions = new Stack<NuGetProjectAction>();
var packageWithDirectoriesToBeDeleted = new HashSet<PackageIdentity>(PackageIdentity.Comparer);
var ideExecutionContext = nuGetProjectContext.ExecutionContext as IDEExecutionContext;
if (ideExecutionContext != null)
{
await ideExecutionContext.SaveExpandedNodeStates(SolutionManager);
}
var logger = new ProjectContextLogger(nuGetProjectContext);
Dictionary<PackageIdentity, PackagePreFetcherResult> downloadTasks = null;
CancellationTokenSource downloadTokenSource = null;
// batch events argument object
PackageProjectEventArgs packageProjectEventArgs = null;
try
{
// PreProcess projects
await nuGetProject.PreProcessAsync(nuGetProjectContext, token);
var actionsList = nuGetProjectActions.ToList();
var hasInstalls = actionsList.Any(action =>
action.NuGetProjectActionType == NuGetProjectActionType.Install);
if (hasInstalls)
{
// Make this independently cancelable.
downloadTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token);
// Download all packages up front in parallel
downloadTasks = await PackagePreFetcher.GetPackagesAsync(
actionsList,
PackagesFolderNuGetProject,
downloadContext,
SettingsUtility.GetGlobalPackagesFolder(Settings),
logger,
downloadTokenSource.Token);
// Log download information
PackagePreFetcher.LogFetchMessages(
downloadTasks.Values,
PackagesFolderNuGetProject.Root,
logger);
}
// raise Nuget batch start event
var batchId = Guid.NewGuid().ToString();
string name;
nuGetProject.TryGetMetadata(NuGetProjectMetadataKeys.Name, out name);
packageProjectEventArgs = new PackageProjectEventArgs(batchId, name);
BatchStart?.Invoke(this, packageProjectEventArgs);
PackageProjectEventsProvider.Instance.NotifyBatchStart(packageProjectEventArgs);
try
{
if (msbuildProject != null)
{
//start batch processing for msbuild
await msbuildProject.ProjectSystem.BeginProcessingAsync();
}
foreach (var nuGetProjectAction in actionsList)
{
if (nuGetProjectAction.NuGetProjectActionType == NuGetProjectActionType.Uninstall)
{
executedNuGetProjectActions.Push(nuGetProjectAction);
await ExecuteUninstallAsync(nuGetProject,
nuGetProjectAction.PackageIdentity,
packageWithDirectoriesToBeDeleted,
nuGetProjectContext, token);
nuGetProjectContext.Log(
ProjectManagement.MessageLevel.Info,
Strings.SuccessfullyUninstalled,
nuGetProjectAction.PackageIdentity,
nuGetProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name));
}
}
}
finally
{
if (msbuildProject != null)
{
// end batch for msbuild and let it save everything.
// always calls it before PostProcessAsync or binding redirects
await msbuildProject.ProjectSystem.EndProcessingAsync();
}
}
try
{
if (msbuildProject != null)
{
//start batch processing for msbuild
await msbuildProject.ProjectSystem.BeginProcessingAsync();
}
foreach (var nuGetProjectAction in actionsList)
{
if (nuGetProjectAction.NuGetProjectActionType == NuGetProjectActionType.Install)
{
executedNuGetProjectActions.Push(nuGetProjectAction);
// Retrieve the downloaded package
// This will wait on the package if it is still downloading
var preFetchResult = downloadTasks[nuGetProjectAction.PackageIdentity];
using (var downloadPackageResult = await preFetchResult.GetResultAsync())
{
// use the version exactly as specified in the nuspec file
var packageIdentity = await downloadPackageResult.PackageReader.GetIdentityAsync(token);
await ExecuteInstallAsync(
nuGetProject,
packageIdentity,
downloadPackageResult,
packageWithDirectoriesToBeDeleted,
nuGetProjectContext,
token);
}
var identityString = string.Format(CultureInfo.InvariantCulture, "{0} {1}",
nuGetProjectAction.PackageIdentity.Id,
nuGetProjectAction.PackageIdentity.Version.ToNormalizedString());
preFetchResult.EmitTelemetryEvent(nuGetProjectContext.OperationId);
nuGetProjectContext.Log(
ProjectManagement.MessageLevel.Info,
Strings.SuccessfullyInstalled,
identityString,
nuGetProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name));
}
}
}
finally
{
if (msbuildProject != null)
{
// end batch for msbuild and let it save everything.
// always calls it before PostProcessAsync or binding redirects
await msbuildProject.ProjectSystem.EndProcessingAsync();
}
}
PackagesConfigLockFileUtility.UpdateLockFile(msbuildProject,
actionsList,
token);
// Post process
await nuGetProject.PostProcessAsync(nuGetProjectContext, token);
// Open readme file
await OpenReadmeFile(nuGetProject, nuGetProjectContext, token);
}
catch (SignatureException ex)
{
var errors = ex.Results.SelectMany(r => r.GetErrorIssues());
var warnings = ex.Results.SelectMany(r => r.GetWarningIssues());
SignatureException unwrappedException = null;
if (errors.Count() == 1)
{
// In case of one error, throw it as the exception
var error = errors.First();
unwrappedException = new SignatureException(error.Code, error.Message, ex.PackageIdentity);
}
else
{
// In case of multiple errors, wrap them in a general NU3000 error
var errorMessage = string.Format(CultureInfo.CurrentCulture,
Strings.SignatureVerificationMultiple,
$"{Environment.NewLine}{string.Join(Environment.NewLine, errors.Select(e => e.FormatWithCode()))}");
unwrappedException = new SignatureException(NuGetLogCode.NU3000, errorMessage, ex.PackageIdentity);
}
foreach (var warning in warnings)
{
nuGetProjectContext.Log(warning);
}
exceptionInfo = ExceptionDispatchInfo.Capture(unwrappedException);
}
catch (Exception ex)
{
exceptionInfo = ExceptionDispatchInfo.Capture(ex);
}
finally
{
if (downloadTasks != null)
{
// Wait for all downloads to cancel and dispose
downloadTokenSource.Cancel();
foreach (var result in downloadTasks.Values)
{
await result.EnsureResultAsync();
result.Dispose();
}
downloadTokenSource.Dispose();
}
if (msbuildProject != null)
{
// raise nuget batch end event
if (packageProjectEventArgs != null)
{
BatchEnd?.Invoke(this, packageProjectEventArgs);
PackageProjectEventsProvider.Instance.NotifyBatchEnd(packageProjectEventArgs);
}
}
}
if (exceptionInfo != null)
{
await RollbackAsync(nuGetProject, executedNuGetProjectActions, packageWithDirectoriesToBeDeleted, nuGetProjectContext, token);
}
if (ideExecutionContext != null)
{
await ideExecutionContext.CollapseAllNodes(SolutionManager);
}
// Delete the package directories as the last step, so that, if an uninstall had to be rolled back, we can just use the package file on the directory
// Also, always perform deletion of package directories, even in a rollback, so that there are no stale package directories
foreach (var packageWithDirectoryToBeDeleted in packageWithDirectoriesToBeDeleted)
{
var packageFolderPath = PackagesFolderNuGetProject.GetInstalledPath(packageWithDirectoryToBeDeleted);
try
{
await DeletePackageAsync(packageWithDirectoryToBeDeleted, nuGetProjectContext, token);
}
finally
{
if (DeleteOnRestartManager != null)
{
if (Directory.Exists(packageFolderPath))
{
DeleteOnRestartManager.MarkPackageDirectoryForDeletion(
packageWithDirectoryToBeDeleted,
packageFolderPath,
nuGetProjectContext);
// Raise the event to notify listners to update the UI etc.
DeleteOnRestartManager.CheckAndRaisePackageDirectoriesMarkedForDeletion();
}
}
}
}
// Save project
await nuGetProject.SaveAsync(token);
// Clear direct install
SetDirectInstall(null, nuGetProjectContext);
}
// calculate total time taken to execute all nuget actions
stopWatch.Stop();
nuGetProjectContext.Log(
MessageLevel.Info, Strings.NugetActionsTotalTime,
DatetimeUtility.ToReadableTimeFormat(stopWatch.Elapsed));
// emit resolve actions telemetry event
var actionTelemetryEvent = new ActionTelemetryStepEvent(
nuGetProjectContext.OperationId.ToString(),
TelemetryConstants.ExecuteActionStepName, stopWatch.Elapsed.TotalSeconds);
TelemetryActivity.EmitTelemetryEvent(actionTelemetryEvent);
if (exceptionInfo != null)
{
exceptionInfo.Throw();
}
}
/// <summary>
/// Run project actions for a build integrated project.
/// </summary>
public async Task<BuildIntegratedProjectAction> PreviewBuildIntegratedProjectActionsAsync(
BuildIntegratedNuGetProject buildIntegratedProject,
IEnumerable<NuGetProjectAction> nuGetProjectActions,
INuGetProjectContext nuGetProjectContext,
CancellationToken token)
{
if (nuGetProjectActions == null)
{
throw new ArgumentNullException(nameof(nuGetProjectActions));
}
if (buildIntegratedProject == null)
{
throw new ArgumentNullException(nameof(buildIntegratedProject));
}
if (nuGetProjectContext == null)
{
throw new ArgumentNullException(nameof(nuGetProjectContext));
}
if (!nuGetProjectActions.Any())
{
// Return null if there are no actions.
return null;
}
var resolvedAction = await PreviewBuildIntegratedProjectsActionsAsync(
new List<BuildIntegratedNuGetProject>() { buildIntegratedProject },
new Dictionary<string, NuGetProjectAction[]>(PathUtility.GetStringComparerBasedOnOS())
{
{ buildIntegratedProject.MSBuildProjectPath, nuGetProjectActions.ToArray()}
},
packageIdentity: null, // since we have nuGetProjectActions no need packageIdentity
primarySources: null, // since we have nuGetProjectActions no need primarySources
nuGetProjectContext,
token
);
return resolvedAction.FirstOrDefault(r => r.Project == buildIntegratedProject)?.Action as BuildIntegratedProjectAction;
}
/// <summary>
/// Run project actions for build integrated many projects.
/// </summary>
private async Task<IEnumerable<ResolvedAction>> PreviewBuildIntegratedProjectsActionsAsync(
IReadOnlyCollection<BuildIntegratedNuGetProject> buildIntegratedProjects,
Dictionary<string, NuGetProjectAction[]> nugetProjectActionsLookup,
PackageIdentity packageIdentity,
IReadOnlyCollection<SourceRepository> primarySources,
INuGetProjectContext nuGetProjectContext,
CancellationToken token)
{
if (nugetProjectActionsLookup == null)
{
nugetProjectActionsLookup = new Dictionary<string, NuGetProjectAction[]>(PathUtility.GetStringComparerBasedOnOS());
}
if (buildIntegratedProjects == null)
{
throw new ArgumentNullException(nameof(buildIntegratedProjects));
}
if (buildIntegratedProjects.Count == 0)
{
// Return empty if there are no buildIntegratedProjects.
return Enumerable.Empty<ResolvedAction>();
}
if (nuGetProjectContext == null)
{
throw new ArgumentNullException(nameof(nuGetProjectContext));
}
if (nugetProjectActionsLookup.Count == 0 && packageIdentity == null)
{
// Return empty if there are neither actions nor packageIdentity.
return Enumerable.Empty<ResolvedAction>();
}
var stopWatch = Stopwatch.StartNew();
var logger = new ProjectContextLogger(nuGetProjectContext);
var result = new List<ResolvedAction>();
var lockFileLookup = new Dictionary<string, LockFile>(PathUtility.GetStringComparerBasedOnOS());
var dependencyGraphContext = new DependencyGraphCacheContext(logger, Settings);
var pathContext = NuGetPathContext.Create(Settings);
var providerCache = new RestoreCommandProvidersCache();
var updatedNugetPackageSpecLookup = new Dictionary<string, PackageSpec>(PathUtility.GetStringComparerBasedOnOS());
var originalNugetPackageSpecLookup = new Dictionary<string, PackageSpec>(PathUtility.GetStringComparerBasedOnOS());
var nuGetProjectSourceLookup = new Dictionary<string, HashSet<SourceRepository>>(PathUtility.GetStringComparerBasedOnOS());
// For installs only use cache entries newer than the current time.
// This is needed for scenarios where a new package shows up in search
// but a previous cache entry does not yet have it.
// So we want to capture the time once here, then pass it down to the two
// restores happening in this flow.
var now = DateTimeOffset.UtcNow;
void cacheModifier(SourceCacheContext cache) => cache.MaxAge = now;
// Add all enabled sources for the existing projects
var enabledSources = SourceRepositoryProvider.GetRepositories();
var allSources = new HashSet<SourceRepository>(enabledSources, new SourceRepositoryComparer());
foreach (var buildIntegratedProject in buildIntegratedProjects)
{
NuGetProjectAction[] nuGetProjectActions;
if (packageIdentity != null)
{
if (primarySources == null || primarySources.Count == 0)
{
throw new ArgumentNullException($"Should have value in {nameof(primarySources)} if there is value for {nameof(packageIdentity)}");
}
var nugetAction = NuGetProjectAction.CreateInstallProjectAction(packageIdentity, primarySources.First(), buildIntegratedProject);
nuGetProjectActions = new[] { nugetAction };
nugetProjectActionsLookup[buildIntegratedProject.MSBuildProjectPath] = nuGetProjectActions;
}
else
{
if (!nugetProjectActionsLookup.ContainsKey(buildIntegratedProject.MSBuildProjectPath))
{
throw new ArgumentNullException($"Either should have value in {nameof(nugetProjectActionsLookup)} for {buildIntegratedProject.MSBuildProjectPath} or {nameof(packageIdentity)} & {nameof(primarySources)}");
}
nuGetProjectActions = nugetProjectActionsLookup[buildIntegratedProject.MSBuildProjectPath];
if (nuGetProjectActions.Length == 0)
{
// Continue to next project if there are no actions for current project.
continue;
}
}
// Find all sources used in the project actions
var sources = new HashSet<SourceRepository>(
nuGetProjectActions.Where(action => action.SourceRepository != null)
.Select(action => action.SourceRepository),
new SourceRepositoryComparer());
allSources.UnionWith(sources);
sources.UnionWith(enabledSources);
nuGetProjectSourceLookup[buildIntegratedProject.MSBuildProjectPath] = sources;
// Read the current lock file if it exists
LockFile originalLockFile = null;
var lockFileFormat = new LockFileFormat();
var lockFilePath = await buildIntegratedProject.GetAssetsFilePathAsync();
if (File.Exists(lockFilePath))
{
originalLockFile = lockFileFormat.Read(lockFilePath);
}
// Get Package Spec as json object
var originalPackageSpec = await DependencyGraphRestoreUtility.GetProjectSpec(buildIntegratedProject, dependencyGraphContext);
originalNugetPackageSpecLookup[buildIntegratedProject.MSBuildProjectPath] = originalPackageSpec;
// Create a copy to avoid modifying the original spec which may be shared.
var updatedPackageSpec = originalPackageSpec.Clone();
// If the lock file does not exist, restore before starting the operations
if (originalLockFile == null)
{
var originalRestoreResult = await DependencyGraphRestoreUtility.PreviewRestoreAsync(
SolutionManager,
buildIntegratedProject,
originalPackageSpec,
dependencyGraphContext,
providerCache,
cacheModifier,
sources,
nuGetProjectContext.OperationId,
logger,
token);
originalLockFile = originalRestoreResult.Result.LockFile;
}
lockFileLookup[buildIntegratedProject.MSBuildProjectPath] = originalLockFile;
foreach (var action in nuGetProjectActions)
{
if (action.NuGetProjectActionType == NuGetProjectActionType.Uninstall)
{
// Remove the package from all frameworks and dependencies section.
PackageSpecOperations.RemoveDependency(updatedPackageSpec, action.PackageIdentity.Id);
}
else if (action.NuGetProjectActionType == NuGetProjectActionType.Install)
{
if (updatedPackageSpec.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference)
{
PackageSpecOperations.AddOrUpdateDependency(updatedPackageSpec, action.PackageIdentity, updatedPackageSpec.TargetFrameworks.Select(e => e.FrameworkName));
}
else
{
PackageSpecOperations.AddOrUpdateDependency(updatedPackageSpec, action.PackageIdentity);
}
}
updatedNugetPackageSpecLookup[buildIntegratedProject.MSBuildProjectPath] = updatedPackageSpec;
dependencyGraphContext.PackageSpecCache[buildIntegratedProject.MSBuildProjectPath] = updatedPackageSpec;
}
}
// Restore based on the modified package specs for many projects. This operation does not write the lock files to disk.
var restoreResults = await DependencyGraphRestoreUtility.PreviewRestoreProjectsAsync(
SolutionManager,
buildIntegratedProjects,
updatedNugetPackageSpecLookup.Values,
dependencyGraphContext,
providerCache,
cacheModifier,
allSources,
nuGetProjectContext.OperationId,
logger,
token);
foreach (var buildIntegratedProject in buildIntegratedProjects)
{
var nuGetProjectActions = nugetProjectActionsLookup[buildIntegratedProject.MSBuildProjectPath];
var nuGetProjectActionsList = nuGetProjectActions;
var updatedPackageSpec = updatedNugetPackageSpecLookup[buildIntegratedProject.MSBuildProjectPath];
var originalPackageSpec = originalNugetPackageSpecLookup[buildIntegratedProject.MSBuildProjectPath];
var originalLockFile = lockFileLookup[buildIntegratedProject.MSBuildProjectPath];
var sources = nuGetProjectSourceLookup[buildIntegratedProject.MSBuildProjectPath];
var allFrameworks = updatedPackageSpec
.TargetFrameworks
.Select(t => t.FrameworkName)
.Distinct()
.ToList();
var restoreResult = restoreResults.Single(r =>
string.Equals(
r.SummaryRequest.Request.Project.RestoreMetadata.ProjectPath,
buildIntegratedProject.MSBuildProjectPath,
StringComparison.OrdinalIgnoreCase));
var unsuccessfulFrameworks = restoreResult
.Result
.CompatibilityCheckResults
.Where(t => !t.Success)
.Select(t => t.Graph.Framework)
.Distinct()
.ToList();
var successfulFrameworks = allFrameworks
.Except(unsuccessfulFrameworks)
.ToList();
var firstAction = nuGetProjectActionsList[0];
// If the restore failed and this was a single package install, try to install the package to a subset of
// the target frameworks.
if (nuGetProjectActionsList.Length == 1 &&
firstAction.NuGetProjectActionType == NuGetProjectActionType.Install &&
!restoreResult.Result.Success &&
successfulFrameworks.Any() &&
unsuccessfulFrameworks.Any() &&
// Exclude upgrades, for now we take the simplest case.
!PackageSpecOperations.HasPackage(originalPackageSpec, firstAction.PackageIdentity.Id))
{
updatedPackageSpec = originalPackageSpec.Clone();
PackageSpecOperations.AddOrUpdateDependency(
updatedPackageSpec,
firstAction.PackageIdentity,
successfulFrameworks);
restoreResult = await DependencyGraphRestoreUtility.PreviewRestoreAsync(
SolutionManager,
buildIntegratedProject,
updatedPackageSpec,
dependencyGraphContext,
providerCache,
cacheModifier,
sources,
nuGetProjectContext.OperationId,
logger,
token);
}
// If HideWarningsAndErrors is true then restore will not display the warnings and errors.
// Further, replay errors and warnings only if restore failed because the assets file will not be committed.
// If there were only warnings then those are written to assets file and committed. The design time build will replay them.
if (updatedPackageSpec.RestoreSettings.HideWarningsAndErrors &&
!restoreResult.Result.Success)
{
await MSBuildRestoreUtility.ReplayWarningsAndErrorsAsync(restoreResult.Result.LockFile?.LogMessages, logger);
}
// Build the installation context
var originalFrameworks = updatedPackageSpec
.TargetFrameworks
.ToDictionary(x => x.FrameworkName, x => x.TargetAlias);
var installationContext = new BuildIntegratedInstallationContext(
successfulFrameworks,
unsuccessfulFrameworks,
originalFrameworks);
InstallationCompatibility.EnsurePackageCompatibility(
buildIntegratedProject,
pathContext,
nuGetProjectActions,
restoreResult.Result);
// If this build integrated project action represents only uninstalls, mark the entire operation
// as an uninstall. Otherwise, mark it as an install. This is important because install operations
// are a bit more sensitive to errors (thus resulting in rollbacks).
var actionType = NuGetProjectActionType.Install;
if (nuGetProjectActions.All(x => x.NuGetProjectActionType == NuGetProjectActionType.Uninstall))
{
actionType = NuGetProjectActionType.Uninstall;
}
var nugetProjectAction = new BuildIntegratedProjectAction(
buildIntegratedProject,
nuGetProjectActions.First().PackageIdentity,
actionType,
originalLockFile,
restoreResult,
sources.ToList(),
nuGetProjectActionsList,
installationContext);
result.Add(new ResolvedAction(buildIntegratedProject, nugetProjectAction));
}
stopWatch.Stop();
var actionTelemetryEvent = new ActionTelemetryStepEvent(
nuGetProjectContext.OperationId.ToString(),
TelemetryConstants.PreviewBuildIntegratedStepName, stopWatch.Elapsed.TotalSeconds);
TelemetryActivity.EmitTelemetryEvent(actionTelemetryEvent);
return result;
}
/// <summary>
/// Run project actions for build integrated projects.
/// </summary>
public async Task ExecuteBuildIntegratedProjectActionsAsync(
BuildIntegratedNuGetProject buildIntegratedProject,
IEnumerable<NuGetProjectAction> nuGetProjectActions,
INuGetProjectContext nuGetProjectContext,
CancellationToken token)
{
BuildIntegratedProjectAction projectAction = null;
if (nuGetProjectActions.Count() == 1
&& nuGetProjectActions.All(action => action is BuildIntegratedProjectAction))
{
projectAction = nuGetProjectActions.Single() as BuildIntegratedProjectAction;
}
else if (nuGetProjectActions.Any())
{
projectAction = await PreviewBuildIntegratedProjectActionsAsync(
buildIntegratedProject,
nuGetProjectActions,
nuGetProjectContext,
token);
}
else
{
// There are no actions, this is a no-op
return;
}
var actions = projectAction.GetProjectActions();
// Check if all actions are uninstalls
var uninstallOnly = projectAction.NuGetProjectActionType == NuGetProjectActionType.Uninstall
&& actions.All(action => action.NuGetProjectActionType == NuGetProjectActionType.Uninstall);
var restoreResult = projectAction.RestoreResult;
// Avoid committing the changes if the restore did not succeed
// For uninstalls continue even if the restore failed to avoid blocking the user
if (restoreResult.Success || uninstallOnly)
{
// Get all install actions
var ignoreActions = new HashSet<NuGetProjectAction>();
var installedIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var action in projectAction.OriginalActions.Reverse())
{
if (action.NuGetProjectActionType == NuGetProjectActionType.Install)
{
installedIds.Add(action.PackageIdentity.Id);
}
else if (installedIds.Contains(action.PackageIdentity.Id))
{
ignoreActions.Add(action);
}
}
var pathResolver = new FallbackPackagePathResolver(
projectAction.RestoreResult.LockFile.PackageSpec.RestoreMetadata.PackagesPath,
projectAction.RestoreResult.LockFile.PackageSpec.RestoreMetadata.FallbackFolders);
foreach (var originalAction in projectAction.OriginalActions.Where(e => !ignoreActions.Contains(e)))
{
if (originalAction.NuGetProjectActionType == NuGetProjectActionType.Install)
{
if (buildIntegratedProject.ProjectStyle == ProjectStyle.PackageReference)
{
BuildIntegratedRestoreUtility.UpdatePackageReferenceMetadata(
projectAction.RestoreResult.LockFile,
pathResolver,
originalAction.PackageIdentity);
var framework = projectAction.InstallationContext.SuccessfulFrameworks.FirstOrDefault();
var resolvedAction = projectAction.RestoreResult.LockFile.PackageSpec.TargetFrameworks.FirstOrDefault(fm => fm.FrameworkName.Equals(framework))
.Dependencies.First(dependency => dependency.Name.Equals(originalAction.PackageIdentity.Id, StringComparison.OrdinalIgnoreCase));
projectAction.InstallationContext.SuppressParent = resolvedAction.SuppressParent;
projectAction.InstallationContext.IncludeType = resolvedAction.IncludeType;
}
// Install the package to the project
await buildIntegratedProject.InstallPackageAsync(
originalAction.PackageIdentity.Id,
new VersionRange(originalAction.PackageIdentity.Version),
nuGetProjectContext,
projectAction.InstallationContext,
token: token);
}
else if (originalAction.NuGetProjectActionType == NuGetProjectActionType.Uninstall)
{
await buildIntegratedProject.UninstallPackageAsync(
originalAction.PackageIdentity,
nuGetProjectContext: nuGetProjectContext,
token: token);
}
}
var logger = new ProjectContextLogger(nuGetProjectContext);
var referenceContext = new DependencyGraphCacheContext(logger, Settings);
var now = DateTime.UtcNow;
void cacheContextModifier(SourceCacheContext c) => c.MaxAge = now;
// Write out the lock file, now no need bubbling re-evaluating of parent projects when you restore from PM UI.
// We already taken account of that concern in PreviewBuildIntegratedProjectsActionsAsync method.
await RestoreRunner.CommitAsync(projectAction.RestoreResultPair, token);
// add packages lock file into project
if (PackagesLockFileUtilities.IsNuGetLockFileEnabled(projectAction.RestoreResult.LockFile.PackageSpec))
{
var lockFilePath = PackagesLockFileUtilities.GetNuGetLockFilePath(projectAction.RestoreResult.LockFile.PackageSpec);
await buildIntegratedProject.AddFileToProjectAsync(lockFilePath);
}
// Write out a message for each action
foreach (var action in actions)
{
var identityString = string.Format(CultureInfo.InvariantCulture, "{0} {1}",
action.PackageIdentity.Id,
action.PackageIdentity.Version.ToNormalizedString());
if (action.NuGetProjectActionType == NuGetProjectActionType.Install)
{
nuGetProjectContext.Log(
MessageLevel.Info,
Strings.SuccessfullyInstalled,
identityString,
buildIntegratedProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name));
}
else
{
// uninstall
nuGetProjectContext.Log(
MessageLevel.Info,
Strings.SuccessfullyUninstalled,
identityString,
buildIntegratedProject.GetMetadata<string>(NuGetProjectMetadataKeys.Name));
}
}
// Run init.ps1 scripts
var addedPackages = BuildIntegratedRestoreUtility.GetAddedPackages(
projectAction.OriginalLockFile,
restoreResult.LockFile);
await BuildIntegratedRestoreUtility.ExecuteInitPs1ScriptsAsync(
buildIntegratedProject,
addedPackages,
pathResolver,
nuGetProjectContext,
token);
// find list of buildintegrated projects
var projects = (await SolutionManager.GetNuGetProjectsAsync()).OfType<BuildIntegratedNuGetProject>().ToList();
// build reference cache if not done already
if (_buildIntegratedProjectsCache == null)
{
_buildIntegratedProjectsCache = await
DependencyGraphRestoreUtility.GetSolutionRestoreSpec(SolutionManager, referenceContext);
}
// Restore parent projects. These will be updated to include the transitive changes.
var parents = BuildIntegratedRestoreUtility.GetParentProjectsInClosure(
projects,
buildIntegratedProject,
_buildIntegratedProjectsCache);
// The settings contained in the context are applied to the dg spec.
var dgSpecForParents = await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(SolutionManager, referenceContext);
dgSpecForParents = dgSpecForParents.WithoutRestores();
foreach (var parent in parents)
{
// We only evaluate unseen parents.
if (_buildIntegratedProjectsUpdateSet == null ||
!_buildIntegratedProjectsUpdateSet.Contains(parent.MSBuildProjectPath))
{
// Mark project for restore
dgSpecForParents.AddRestore(parent.MSBuildProjectPath);
_buildIntegratedProjectsUpdateSet?.Add(parent.MSBuildProjectPath);
}
}
if (dgSpecForParents.Restore.Count > 0)
{
// Restore and commit the lock file to disk regardless of the result
// This will restore all parents in a single restore
await DependencyGraphRestoreUtility.RestoreAsync(
SolutionManager,
dgSpecForParents,
referenceContext,
GetRestoreProviderCache(),
cacheContextModifier,
projectAction.Sources,
nuGetProjectContext.OperationId,
forceRestore: false, // No need to force restore as the inputs would've changed here anyways
isRestoreOriginalAction: false, // not an explicit restore request instead being done as part of install or update
log: logger,
token: token);
}
}
else
{
// Fail and display a rollback message to let the user know they have returned to the original state
var message = string.Format(
CultureInfo.InvariantCulture,
Strings.RestoreFailedRollingBack,
buildIntegratedProject.ProjectName);
// Read additional errors from the lock file if one exists
var logMessages = restoreResult.LockFile?
.LogMessages
.Where(e => e.Level == LogLevel.Error || e.Level == LogLevel.Warning)
.Select(e => e.AsRestoreLogMessage())
?? Enumerable.Empty<ILogMessage>();
// Throw an exception containing all errors, these will be displayed in the error list
throw new PackageReferenceRollbackException(message, logMessages);
}
await OpenReadmeFile(buildIntegratedProject, nuGetProjectContext, token);
}
private async Task RollbackAsync(
NuGetProject nuGetProject,
Stack<NuGetProjectAction> executedNuGetProjectActions,
HashSet<PackageIdentity> packageWithDirectoriesToBeDeleted,
INuGetProjectContext nuGetProjectContext,
CancellationToken token)
{
if (executedNuGetProjectActions.Count > 0)
{
// Only print the rollback warning if we have something to rollback
nuGetProjectContext.Log(MessageLevel.Warning, Strings.Warning_RollingBack);
}
while (executedNuGetProjectActions.Count > 0)
{
var nuGetProjectAction = executedNuGetProjectActions.Pop();
try
{
if (nuGetProjectAction.NuGetProjectActionType == NuGetProjectActionType.Install)
{
// Rolling back an install would be to uninstall the package
await ExecuteUninstallAsync(nuGetProject, nuGetProjectAction.PackageIdentity, packageWithDirectoriesToBeDeleted, nuGetProjectContext, token);
}
else
{
packageWithDirectoriesToBeDeleted.Remove(nuGetProjectAction.PackageIdentity);
var packagePath = PackagesFolderNuGetProject.GetInstalledPackageFilePath(nuGetProjectAction.PackageIdentity);
if (File.Exists(packagePath))
{
using (var downloadResourceResult = new DownloadResourceResult(File.OpenRead(packagePath), nuGetProjectAction.SourceRepository?.PackageSource?.Source))
{
await ExecuteInstallAsync(nuGetProject, nuGetProjectAction.PackageIdentity, downloadResourceResult, packageWithDirectoriesToBeDeleted, nuGetProjectContext, token);
}
}
}
}
catch (Exception)
{
// TODO: We are ignoring exceptions on rollback. Is this OK?
}
}
}
private Task OpenReadmeFile(NuGetProject nuGetProject, INuGetProjectContext nuGetProjectContext, CancellationToken token)
{
var executionContext = nuGetProjectContext.ExecutionContext;
if (executionContext != null
&& executionContext.DirectInstall != null)
{
//packagesPath is different for project.json vs Packages.config scenarios. So check if the project is a build-integrated project
var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;
var readmeFilePath = string.Empty;
if (buildIntegratedProject != null)
{
var pathContext = NuGetPathContext.Create(Settings);
var pathResolver = new FallbackPackagePathResolver(pathContext);
var identity = nuGetProjectContext.ExecutionContext.DirectInstall;
var packageFolderPath = pathResolver.GetPackageDirectory(identity.Id, identity.Version);
if (!string.IsNullOrEmpty(packageFolderPath))
{
readmeFilePath = Path.Combine(packageFolderPath, Constants.ReadmeFileName);
}
}
else
{
var packagePath = PackagesFolderNuGetProject.GetInstalledPackageFilePath(executionContext.DirectInstall);
if (!string.IsNullOrEmpty(packagePath))
{
readmeFilePath = Path.Combine(Path.GetDirectoryName(packagePath), Constants.ReadmeFileName);
}
}
if (!token.IsCancellationRequested &&
!string.IsNullOrEmpty(readmeFilePath) &&
File.Exists(readmeFilePath))
{
return executionContext.OpenFile(readmeFilePath);
}
}
return Task.FromResult(false);
}
/// <summary>
/// RestorePackage is only allowed on a folderNuGetProject. In most cases, one will simply use the
/// packagesFolderPath from NuGetPackageManager
/// to create a folderNuGetProject before calling into this method
/// </summary>
public async Task<bool> RestorePackageAsync(
PackageIdentity packageIdentity,
INuGetProjectContext nuGetProjectContext,
PackageDownloadContext downloadContext,
IEnumerable<SourceRepository> sourceRepositories,
CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (PackageExistsInPackagesFolder(packageIdentity, nuGetProjectContext.PackageExtractionContext.PackageSaveMode))
{
return false;
}
token.ThrowIfCancellationRequested();
nuGetProjectContext.Log(MessageLevel.Info, string.Format(Strings.RestoringPackage, packageIdentity));
var enabledSources = (sourceRepositories != null && sourceRepositories.Any()) ? sourceRepositories :
SourceRepositoryProvider.GetRepositories().Where(e => e.PackageSource.IsEnabled);
token.ThrowIfCancellationRequested();
using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync(
enabledSources,
packageIdentity,
downloadContext,
SettingsUtility.GetGlobalPackagesFolder(Settings),
new ProjectContextLogger(nuGetProjectContext),
token))
{
// Install package whether returned from the cache or a direct download
await PackagesFolderNuGetProject.InstallPackageAsync(packageIdentity, downloadResult, nuGetProjectContext, token);
}
return true;
}
public Task<bool> CopySatelliteFilesAsync(PackageIdentity packageIdentity, INuGetProjectContext nuGetProjectContext, CancellationToken token)
{
return PackagesFolderNuGetProject.CopySatelliteFilesAsync(packageIdentity, nuGetProjectContext, token);
}
/// <summary>
/// Checks whether package exists in packages folder and verifies that nupkg and nuspec are present as specified by packageSaveMode
/// </summary>
public bool PackageExistsInPackagesFolder(PackageIdentity packageIdentity, PackageSaveMode packageSaveMode)
{
return PackagesFolderNuGetProject.PackageExists(packageIdentity, packageSaveMode);
}
public bool PackageExistsInPackagesFolder(PackageIdentity packageIdentity)
{
return PackagesFolderNuGetProject.PackageExists(packageIdentity);
}
private async Task ExecuteInstallAsync(
NuGetProject nuGetProject,
PackageIdentity packageIdentity,
DownloadResourceResult resourceResult,
HashSet<PackageIdentity> packageWithDirectoriesToBeDeleted,
INuGetProjectContext nuGetProjectContext,
CancellationToken token)
{
// TODO: EnsurePackageCompatibility check should be performed in preview. Can easily avoid a lot of rollback
await InstallationCompatibility.EnsurePackageCompatibilityAsync(nuGetProject, packageIdentity, resourceResult, token);
packageWithDirectoriesToBeDeleted.Remove(packageIdentity);
await nuGetProject.InstallPackageAsync(packageIdentity, resourceResult, nuGetProjectContext, token);
}
private async Task ExecuteUninstallAsync(NuGetProject nuGetProject, PackageIdentity packageIdentity, HashSet<PackageIdentity> packageWithDirectoriesToBeDeleted,
INuGetProjectContext nuGetProjectContext, CancellationToken token)
{
// Step-1: Call nuGetProject.UninstallPackage
await nuGetProject.UninstallPackageAsync(packageIdentity, nuGetProjectContext, token);
// Step-2: Check if the package directory could be deleted
if (!(nuGetProject is INuGetIntegratedProject)
&& !await PackageExistsInAnotherNuGetProject(nuGetProject, packageIdentity, SolutionManager, token, excludeIntegrated: true))
{
packageWithDirectoriesToBeDeleted.Add(packageIdentity);
}
// TODO: Consider using CancelEventArgs instead of a regular EventArgs??
//if (packageOperationEventArgs.Cancel)
//{
// return;
//}
}
/// <summary>
/// Checks if package <paramref name="packageIdentity" /> that is installed in
/// project <paramref name="nuGetProject" /> is also installed in any
/// other projects in the solution.
/// </summary>
public static async Task<bool> PackageExistsInAnotherNuGetProject(NuGetProject nuGetProject, PackageIdentity packageIdentity, ISolutionManager solutionManager, CancellationToken token, bool excludeIntegrated = false)
{
if (nuGetProject == null)
{
throw new ArgumentNullException(nameof(nuGetProject));
}
if (packageIdentity == null)
{
throw new ArgumentNullException(nameof(packageIdentity));
}
if (solutionManager == null)
{
// If the solution manager is null, simply assume that the
// package exists on another nuget project to not delete it
return true;
}
var nuGetProjectName = NuGetProject.GetUniqueNameOrName(nuGetProject);
foreach (var otherNuGetProject in (await solutionManager.GetNuGetProjectsAsync()))
{
if (excludeIntegrated && otherNuGetProject is INuGetIntegratedProject)
{
continue;
}
var otherNuGetProjectName = NuGetProject.GetUniqueNameOrName(otherNuGetProject);
if (otherNuGetProjectName.Equals(nuGetProjectName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
var packageExistsInAnotherNuGetProject = (await otherNuGetProject.GetInstalledPackagesAsync(token)).Any(pr => pr.PackageIdentity.Equals(packageIdentity));
if (packageExistsInAnotherNuGetProject)
{
return true;
}
}
return false;
}
private async Task<bool> DeletePackageAsync(PackageIdentity packageIdentity, INuGetProjectContext nuGetProjectContext, CancellationToken token)
{
if (packageIdentity == null)
{
throw new ArgumentNullException(nameof(packageIdentity));
}
if (nuGetProjectContext == null)
{
throw new ArgumentNullException(nameof(nuGetProjectContext));
}
// 1. Check if the Package exists at root, if not, return false
if (!PackagesFolderNuGetProject.PackageExists(packageIdentity))
{
nuGetProjectContext.Log(ProjectManagement.MessageLevel.Warning, Strings.PackageDoesNotExistInFolder, packageIdentity, PackagesFolderNuGetProject.Root);
return false;
}
nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.RemovingPackageFromFolder, packageIdentity, PackagesFolderNuGetProject.Root);
// 2. Delete the package folder and files from the root directory of this FileSystemNuGetProject
// Remember that the following code may throw System.UnauthorizedAccessException
await PackagesFolderNuGetProject.DeletePackage(packageIdentity, nuGetProjectContext, token);
nuGetProjectContext.Log(ProjectManagement.MessageLevel.Info, Strings.RemovedPackageFromFolder, packageIdentity, PackagesFolderNuGetProject.Root);
return true;
}
public static Task<ResolvedPackage> GetLatestVersionAsync(
string packageId,
NuGetFramework framework,
ResolutionContext resolutionContext,
SourceRepository primarySourceRepository,
Common.ILogger log,
CancellationToken token)
{
return GetLatestVersionAsync(
packageId,
framework,
resolutionContext,
new List<SourceRepository> { primarySourceRepository },
log,
token);
}
public static Task<ResolvedPackage> GetLatestVersionAsync(
string packageId,
NuGetProject project,
ResolutionContext resolutionContext,
SourceRepository primarySourceRepository,
Common.ILogger log,
CancellationToken token)
{
NuGetFramework framework;
if (!project.TryGetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework, out framework))
{
// Default to the any framework if the project does not specify a framework.
framework = NuGetFramework.AnyFramework;
}
return GetLatestVersionAsync(
packageId,
framework,
resolutionContext,
new List<SourceRepository> { primarySourceRepository },
log,
token);
}
public static async Task<ResolvedPackage> GetLatestVersionAsync(
string packageId,
NuGetProject project,
ResolutionContext resolutionContext,
IEnumerable<SourceRepository> sources,
Common.ILogger log,
CancellationToken token)
{
var tasks = new List<Task<NuGetVersion>>();
NuGetFramework framework;
if (!project.TryGetMetadata<NuGetFramework>(NuGetProjectMetadataKeys.TargetFramework, out framework))
{
// Default to the any framework if the project does not specify a framework.
framework = NuGetFramework.AnyFramework;
}
return await GetLatestVersionAsync(packageId, framework, resolutionContext, sources, log, token);
}
public static async Task<ResolvedPackage> GetLatestVersionAsync(
string packageId,
NuGetFramework framework,
ResolutionContext resolutionContext,
IEnumerable<SourceRepository> sources,
Common.ILogger log,
CancellationToken token)
{
var tasks = new List<Task<ResolvedPackage>>();
NuGetVersion version = null;
foreach (var source in sources)
{
tasks.Add(Task.Run(async ()
=> await GetLatestVersionCoreAsync(packageId, version, framework, resolutionContext, source, log, token)));
}
var resolvedPackages = await Task.WhenAll(tasks);
var latestVersion = resolvedPackages.Select(v => v.LatestVersion).Where(v => v != null).Max();
return new ResolvedPackage(latestVersion, resolvedPackages.Any(p => p.Exists));
}
public static async Task<ResolvedPackage> GetLatestVersionAsync(
PackageReference package,
NuGetFramework framework,
ResolutionContext resolutionContext,
IEnumerable<SourceRepository> sources,
Common.ILogger log,
CancellationToken token)
{
var tasks = new List<Task<ResolvedPackage>>();
foreach (var source in sources)
{
tasks.Add(Task.Run(async ()
=> await GetLatestVersionCoreAsync(package.PackageIdentity.Id, package.PackageIdentity.Version, framework, resolutionContext, source, log, token)));
}
var resolvedPackages = await Task.WhenAll(tasks);
var latestVersion = resolvedPackages
.Select(v => v.LatestVersion)
.Where(v => v != null && (package.AllowedVersions == null || package.AllowedVersions.Satisfies(v))).Max();
return new ResolvedPackage(latestVersion, resolvedPackages.Any(p => p.Exists));
}
private static async Task<ResolvedPackage> GetLatestVersionCoreAsync(
string packageId,
NuGetVersion version,
NuGetFramework framework,
ResolutionContext resolutionContext,
SourceRepository source,
Common.ILogger log,
CancellationToken token)
{
var dependencyInfoResource = await source.GetResourceAsync<DependencyInfoResource>();
// Resolve the package for the project framework and cache the results in the
// resolution context for the gather to use during the next step.
// Using the metadata resource will result in multiple calls to the same url during an install.
var packages = (await dependencyInfoResource.ResolvePackages(packageId, framework, resolutionContext.SourceCacheContext, log, token)).ToList();
Debug.Assert(resolutionContext.GatherCache != null);
// Cache the results, even if the package was not found.
resolutionContext.GatherCache.AddAllPackagesForId(
source.PackageSource,
packageId,
framework,
packages);
if (version != null)
{
packages = PrunePackageTree.PruneByUpdateConstraints(packages, version, resolutionContext.VersionConstraints).ToList();
}
// Find the latest version
var latestVersion = packages.Where(package => (package.Listed || resolutionContext.IncludeUnlisted)
&& (resolutionContext.IncludePrerelease || !package.Version.IsPrerelease))
.OrderByDescending(package => package.Version, VersionComparer.Default)
.Select(package => package.Version)
.FirstOrDefault();
return new ResolvedPackage(latestVersion, packages.Count > 0);
}
private IEnumerable<SourceRepository> GetEffectiveSources(IEnumerable<SourceRepository> primarySources, IEnumerable<SourceRepository> secondarySources)
{
// Always have to add the packages folder as the primary repository so that
// dependency info for an installed package that is unlisted from the server is still available :(
// count = primarySources.Count + secondarySources.Count + 1 for PackagesFolderSourceRepository
var count = (primarySources?.Count() ?? 0) +
(secondarySources?.Count() ?? 0)
+ 1;
var effectiveSources = new List<SourceRepository>(count)
{
PackagesFolderSourceRepository
};
effectiveSources.AddRange(primarySources);
effectiveSources.AddRange(secondarySources);
return new HashSet<SourceRepository>(effectiveSources, new SourceRepositoryComparer());
}
public static void SetDirectInstall(PackageIdentity directInstall,
INuGetProjectContext nuGetProjectContext)
{
if (directInstall != null
&& nuGetProjectContext != null
&& nuGetProjectContext.ExecutionContext != null)
{
var ideExecutionContext = nuGetProjectContext.ExecutionContext as IDEExecutionContext;
if (ideExecutionContext != null)
{
ideExecutionContext.IDEDirectInstall = directInstall;
}
}
}
public static void ClearDirectInstall(INuGetProjectContext nuGetProjectContext)
{
if (nuGetProjectContext != null
&& nuGetProjectContext.ExecutionContext != null)
{
var ideExecutionContext = nuGetProjectContext.ExecutionContext as IDEExecutionContext;
if (ideExecutionContext != null)
{
ideExecutionContext.IDEDirectInstall = null;
}
}
}
private RestoreCommandProvidersCache GetRestoreProviderCache()
{
if (_restoreProviderCache == null)
{
_restoreProviderCache = new RestoreCommandProvidersCache();
}
return _restoreProviderCache;
}
}
}
| 48.38923 | 254 | 0.596447 | [
"Apache-2.0"
] | davkean/NuGet.Client | src/NuGet.Core/NuGet.PackageManagement/NuGetPackageManager.cs | 173,427 | C# |
namespace WHMS.Web.ViewModels.Orders
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using WHMS.Data;
using WHMS.Web.ViewModels.ValidationAttributes;
public class ShipOrderInputModel : IValidatableObject
{
public int OrderId { get; set; }
public ShippingMethodInputModel ShippingMethod { get; set; }
public IEnumerable<CarrierViewModel> Carriers { get; set; }
[Required]
[Display(Name = "Tracking number")]
public string TrackingNumber { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var context = (WHMSDbContext)validationContext.GetService(typeof(WHMSDbContext));
var order = context.Orders.Find(this.OrderId);
if (order == null)
{
yield return new ValidationResult("Order doesn't exist");
}
if (order?.ShippingStatus == Data.Models.Orders.Enum.ShippingStatus.Shipped)
{
yield return new ValidationResult("Order already shipped");
}
if (order?.PaymentStatus != Data.Models.Orders.Enum.PaymentStatus.FullyCharged)
{
yield return new ValidationResult("Order is not fully charged. Cannot ship this order!");
}
}
}
}
| 33.047619 | 105 | 0.628242 | [
"MIT"
] | jivkopiskov/WHMS | src/Web/WHMS.Web.ViewModels/Orders/ShipOrderInputModel.cs | 1,390 | C# |
using System;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Core.Contracts;
using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros.Config;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Macros
{
public class RandomMacro : IMacro, IDeferredMacro
{
public Guid Id => new Guid("011E8DC1-8544-4360-9B40-65FD916049B7");
public string Type => "random";
public void EvaluateConfig(IEngineEnvironmentSettings environmentSettings, IVariableCollection vars, IMacroConfig rawConfig, IParameterSet parameters, ParameterSetter setter)
{
RandomMacroConfig config = rawConfig as RandomMacroConfig;
if (config == null)
{
throw new InvalidCastException("Couldn't cast the rawConfig as RandomMacroConfig");
}
Random rnd = new Random();
int value = rnd.Next(config.Low, config.High);
Parameter p;
if (parameters.TryGetParameterDefinition(config.VariableName, out ITemplateParameter existingParam))
{
// If there is an existing parameter with this name, it must be reused so it can be referenced by name
// for other processing, for example: if the parameter had value forms defined for creating variants.
// When the param already exists, use its definition, but set IsVariable = true for consistency.
p = (Parameter)existingParam;
p.IsVariable = true;
}
else
{
p = new Parameter
{
IsVariable = true,
Name = config.VariableName
};
}
vars[config.VariableName] = value.ToString();
setter(p, value.ToString());
}
public IMacroConfig CreateConfig(IEngineEnvironmentSettings environmentSettings, IMacroConfig rawConfig)
{
GeneratedSymbolDeferredMacroConfig deferredConfig = rawConfig as GeneratedSymbolDeferredMacroConfig;
if (deferredConfig == null)
{
throw new InvalidCastException("Couldn't cast the rawConfig as a GeneratedSymbolDeferredMacroConfig");
}
int low;
int high;
if (!deferredConfig.Parameters.TryGetValue("low", out JToken lowToken))
{
throw new ArgumentNullException("low");
}
else
{
low = lowToken.Value<int>();
}
if (!deferredConfig.Parameters.TryGetValue("high", out JToken highToken))
{
high = int.MaxValue;
}
else
{
high = highToken.Value<int>();
}
IMacroConfig realConfig = new RandomMacroConfig(deferredConfig.VariableName, low, high);
return realConfig;
}
}
}
| 36.552941 | 183 | 0.578693 | [
"MIT"
] | mmitche/templating | src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RandomMacro.cs | 3,023 | C# |
using API;
using Newtonsoft.Json;
using PxStat.Template;
namespace PxStat.Security
{
/// <summary>
/// Reads a Trace. Required parameters StartDate,EndDate and optionally AuthenticationType
/// </summary>
internal class Trace_BSO_Read : BaseTemplate_Read<Trace_DTO_Read, Trace_VLD_Read>
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="request"></param>
public Trace_BSO_Read(JSONRPC_API request) : base(request, new Trace_VLD_Read())
{
}
/// <summary>
/// Test privilege
/// </summary>
/// <returns></returns>
override protected bool HasPrivilege()
{
return IsAdministrator();
}
/// <summary>
/// Execute
/// </summary>
/// <returns></returns>
protected override bool Execute()
{
//Validation of parameters and user have been successful. We may now proceed to read from the database
var adoTrace = new Trace_ADO();
//Traces are returned as an ADO result
ADO_readerOutput result = adoTrace.Read(Ado, DTO);
if (!result.hasData)
{
return false;
}
Log.Instance.Debug("Data found :" + JsonConvert.SerializeObject(result));
Response.data = result.data;
return true;
}
}
} | 27.480769 | 114 | 0.554234 | [
"MIT"
] | CSOIreland/PxStat | server/PxStat/Entities/Security/Trace/BSO/Trace_BSO_Read.cs | 1,431 | C# |
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using Projac.Sql;
namespace Projac.SqlClient
{
/// <summary>
/// Represents the T-SQL DATETIME2 parameter value.
/// </summary>
public class TSqlDateTime2Value : IDbParameterValue
{
private readonly TSqlDateTime2Precision _precision;
private readonly DateTime _value;
/// <summary>
/// Initializes a new instance of the <see cref="TSqlDateTime2Value" /> class.
/// </summary>
/// <param name="value">The parameter value.</param>
/// <param name="precision">The parameter precision.</param>
public TSqlDateTime2Value(DateTime value, TSqlDateTime2Precision precision)
{
_value = value;
_precision = precision;
}
/// <summary>
/// Creates a <see cref="DbParameter" /> instance based on this instance.
/// </summary>
/// <param name="parameterName">The name of the parameter.</param>
/// <returns>
/// A <see cref="DbParameter" />.
/// </returns>
public DbParameter ToDbParameter(string parameterName)
{
return ToSqlParameter(parameterName);
}
/// <summary>
/// Creates a <see cref="SqlParameter" /> instance based on this instance.
/// </summary>
/// <param name="parameterName">The name of the parameter.</param>
/// <returns>
/// A <see cref="SqlParameter" />.
/// </returns>
public SqlParameter ToSqlParameter(string parameterName)
{
#if NET46 || NET452
return new SqlParameter(
parameterName,
SqlDbType.DateTime2,
8,
ParameterDirection.Input,
false,
_precision,
0,
"",
DataRowVersion.Default,
_value);
#elif NETSTANDARD2_0
return new SqlParameter
{
ParameterName = parameterName,
Direction = ParameterDirection.Input,
SqlDbType = SqlDbType.DateTime2,
Size = 8,
Value = _value,
SourceColumn = "",
IsNullable = false,
Precision = _precision,
Scale = 0,
SourceVersion = DataRowVersion.Default
};
#endif
}
private bool Equals(TSqlDateTime2Value other)
{
return (_value == other._value) && (_precision == other._precision);
}
/// <summary>
/// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((TSqlDateTime2Value) obj);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return _value.GetHashCode() ^ _precision;
}
}
} | 34.825688 | 125 | 0.533983 | [
"BSD-3-Clause"
] | BitTacklr/Projac | src/Projac.SqlClient/TSqlDateTime2Value.cs | 3,796 | C# |
// _ _ _ ____ _ _____
// / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
// / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
// / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
// /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
// |
// Copyright 2015-2019 Łukasz "JustArchi" Domeradzki
// Contact: JustArchi@JustArchi.net
// |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// |
// http://www.apache.org/licenses/LICENSE-2.0
// |
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Xml;
using ArchiSteamFarm.Localization;
using ArchiSteamFarm.NLog;
using HtmlAgilityPack;
using JetBrains.Annotations;
using Newtonsoft.Json;
namespace ArchiSteamFarm {
public sealed class WebBrowser : IDisposable {
internal const byte MaxConnections = 5; // Defines maximum number of connections per ServicePoint. Be careful, as it also defines maximum number of sockets in CLOSE_WAIT state
internal const byte MaxTries = 5; // Defines maximum number of recommended tries for a single request
private const byte ExtendedTimeoutMultiplier = 10; // Defines multiplier of timeout for WebBrowsers dealing with huge data (ASF update)
private const byte MaxIdleTime = 15; // Defines in seconds, how long socket is allowed to stay in CLOSE_WAIT state after there are no connections to it
internal readonly CookieContainer CookieContainer = new CookieContainer();
internal TimeSpan Timeout => HttpClient.Timeout;
private readonly ArchiLogger ArchiLogger;
private readonly HttpClient HttpClient;
private readonly HttpClientHandler HttpClientHandler;
internal WebBrowser([NotNull] ArchiLogger archiLogger, IWebProxy webProxy = null, bool extendedTimeout = false) {
ArchiLogger = archiLogger ?? throw new ArgumentNullException(nameof(archiLogger));
HttpClientHandler = new HttpClientHandler {
AllowAutoRedirect = false, // This must be false if we want to handle custom redirection schemes such as "steammobile://"
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
CookieContainer = CookieContainer
};
if (webProxy != null) {
HttpClientHandler.Proxy = webProxy;
HttpClientHandler.UseProxy = true;
}
if (!RuntimeCompatibility.IsRunningOnMono) {
HttpClientHandler.MaxConnectionsPerServer = MaxConnections;
}
HttpClient = GenerateDisposableHttpClient(extendedTimeout);
}
public void Dispose() {
HttpClient.Dispose();
HttpClientHandler.Dispose();
}
[NotNull]
[PublicAPI]
public HttpClient GenerateDisposableHttpClient(bool extendedTimeout = false) {
HttpClient result = new HttpClient(HttpClientHandler, false) {
Timeout = TimeSpan.FromSeconds(extendedTimeout ? ExtendedTimeoutMultiplier * ASF.GlobalConfig.ConnectionTimeout : ASF.GlobalConfig.ConnectionTimeout)
};
// Most web services expect that UserAgent is set, so we declare it globally
// If you by any chance came here with a very "clever" idea of hiding your ass by changing default ASF user-agent then here is a very good advice from me: don't, for your own safety - you've been warned
result.DefaultRequestHeaders.UserAgent.ParseAdd(SharedInfo.PublicIdentifier + "/" + SharedInfo.Version + " (+" + SharedInfo.ProjectURL + ")");
return result;
}
[ItemCanBeNull]
[PublicAPI]
public async Task<HtmlDocumentResponse> UrlGetToHtmlDocument(string request, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) {
if (string.IsNullOrEmpty(request) || (maxTries == 0)) {
ArchiLogger.LogNullError(nameof(request) + " || " + nameof(maxTries));
return null;
}
StringResponse response = await UrlGetToString(request, referer, requestOptions, maxTries).ConfigureAwait(false);
return response != null ? new HtmlDocumentResponse(response) : null;
}
[ItemCanBeNull]
[PublicAPI]
public async Task<ObjectResponse<T>> UrlGetToJsonObject<T>(string request, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) where T : class {
if (string.IsNullOrEmpty(request) || (maxTries == 0)) {
ArchiLogger.LogNullError(nameof(request) + " || " + nameof(maxTries));
return null;
}
ObjectResponse<T> result = null;
for (byte i = 0; i < maxTries; i++) {
StringResponse response = await UrlGetToString(request, referer, requestOptions | ERequestOptions.ReturnClientErrors, 1).ConfigureAwait(false);
// ReSharper disable once UseNullPropagationWhenPossible - false check
if (response == null) {
continue;
}
if (response.StatusCode.IsClientErrorCode()) {
if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) {
result = new ObjectResponse<T>(response);
}
break;
}
if (string.IsNullOrEmpty(response.Content)) {
continue;
}
T obj;
try {
obj = JsonConvert.DeserializeObject<T>(response.Content);
} catch (JsonException e) {
ArchiLogger.LogGenericWarningException(e);
if (Debugging.IsUserDebugging) {
ArchiLogger.LogGenericDebug(string.Format(Strings.Content, response.Content));
}
continue;
}
return new ObjectResponse<T>(response, obj);
}
if (maxTries > 1) {
ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorRequestFailedTooManyTimes, maxTries));
ArchiLogger.LogGenericDebug(string.Format(Strings.ErrorFailingRequest, request));
}
return result;
}
[ItemCanBeNull]
[PublicAPI]
public async Task<XmlDocumentResponse> UrlGetToXmlDocument(string request, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) {
if (string.IsNullOrEmpty(request) || (maxTries == 0)) {
ArchiLogger.LogNullError(nameof(request) + " || " + nameof(maxTries));
return null;
}
XmlDocumentResponse result = null;
for (byte i = 0; i < maxTries; i++) {
StringResponse response = await UrlGetToString(request, referer, requestOptions | ERequestOptions.ReturnClientErrors, 1).ConfigureAwait(false);
// ReSharper disable once UseNullPropagationWhenPossible - false check
if (response == null) {
continue;
}
if (response.StatusCode.IsClientErrorCode()) {
if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) {
result = new XmlDocumentResponse(response);
}
break;
}
if (string.IsNullOrEmpty(response.Content)) {
continue;
}
XmlDocument xmlDocument = new XmlDocument();
try {
xmlDocument.LoadXml(response.Content);
} catch (XmlException e) {
ArchiLogger.LogGenericWarningException(e);
continue;
}
return new XmlDocumentResponse(response, xmlDocument);
}
if (maxTries > 1) {
ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorRequestFailedTooManyTimes, maxTries));
ArchiLogger.LogGenericDebug(string.Format(Strings.ErrorFailingRequest, request));
}
return result;
}
[ItemCanBeNull]
[PublicAPI]
public async Task<BasicResponse> UrlHead(string request, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) {
if (string.IsNullOrEmpty(request) || (maxTries == 0)) {
ArchiLogger.LogNullError(nameof(request) + " || " + nameof(maxTries));
return null;
}
BasicResponse result = null;
for (byte i = 0; i < maxTries; i++) {
using (HttpResponseMessage response = await InternalHead(request, referer).ConfigureAwait(false)) {
if (response == null) {
continue;
}
if (response.StatusCode.IsClientErrorCode()) {
if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) {
result = new BasicResponse(response);
}
break;
}
return new BasicResponse(response);
}
}
if (maxTries > 1) {
ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorRequestFailedTooManyTimes, maxTries));
ArchiLogger.LogGenericDebug(string.Format(Strings.ErrorFailingRequest, request));
}
return result;
}
[ItemCanBeNull]
[PublicAPI]
public async Task<BasicResponse> UrlPost(string request, IReadOnlyCollection<KeyValuePair<string, string>> data = null, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) {
if (string.IsNullOrEmpty(request) || (maxTries == 0)) {
ArchiLogger.LogNullError(nameof(request) + " || " + nameof(maxTries));
return null;
}
BasicResponse result = null;
for (byte i = 0; i < maxTries; i++) {
using (HttpResponseMessage response = await InternalPost(request, data, referer).ConfigureAwait(false)) {
if (response == null) {
continue;
}
if (response.StatusCode.IsClientErrorCode()) {
if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) {
result = new BasicResponse(response);
}
break;
}
return new BasicResponse(response);
}
}
if (maxTries > 1) {
ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorRequestFailedTooManyTimes, maxTries));
ArchiLogger.LogGenericDebug(string.Format(Strings.ErrorFailingRequest, request));
}
return result;
}
[ItemCanBeNull]
[PublicAPI]
public async Task<HtmlDocumentResponse> UrlPostToHtmlDocument(string request, IReadOnlyCollection<KeyValuePair<string, string>> data = null, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) {
if (string.IsNullOrEmpty(request) || (maxTries == 0)) {
ArchiLogger.LogNullError(nameof(request) + " || " + nameof(maxTries));
return null;
}
StringResponse response = await UrlPostToString(request, data, referer, requestOptions, maxTries).ConfigureAwait(false);
return response != null ? new HtmlDocumentResponse(response) : null;
}
[ItemCanBeNull]
[PublicAPI]
public async Task<ObjectResponse<T>> UrlPostToJsonObject<T>(string request, IReadOnlyCollection<KeyValuePair<string, string>> data = null, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) where T : class {
if (string.IsNullOrEmpty(request) || (maxTries == 0)) {
ArchiLogger.LogNullError(nameof(request) + " || " + nameof(maxTries));
return null;
}
ObjectResponse<T> result = null;
for (byte i = 0; i < maxTries; i++) {
StringResponse response = await UrlPostToString(request, data, referer, requestOptions | ERequestOptions.ReturnClientErrors, 1).ConfigureAwait(false);
if (response == null) {
return null;
}
if (response.StatusCode.IsClientErrorCode()) {
if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) {
result = new ObjectResponse<T>(response);
}
break;
}
if (string.IsNullOrEmpty(response.Content)) {
continue;
}
T obj;
try {
obj = JsonConvert.DeserializeObject<T>(response.Content);
} catch (JsonException e) {
ArchiLogger.LogGenericWarningException(e);
if (Debugging.IsUserDebugging) {
ArchiLogger.LogGenericDebug(string.Format(Strings.Content, response.Content));
}
continue;
}
return new ObjectResponse<T>(response, obj);
}
if (maxTries > 1) {
ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorRequestFailedTooManyTimes, maxTries));
ArchiLogger.LogGenericDebug(string.Format(Strings.ErrorFailingRequest, request));
}
return result;
}
internal static void Init() {
// Set max connection limit from default of 2 to desired value
ServicePointManager.DefaultConnectionLimit = MaxConnections;
// Set max idle time from default of 100 seconds (100 * 1000) to desired value
ServicePointManager.MaxServicePointIdleTime = MaxIdleTime * 1000;
// Don't use Expect100Continue, we're sure about our POSTs, save some TCP packets
ServicePointManager.Expect100Continue = false;
// Reuse ports if possible
if (!RuntimeCompatibility.IsRunningOnMono) {
ServicePointManager.ReusePort = true;
}
}
internal static HtmlDocument StringToHtmlDocument(string html) {
if (html == null) {
ASF.ArchiLogger.LogNullError(nameof(html));
return null;
}
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
return htmlDocument;
}
[ItemCanBeNull]
internal async Task<BinaryResponse> UrlGetToBinaryWithProgress(string request, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) {
if (string.IsNullOrEmpty(request) || (maxTries == 0)) {
ArchiLogger.LogNullError(nameof(request) + " || " + nameof(maxTries));
return null;
}
BinaryResponse result = null;
for (byte i = 0; i < maxTries; i++) {
const byte printPercentage = 10;
const byte maxBatches = 99 / printPercentage;
using (HttpResponseMessage response = await InternalGet(request, referer, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false)) {
if (response == null) {
continue;
}
if (response.StatusCode.IsClientErrorCode()) {
if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) {
result = new BinaryResponse(response);
}
break;
}
ArchiLogger.LogGenericDebug("0%...");
uint contentLength = (uint) response.Content.Headers.ContentLength.GetValueOrDefault();
using (MemoryStream ms = new MemoryStream((int) contentLength)) {
try {
using (Stream contentStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) {
byte batch = 0;
uint readThisBatch = 0;
byte[] buffer = new byte[8192]; // This is HttpClient's buffer, using more doesn't make sense
while (contentStream.CanRead) {
int read = await contentStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
if (read == 0) {
break;
}
await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false);
if ((contentLength == 0) || (batch >= maxBatches)) {
continue;
}
readThisBatch += (uint) read;
if (readThisBatch < contentLength / printPercentage) {
continue;
}
readThisBatch -= contentLength / printPercentage;
ArchiLogger.LogGenericDebug((++batch * printPercentage) + "%...");
}
}
} catch (Exception e) {
ArchiLogger.LogGenericDebuggingException(e);
return null;
}
ArchiLogger.LogGenericDebug("100%");
return new BinaryResponse(response, ms.ToArray());
}
}
}
if (maxTries > 1) {
ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorRequestFailedTooManyTimes, maxTries));
ArchiLogger.LogGenericDebug(string.Format(Strings.ErrorFailingRequest, request));
}
return result;
}
[ItemCanBeNull]
internal async Task<StringResponse> UrlGetToString(string request, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) {
if (string.IsNullOrEmpty(request) || (maxTries == 0)) {
ArchiLogger.LogNullError(nameof(request) + " || " + nameof(maxTries));
return null;
}
StringResponse result = null;
for (byte i = 0; i < maxTries; i++) {
using (HttpResponseMessage response = await InternalGet(request, referer).ConfigureAwait(false)) {
if (response == null) {
continue;
}
if (response.StatusCode.IsClientErrorCode()) {
if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) {
result = new StringResponse(response);
}
break;
}
return new StringResponse(response, await response.Content.ReadAsStringAsync().ConfigureAwait(false));
}
}
if (maxTries > 1) {
ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorRequestFailedTooManyTimes, maxTries));
ArchiLogger.LogGenericDebug(string.Format(Strings.ErrorFailingRequest, request));
}
return result;
}
private async Task<HttpResponseMessage> InternalGet(string request, string referer = null, HttpCompletionOption httpCompletionOptions = HttpCompletionOption.ResponseContentRead) {
if (string.IsNullOrEmpty(request)) {
ArchiLogger.LogNullError(nameof(request));
return null;
}
return await InternalRequest(new Uri(request), HttpMethod.Get, null, referer, httpCompletionOptions).ConfigureAwait(false);
}
private async Task<HttpResponseMessage> InternalHead(string request, string referer = null) {
if (string.IsNullOrEmpty(request)) {
ArchiLogger.LogNullError(nameof(request));
return null;
}
return await InternalRequest(new Uri(request), HttpMethod.Head, null, referer).ConfigureAwait(false);
}
private async Task<HttpResponseMessage> InternalPost(string request, IReadOnlyCollection<KeyValuePair<string, string>> data = null, string referer = null) {
if (string.IsNullOrEmpty(request)) {
ArchiLogger.LogNullError(nameof(request));
return null;
}
return await InternalRequest(new Uri(request), HttpMethod.Post, data, referer).ConfigureAwait(false);
}
private async Task<HttpResponseMessage> InternalRequest(Uri requestUri, HttpMethod httpMethod, IReadOnlyCollection<KeyValuePair<string, string>> data = null, string referer = null, HttpCompletionOption httpCompletionOption = HttpCompletionOption.ResponseContentRead, byte maxRedirections = MaxTries) {
if ((requestUri == null) || (httpMethod == null)) {
ArchiLogger.LogNullError(nameof(requestUri) + " || " + nameof(httpMethod));
return null;
}
HttpResponseMessage response;
using (HttpRequestMessage request = new HttpRequestMessage(httpMethod, requestUri)) {
if (data != null) {
try {
request.Content = new FormUrlEncodedContent(data);
} catch (UriFormatException e) {
ArchiLogger.LogGenericException(e);
return null;
}
}
if (!string.IsNullOrEmpty(referer)) {
request.Headers.Referrer = new Uri(referer);
}
if (Debugging.IsUserDebugging) {
ArchiLogger.LogGenericDebug(httpMethod + " " + requestUri);
}
try {
response = await HttpClient.SendAsync(request, httpCompletionOption).ConfigureAwait(false);
} catch (Exception e) {
ArchiLogger.LogGenericDebuggingException(e);
return null;
}
}
if (response == null) {
if (Debugging.IsUserDebugging) {
ArchiLogger.LogGenericDebug("null <- " + httpMethod + " " + requestUri);
}
return null;
}
if (Debugging.IsUserDebugging) {
ArchiLogger.LogGenericDebug(response.StatusCode + " <- " + httpMethod + " " + requestUri);
}
if (response.IsSuccessStatusCode) {
return response;
}
// WARNING: We still have not disposed response by now, make sure to dispose it ASAP if we're not returning it!
if ((response.StatusCode >= HttpStatusCode.Ambiguous) && (response.StatusCode < HttpStatusCode.BadRequest) && (maxRedirections > 0)) {
Uri redirectUri = response.Headers.Location;
if (redirectUri.IsAbsoluteUri) {
switch (redirectUri.Scheme) {
case "http":
case "https":
break;
case "steammobile":
// Those redirections are invalid, but we're aware of that and we have extra logic for them
return response;
default:
// We have no clue about those, but maybe HttpClient can handle them for us
ASF.ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(redirectUri.Scheme), redirectUri.Scheme));
break;
}
} else {
redirectUri = new Uri(requestUri, redirectUri);
}
response.Dispose();
// Per https://tools.ietf.org/html/rfc7231#section-7.1.2, a redirect location without a fragment should inherit the fragment from the original URI
if (!string.IsNullOrEmpty(requestUri.Fragment) && string.IsNullOrEmpty(redirectUri.Fragment)) {
redirectUri = new UriBuilder(redirectUri) { Fragment = requestUri.Fragment }.Uri;
}
return await InternalRequest(redirectUri, httpMethod, data, referer, httpCompletionOption, --maxRedirections).ConfigureAwait(false);
}
if (response.StatusCode.IsClientErrorCode()) {
if (Debugging.IsUserDebugging) {
ArchiLogger.LogGenericDebug(string.Format(Strings.Content, await response.Content.ReadAsStringAsync().ConfigureAwait(false)));
}
// Do not retry on client errors
return response;
}
using (response) {
if (Debugging.IsUserDebugging) {
ArchiLogger.LogGenericDebug(string.Format(Strings.Content, await response.Content.ReadAsStringAsync().ConfigureAwait(false)));
}
return null;
}
}
[ItemCanBeNull]
private async Task<StringResponse> UrlPostToString(string request, IReadOnlyCollection<KeyValuePair<string, string>> data = null, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) {
if (string.IsNullOrEmpty(request) || (maxTries == 0)) {
ArchiLogger.LogNullError(nameof(request) + " || " + nameof(maxTries));
return null;
}
StringResponse result = null;
for (byte i = 0; i < maxTries; i++) {
using (HttpResponseMessage response = await InternalPost(request, data, referer).ConfigureAwait(false)) {
if (response == null) {
continue;
}
if (response.StatusCode.IsClientErrorCode()) {
if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) {
result = new StringResponse(response);
}
break;
}
return new StringResponse(response, await response.Content.ReadAsStringAsync().ConfigureAwait(false));
}
}
if (maxTries > 1) {
ArchiLogger.LogGenericWarning(string.Format(Strings.ErrorRequestFailedTooManyTimes, maxTries));
ArchiLogger.LogGenericDebug(string.Format(Strings.ErrorFailingRequest, request));
}
return result;
}
public class BasicResponse {
[PublicAPI]
public readonly HttpStatusCode StatusCode;
internal readonly Uri FinalUri;
internal BasicResponse([NotNull] HttpResponseMessage httpResponseMessage) {
if (httpResponseMessage == null) {
throw new ArgumentNullException(nameof(httpResponseMessage));
}
FinalUri = httpResponseMessage.Headers.Location ?? httpResponseMessage.RequestMessage.RequestUri;
StatusCode = httpResponseMessage.StatusCode;
}
internal BasicResponse([NotNull] BasicResponse basicResponse) {
if (basicResponse == null) {
throw new ArgumentNullException(nameof(basicResponse));
}
FinalUri = basicResponse.FinalUri;
StatusCode = basicResponse.StatusCode;
}
}
public sealed class HtmlDocumentResponse : BasicResponse {
[PublicAPI]
public readonly HtmlDocument Content;
internal HtmlDocumentResponse([NotNull] StringResponse stringResponse) : base(stringResponse) {
if (stringResponse == null) {
throw new ArgumentNullException(nameof(stringResponse));
}
if (!string.IsNullOrEmpty(stringResponse.Content)) {
Content = StringToHtmlDocument(stringResponse.Content);
}
}
}
public sealed class ObjectResponse<T> : BasicResponse {
[PublicAPI]
public readonly T Content;
internal ObjectResponse([NotNull] StringResponse stringResponse, T content) : base(stringResponse) {
if (stringResponse == null) {
throw new ArgumentNullException(nameof(stringResponse));
}
Content = content;
}
internal ObjectResponse([NotNull] BasicResponse basicResponse) : base(basicResponse) { }
}
public sealed class XmlDocumentResponse : BasicResponse {
[PublicAPI]
public readonly XmlDocument Content;
internal XmlDocumentResponse([NotNull] StringResponse stringResponse, XmlDocument content) : base(stringResponse) {
if (stringResponse == null) {
throw new ArgumentNullException(nameof(stringResponse));
}
Content = content;
}
internal XmlDocumentResponse([NotNull] BasicResponse basicResponse) : base(basicResponse) { }
}
[Flags]
public enum ERequestOptions : byte {
None = 0,
ReturnClientErrors = 1
}
internal sealed class BinaryResponse : BasicResponse {
internal readonly byte[] Content;
internal BinaryResponse([NotNull] HttpResponseMessage httpResponseMessage, [NotNull] byte[] content) : base(httpResponseMessage) {
if ((httpResponseMessage == null) || (content == null)) {
throw new ArgumentNullException(nameof(httpResponseMessage) + " || " + nameof(content));
}
Content = content;
}
internal BinaryResponse([NotNull] HttpResponseMessage httpResponseMessage) : base(httpResponseMessage) { }
}
internal sealed class StringResponse : BasicResponse {
internal readonly string Content;
internal StringResponse([NotNull] HttpResponseMessage httpResponseMessage, [NotNull] string content) : base(httpResponseMessage) {
if ((httpResponseMessage == null) || (content == null)) {
throw new ArgumentNullException(nameof(httpResponseMessage) + " || " + nameof(content));
}
Content = content;
}
internal StringResponse([NotNull] HttpResponseMessage httpResponseMessage) : base(httpResponseMessage) { }
}
}
}
| 33.277992 | 303 | 0.703523 | [
"Apache-2.0"
] | 439qi/ArchiSteamFarm | ArchiSteamFarm/WebBrowser.cs | 25,858 | C# |
using Inversion.Data;
namespace Inversion.Messaging.Logging
{
public interface ILoggingStore : IStore
{
void Log(string entity, string message);
void LogDebug(string entity, string message);
}
} | 22.4 | 53 | 0.691964 | [
"MIT"
] | fractos/inversion-messaging | Inversion.Messaging/Logging/ILoggingStore.cs | 226 | C# |
#region Copyright
//
<<<<<<< HEAD
<<<<<<< HEAD
=======
=======
>>>>>>> update form orginal repo
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
<<<<<<< HEAD
>>>>>>> Merges latest changes from release/9.4.x into development (#3178)
=======
>>>>>>> update form orginal repo
#region Usings
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Icons;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Framework.JavaScriptLibraries;
using DotNetNuke.Instrumentation;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Modules;
using DotNetNuke.Web.Client.ClientResourceManagement;
#endregion
namespace DotNetNuke.Framework
{
/// -----------------------------------------------------------------------------
/// Namespace: DotNetNuke.Framework
/// Project: DotNetNuke
/// Class: PageBase
/// -----------------------------------------------------------------------------
/// <summary>
/// PageBase provides a custom DotNetNuke base class for pages
/// </summary>
/// -----------------------------------------------------------------------------
public abstract class PageBase : Page
{
private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (PageBase));
private readonly ILog _tracelLogger = LoggerSource.Instance.GetLogger("DNN.Trace");
private const string LinkItemPattern = "<(a|link|img|script|input|form|object).[^>]*(href|src|action)=(\\\"|'|)(.[^\\\"']*)(\\\"|'|)[^>]*>";
private static readonly Regex LinkItemMatchRegex = new Regex(LinkItemPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
private PageStatePersister _persister;
#region Private Members
private readonly NameValueCollection _htmlAttributes = new NameValueCollection();
private readonly ArrayList _localizedControls;
private CultureInfo _pageCulture;
private string _localResourceFile;
#endregion
#region Constructors
/// -----------------------------------------------------------------------------
/// <summary>
/// Creates the Page
/// </summary>
/// -----------------------------------------------------------------------------
protected PageBase()
{
_localizedControls = new ArrayList();
}
#endregion
#region Protected Properties
/// -----------------------------------------------------------------------------
/// <summary>
/// PageStatePersister returns an instance of the class that will be used to persist the Page State
/// </summary>
/// <returns>A System.Web.UI.PageStatePersister</returns>
/// -----------------------------------------------------------------------------
protected override PageStatePersister PageStatePersister
{
get
{
//Set ViewState Persister to default (as defined in Base Class)
if (_persister == null)
{
_persister = base.PageStatePersister;
if (Globals.Status == Globals.UpgradeStatus.None)
{
switch (Host.PageStatePersister)
{
case "M":
_persister = new CachePageStatePersister(this);
break;
case "D":
_persister = new DiskPageStatePersister(this);
break;
}
}
}
return _persister;
}
}
#endregion
#region Public Properties
public PortalSettings PortalSettings
{
get
{
return PortalController.Instance.GetCurrentPortalSettings();
}
}
public NameValueCollection HtmlAttributes
{
get
{
return _htmlAttributes;
}
}
public CultureInfo PageCulture
{
get
{
return _pageCulture ?? (_pageCulture = Localization.GetPageLocale(PortalSettings));
}
}
public string LocalResourceFile
{
get
{
string fileRoot;
var page = Request.ServerVariables["SCRIPT_NAME"].Split('/');
if (String.IsNullOrEmpty(_localResourceFile))
{
fileRoot = string.Concat(TemplateSourceDirectory, "/", Localization.LocalResourceDirectory, "/", page[page.GetUpperBound(0)], ".resx");
}
else
{
fileRoot = _localResourceFile;
}
return fileRoot;
}
set
{
_localResourceFile = value;
}
}
public string CanonicalLinkUrl { get; set; }
/// <summary>
/// Indicate whether http headers has been sent to client.
/// </summary>
public bool HeaderIsWritten { get; internal set; }
#endregion
#region Private Methods
private string GetErrorUrl(string url, Exception exc, bool hideContent = true)
{
if (Request.QueryString["error"] != null)
{
url += string.Concat((url.IndexOf("?", StringComparison.Ordinal) == -1 ? "?" : "&"), "error=terminate");
}
else
{
url += string.Concat(
(url.IndexOf("?", StringComparison.Ordinal) == -1 ? "?" : "&"),
"error=",
(exc == null || UserController.Instance.GetCurrentUserInfo() == null || !UserController.Instance.GetCurrentUserInfo().IsSuperUser ? "An unexpected error has occurred" : Server.UrlEncode(exc.Message))
);
if (!Globals.IsAdminControl() && hideContent)
{
url += "&content=0";
}
}
return url;
}
private bool IsViewStateFailure(Exception e)
{
return !User.Identity.IsAuthenticated && e != null && e.InnerException is ViewStateException;
}
private void IterateControls(ControlCollection controls, ArrayList affectedControls, string resourceFileRoot)
{
foreach (Control c in controls)
{
ProcessControl(c, affectedControls, true, resourceFileRoot);
LogDnnTrace("PageBase.IterateControls","Info", $"ControlId: {c.ID}");
}
}
private void LogDnnTrace(string origin, string action, string message)
{
var tabId = -1;
if (PortalSettings?.ActiveTab != null)
{
tabId = PortalSettings.ActiveTab.TabID;
}
if (_tracelLogger.IsDebugEnabled)
_tracelLogger.Debug($"{origin} {action} (TabId:{tabId},{message})");
}
#endregion
#region Protected Methods
protected virtual void RegisterAjaxScript()
{
if (ServicesFrameworkInternal.Instance.IsAjaxScriptSupportRequired)
{
ServicesFrameworkInternal.Instance.RegisterAjaxScript(Page);
}
}
protected override void OnError(EventArgs e)
{
base.OnError(e);
Exception exc = Server.GetLastError();
Logger.Fatal("An error has occurred while loading page.", exc);
string strURL = Globals.ApplicationURL();
if (exc is HttpException && !IsViewStateFailure(exc))
{
try
{
//if the exception's status code set to 404, we need display 404 page if defined or show no found info.
var statusCode = (exc as HttpException).GetHttpCode();
if (statusCode == 404)
{
UrlUtils.Handle404Exception(Response, PortalSettings);
}
if (PortalSettings?.ErrorPage500 != -1)
{
var url = GetErrorUrl(string.Concat("~/Default.aspx?tabid=", PortalSettings.ErrorPage500), exc,
false);
HttpContext.Current.Response.Redirect(url);
}
else
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Server.Transfer("~/ErrorPage.aspx");
}
}
catch (Exception)
{
HttpContext.Current.Response.Clear();
var errorMessage = HttpUtility.UrlEncode(Localization.GetString("NoSitesForThisInstallation.Error", Localization.GlobalResourceFile));
HttpContext.Current.Server.Transfer("~/ErrorPage.aspx?status=503&error="+errorMessage);
}
}
strURL = GetErrorUrl(strURL, exc);
Exceptions.ProcessPageLoadException(exc, strURL);
}
protected override void OnInit(EventArgs e)
{
var isInstallPage = HttpContext.Current.Request.Url.LocalPath.ToLowerInvariant().Contains("installwizard.aspx");
if (!isInstallPage)
{
Localization.SetThreadCultures(PageCulture, PortalSettings);
}
if (ScriptManager.GetCurrent(this) == null)
{
AJAX.AddScriptManager(this, !isInstallPage);
}
var dnncoreFilePath = HttpContext.Current.IsDebuggingEnabled
? "~/js/Debug/dnncore.js"
: "~/js/dnncore.js";
ClientResourceManager.RegisterScript(this, dnncoreFilePath);
base.OnInit(e);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
//Because we have delayed registration of the jQuery script,
//Modules can override the standard behavior by including their own script on the page.
//The module must register the script with the "jQuery" key and should notify user
//of potential version conflicts with core jQuery support.
//if (jQuery.IsRequested)
//{
// jQuery.RegisterJQuery(Page);
//}
//if (jQuery.IsUIRequested)
//{
// jQuery.RegisterJQueryUI(Page);
//}
//if (jQuery.AreDnnPluginsRequested)
//{
// jQuery.RegisterDnnJQueryPlugins(Page);
//}
//if (jQuery.IsHoverIntentRequested)
//{
// jQuery.RegisterHoverIntent(Page);
//}
if (ServicesFrameworkInternal.Instance.IsAjaxAntiForgerySupportRequired)
{
ServicesFrameworkInternal.Instance.RegisterAjaxAntiForgery(Page);
}
RegisterAjaxScript();
}
protected override void Render(HtmlTextWriter writer)
{
LogDnnTrace("PageBase.Render", "Start", $"{Page.Request.Url.AbsoluteUri}");
IterateControls(Controls, _localizedControls, LocalResourceFile);
RemoveKeyAttribute(_localizedControls);
AJAX.RemoveScriptManager(this);
base.Render(writer);
LogDnnTrace("PageBase.Render", "End", $"{Page.Request.Url.AbsoluteUri}");
}
#endregion
#region Public Methods
/// <summary>
/// <para>GetControlAttribute looks a the type of control and does it's best to find an AttributeCollection.</para>
/// </summary>
/// <param name="control">Control to find the AttributeCollection on</param>
/// <param name="affectedControls">ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute.</param>
/// <param name="attributeName">Name of key to search for.</param>
/// <returns>A string containing the key for the specified control or null if a key attribute wasn't found</returns>
internal static string GetControlAttribute(Control control, ArrayList affectedControls, string attributeName)
{
AttributeCollection attributeCollection = null;
string key = null;
if (!(control is LiteralControl))
{
var webControl = control as WebControl;
if (webControl != null)
{
attributeCollection = webControl.Attributes;
key = attributeCollection[attributeName];
}
else
{
var htmlControl = control as HtmlControl;
if (htmlControl != null)
{
attributeCollection = htmlControl.Attributes;
key = attributeCollection[attributeName];
}
else
{
var userControl = control as UserControl;
if (userControl != null)
{
attributeCollection = userControl.Attributes;
key = attributeCollection[attributeName];
}
else
{
var controlType = control.GetType();
var attributeProperty = controlType.GetProperty("Attributes", typeof(AttributeCollection));
if (attributeProperty != null)
{
attributeCollection = (AttributeCollection)attributeProperty.GetValue(control, null);
key = attributeCollection[attributeName];
}
}
}
}
}
if (key != null && affectedControls != null)
{
affectedControls.Add(attributeCollection);
}
return key;
}
private void LocalizeControl(Control control, string value)
{
if (string.IsNullOrEmpty(value)) return;
var validator = control as BaseValidator;
if (validator != null)
{
validator.ErrorMessage = value;
validator.Text = value;
return;
}
var label = control as Label;
if (label != null)
{
label.Text = value;
return;
}
var linkButton = control as LinkButton;
if (linkButton != null)
{
var imgMatches = LinkItemMatchRegex.Matches(value);
foreach (Match match in imgMatches)
{
if ((match.Groups[match.Groups.Count - 2].Value.IndexOf("~", StringComparison.Ordinal) == -1))
continue;
var resolvedUrl = Page.ResolveUrl(match.Groups[match.Groups.Count - 2].Value);
value = value.Replace(match.Groups[match.Groups.Count - 2].Value, resolvedUrl);
}
linkButton.Text = value;
if (string.IsNullOrEmpty(linkButton.ToolTip))
{
linkButton.ToolTip = value;
}
return;
}
var hyperLink = control as HyperLink;
if (hyperLink != null)
{
hyperLink.Text = value;
return;
}
var button = control as Button;
if (button != null)
{
button.Text = value;
return;
}
var htmlButton = control as HtmlButton;
if (htmlButton != null)
{
htmlButton.Attributes["Title"] = value;
return;
}
var htmlImage = control as HtmlImage;
if (htmlImage != null)
{
htmlImage.Alt = value;
return;
}
var checkBox = control as CheckBox;
if (checkBox != null)
{
checkBox.Text = value;
return;
}
var image = control as Image;
if (image != null)
{
image.AlternateText = value;
image.ToolTip = value;
return;
}
var textBox = control as TextBox;
if (textBox != null)
{
textBox.ToolTip = value;
}
}
/// <summary>
/// <para>ProcessControl peforms the high level localization for a single control and optionally it's children.</para>
/// </summary>
/// <param name="control">Control to find the AttributeCollection on</param>
/// <param name="affectedControls">ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute.</param>
/// <param name="includeChildren">If true, causes this method to process children of this controls.</param>
/// <param name="resourceFileRoot">Root Resource File.</param>
internal void ProcessControl(Control control, ArrayList affectedControls, bool includeChildren, string resourceFileRoot)
{
if (!control.Visible) return;
//Perform the substitution if a key was found
var key = GetControlAttribute(control, affectedControls, Localization.KeyName);
if (!string.IsNullOrEmpty(key))
{
//Translation starts here ....
var value = Localization.GetString(key, resourceFileRoot);
LocalizeControl(control, value);
}
//Translate listcontrol items here
var listControl = control as ListControl;
if (listControl != null)
{
for (var i = 0; i <= listControl.Items.Count - 1; i++)
{
var attributeCollection = listControl.Items[i].Attributes;
key = attributeCollection[Localization.KeyName];
if (key != null)
{
var value = Localization.GetString(key, resourceFileRoot);
if (!String.IsNullOrEmpty(value))
{
listControl.Items[i].Text = value;
}
}
if (key != null && affectedControls != null)
{
affectedControls.Add(attributeCollection);
}
}
}
//UrlRewriting Issue - ResolveClientUrl gets called instead of ResolveUrl
//Manual Override to ResolveUrl
var image = control as Image;
if (image != null)
{
if (image.ImageUrl.IndexOf("~", StringComparison.Ordinal) != -1)
{
image.ImageUrl = Page.ResolveUrl(image.ImageUrl);
}
//Check for IconKey
if (string.IsNullOrEmpty(image.ImageUrl))
{
var iconKey = GetControlAttribute(control, affectedControls, IconController.IconKeyName);
var iconSize = GetControlAttribute(control, affectedControls, IconController.IconSizeName);
var iconStyle = GetControlAttribute(control, affectedControls, IconController.IconStyleName);
image.ImageUrl = IconController.IconURL(iconKey, iconSize, iconStyle);
}
}
//UrlRewriting Issue - ResolveClientUrl gets called instead of ResolveUrl
//Manual Override to ResolveUrl
var htmlImage = control as HtmlImage;
if (htmlImage != null)
{
if (htmlImage.Src.IndexOf("~", StringComparison.Ordinal) != -1)
{
htmlImage.Src = Page.ResolveUrl(htmlImage.Src);
}
//Check for IconKey
if (string.IsNullOrEmpty(htmlImage.Src))
{
var iconKey = GetControlAttribute(control, affectedControls, IconController.IconKeyName);
var iconSize = GetControlAttribute(control, affectedControls, IconController.IconSizeName);
var iconStyle = GetControlAttribute(control, affectedControls, IconController.IconStyleName);
htmlImage.Src = IconController.IconURL(iconKey, iconSize, iconStyle);
}
}
//UrlRewriting Issue - ResolveClientUrl gets called instead of ResolveUrl
//Manual Override to ResolveUrl
var ctrl = control as HyperLink;
if (ctrl != null)
{
if ((ctrl.NavigateUrl.IndexOf("~", StringComparison.Ordinal) != -1))
{
ctrl.NavigateUrl = Page.ResolveUrl(ctrl.NavigateUrl);
}
if ((ctrl.ImageUrl.IndexOf("~", StringComparison.Ordinal) != -1))
{
ctrl.ImageUrl = Page.ResolveUrl(ctrl.ImageUrl);
}
//Check for IconKey
if (string.IsNullOrEmpty(ctrl.ImageUrl))
{
var iconKey = GetControlAttribute(control, affectedControls, IconController.IconKeyName);
var iconSize = GetControlAttribute(control, affectedControls, IconController.IconSizeName);
var iconStyle = GetControlAttribute(control, affectedControls, IconController.IconStyleName);
ctrl.ImageUrl = IconController.IconURL(iconKey, iconSize, iconStyle);
}
}
//Process child controls
if (!includeChildren || !control.HasControls()) return;
var objModuleControl = control as IModuleControl;
if (objModuleControl == null)
{
//Cache results from reflection calls for performance
var pi = control.GetType().GetProperty("LocalResourceFile");
if (pi != null)
{
//Attempt to get property value
var pv = pi.GetValue(control, null);
//If controls has a LocalResourceFile property use this, otherwise pass the resource file root
IterateControls(control.Controls, affectedControls, pv == null ? resourceFileRoot : pv.ToString());
}
else
{
//Pass Resource File Root through
IterateControls(control.Controls, affectedControls, resourceFileRoot);
}
}
else
{
//Get Resource File Root from Controls LocalResourceFile Property
IterateControls(control.Controls, affectedControls, objModuleControl.LocalResourceFile);
}
}
/// <summary>
/// <para>RemoveKeyAttribute remove the key attribute from the control. If this isn't done, then the HTML output will have
/// a bad attribute on it which could cause some older browsers problems.</para>
/// </summary>
/// <param name="affectedControls">ArrayList that hold the controls that have been localized. This is later used for the removal of the key attribute.</param>
public static void RemoveKeyAttribute(ArrayList affectedControls)
{
if (affectedControls == null)
{
return;
}
int i;
for (i = 0; i <= affectedControls.Count - 1; i++)
{
var ac = (AttributeCollection)affectedControls[i];
ac.Remove(Localization.KeyName);
ac.Remove(IconController.IconKeyName);
ac.Remove(IconController.IconSizeName);
ac.Remove(IconController.IconStyleName);
}
}
#endregion
}
}
| 38.765579 | 219 | 0.527136 | [
"MIT"
] | DnnSoftwarePersian/Dnn.Platform | DNN Platform/Library/Framework/PageBase.cs | 26,129 | C# |
using GroupDocsAnnotationVisualStudioPlugin.Core;
namespace GroupDocsAnnotationVisualStudioPlugin.GUI
{
partial class ComponentWizardPage
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ComponentWizardPage));
this.groupBoxCommonUses = new System.Windows.Forms.GroupBox();
this.label2 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.linkLabelGroupDocs = new System.Windows.Forms.LinkLabel();
this.progressBar = new System.Windows.Forms.ProgressBar();
this.toolStripStatusMessage = new System.Windows.Forms.Label();
this.AbortButton = new System.Windows.Forms.Button();
this.ContinueButton = new System.Windows.Forms.Button();
this.panel1 = new System.Windows.Forms.Panel();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.label1 = new System.Windows.Forms.Label();
this.groupBoxCommonUses.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.tableLayoutPanel2.SuspendLayout();
this.SuspendLayout();
//
// groupBoxCommonUses
//
this.groupBoxCommonUses.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBoxCommonUses.Controls.Add(this.label2);
this.groupBoxCommonUses.Controls.Add(this.pictureBox1);
this.groupBoxCommonUses.Controls.Add(this.linkLabelGroupDocs);
this.groupBoxCommonUses.Font = new System.Drawing.Font("Calibri", 8.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.groupBoxCommonUses.Location = new System.Drawing.Point(12, 136);
this.groupBoxCommonUses.Name = "groupBoxCommonUses";
this.groupBoxCommonUses.Size = new System.Drawing.Size(469, 275);
this.groupBoxCommonUses.TabIndex = 1;
this.groupBoxCommonUses.TabStop = false;
this.groupBoxCommonUses.Text = "Common Uses:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Dock = System.Windows.Forms.DockStyle.Right;
this.label2.Font = new System.Drawing.Font("Calibri", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(147, 17);
this.label2.MaximumSize = new System.Drawing.Size(320, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(319, 152);
this.label2.TabIndex = 3;
this.label2.Text = resources.GetString("label2.Text");
this.label2.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
//
// pictureBox1
//
this.pictureBox1.Image = global::GroupDocsAnnotationVisualStudioPlugin.Properties.Resources.groupdocs_Annotation;
this.pictureBox1.Location = new System.Drawing.Point(6, 38);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(133, 135);
this.pictureBox1.TabIndex = 2;
this.pictureBox1.TabStop = false;
//
// linkLabelGroupDocs
//
this.linkLabelGroupDocs.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.linkLabelGroupDocs.AutoSize = true;
this.linkLabelGroupDocs.LinkArea = new System.Windows.Forms.LinkArea(6, 9);
this.linkLabelGroupDocs.Location = new System.Drawing.Point(12, 255);
this.linkLabelGroupDocs.Name = "linkLabelGroupDocs";
this.linkLabelGroupDocs.Size = new System.Drawing.Size(161, 19);
this.linkLabelGroupDocs.TabIndex = 1;
this.linkLabelGroupDocs.TabStop = true;
this.linkLabelGroupDocs.Text = "Visit GroupDocs for more details.";
this.linkLabelGroupDocs.UseCompatibleTextRendering = true;
this.linkLabelGroupDocs.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelGroupDocs_LinkClicked);
//
// progressBar
//
this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.progressBar.Location = new System.Drawing.Point(12, 102);
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(469, 28);
this.progressBar.TabIndex = 3;
//
// toolStripStatusMessage
//
this.toolStripStatusMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.toolStripStatusMessage.AutoSize = true;
this.toolStripStatusMessage.Font = new System.Drawing.Font("Calibri", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.toolStripStatusMessage.Location = new System.Drawing.Point(10, 85);
this.toolStripStatusMessage.Name = "toolStripStatusMessage";
this.toolStripStatusMessage.Size = new System.Drawing.Size(99, 14);
this.toolStripStatusMessage.TabIndex = 4;
this.toolStripStatusMessage.Text = "Fetching API info...";
//
// AbortButton
//
this.AbortButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.AbortButton.Font = new System.Drawing.Font("Calibri", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.AbortButton.Location = new System.Drawing.Point(394, 437);
this.AbortButton.Name = "AbortButton";
this.AbortButton.Size = new System.Drawing.Size(70, 23);
this.AbortButton.TabIndex = 7;
this.AbortButton.Text = "Abort";
this.AbortButton.UseVisualStyleBackColor = true;
this.AbortButton.Click += new System.EventHandler(this.AbortButton_Click);
//
// ContinueButton
//
this.ContinueButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ContinueButton.Font = new System.Drawing.Font("Calibri", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ContinueButton.Location = new System.Drawing.Point(310, 437);
this.ContinueButton.Name = "ContinueButton";
this.ContinueButton.Size = new System.Drawing.Size(70, 23);
this.ContinueButton.TabIndex = 6;
this.ContinueButton.Text = "Continue";
this.ContinueButton.UseVisualStyleBackColor = true;
this.ContinueButton.Click += new System.EventHandler(this.ContinueButton_Click);
//
// panel1
//
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Location = new System.Drawing.Point(0, 418);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(585, 1);
this.panel1.TabIndex = 5;
//
// timer1
//
this.timer1.Interval = 200;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.BackgroundImage = global::GroupDocsAnnotationVisualStudioPlugin.Properties.Resources.long_banner1;
this.tableLayoutPanel2.ColumnCount = 1;
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 584F));
this.tableLayoutPanel2.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel2.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel2.Margin = new System.Windows.Forms.Padding(0);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 1;
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 80F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 80F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 80F));
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 80F));
this.tableLayoutPanel2.Size = new System.Drawing.Size(503, 63);
this.tableLayoutPanel2.TabIndex = 4;
//
// label1
//
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Calibri", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.SystemColors.HighlightText;
this.label1.Location = new System.Drawing.Point(3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(292, 63);
this.label1.TabIndex = 1;
this.label1.Text = "GroupDocs.Annotation .NET API Examples";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// ComponentWizardPage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(493, 462);
this.ControlBox = false;
this.Controls.Add(this.AbortButton);
this.Controls.Add(this.ContinueButton);
this.Controls.Add(this.panel1);
this.Controls.Add(this.tableLayoutPanel2);
this.Controls.Add(this.toolStripStatusMessage);
this.Controls.Add(this.progressBar);
this.Controls.Add(this.groupBoxCommonUses);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(590, 500);
this.MinimizeBox = false;
this.Name = "ComponentWizardPage";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "GroupDocs Visual Studio Plugin";
this.groupBoxCommonUses.ResumeLayout(false);
this.groupBoxCommonUses.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.tableLayoutPanel2.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupBoxCommonUses;
private System.Windows.Forms.LinkLabel linkLabelGroupDocs;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.ProgressBar progressBar;
private System.Windows.Forms.Label toolStripStatusMessage;
private System.Windows.Forms.Button AbortButton;
private System.Windows.Forms.Button ContinueButton;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.PictureBox pictureBox1;
}
} | 58.443038 | 169 | 0.636488 | [
"MIT"
] | atirtahirgroupdocs/GroupDocs.Annotation-for-.NET | Plugins/GroupDocs_Annotation_VSPlugin/GroupDocs.Annotation.VisualStudioPlugin/GroupDocsVisualStudioPlugin/GUI/ComponentWizardPage.Designer.cs | 13,853 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Flurl;
using Flurl.Http;
namespace SKIT.FlurlHttpClient.Wechat.TenpayV3
{
/// <summary>
/// 为 <see cref="WechatTenpayClient"/> 提供证书相关的 API 扩展方法。
/// </summary>
public static class WechatTenpayClientExecuteCertificatesExtensions
{
/// <summary>
/// <para>异步调用 [GET] /certificates 接口。</para>
/// <para>REF: https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay5_1.shtml </para>
/// <para>REF: https://pay.weixin.qq.com/wiki/doc/apiv3_partner/wechatpay/wechatpay5_1.shtml </para>
/// </summary>
/// <param name="client"></param>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task<Models.QueryCertificatesResponse> ExecuteQueryCertificatesAsync(this WechatTenpayClient client, Models.QueryCertificatesRequest request, CancellationToken cancellationToken = default)
{
if (client is null) throw new ArgumentNullException(nameof(client));
if (request is null) throw new ArgumentNullException(nameof(request));
IFlurlRequest flurlReq = client
.CreateRequest(request, HttpMethod.Get, "certificates");
return await client.SendRequestWithJsonAsync<Models.QueryCertificatesResponse>(flurlReq, data: request, cancellationToken: cancellationToken);
}
}
}
| 41.157895 | 216 | 0.684783 | [
"MIT"
] | ZUOXIANGE/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.TenpayV3/Extensions/WechatTenpayClientExecuteCertificatesExtensions.cs | 1,606 | C# |
using RavenBot.Core.Ravenfall.Models;
namespace RavenBot.Core.Ravenfall.Requests
{
public class ArenaKickRequest
{
public Player Player { get; }
public Player TargetPlayer { get; }
public ArenaKickRequest(Player player, Player targetPlayer)
{
Player = player;
TargetPlayer = targetPlayer;
}
}
} | 23.3125 | 67 | 0.624665 | [
"MIT"
] | AbbyTheRat/RavenBot | src/RavenBot.Core.Ravenfall/Requests/ArenaKickRequest.cs | 375 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace profiler
{
public partial class gchart
{
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
}
}
| 27.185185 | 84 | 0.463215 | [
"MIT"
] | SAEONData/Profiler | gchart.aspx.designer.cs | 736 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.