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.Text;
using Thunder.Blazor.Models;
namespace Thunder.Blazor.Components
{
/// <summary>
/// 基础对象
/// </summary>
public interface IThunderObject
{
/// <summary>
/// 对象名称
/// </summary>
string ObjectName { get; set; }
/// <summary>
/// 自定义对象
/// </summary>
object Tag { get; set; }
}
/// <summary>
/// 节点接口
/// </summary>
public interface INode<TModel>
{
/// <summary>
/// 父节点
/// </summary>
TModel ParentNode { get; set; }
/// <summary>
/// 子节点
/// </summary>
IList<TModel> ChildNodes { get; }
//void AddChild(TModel child);
//void AddRangChild(IList<TModel> childs);
//void RemoveChild(TModel child);
//void ClearChild();
}
/// <summary>
/// 基础行为
/// </summary>
public interface IBaseBehaver
{
/// <summary>
/// 是否可见
/// </summary>
bool IsVisabled { get; set; }
/// <summary>
/// 是否激活
/// </summary>
bool IsActived { get; set; }
/// <summary>
/// 是否有效
/// </summary>
bool IsEnabled { get; set; }
/// <summary>
/// 操作指令
/// </summary>
Action<object> CommandAction { get; set; }
Action<object> OnClosed { get; set; }
Action<object> OnClosing { get; set; }
}
/// <summary>
/// 组件行为
/// </summary>
public interface IBehaverComponent
{
/// <summary>
/// 操作指令
/// </summary>
EventHandler<ContextResult> OnCommand { get; set; }
/// <summary>
/// 显示 / 激活
/// </summary>
void Show();
/// <summary>
/// 关闭
/// </summary>
void Close();
}
public interface IBehaver
{
/// <summary>
/// 加载
/// </summary>
Action<object> Load { get; set; }
/// <summary>
/// 显示 / 激活
/// </summary>
Action Show { get; set; }
/// <summary>
/// 关闭
/// </summary>
Action Close { get; set; }
}
/// <summary>
/// 行为接口
/// </summary>
public interface IBehaver<T>: IBehaver
{
/// <summary>
/// 加载
/// </summary>
Action<T> LoadItem { get; set; }
/// <summary>
/// 显示 / 激活
/// </summary>
Action<T> ShowItem { get; set; }
/// <summary>
/// 关闭
/// </summary>
Action<T> CloseItem { get; set; }
}
/// <summary>
/// 可视化接口
/// </summary>
public interface IVisual
{
Action StateHasChanged { get; }
}
/// <summary>
/// 容器
/// </summary>
public interface IContainer
{
TComponent Content { get; set; }
}
/// <summary>
/// CSS 动画
/// </summary>
public interface IAnimate
{
/// <summary>
/// 启用动画
/// </summary>
bool AnimateEnabled { get; set; }
/// <summary>
/// 进入动画
/// </summary>
string AnimateEnter { get; set; }
/// <summary>
/// 退出动画
/// </summary>
string AnimateExit { get; set; }
}
/// <summary>
/// 附加信息
/// </summary>
public interface IAttachment
{
/// <summary>
/// 附加信息
/// </summary>
string AttachmentInfo { get; set; }
/// <summary>
/// 标注信息
/// </summary>
string BadgeInfo { get; set; }
}
}
| 20.936416 | 59 | 0.437604 | [
"MIT"
] | alislin/Thunder.Blazor | Thunder.Blazor/Thunder.Blazor/Components/Base/IBlazorObject.cs | 3,844 | C# |
<<<<<<< HEAD
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Media3D;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Controls;
using System.Diagnostics;
=======
using System.Windows;
>>>>>>> 2ec6f35c8f2f9655bb27eff3fb81c69c167a56c6
using Microsoft.FSharp.Collections;
using Microsoft.Kinect;
using Dynamo.Connectors;
<<<<<<< HEAD
using Dynamo.FSchemeInterop;
using Dynamo.FSchemeInterop.Node;
using Dynamo.Utilities;
=======
>>>>>>> 2ec6f35c8f2f9655bb27eff3fb81c69c167a56c6
using Value = Dynamo.FScheme.Value;
namespace Dynamo.Nodes
{
[NodeName("Kinect")]
[NodeCategory(BuiltinNodeCategories.COMMUNICATION)]
[NodeDescription("Read from a Kinect.")]
public class dynKinect : dynNodeWithOneOutput
{
//Kinect Runtime
//Image image1;
//ColorImageFrame planarImage;
//XYZ rightHandLoc = new XYZ();
//ReferencePoint rightHandPt;
//Point3D rightHandPt;
//System.Windows.Shapes.Ellipse rightHandEllipse;
public dynKinect()
{
InPortData.Add(new PortData("exec", "Execution Interval", typeof(object)));
InPortData.Add(new PortData("X scale", "The amount to scale the skeletal measurements in the X direction.", typeof(double)));
InPortData.Add(new PortData("Y scale", "The amount to scale the skeletal measurements in the Y direction.", typeof(double)));
InPortData.Add(new PortData("Z scale", "The amount to scale the skeletal measurements in the Z direction.", typeof(double)));
OutPortData.Add(new PortData("kinect data", "position data from the kinect", typeof(object)));
//int width = 320;
//int height = 240;
//WriteableBitmap wbitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);
//// Create an array of pixels to contain pixel color values
//uint[] pixels = new uint[width * height];
//int red;
//int green;
//int blue;
//int alpha;
//for (int x = 0; x < width; ++x)
//{
// for (int y = 0; y < height; ++y)
// {
// int i = width * y + x;
// red = 0;
// green = 255 * y / height;
// blue = 255 * (width - x) / width;
// alpha = 255;
// pixels[i] = (uint)((blue << 24) + (green << 16) + (red << 8) + alpha);
// }
//}
//// apply pixels to bitmap
//wbitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * 4, 0);
//image1 = new Image();
//image1.Width = width;
//image1.Height = height;
//image1.Margin = new Thickness(5);
//image1.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
//image1.Name = "image1";
//image1.VerticalAlignment = System.Windows.VerticalAlignment.Top;
//image1.Source = wbitmap;
////image1.Margin = new Thickness(0, 0, 0, 0);
//Canvas trackingCanvas = new Canvas();
//trackingCanvas.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
//trackingCanvas.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
////add an ellipse to track the hand
//rightHandEllipse = new System.Windows.Shapes.Ellipse();
//rightHandEllipse.Height = 10;
//rightHandEllipse.Width = 10;
//rightHandEllipse.Name = "rightHandEllipse";
//SolidColorBrush yellowBrush = new SolidColorBrush(System.Windows.Media.Colors.OrangeRed);
//rightHandEllipse.Fill = yellowBrush;
//NodeUI.inputGrid.Children.Add(image1);
//NodeUI.inputGrid.Children.Add(trackingCanvas);
//trackingCanvas.Children.Add(rightHandEllipse);
<<<<<<< HEAD
//RegisterAllPorts();
=======
//NodeUI.RegisterAllPorts();
>>>>>>> 2ec6f35c8f2f9655bb27eff3fb81c69c167a56c6
//NodeUI.Width = width + 120;// 450;
//NodeUI.Height = height + 5;
//NodeUI.Loaded += new RoutedEventHandler(topControl_Loaded);
}
//void topControl_Loaded(object sender, RoutedEventArgs e)
//{
// SetupKinect();
// nui.VideoFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_VideoFrameReady);
// nui.DepthFrameReady += new EventHandler<ImageFrameReadyEventArgs>(nui_DepthFrameReady);
// nui.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(nui_SkeletonFrameReady);
// nui.VideoStream.Open(ImageStreamType.Video, 2, Microsoft.Research.Kinect.Nui.ImageResolution.Resolution640x480, ImageType.Color);
// nui.DepthStream.Open(ImageStreamType.Depth, 2, Microsoft.Kinect.ImageResolution.Resolution320x240, ImageType.Depth);
//}
public override Value Evaluate(FSharpList<Value> args)
{
//if (rightHandPt == null)
//{
// //create a reference point to track the right hand
// //rightHandPt = dynSettings.Instance.Doc.Document.FamilyCreate.NewReferencePoint(rightHandLoc);
// System.Windows.Point relativePoint = rightHandEllipse.TransformToAncestor(dynSettings.Bench.WorkBench)
// .Transform(new System.Windows.Point(0, 0));
// Canvas.SetLeft(rightHandEllipse, relativePoint.X);
// Canvas.SetTop(rightHandEllipse, relativePoint.Y);
// //add the right hand point at the base of the tree
// //this.Tree.Trunk.Leaves.Add(rightHandPt);
//}
//if (((Value.Number)args[0]).Item == 1)
//{
// var input = (Element)((Value.Container)args[0]).Item;
// double xScale = (double)((Value.Container)args[1]).Item;
// double yScale = (double)((Value.Container)args[2]).Item;
// double zScale = (double)((Value.Container)args[3]).Item;
// //update the image
// image1.Source = nui.DepthStream.GetNextFrame(0).ToBitmapSource();
// //get skeletonData
// SkeletonFrame allSkeletons = nui.SkeletonEngine.GetNextFrame(0);
// if (allSkeletons != null)
// {
// //get the first tracked skeleton
// Skeleton skeleton = (from s in allSkeletons.Skeletons
// where s.TrackingState == SkeletonTrackingState.Tracked
// select s).FirstOrDefault();
// if (skeleton != null)
// {
// Joint HandRight = skeleton.Joints[JointID.HandRight];
// rightHandLoc = new Point3D(HandRight.Position.X * xScale, HandRight.Position.Z * zScale, HandRight.Position.Y * yScale);
// SetEllipsePosition(rightHandEllipse, HandRight);
// Point3D vec = rightHandLoc - rightHandPt.Position;
// Debug.WriteLine(vec.ToString());
// //move the reference point
// dynSettings.Instance.Doc.Document.Move(rightHandPt, vec);
// dynSettings.Instance.Doc.RefreshActiveView();
// }
// }
//}
return Value.NewNumber(0);
}
private void SetEllipsePosition(FrameworkElement ellipse, Joint joint)
{
//var scaledJoint = joint.ScaleTo(320, 240, .5f, .5f);
//System.Windows.Point relativePoint = ellipse.TransformToAncestor(dynSettings.Instance.Bench.workBench)
// .Transform(new System.Windows.Point(scaledJoint.Position.X, scaledJoint.Position.Y));
//Canvas.SetLeft(ellipse, relativePoint.X);
//Canvas.SetTop(ellipse, relativePoint.Y);
// Canvas.SetLeft(ellipse, scaledJoint.Position.X);
// Canvas.SetTop(ellipse, scaledJoint.Position.Y);
}
//void nui_VideoFrameReady(object sender, ImageFrameReadyEventArgs e)
//{
// PlanarImage image = e.ImageFrame.Image;
// image1.Source = e.ImageFrame.ToBitmapSource();
//}
//void nui_DepthFrameReady(object sender, ImageFrameReadyEventArgs e)
//{
// planarImage = e.ImageFrame.Image;
// image1.Source = e.ImageFrame.ToBitmapSource();
//}
//void nui_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
//{
// SkeletonFrame allSkeletons = e.SkeletonFrame;
// //get the first tracked skeleton
// SkeletonData skeleton = (from s in allSkeletons.Skeletons
// where s.TrackingState == SkeletonTrackingState.Tracked
// select s).FirstOrDefault();
// Joint HandRight = skeleton.Joints[JointID.HandRight];
// rightHandLoc = new XYZ(HandRight.Position.X, HandRight.Position.Y, HandRight.Position.Z);
// //move the reference point
// dynSettings.Instance.Doc.Document.Move(rightHandPt, rightHandLoc - rightHandPt.Position);
//}
//private void SetupKinect()
//{
// if (Microsoft.Kinect.KinectSensorCollection == 0)
// {
// this.NodeUI.ToolTipText = "No Kinect connected";
// }
// else
// {
// //use first Kinect
// nui = Runtime.Kinects[0]; //Initialize to return both Color & Depth images
// //nui.Initialize(RuntimeOptions.UseColor | RuntimeOptions.UseDepth);
// nui.Initialize(RuntimeOptions.UseDepth | RuntimeOptions.UseSkeletalTracking);
// }
//}
}
} | 40.289683 | 146 | 0.577169 | [
"Apache-2.0",
"MIT"
] | frankfralick/Dynamo | src/Legacy/DynamoKinect/dynKinect.cs | 10,155 | C# |
// Copyright (c) Russlan Akiev. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace ServiceBase
{
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
/// <summary>
/// Configuration utilities
/// </summary>
public static class ConfigUtils
{
public static string GetConfigFilePath(string basePath)
{
string configRoot = EnironmentUtils.GetConfigRoot();
if (string.IsNullOrWhiteSpace(configRoot))
{
configRoot = Path.Combine(basePath, "config");
}
string configFilePath = Path.Combine(configRoot, "config.json");
if (!File.Exists(Path.Combine(basePath, configFilePath)))
{
throw new ApplicationException(
$"Config file does not exists \"{configFilePath}\"");
}
return configFilePath;
}
public static IConfigurationRoot LoadConfig<TStartup>(
string[] args,
string basePath)
where TStartup : class
{
IConfigurationBuilder configBuilder = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile(
path: ConfigUtils.GetConfigFilePath(basePath),
optional: false,
reloadOnChange: false);
if (EnironmentUtils.IsDevelopmentEnvironment())
{
configBuilder.AddUserSecrets<TStartup>();
}
configBuilder.AddEnvironmentVariables();
if (args != null)
{
configBuilder.AddCommandLine(args);
}
return configBuilder.Build();
}
}
} | 29.774194 | 107 | 0.56338 | [
"Apache-2.0"
] | aruss/ServiceBase | src/ServiceBase/ConfigUtils.cs | 1,848 | C# |
namespace Sakuno.KanColle.Amatsukaze.Views.Overviews
{
/// <summary>
/// EquipmentOverviewWindow.xaml の相互作用ロジック
/// </summary>
partial class EquipmentOverviewWindow
{
public EquipmentOverviewWindow()
{
InitializeComponent();
}
}
}
| 20.857143 | 53 | 0.616438 | [
"MIT"
] | ly931003/ing | src/HeavenlyWind/Views/Overviews/EquipmentOverviewWindow.xaml.cs | 312 | C# |
namespace FluentFiles.Core.Base
{
using System;
using System.Reflection;
using FluentFiles.Core.Conversion;
using FluentFiles.Core.Extensions;
internal abstract class FieldSettingsBase : IFieldSettingsContainer
{
private IFieldValueConverter? _converter;
private readonly Func<object, object?> _getValue;
private readonly Action<object, object?> _setValue;
protected readonly IFieldValueConverter DefaultConverter;
protected FieldSettingsBase(MemberInfo member)
{
Type = member.MemberType();
Member = member;
DefaultConverter = Type.GetConverter();
UniqueKey = $"[{member.DeclaringType.AssemblyQualifiedName}]:{member.Name}";
_getValue = ReflectionHelper.CreateMemberGetter(member);
_setValue = ReflectionHelper.CreateMemberSetter(member);
}
protected FieldSettingsBase(MemberInfo member, IFieldSettings settings)
: this(member)
{
Index = settings.Index;
IsNullable = settings.IsNullable;
NullValue = settings.NullValue;
Converter = settings.Converter;
}
public string UniqueKey { get; }
public int? Index { get; set; }
public bool IsNullable { get; set; }
public string? NullValue { get; set; }
public IFieldValueConverter? Converter
{
get => _converter ?? DefaultConverter;
set => _converter = value;
}
public MemberInfo Member { get; }
public Type Type { get; }
public object? GetValueOf(object instance) => _getValue(instance);
public void SetValueOf(object instance, object? value) => _setValue(instance, value);
}
} | 33.037037 | 93 | 0.632848 | [
"MIT"
] | mthamil/FlatFile | src/FluentFiles.Core/Base/FieldSettingsBase.cs | 1,786 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace StudentSystem.WebApi.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
| 17.411765 | 44 | 0.652027 | [
"MIT"
] | vic-alexiev/TelerikAcademy | JavaScript Frameworks/Homework Assignments/2. Mustache.js/StudentSystem.Services/Controllers/HomeController.cs | 298 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class weapon_laser : MonoBehaviour
{
Ray2D ray;
public LineRenderer lineRenderer;
public Transform LaserShoot;
public Transform LaserHit;
private Vector2 playerPos;
public float offsetLaser;
public LayerMask mask;
public GameObject target;
public GameObject hitParticle;
public GameObject followingMe;
public int followDistance;
private List<Vector3> storedPositions;
public bool shoot;
public int powerShot;
void Start()
{
storedPositions = new List<Vector3>();
lineRenderer.useWorldSpace = true;
LaserHit = GameObject.Find("NinjaHero").transform;
}
void FixedUpdate()
{
if (shoot) {
raycast_travel();
}
else
{
RemoveLaser();
}
}
public void raycast_travel()
{
playerPos = new Vector2(LaserHit.position.x, LaserHit.position.y);
playerPos = new Vector2(LaserHit.position.x - LaserShoot.position.x, LaserHit.position.y - LaserShoot.position.y);
storedPositions.Add(playerPos);
if (storedPositions.Count > followDistance)
{
//followingMe.transform.position = storedPositions[0];
ray = new Ray2D(LaserShoot.position, storedPositions[0]);
RaycastHit2D info = Physics2D.Raycast(ray.origin, ray.direction + new Vector2(0, 0.2f), 100f, mask);
//Debug.DrawRay(ray.origin,ray.direction,Color.blue);
lineRenderer.SetPosition(0, LaserShoot.position);
lineRenderer.SetPosition(1, info.point);
hitParticle.transform.position = info.point;
hitParticle.SetActive(true);
if (info.collider != null)
{
//Debug.Log("RayCast: " + info.transform.gameObject);
if (info.transform.gameObject.CompareTag("Player"))
{
//Debug.LogWarning("Detected Enemies");
if (Random.Range(-50f, 100f) > 70f)
{
general.Instance.DamageHero(powerShot);
LaserHit.GetComponent<hero_controller>().dano(general.Instance.lifeHero);
}
else
{
}
}
else
{
//Debug.Log("Detected other objects");
}
}
else
{
//Debug.Log("No collisions with any objects");
}
storedPositions.RemoveAt(0);
}
}
private void RemoveLaser()
{
lineRenderer.SetPosition(0, Vector2.zero);
lineRenderer.SetPosition(1, Vector2.zero);
hitParticle.SetActive(false);
}
public void shootState(bool state)
{
if (state)
{
shoot = true;
}
else
{
shoot = false;
}
}
}
| 22.785185 | 122 | 0.542588 | [
"MIT"
] | ConradoAndrade/Dont-Trust-in-Drones | Assets/codes/weapon_laser.cs | 3,076 | C# |
using System;
using System.Collections.Generic;
namespace SKIT.FlurlHttpClient.Wechat.TenpayV3.Models
{
/// <summary>
/// <para>表示 [POST] /goldplan/merchants/close-advertising-show 接口的响应。</para>
/// </summary>
public class CloseGoldPlanAdvertisingShowResponse : WechatTenpayResponse
{
}
}
| 24.230769 | 80 | 0.714286 | [
"MIT"
] | KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.TenpayV3/Models/GoldPlan/CloseGoldPlanAdvertisingShowResponse.cs | 333 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DasContract.Editor.Entities.Exceptions
{
public class EditorContractException: Exception
{
public EditorContractException(string message) : base(message)
{
}
public EditorContractException(string message, Exception innerException) : base(message, innerException)
{
}
public EditorContractException()
{
}
}
}
| 21.5 | 112 | 0.663848 | [
"MIT"
] | drozdik-m/DasContractEditor | DasContract.Editor/DasContract.Editor.Entities/Exceptions/EditorContractException.cs | 475 | C# |
using UnityEngine;
using UnityEngine.SceneManagement;
public class Zumbi : MonoBehaviour
{
public Animator anim;
public Rigidbody rb;
public Collider coll;
private Transform jogador;
public float delay = 1f;
public float delayDamage = 1f;
private bool andando = false;
private bool vivo = true;
public float speed = 0.35f;
public int hp = 2;
private void Start()
{
jogador = GameObject.FindGameObjectWithTag("Player").transform;
transform.LookAt(jogador);
transform.eulerAngles = new Vector3(
0,
transform.eulerAngles.y,
0
);
Invoke(nameof(Andar), delay);
}
private void Andar()
{
andando = true;
}
public void Update()
{
if (andando)
{
rb.velocity = transform.forward * speed;
}
}
private void OnTriggerEnter(Collider other)
{
if (vivo && other.CompareTag("Projétil"))
{
AplicarDano();
Destroy(other.gameObject);
}
}
private void AplicarDano()
{
hp--;
if (hp <= 0)
{
Morrer();
}
else
{
anim.SetTrigger("Damage");
andando = false;
Invoke(nameof(Andar), delayDamage);
}
}
private void Morrer()
{
rb.isKinematic = true;
coll.enabled = false;
andando = false;
vivo = false;
anim.SetTrigger("Die");
}
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Player"))
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
}
| 17.777778 | 77 | 0.53125 | [
"MIT"
] | paulosalvatore/Intensivo8_Ocean_VR | Assets/Scripts/Zumbi.cs | 1,763 | C# |
//
// CounterAssemblyBuilder.cs
//
// Author:
// Sergiy Sakharov (sakharov@gmail.com)
//
// (C) 2011 Sergiy Sakharov
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Linq.Expressions;
using Coverage.Common;
using Mono.Cecil;
using Mono.Cecil.Cil;
using System.Reflection;
namespace Coverage.Instrument
{
/// <summary>
/// Creates custom Coverage.Counter assembly
/// This assembly has build-in location of
/// coverage xml file.
/// Also provides method definition of a Hit
/// method of counter in created assembly
/// </summary>
public class CounterAssemblyBuilder
{
private MethodDefinition _counterMethodDef;
private AssemblyDefinition _counterAssemblyDef;
/// <summary>
/// Gets Hit method definition
/// </summary>
public MethodDefinition CounterMethodDef
{
get
{
if(_counterMethodDef == null)
{
//Retrieving MethodInfo using expressions will guarantee compile time error if method signature changes
Expression<Action<string, int>> counterExpression = (moduleId, id) => Counter.Hit(moduleId, id);
var counterMethodToken = ((MethodCallExpression)counterExpression.Body).Method.MetadataToken;
_counterMethodDef = (MethodDefinition)CounterAssemblyDef.MainModule.LookupToken(counterMethodToken);
}
return _counterMethodDef;
}
}
/// <summary>
/// Gets counter assembly definition with auto-"hardcoded" coverage file location
/// </summary>
public AssemblyDefinition CounterAssemblyDef
{
get
{
if (_counterAssemblyDef == null)
{
_counterAssemblyDef = AssemblyDefinition.ReadAssembly(typeof(Counter).Assembly.Location);
_counterAssemblyDef.Name.Name += ".Gen";
SetCoverageFilePath(Path.GetFullPath(Configuration.CoverageFile));
}
return _counterAssemblyDef;
}
}
private void SetCoverageFilePath(string coverageReportPath)
{
//Retrieving PropertyInfo using expressions
Expression<Func<string>> coverageFileResolver = () => Counter.CoverageFilePath;
//Modifying getter of the coverage file path - adding 2 instructions at the beginning: loadstr /new path/ and ret.
//Old instructions become unreachable...
/*
* TODO: Awaiting Mono.Cecil fix
* var pathAccessorToken = ((MemberExpression)coverageFileResolver.Body).Member.MetadataToken;
* var pathAccessorDef = (PropertyDefinition)CounterAssemblyDef.MainModule.LookupByToken(new MetadataToken(pathAccessorToken));
* var pathGetterDef = pathAccessorDef.GetMethod;
*/
var pathGetterToken = ((PropertyInfo)((MemberExpression)coverageFileResolver.Body).Member).GetGetMethod().MetadataToken;
var pathGetterDef = (MethodDefinition)CounterAssemblyDef.MainModule.LookupToken(pathGetterToken);
var worker = pathGetterDef.Body.GetILProcessor();
worker.InsertBefore(pathGetterDef.Body.Instructions[0], worker.Create(OpCodes.Ret));
worker.InsertBefore(pathGetterDef.Body.Instructions[0], worker.Create(OpCodes.Ldstr, coverageReportPath));
}
/// <summary>
/// Saves customized Counter assembly to specified location
/// </summary>
/// <param name="path">Path</param>
public void Save(string path)
{
var counterAssemblyFile = Path.Combine(path, CounterAssemblyDef.Name.Name + ".dll");
CounterAssemblyDef.Write(counterAssemblyFile);
Configuration.CleanupCallback += () => File.Delete(counterAssemblyFile);
}
}
} | 37.406504 | 131 | 0.7218 | [
"MIT"
] | SteveGilham/dot-net-coverage | Coverage/Instrument/CounterAssemblyBuilder.cs | 4,601 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Cipher
{
public interface IVigenere
{
public string DefaultAlphabet { get; }
public string Encrypt(string source, string key);
public string Decrypt(string encrypted, string key);
public IEnumerable<string> Encrypt(IEnumerable<string> source, string key);
public IEnumerable<string> Decrypt(IEnumerable<string> encrypted, string key);
}
}
| 23.761905 | 86 | 0.669339 | [
"MIT"
] | s1nav/TestTasks | SpeechPro/Cipher/IVigenere.cs | 501 | C# |
using DragonSpark.Runtime;
using System;
using System.IO;
using DragonSpark.Windows;
namespace DevelopersWin.VoteReporter
{
public interface IStorage
{
Uri Save( object item, string fileName = null );
}
public sealed class Storage : IStorage
{
readonly ISerializer serializer;
readonly DirectoryInfo directory;
public Storage( ISerializer serializer, DirectoryInfo directory )
{
this.serializer = serializer;
this.directory = directory;
}
public Uri Save( object item, string fileName = null )
{
var extension = item is string ? "txt" : "xaml";
var path = Path.Combine( directory.FullName, fileName ?? $"{FileSystem.GetValidPath()}.{extension}" );
var content = item as string ?? serializer.Save( item );
File.WriteAllText( path, content );
var result = new Uri( path );
return result;
}
}
} | 24.114286 | 105 | 0.709716 | [
"MIT"
] | DragonSpark/VoteReporter | DevelopersWin.VoteReporter/IStorage.cs | 844 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace JpegLibrary.Benchmarks
{
internal class JpegRgbToYCbCrComponentConverter
{
public static JpegRgbToYCbCrComponentConverter Shared { get; } = new JpegRgbToYCbCrComponentConverter();
private int[] _yRTable;
private int[] _yGTable;
private int[] _yBTable;
private int[] _cbRTable;
private int[] _cbGTable;
private int[] _cbBTable;
private int[] _crGTable;
private int[] _crBTable;
private const int ScaleBits = 16;
private const int CBCrOffset = 128 << ScaleBits;
private const int Half = 1 << (ScaleBits - 1);
public JpegRgbToYCbCrComponentConverter()
{
_yRTable = new int[256];
_yGTable = new int[256];
_yBTable = new int[256];
_cbRTable = new int[256];
_cbGTable = new int[256];
_cbBTable = new int[256];
_crGTable = new int[256];
_crBTable = new int[256];
for (int i = 0; i < 256; i++)
{
// The values for the calculations are left scaled up since we must add them together before rounding.
_yRTable[i] = Fix(0.299F) * i;
_yGTable[i] = Fix(0.587F) * i;
_yBTable[i] = (Fix(0.114F) * i) + Half;
_cbRTable[i] = (-Fix(0.168735892F)) * i;
_cbGTable[i] = (-Fix(0.331264108F)) * i;
// We use a rounding fudge - factor of 0.5 - epsilon for Cb and Cr.
// This ensures that the maximum output will round to 255
// not 256, and thus that we don't have to range-limit.
//
// B=>Cb and R=>Cr tables are the same
_cbBTable[i] = (Fix(0.5F) * i) + CBCrOffset + Half - 1;
_crGTable[i] = (-Fix(0.418687589F)) * i;
_crBTable[i] = (-Fix(0.081312411F)) * i;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int Fix(float x)
{
return (int)((x * (1L << ScaleBits)) + 0.5F);
}
public void ConvertRgba32ToYComponent(ReadOnlySpan<byte> rgba, ref short y, int count)
{
if (rgba.Length < 4 * count)
{
throw new ArgumentException("RGB buffer is too small.", nameof(rgba));
}
int[] yRTable = _yRTable;
int[] yGTable = _yGTable;
int[] yBTable = _yBTable;
ref byte sourceRef = ref MemoryMarshal.GetReference(rgba);
byte r, g, b;
for (int i = 0; i < count; i++)
{
r = sourceRef;
g = Unsafe.Add(ref sourceRef, 1);
b = Unsafe.Add(ref sourceRef, 2);
Unsafe.Add(ref y, i) = (short)((yRTable[r] + yGTable[g] + yBTable[b]) >> ScaleBits);
sourceRef = ref Unsafe.Add(ref sourceRef, 4);
}
}
public void ConvertRgba32ToCbComponent(ReadOnlySpan<byte> rgba, ref short cb, int count)
{
if (rgba.Length < 4 * count)
{
throw new ArgumentException("RGB buffer is too small.", nameof(rgba));
}
int[] cbRTable = _cbRTable;
int[] cbGTable = _cbGTable;
int[] cbBTable =_cbBTable;
ref byte sourceRef = ref MemoryMarshal.GetReference(rgba);
byte r, g, b;
for (int i = 0; i < count; i++)
{
r = sourceRef;
g = Unsafe.Add(ref sourceRef, 1);
b = Unsafe.Add(ref sourceRef, 2);
Unsafe.Add(ref cb, i) = (short)((cbRTable[r] + cbGTable[g] + cbBTable[b]) >> ScaleBits);
sourceRef = ref Unsafe.Add(ref sourceRef, 4);
}
}
public void ConvertRgba32ToCrComponent(ReadOnlySpan<byte> rgba, ref short cr, int count)
{
if (rgba.Length < 4 * count)
{
throw new ArgumentException("RGB buffer is too small.", nameof(rgba));
}
int[] cbBTable = _cbBTable;
int[] crGTable = _crGTable;
int[] crBTable = _crBTable;
ref byte sourceRef = ref MemoryMarshal.GetReference(rgba);
byte r, g, b;
for (int i = 0; i < count; i++)
{
r = sourceRef;
g = Unsafe.Add(ref sourceRef, 1);
b = Unsafe.Add(ref sourceRef, 2);
Unsafe.Add(ref cr, i) = (short)((cbBTable[r] + crGTable[g] + crBTable[b]) >> ScaleBits);
sourceRef = ref Unsafe.Add(ref sourceRef, 4);
}
}
}
}
| 33.395833 | 118 | 0.509461 | [
"MIT"
] | yigolden/JpegLibrary | tests/JpegLibrary.Benchmarks/JpegRgbToYCbCrComponentConverter.cs | 4,811 | C# |
using System.Threading.Tasks;
using Toss.Shared;
namespace Toss.Client.Services
{
/// <summary>
/// Access to account informations
/// </summary>
public interface IAccountService
{
/// <summary>
/// Get the current user account details from backend
/// </summary>
/// <returns></returns>
Task<AccountViewModel> CurrentAccount();
}
} | 22.166667 | 61 | 0.606516 | [
"Apache-2.0"
] | OsvaldoMartini/Blazor_Projects | Toss.Blazor/Toss/Toss.Client/Services/IAccountService.cs | 401 | C# |
using Fuchsbau.Components.CrossCutting.DataTypes;
namespace Fuchsbau.Components.Data.DataStoring.Contract
{
public interface IComplaintImageRepository : IRepository<ComplaintImage>
{
}
} | 25 | 76 | 0.795 | [
"MIT"
] | hubertfuchs/Components | DataStoring.Contract/IComplaintImageRepository.cs | 202 | C# |
using System;
using System.Collections.Generic;
namespace FHIRGenomicsImporter.Model
{
public partial class AgspatientCtmsdata
{
public int PatientId { get; set; }
public int MessageId { get; set; }
public string StudyId { get; set; }
public string IndicationForTesting { get; set; }
public string DiseaseStatus { get; set; }
public string HasPreviouslyKnownMutations { get; set; }
public string PreviouslyKnownMutations { get; set; }
public DateTime UpdatedDate { get; set; }
}
}
| 32 | 64 | 0.642361 | [
"Apache-2.0"
] | emerge-ehri/FHIRGenomicsImporter | FHIRGenomicsImporter/Model/AgspatientCtmsdata.cs | 578 | C# |
using System.Collections.Generic;
using System.Linq;
using Abp.MultiTenancy;
using Afonsoft.Ranking.Authorization;
namespace Afonsoft.Ranking.DashboardCustomization.Definitions
{
public class DashboardConfiguration
{
public List<DashboardDefinition> DashboardDefinitions { get; } = new List<DashboardDefinition>();
public List<WidgetDefinition> WidgetDefinitions { get; } = new List<WidgetDefinition>();
public List<WidgetFilterDefinition> WidgetFilterDefinitions { get; } = new List<WidgetFilterDefinition>();
public DashboardConfiguration()
{
#region FilterDefinitions
// These are global filter which all widgets can use
var dateRangeFilter = new WidgetFilterDefinition(
RankingDashboardCustomizationConsts.Filters.FilterDateRangePicker,
"FilterDateRangePicker"
);
WidgetFilterDefinitions.Add(dateRangeFilter);
// Add your filters here
#endregion
#region WidgetDefinitions
// Define Widgets
#region TenantWidgets
var tenantWidgetsDefaultPermission = new List<string>
{
AppPermissions.Pages_Tenant_Dashboard
};
var dailySales = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Tenant.DailySales,
"WidgetDailySales",
side: MultiTenancySides.Tenant,
usedWidgetFilters: new List<string> { dateRangeFilter.Id },
permissions: tenantWidgetsDefaultPermission
);
var generalStats = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Tenant.GeneralStats,
"WidgetGeneralStats",
side: MultiTenancySides.Tenant,
permissions: tenantWidgetsDefaultPermission.Concat(new List<string>{ AppPermissions.Pages_Administration_AuditLogs }).ToList());
var profitShare = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Tenant.ProfitShare,
"WidgetProfitShare",
side: MultiTenancySides.Tenant,
permissions: tenantWidgetsDefaultPermission);
var memberActivity = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Tenant.MemberActivity,
"WidgetMemberActivity",
side: MultiTenancySides.Tenant,
permissions: tenantWidgetsDefaultPermission);
var regionalStats = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Tenant.RegionalStats,
"WidgetRegionalStats",
side: MultiTenancySides.Tenant,
permissions: tenantWidgetsDefaultPermission);
var salesSummary = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Tenant.SalesSummary,
"WidgetSalesSummary",
usedWidgetFilters: new List<string>() { dateRangeFilter.Id },
side: MultiTenancySides.Tenant,
permissions: tenantWidgetsDefaultPermission);
var topStats = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Tenant.TopStats,
"WidgetTopStats",
side: MultiTenancySides.Tenant,
permissions: tenantWidgetsDefaultPermission);
WidgetDefinitions.Add(generalStats);
WidgetDefinitions.Add(dailySales);
WidgetDefinitions.Add(profitShare);
WidgetDefinitions.Add(memberActivity);
WidgetDefinitions.Add(regionalStats);
WidgetDefinitions.Add(topStats);
WidgetDefinitions.Add(salesSummary);
// Add your tenant side widgets here
#endregion
#region HostWidgets
var hostWidgetsDefaultPermission = new List<string>
{
AppPermissions.Pages_Administration_Host_Dashboard
};
var incomeStatistics = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Host.IncomeStatistics,
"WidgetIncomeStatistics",
side: MultiTenancySides.Host,
permissions: hostWidgetsDefaultPermission);
var hostTopStats = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Host.TopStats,
"WidgetTopStats",
side: MultiTenancySides.Host,
permissions: hostWidgetsDefaultPermission);
var editionStatistics = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Host.EditionStatistics,
"WidgetEditionStatistics",
side: MultiTenancySides.Host,
permissions: hostWidgetsDefaultPermission);
var subscriptionExpiringTenants = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Host.SubscriptionExpiringTenants,
"WidgetSubscriptionExpiringTenants",
side: MultiTenancySides.Host,
permissions: hostWidgetsDefaultPermission);
var recentTenants = new WidgetDefinition(
RankingDashboardCustomizationConsts.Widgets.Host.RecentTenants,
"WidgetRecentTenants",
side: MultiTenancySides.Host,
usedWidgetFilters: new List<string>() { dateRangeFilter.Id },
permissions: hostWidgetsDefaultPermission);
WidgetDefinitions.Add(incomeStatistics);
WidgetDefinitions.Add(hostTopStats);
WidgetDefinitions.Add(editionStatistics);
WidgetDefinitions.Add(subscriptionExpiringTenants);
WidgetDefinitions.Add(recentTenants);
// Add your host side widgets here
#endregion
#endregion
#region DashboardDefinitions
// Create dashboard
var defaultTenantDashboard = new DashboardDefinition(
RankingDashboardCustomizationConsts.DashboardNames.DefaultTenantDashboard,
new List<string>
{
generalStats.Id, dailySales.Id, profitShare.Id, memberActivity.Id, regionalStats.Id, topStats.Id, salesSummary.Id
});
DashboardDefinitions.Add(defaultTenantDashboard);
var defaultHostDashboard = new DashboardDefinition(
RankingDashboardCustomizationConsts.DashboardNames.DefaultHostDashboard,
new List<string>
{
incomeStatistics.Id,
hostTopStats.Id,
editionStatistics.Id,
subscriptionExpiringTenants.Id,
recentTenants.Id
});
DashboardDefinitions.Add(defaultHostDashboard);
// Add your dashboard definiton here
#endregion
}
}
}
| 38.956044 | 144 | 0.627645 | [
"MIT"
] | afonsoft/Ranking | src/Afonsoft.Ranking.Core/DashboardCustomization/Definitions/DashboardConfiguration.cs | 7,092 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace OnlineTradingSystem
{
public partial class MainWindow : Window
{
List<Int32> numbersID;
readonly DA dal;
DataTable dt;
#region Add Item
private void AddItem_Click(object sender, RoutedEventArgs e)
{
TabItem tab = tabsTopControl.SelectedItem as TabItem;
switch (tab.Name)
{
case "Product_List":
Add_product_click(sender, e);
break;
case "Supplier_List":
Add_supplier_click(sender, e);
break;
}
// Add item to the data tabel
}
#endregion
#region Exsport Data Table To Sql Server
private void Export_data_Click(object sender, RoutedEventArgs e)
{
sqldata.ExportSqlData(products, regis);
Export_data.Click += new RoutedEventHandler(Window_Activated);
}
#endregion
#region Import Data table To GrideData
private void Import_data_Click(object sender, RoutedEventArgs e)
{
numbersID = new List<Int32>();
sqldata.ImportStoreName();
numbersID = sqldata.ImportListNumberId();
Warp.Children.Clear();
Show_product();
Show_supplier();
}
#endregion
#region Remove Product
private void RemoveItem_Click(object sender, RoutedEventArgs e)
{
if (RemoveItem.IsChecked == true)
{
Border item = sender as Border;
try
{
Warp.Children.Remove(item);
int index = dataGridProduct.SelectedIndex;
var indx = dataGridProduct.SelectedItems;
if (indx.Count == 0)
{
string bordName = item.Name;
int num = Convert.ToInt32(bordName.Remove(0, 1));
Product pid = products.Where<Product>(X => X.ID == num).Single<Product>();
index = products.IndexOf(pid);
products.RemoveRange(index, 1);
}
else if (indx.Count != 0)
{
products.RemoveRange(index, indx.Count);
bord.RemoveRange(index, indx.Count);
Warp.Children.RemoveRange(index, indx.Count);
}
}
catch
{
return;
}
finally
{
dataGridProduct.Items.Refresh();
}
}
}
#endregion
#region Enter new Colume
public static class Prompt
{
public static string ShowDialog()
{
System.Windows.Forms.Form prompt = new System.Windows.Forms.Form()
{
Width = 200,
Height = 150,
Left = 0,
Text = "New Column"
};
System.Windows.Forms.Label textLabel = new System.Windows.Forms.Label() { Left = 50, Top = 20, Text = "Enter new Colume" };
System.Windows.Forms.TextBox textBox = new System.Windows.Forms.TextBox() { Left = 50, Top = 50, Width = 100 };
System.Windows.Forms.Button confirmation = new System.Windows.Forms.Button() { Text = "Ok", Left = 90, Width = 50, Top = 70 };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.Controls.Add(textBox);
prompt.ShowDialog();
return textBox.Text;
}
}
#endregion
#region Product Sales Click
private void Product_Sales_Click(object sender, RoutedEventArgs e)
{
dt = new DataTable();
dt = dal.Product_Sales_by_Store_Id(regis);
dataGridProduct.ItemsSource = dt.AsDataView();
}
#endregion
#region Show Custumer List
private void Custumer_List_click(object sender, RoutedEventArgs e)
{
dt = new DataTable();
dt = dal.Customer_List_By_Store_Id(regis);
dataGridProduct.ItemsSource = dt.AsDataView();
}
#endregion
}
}
| 27.005714 | 142 | 0.495133 | [
"BSD-2-Clause"
] | orenber/Online-Trading-System | OnlineTradingSystem/OnlineTradingSystem/OnlineStoreMenu.xaml.cs | 4,728 | 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("ManagedHandleUtils")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Google Inc.")]
[assembly: AssemblyProduct("ManagedHandleUtils")]
[assembly: AssemblyCopyright("Copyright © Google Inc. 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("4146b337-25d5-4ceb-a1a0-c6b9cca19a3f")]
// 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.1.4.0")]
[assembly: AssemblyInformationalVersion("1.1.4")]
| 38.973684 | 84 | 0.749494 | [
"Apache-2.0"
] | 1orenz0/sandbox-attacksurface-analysis-tools | ManagedHandleUtils/Properties/AssemblyInfo.cs | 1,484 | C# |
// This code is in the Public Domain. It is provided "as is"
// without express or implied warranty of any kind.
using System;
using System.Drawing;
using System.Windows.Forms;
using OpenTK.Graphics.OpenGL;
namespace Examples.WinForms
{
[Example("GLControl Simple", ExampleCategory.OpenTK, "GLControl", 1, Documentation="GLControlSimple")]
public partial class SimpleForm : Form
{
public SimpleForm()
{
InitializeComponent();
}
#region Events
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
glControl1_Resize(this, EventArgs.Empty); // Ensure the Viewport is set up correctly
GL.ClearColor(Color.Crimson);
}
private void redButton_Click(object sender, EventArgs e)
{
GL.ClearColor(Color.Crimson);
glControl1.Invalidate();
}
private void greenButton_Click(object sender, EventArgs e)
{
GL.ClearColor(Color.ForestGreen);
glControl1.Invalidate();
}
private void blueButton_Click(object sender, EventArgs e)
{
GL.ClearColor(Color.RoyalBlue);
glControl1.Invalidate();
}
private void glControl1_Paint(object sender, PaintEventArgs e)
{
glControl1.MakeCurrent();
GL.Clear(ClearBufferMask.ColorBufferBit);
glControl1.SwapBuffers();
}
private void glControl1_Resize(object sender, EventArgs e)
{
if (glControl1.ClientSize.Height == 0)
glControl1.ClientSize = new System.Drawing.Size(glControl1.ClientSize.Width, 1);
GL.Viewport(0, 0, glControl1.ClientSize.Width, glControl1.ClientSize.Height);
}
private void glControl1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData)
{
case Keys.Escape:
this.Close();
break;
}
}
#endregion
#region public static void Main()
/// <summary>
/// Entry point of this example.
/// </summary>
[STAThread]
public static void Main()
{
using (SimpleForm example = new SimpleForm())
{
Utilities.SetWindowTitle(example);
example.ShowDialog();
}
}
#endregion
}
}
| 26.319149 | 106 | 0.565077 | [
"MIT"
] | jwatte/gears | OpenTK/1.0/Source/Examples/Examples/OpenTK/GLControl/GLControlSimple.cs | 2,476 | C# |
using System;
using System.Collections.Generic;
namespace OpenInvoicePeru.Estructuras.CommonAggregateComponents
{
[Serializable]
public class PricingReference
{
public List<AlternativeConditionPrice> AlternativeConditionPrices { get; set; }
public PricingReference()
{
AlternativeConditionPrices = new List<AlternativeConditionPrice>();
}
}
} | 25.3125 | 87 | 0.706173 | [
"Apache-2.0"
] | MrJmpl3-Forks/openinvoiceperu | OpenInvoicePeru/OpenInvoicePeru.Estructuras/CommonAggregateComponents/PricingReference.cs | 407 | C# |
using System;
using System.Collections.Generic;
using Cassette.Scripts;
using Moq;
using Should;
using Xunit;
namespace Cassette.RequireJS
{
public class ModuleInitializerTests
{
readonly ModuleInitializer configuration;
readonly List<Bundle> bundles;
public ModuleInitializerTests()
{
bundles = new List<Bundle>();
configuration = new ModuleInitializer(Mock.Of<IConfigurationScriptBuilder>());
GivenBundle("~/shared", new StubAsset("~/shared/require.js"));
}
[Fact]
public void InitializeModulesFromBundlesAssignsMainBundlePath()
{
configuration.InitializeModules(bundles, "~/shared/require.js");
configuration.MainBundlePath.ShouldEqual("~/shared");
}
[Fact]
public void GivenRequireJsPathNotFoundThenInitializeModulesFromBundlesThrows()
{
Assert.Throws<ArgumentException>(
() => configuration.InitializeModules(bundles, "~/fail/require.js")
);
}
[Fact]
public void SetImportAliasSetsModuleAlias()
{
GivenBundle(
"~/shared/jquery.js",
new StubAsset("~/shared/jquery.js", "define(\"jquery\",[],function(){})")
);
configuration.InitializeModules(bundles, "~/shared/require.js");
configuration.SetImportAlias("~/shared/jquery.js", "$");
configuration["~/shared/jquery.js"].Alias.ShouldEqual("$");
}
[Fact]
public void GivenUnknownScriptPathThenSetImportAliasThrowsArgumentException()
{
configuration.InitializeModules(bundles, "~/shared/require.js");
Assert.Throws<ArgumentException>(
() => configuration.SetImportAlias("~/shared/notfound.js", "$")
);
}
[Fact]
public void SetModuleReturnExpressionChangesPlainScriptModuleReturnExpression()
{
GivenBundle("~", new StubAsset("~/test.js"));
configuration.InitializeModules(bundles, "~/shared/require.js");
configuration.SetModuleReturnExpression("~/test.js", "{ test: 1 }");
((PlainScript)configuration["~/test.js"]).ModuleReturnExpression.ShouldEqual("{ test: 1 }");
}
[Fact]
public void GivenNamedBundleThenSetModuleReturnExpressionThrowsException()
{
GivenBundle("~", new StubAsset("~/test.js", "define(\"test\",[],function(){})"));
configuration.InitializeModules(bundles, "~/shared/require.js");
Assert.Throws<ArgumentException>(
() => configuration.SetModuleReturnExpression("~/test.js", "{ test: 1 }")
);
}
void GivenBundle(string path, params IAsset[] assets)
{
var bundle = new ScriptBundle(path);
foreach (var asset in assets)
{
bundle.Assets.Add(asset);
}
bundles.Add(bundle);
}
}
} | 34.022222 | 104 | 0.585892 | [
"MIT"
] | WS-QA/cassette | src/Cassette.RequireJS.UnitTests/ModuleInitializer.cs | 3,064 | C# |
namespace DddInPractice.UI.Common
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
}
| 16.769231 | 46 | 0.550459 | [
"Apache-2.0"
] | NicoDeAstis/DddInPractice | DddInPractice.UI/Common/MainWindow.xaml.cs | 220 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Bot Builder SDK GitHub:
// https://github.com/Microsoft/BotBuilder
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Threading.Tasks;
using Autofac;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Bot.Builder.Tests
{
[TestClass]
public sealed class EndConversationTests : DialogTestBase
{
[Serializable]
private sealed class TestResetDialog : IDialog<object>
{
async Task IDialog<object>.StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
}
public static int Increment(IBotDataBag bag, int start)
{
const string Key = "key";
int value;
if (bag.TryGetValue(Key, out value))
{
value = value + 1;
}
else
{
value = start;
}
bag.SetValue(Key, value);
return value;
}
public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> item)
{
var message = await item;
if (message.Text == "reset")
{
context.EndConversation("end of conversation");
}
else
{
var v1 = Increment(context.PrivateConversationData, 1);
var v2 = Increment(context.ConversationData, 2);
var v3 = Increment(context.UserData, 3);
await context.PostAsync($"echo {message.Text} {v1} {v2} {v3}");
context.Wait(MessageReceivedAsync);
}
}
}
[TestMethod]
public async Task EndConversation_Resets_Data()
{
using (var container = Build(Options.ResolveDialogFromContainer))
{
var dialog =
new TestResetDialog();
var builder = new ContainerBuilder();
builder
.RegisterInstance(dialog)
.As<IDialog<object>>();
builder.Update(container);
await AssertScriptAsync(container,
"hello",
"echo hello 1 2 3",
"world",
"echo world 2 3 4",
"reset",
"end of conversation",
"hello",
"echo hello 1 2 5",
"world",
"echo world 2 3 6"
);
}
}
}
}
| 33.595041 | 109 | 0.560394 | [
"MIT"
] | AskYous/botbuilder | CSharp/Tests/Microsoft.Bot.Builder.Tests/EndConversationTests.cs | 4,067 | C# |
// ==========================================================================
// This software is subject to the provisions of the Zope Public License,
// Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
// WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
// FOR A PARTICULAR PURPOSE.
// ==========================================================================
using System;
using System.Runtime.InteropServices;
using System.Security;
#if (UCS4)
using System.Text;
using Mono.Unix;
#endif
namespace Python.Runtime {
[SuppressUnmanagedCodeSecurityAttribute()]
public class Runtime {
/// <summary>
/// Encapsulates the low-level Python C API. Note that it is
/// the responsibility of the caller to have acquired the GIL
/// before calling any of these methods.
/// </summary>
#if (UCS4)
public const int UCS = 4;
#endif
#if (UCS2)
public const int UCS = 2;
#endif
#if ! (UCS2 || UCS4)
#error You must define either UCS2 or UCS4!
#endif
#if (PYTHON23)
public const string dll = "python23";
public const string pyversion = "2.3";
public const int pyversionnumber = 23;
#endif
#if (PYTHON24)
public const string dll = "python24";
public const string pyversion = "2.4";
public const int pyversionnumber = 24;
#endif
#if (PYTHON25)
public const string dll = "python25";
public const string pyversion = "2.5";
public const int pyversionnumber = 25;
#endif
#if (PYTHON26)
public const string dll = "python26";
public const string pyversion = "2.6";
public const int pyversionnumber = 26;
#endif
#if (PYTHON27)
public const string dll = "python27";
public const string pyversion = "2.7";
public const int pyversionnumber = 27;
#endif
#if ! (PYTHON23 || PYTHON24 || PYTHON25 || PYTHON26 || PYTHON27)
#error You must define one of PYTHON23 to PYTHON27
#endif
public static bool wrap_exceptions;
public static bool is32bit;
/// <summary>
/// Intitialize the runtime...
/// </summary>
public static void Initialize() {
is32bit = IntPtr.Size == 4;
Runtime.Py_Initialize();
Runtime.PyEval_InitThreads();
IntPtr dict = Runtime.PyImport_GetModuleDict();
IntPtr op = Runtime.PyDict_GetItemString(dict, "__builtin__");
PyBaseObjectType = Runtime.PyObject_GetAttrString(op, "object");
PyModuleType = Runtime.PyObject_Type(op);
PyNone = Runtime.PyObject_GetAttrString(op, "None");
PyTrue = Runtime.PyObject_GetAttrString(op, "True");
PyFalse = Runtime.PyObject_GetAttrString(op, "False");
PyBoolType = Runtime.PyObject_Type(PyTrue);
PyNoneType = Runtime.PyObject_Type(PyNone);
PyTypeType = Runtime.PyObject_Type(PyNoneType);
op = Runtime.PyObject_GetAttrString(dict, "keys");
PyMethodType = Runtime.PyObject_Type(op);
Runtime.Decref(op);
op = Runtime.PyString_FromString("string");
PyStringType = Runtime.PyObject_Type(op);
Runtime.Decref(op);
op = Runtime.PyUnicode_FromString("unicode");
PyUnicodeType = Runtime.PyObject_Type(op);
Runtime.Decref(op);
op = Runtime.PyTuple_New(0);
PyTupleType = Runtime.PyObject_Type(op);
Runtime.Decref(op);
op = Runtime.PyList_New(0);
PyListType = Runtime.PyObject_Type(op);
Runtime.Decref(op);
op = Runtime.PyDict_New();
PyDictType = Runtime.PyObject_Type(op);
Runtime.Decref(op);
op = Runtime.PyInt_FromInt32(0);
PyIntType = Runtime.PyObject_Type(op);
Runtime.Decref(op);
op = Runtime.PyLong_FromLong(0);
PyLongType = Runtime.PyObject_Type(op);
Runtime.Decref(op);
op = Runtime.PyFloat_FromDouble(0);
PyFloatType = Runtime.PyObject_Type(op);
Runtime.Decref(op);
IntPtr s = Runtime.PyString_FromString("_temp");
IntPtr d = Runtime.PyDict_New();
IntPtr c = Runtime.PyClass_New(IntPtr.Zero, d, s);
PyClassType = Runtime.PyObject_Type(c);
IntPtr i = Runtime.PyInstance_New(c, IntPtr.Zero, IntPtr.Zero);
PyInstanceType = Runtime.PyObject_Type(i);
Runtime.Decref(s);
Runtime.Decref(i);
Runtime.Decref(c);
Runtime.Decref(d);
Error = new IntPtr(-1);
// Determine whether we need to wrap exceptions for versions of
// of the Python runtime that do not allow new-style classes to
// be used as exceptions (Python versions 2.4 and lower).
#if (PYTHON25 || PYTHON26 || PYTHON27)
wrap_exceptions = false;
#else
IntPtr m = PyImport_ImportModule("exceptions");
Exceptions.ErrorCheck(m);
op = Runtime.PyObject_GetAttrString(m, "Exception");
Exceptions.ErrorCheck(op);
if (Runtime.PyObject_TYPE(op) == PyClassType) {
wrap_exceptions = true;
}
Runtime.Decref(op);
Runtime.Decref(m);
#endif
// Initialize modules that depend on the runtime class.
AssemblyManager.Initialize();
PyCLRMetaType = MetaType.Initialize();
Exceptions.Initialize();
ImportHook.Initialize();
// Need to add the runtime directory to sys.path so that we
// can find built-in assemblies like System.Data, et. al.
string rtdir = RuntimeEnvironment.GetRuntimeDirectory();
IntPtr path = Runtime.PySys_GetObject("path");
IntPtr item = Runtime.PyString_FromString(rtdir);
Runtime.PyList_Append(path, item);
Runtime.Decref(item);
AssemblyManager.UpdatePath();
}
public static void Shutdown() {
AssemblyManager.Shutdown();
Exceptions.Shutdown();
ImportHook.Shutdown();
Py_Finalize();
}
public static IntPtr Py_single_input = (IntPtr)256;
public static IntPtr Py_file_input = (IntPtr)257;
public static IntPtr Py_eval_input = (IntPtr)258;
public static IntPtr PyBaseObjectType;
public static IntPtr PyModuleType;
public static IntPtr PyClassType;
public static IntPtr PyInstanceType;
public static IntPtr PyCLRMetaType;
public static IntPtr PyMethodType;
public static IntPtr PyUnicodeType;
public static IntPtr PyStringType;
public static IntPtr PyTupleType;
public static IntPtr PyListType;
public static IntPtr PyDictType;
public static IntPtr PyIntType;
public static IntPtr PyLongType;
public static IntPtr PyFloatType;
public static IntPtr PyBoolType;
public static IntPtr PyNoneType;
public static IntPtr PyTypeType;
public static IntPtr PyTrue;
public static IntPtr PyFalse;
public static IntPtr PyNone;
public static IntPtr Error;
public static IntPtr GetBoundArgTuple(IntPtr obj, IntPtr args) {
if (Runtime.PyObject_TYPE(args) != Runtime.PyTupleType) {
Exceptions.SetError(Exceptions.TypeError, "tuple expected");
return IntPtr.Zero;
}
int size = Runtime.PyTuple_Size(args);
IntPtr items = Runtime.PyTuple_New(size + 1);
Runtime.PyTuple_SetItem(items, 0, obj);
Runtime.Incref(obj);
for (int i = 0; i < size; i++) {
IntPtr item = Runtime.PyTuple_GetItem(args, i);
Runtime.Incref(item);
Runtime.PyTuple_SetItem(items, i + 1, item);
}
return items;
}
public static IntPtr ExtendTuple(IntPtr t, params IntPtr[] args) {
int size = Runtime.PyTuple_Size(t);
int add = args.Length;
IntPtr item;
IntPtr items = Runtime.PyTuple_New(size + add);
for (int i = 0; i < size; i++) {
item = Runtime.PyTuple_GetItem(t, i);
Runtime.Incref(item);
Runtime.PyTuple_SetItem(items, i, item);
}
for (int n = 0; n < add; n++) {
item = args[n];
Runtime.Incref(item);
Runtime.PyTuple_SetItem(items, size + n, item);
}
return items;
}
public static Type[] PythonArgsToTypeArray(IntPtr arg) {
return PythonArgsToTypeArray(arg, false);
}
public static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects) {
// Given a PyObject * that is either a single type object or a
// tuple of (managed or unmanaged) type objects, return a Type[]
// containing the CLR Type objects that map to those types.
IntPtr args = arg;
bool free = false;
if (!Runtime.PyTuple_Check(arg)) {
args = Runtime.PyTuple_New(1);
Runtime.Incref(arg);
Runtime.PyTuple_SetItem(args, 0, arg);
free = true;
}
int n = Runtime.PyTuple_Size(args);
Type[] types = new Type[n];
Type t = null;
for (int i = 0; i < n; i++) {
IntPtr op = Runtime.PyTuple_GetItem(args, i);
if (mangleObjects && (!Runtime.PyType_Check(op))) {
op = Runtime.PyObject_TYPE(op);
}
ManagedType mt = ManagedType.GetManagedObject(op);
if (mt is ClassBase) {
t = ((ClassBase)mt).type;
}
else if (mt is CLRObject) {
object inst = ((CLRObject)mt).inst;
if (inst is Type) {
t = inst as Type;
}
}
else {
t = Converter.GetTypeByAlias(op);
}
if (t == null) {
types = null;
break;
}
types[i] = t;
}
if (free) {
Runtime.Decref(args);
}
return types;
}
//===================================================================
// Managed exports of the Python C API. Where appropriate, we do
// some optimization to avoid managed <--> unmanaged transitions
// (mostly for heavily used methods).
//===================================================================
public unsafe static void Incref(IntPtr op) {
#if (Py_DEBUG)
Py_IncRef(op);
return;
#else
void *p = (void *)op;
if ((void *)0 != p) {
if (is32bit) { (*(int *)p)++; }
else { (*(long *)p)++; }
}
#endif
}
public unsafe static void Decref(IntPtr op) {
if (op == IntPtr.Zero) {
DebugUtil.Print("Decref(NULL)");
}
#if (Py_DEBUG)
// Py_DecRef calls Python's Py_DECREF
Py_DecRef(op);
return;
#else
void* p = (void*) op;
if ((void*) 0 != p) {
if (is32bit) { --(*(int*) p); }
else { --(*(long*) p); }
if ((*(int*) p) == 0) {
// PyObject_HEAD: struct _typeobject *ob_type
void* t = is32bit ? (void*) (*((uint*) p + 1)) :
(void*) (*((ulong*) p + 1));
// PyTypeObject: destructor tp_dealloc
void* f = is32bit ? (void*) (*((uint*) t + 6)) :
(void*) (*((ulong*) t + 6));
if ((void*) 0 == f) {
return;
}
NativeCall.Impl.Void_Call_1(new IntPtr(f), op);
return;
}
}
#endif
}
#if (Py_DEBUG)
// Py_IncRef and Py_DecRef are taking care of the extra payload
// in Py_DEBUG builds of Python like _Py_RefTotal
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
private unsafe static extern void
Py_IncRef(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
private unsafe static extern void
Py_DecRef(IntPtr ob);
#endif
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
Py_Initialize();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
Py_IsInitialized();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
Py_Finalize();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
Py_NewInterpreter();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
Py_EndInterpreter(IntPtr threadState);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyThreadState_New(IntPtr istate);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyThreadState_Get();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyThread_get_key_value(IntPtr key);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyThread_get_thread_ident();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyThread_set_key_value(IntPtr key, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyThreadState_Swap(IntPtr key);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyGILState_Ensure();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyGILState_Release(IntPtr gs);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyGILState_GetThisThreadState();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
Py_Main(int argc, string[] argv);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyEval_InitThreads();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyEval_AcquireLock();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyEval_ReleaseLock();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyEval_AcquireThread(IntPtr tstate);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyEval_ReleaseThread(IntPtr tstate);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyEval_SaveThread();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyEval_RestoreThread(IntPtr tstate);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyEval_GetBuiltins();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyEval_GetGlobals();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyEval_GetLocals();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern string
Py_GetProgramName();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
Py_SetProgramName(string name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern string
Py_GetPythonHome();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
Py_SetPythonHome(string home);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern string
Py_GetVersion();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern string
Py_GetPlatform();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern string
Py_GetCopyright();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern string
Py_GetCompiler();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern string
Py_GetBuildInfo();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyRun_SimpleString(string code);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyRun_String(string code, IntPtr st, IntPtr globals, IntPtr locals);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
Py_CompileString(string code, string file, IntPtr tok);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyImport_ExecCodeModule(string name, IntPtr code);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyCFunction_New(IntPtr ml, IntPtr self);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyCFunction_NewEx(IntPtr ml, IntPtr self, IntPtr mod);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyCFunction_Call(IntPtr func, IntPtr args, IntPtr kw);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyClass_New(IntPtr bases, IntPtr dict, IntPtr name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyInstance_New(IntPtr cls, IntPtr args, IntPtr kw);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyInstance_NewRaw(IntPtr cls, IntPtr dict);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyMethod_New(IntPtr func, IntPtr self, IntPtr cls);
//====================================================================
// Python abstract object API
//====================================================================
// A macro-like method to get the type of a Python object. This is
// designed to be lean and mean in IL & avoid managed <-> unmanaged
// transitions. Note that this does not incref the type object.
public unsafe static IntPtr
PyObject_TYPE(IntPtr op) {
void* p = (void*)op;
if ((void*)0 == p) {
return IntPtr.Zero;
}
#if (Py_DEBUG)
int n = 3;
#else
int n = 1;
#endif
if (is32bit) {
return new IntPtr((void*)(*((uint*)p + n)));
}
else {
return new IntPtr((void*)(*((ulong*)p + n)));
}
}
// Managed version of the standard Python C API PyObject_Type call.
// This version avoids a managed <-> unmanaged transition. This one
// does incref the returned type object.
public unsafe static IntPtr
PyObject_Type(IntPtr op) {
IntPtr tp = PyObject_TYPE(op);
Runtime.Incref(tp);
return tp;
}
public static string PyObject_GetTypeName(IntPtr op) {
IntPtr pyType = Marshal.ReadIntPtr(op, ObjectOffset.ob_type);
IntPtr ppName = Marshal.ReadIntPtr(pyType, TypeOffset.tp_name);
return Marshal.PtrToStringAnsi(ppName);
}
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_HasAttrString(IntPtr pointer, string name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_GetAttrString(IntPtr pointer, string name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_SetAttrString(IntPtr pointer, string name, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_HasAttr(IntPtr pointer, IntPtr name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_GetAttr(IntPtr pointer, IntPtr name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_SetAttr(IntPtr pointer, IntPtr name, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_GetItem(IntPtr pointer, IntPtr key);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_SetItem(IntPtr pointer, IntPtr key, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_DelItem(IntPtr pointer, IntPtr key);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_GetIter(IntPtr op);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_CallObject(IntPtr pointer, IntPtr args);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_Compare(IntPtr value1, IntPtr value2);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_IsInstance(IntPtr ob, IntPtr type);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_IsSubclass(IntPtr ob, IntPtr type);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyCallable_Check(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_IsTrue(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_Size(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_Hash(IntPtr op);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_Repr(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_Str(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
ExactSpelling = true, CharSet = CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_Unicode(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_Dir(IntPtr pointer);
//====================================================================
// Python number API
//====================================================================
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyNumber_Int(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyNumber_Long(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyNumber_Float(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern bool
PyNumber_Check(IntPtr ob);
public static bool PyInt_Check(IntPtr ob) {
return PyObject_TypeCheck(ob, Runtime.PyIntType);
}
public static bool PyBool_Check(IntPtr ob) {
return PyObject_TypeCheck(ob, Runtime.PyBoolType);
}
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
private unsafe static extern IntPtr
PyInt_FromLong(IntPtr value);
public static IntPtr PyInt_FromInt32(int value) {
IntPtr v = new IntPtr(value);
return PyInt_FromLong(v);
}
public static IntPtr PyInt_FromInt64(long value) {
IntPtr v = new IntPtr(value);
return PyInt_FromLong(v);
}
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyInt_AsLong(IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyInt_FromString(string value, IntPtr end, int radix);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyInt_GetMax();
public static bool PyLong_Check(IntPtr ob) {
return PyObject_TYPE(ob) == Runtime.PyLongType;
}
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyLong_FromLong(long value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyLong_FromUnsignedLong(uint value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyLong_FromDouble(double value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyLong_FromLongLong(long value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyLong_FromUnsignedLongLong(ulong value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyLong_FromString(string value, IntPtr end, int radix);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyLong_AsLong(IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern uint
PyLong_AsUnsignedLong(IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern long
PyLong_AsLongLong(IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern ulong
PyLong_AsUnsignedLongLong(IntPtr value);
public static bool PyFloat_Check(IntPtr ob) {
return PyObject_TYPE(ob) == Runtime.PyFloatType;
}
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyFloat_FromDouble(double value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyFloat_FromString(IntPtr value, IntPtr junk);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern double
PyFloat_AsDouble(IntPtr ob);
//====================================================================
// Python sequence API
//====================================================================
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern bool
PySequence_Check(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PySequence_GetItem(IntPtr pointer, int index);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PySequence_SetItem(IntPtr pointer, int index, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PySequence_DelItem(IntPtr pointer, int index);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PySequence_GetSlice(IntPtr pointer, int i1, int i2);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PySequence_SetSlice(IntPtr pointer, int i1, int i2, IntPtr v);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PySequence_DelSlice(IntPtr pointer, int i1, int i2);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PySequence_Size(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PySequence_Contains(IntPtr pointer, IntPtr item);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PySequence_Concat(IntPtr pointer, IntPtr other);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PySequence_Repeat(IntPtr pointer, int count);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PySequence_Index(IntPtr pointer, IntPtr item);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PySequence_Count(IntPtr pointer, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PySequence_Tuple(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PySequence_List(IntPtr pointer);
//====================================================================
// Python string API
//====================================================================
public static bool IsStringType(IntPtr op) {
IntPtr t = PyObject_TYPE(op);
return (t == PyStringType) || (t == PyUnicodeType);
}
public static bool PyString_Check(IntPtr ob) {
return PyObject_TYPE(ob) == Runtime.PyStringType;
}
public static IntPtr PyString_FromString(string value) {
return PyString_FromStringAndSize(value, value.Length);
}
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyString_FromStringAndSize(string value, int size);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
EntryPoint="PyString_AsString",
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyString_AS_STRING(IntPtr op);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyString_Size(IntPtr pointer);
public static bool PyUnicode_Check(IntPtr ob) {
return PyObject_TYPE(ob) == Runtime.PyUnicodeType;
}
#if (UCS2)
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
EntryPoint="PyUnicodeUCS2_FromObject",
ExactSpelling=true, CharSet=CharSet.Unicode)]
public unsafe static extern IntPtr
PyUnicode_FromObject(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
EntryPoint="PyUnicodeUCS2_FromEncodedObject",
ExactSpelling=true, CharSet=CharSet.Unicode)]
public unsafe static extern IntPtr
PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
EntryPoint="PyUnicodeUCS2_FromUnicode",
ExactSpelling=true, CharSet=CharSet.Unicode)]
public unsafe static extern IntPtr
PyUnicode_FromUnicode(string s, int size);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
EntryPoint="PyUnicodeUCS2_GetSize",
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyUnicode_GetSize(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
EntryPoint="PyUnicodeUCS2_AsUnicode",
ExactSpelling=true)]
public unsafe static extern char *
PyUnicode_AsUnicode(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
EntryPoint="PyUnicodeUCS2_AsUnicode",
ExactSpelling=true, CharSet=CharSet.Unicode)]
public unsafe static extern IntPtr
PyUnicode_AS_UNICODE(IntPtr op);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
EntryPoint="PyUnicodeUCS2_FromOrdinal",
ExactSpelling=true, CharSet=CharSet.Unicode)]
public unsafe static extern IntPtr
PyUnicode_FromOrdinal(int c);
public static IntPtr PyUnicode_FromString(string s)
{
return PyUnicode_FromUnicode(s, (s.Length));
}
public unsafe static string GetManagedString(IntPtr op)
{
IntPtr type = PyObject_TYPE(op);
if (type == Runtime.PyStringType)
{
return Marshal.PtrToStringAnsi(
PyString_AS_STRING(op),
Runtime.PyString_Size(op)
);
}
if (type == Runtime.PyUnicodeType)
{
char* p = Runtime.PyUnicode_AsUnicode(op);
int size = Runtime.PyUnicode_GetSize(op);
return new String(p, 0, size);
}
return null;
}
#endif
#if (UCS4)
[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
EntryPoint = "PyUnicodeUCS4_FromObject",
ExactSpelling = true, CharSet = CharSet.Unicode)]
public unsafe static extern IntPtr
PyUnicode_FromObject(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
EntryPoint = "PyUnicodeUCS4_FromEncodedObject",
ExactSpelling = true, CharSet = CharSet.Unicode)]
public unsafe static extern IntPtr
PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err);
[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
EntryPoint = "PyUnicodeUCS4_FromUnicode",
ExactSpelling = true)]
public unsafe static extern IntPtr
PyUnicode_FromUnicode(
[MarshalAs (UnmanagedType.CustomMarshaler,
MarshalTypeRef=typeof(Utf32Marshaler))]
string s, int size);
[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
EntryPoint = "PyUnicodeUCS4_GetSize",
ExactSpelling = true, CharSet = CharSet.Ansi)]
public unsafe static extern int
PyUnicode_GetSize(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
EntryPoint = "PyUnicodeUCS4_AsUnicode",
ExactSpelling = true)]
public unsafe static extern IntPtr
PyUnicode_AsUnicode(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
EntryPoint = "PyUnicodeUCS4_AsUnicode",
ExactSpelling = true, CharSet = CharSet.Unicode)]
public unsafe static extern IntPtr
PyUnicode_AS_UNICODE(IntPtr op);
[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
EntryPoint = "PyUnicodeUCS4_FromOrdinal",
ExactSpelling = true, CharSet = CharSet.Unicode)]
public unsafe static extern IntPtr
PyUnicode_FromOrdinal(int c);
public static IntPtr PyUnicode_FromString(string s)
{
return PyUnicode_FromUnicode(s, (s.Length));
}
public unsafe static string GetManagedString(IntPtr op)
{
IntPtr type = PyObject_TYPE(op);
if (type == Runtime.PyStringType)
{
return Marshal.PtrToStringAnsi(
PyString_AS_STRING(op),
Runtime.PyString_Size(op)
);
}
if (type == Runtime.PyUnicodeType)
{
IntPtr p = Runtime.PyUnicode_AsUnicode(op);
return UnixMarshal.PtrToString(p, Encoding.UTF32);
}
return null;
}
#endif
//====================================================================
// Python dictionary API
//====================================================================
public static bool PyDict_Check(IntPtr ob) {
return PyObject_TYPE(ob) == Runtime.PyDictType;
}
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyDict_New();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyDictProxy_New(IntPtr dict);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyDict_GetItem(IntPtr pointer, IntPtr key);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyDict_GetItemString(IntPtr pointer, string key);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyDict_SetItem(IntPtr pointer, IntPtr key, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyDict_SetItemString(IntPtr pointer, string key, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyDict_DelItem(IntPtr pointer, IntPtr key);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyMapping_HasKey(IntPtr pointer, IntPtr key);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyDict_Keys(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyDict_Values(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyDict_Items(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyDict_Copy(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyDict_Update(IntPtr pointer, IntPtr other);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyDict_Clear(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyDict_Size(IntPtr pointer);
//====================================================================
// Python list API
//====================================================================
public static bool PyList_Check(IntPtr ob) {
return PyObject_TYPE(ob) == Runtime.PyListType;
}
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyList_New(int size);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyList_AsTuple(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyList_GetItem(IntPtr pointer, int index);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyList_SetItem(IntPtr pointer, int index, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyList_Insert(IntPtr pointer, int index, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyList_Append(IntPtr pointer, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyList_Reverse(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyList_Sort(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyList_GetSlice(IntPtr pointer, int start, int end);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyList_SetSlice(IntPtr pointer, int start, int end, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyList_Size(IntPtr pointer);
//====================================================================
// Python tuple API
//====================================================================
public static bool PyTuple_Check(IntPtr ob) {
return PyObject_TYPE(ob) == Runtime.PyTupleType;
}
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyTuple_New(int size);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyTuple_GetItem(IntPtr pointer, int index);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyTuple_SetItem(IntPtr pointer, int index, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyTuple_GetSlice(IntPtr pointer, int start, int end);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyTuple_Size(IntPtr pointer);
//====================================================================
// Python iterator API
//====================================================================
[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
ExactSpelling = true, CharSet = CharSet.Ansi)]
public unsafe static extern bool
PyIter_Check(IntPtr pointer);
[DllImport(Runtime.dll, CallingConvention = CallingConvention.Cdecl,
ExactSpelling = true, CharSet = CharSet.Ansi)]
public unsafe static extern IntPtr
PyIter_Next(IntPtr pointer);
//====================================================================
// Python module API
//====================================================================
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern string
PyModule_GetName(IntPtr module);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyModule_GetDict(IntPtr module);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern string
PyModule_GetFilename(IntPtr module);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyImport_Import(IntPtr name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyImport_ImportModule(string name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyImport_ReloadModule(IntPtr module);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyImport_AddModule(string name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyImport_GetModuleDict();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PySys_SetArgv(int argc, IntPtr argv);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PySys_GetObject(string name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PySys_SetObject(string name, IntPtr ob);
//====================================================================
// Python type object API
//====================================================================
public static bool PyType_Check(IntPtr ob) {
return PyObject_TypeCheck(ob, Runtime.PyTypeType);
}
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern bool
PyType_IsSubtype(IntPtr t1, IntPtr t2);
public static bool PyObject_TypeCheck(IntPtr ob, IntPtr tp) {
IntPtr t = PyObject_TYPE(ob);
return (t == tp) || PyType_IsSubtype(t, tp);
}
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyType_GenericNew(IntPtr type, IntPtr args, IntPtr kw);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyType_GenericAlloc(IntPtr type, int n);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyType_Ready(IntPtr type);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
_PyType_Lookup(IntPtr type, IntPtr name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_GenericGetAttr(IntPtr obj, IntPtr name);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyObject_GenericSetAttr(IntPtr obj, IntPtr name, IntPtr value);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
_PyObject_GetDictPtr(IntPtr obj);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyObject_GC_New(IntPtr tp);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyObject_GC_Del(IntPtr tp);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyObject_GC_Track(IntPtr tp);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyObject_GC_UnTrack(IntPtr tp);
//====================================================================
// Python memory API
//====================================================================
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyMem_Malloc(int size);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyMem_Realloc(IntPtr ptr, int size);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyMem_Free(IntPtr ptr);
//====================================================================
// Python exception API
//====================================================================
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyErr_SetString(IntPtr ob, string message);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyErr_SetObject(IntPtr ob, IntPtr message);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyErr_SetFromErrno(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyErr_SetNone(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyErr_ExceptionMatches(IntPtr exception);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyErr_GivenExceptionMatches(IntPtr ob, IntPtr val);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyErr_NormalizeException(IntPtr ob, IntPtr val, IntPtr tb);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern int
PyErr_Occurred();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyErr_Fetch(ref IntPtr ob, ref IntPtr val, ref IntPtr tb);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyErr_Restore(IntPtr ob, IntPtr val, IntPtr tb);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyErr_Clear();
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern void
PyErr_Print();
//====================================================================
// Miscellaneous
//====================================================================
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyMethod_Self(IntPtr ob);
[DllImport(Runtime.dll, CallingConvention=CallingConvention.Cdecl,
ExactSpelling=true, CharSet=CharSet.Ansi)]
public unsafe static extern IntPtr
PyMethod_Function(IntPtr ob);
}
}
| 36.98377 | 80 | 0.677086 | [
"MIT"
] | Alfred-Sun/Wox | Pythonnet.Runtime/runtime.cs | 59,248 | C# |
using MasterServerToolkit.Logging;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace MasterServerToolkit.Networking
{
/// <summary>
/// Client for connecting to websocket server.
/// </summary>
public class ClientSocketWs : BaseClientSocket<PeerWs>, IClientSocket, IUpdatable
{
IPeer IMsgDispatcher<IPeer>.Peer { get; }
private WebSocket webSocket;
private ConnectionStatus status;
private readonly Dictionary<short, IPacketHandler> handlers;
private float connectionTimeout = 10f;
public bool IsConnected { get; private set; } = false;
public bool IsConnecting { get { return status == ConnectionStatus.Connecting; } }
public string ConnectionIp { get; private set; }
public int ConnectionPort { get; private set; }
public ConnectionStatus Status
{
get
{
return status;
}
set
{
if (status != value)
{
status = value;
OnStatusChangedEvent?.Invoke(status);
}
}
}
public bool UseSsl { get; set; }
public event Action OnConnectedEvent;
public event Action OnDisconnectedEvent;
public event Action<ConnectionStatus> OnStatusChangedEvent;
public ClientSocketWs()
{
SetStatus(ConnectionStatus.Disconnected);
handlers = new Dictionary<short, IPacketHandler>();
}
private void SetStatus(ConnectionStatus status)
{
switch (status)
{
case ConnectionStatus.Connecting:
if (Status != ConnectionStatus.Connecting)
{
Status = ConnectionStatus.Connecting;
}
break;
case ConnectionStatus.Connected:
if (Status != ConnectionStatus.Connected)
{
Status = ConnectionStatus.Connected;
MstTimer.Instance.StartCoroutine(Peer.SendDelayedMessages());
OnConnectedEvent?.Invoke();
}
break;
case ConnectionStatus.Disconnected:
if (Status != ConnectionStatus.Disconnected)
{
Status = ConnectionStatus.Disconnected;
OnDisconnectedEvent?.Invoke();
}
break;
}
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
private void HandleMessage(IIncommingMessage message)
{
try
{
if (handlers.TryGetValue(message.OpCode, out IPacketHandler handler))
{
if (handler != null)
{
handler.Handle(message);
}
else
{
Logs.Error($"Connection is missing a handler. OpCode: {message.OpCode}");
}
}
else if (message.IsExpectingResponse)
{
Logs.Error($"Connection is missing a handler. OpCode: {message.OpCode}");
message.Respond(ResponseStatus.Error);
}
}
catch (Exception e)
{
Logs.Error($"Failed to handle a message. OpCode: {message.OpCode}, Error: {e}");
if (!message.IsExpectingResponse)
{
return;
}
try
{
message.Respond(ResponseStatus.Error);
}
catch (Exception exception)
{
Logs.Error(exception);
}
}
}
public void WaitForConnection(Action<IClientSocket> connectionCallback, float timeoutSeconds)
{
if (IsConnected)
{
connectionCallback.Invoke(this);
return;
}
var isConnected = false;
var timedOut = false;
// Make local function
void onConnected()
{
OnConnectedEvent -= onConnected;
isConnected = true;
if (!timedOut)
{
connectionCallback.Invoke(this);
}
}
// Listen to connection event
OnConnectedEvent += onConnected;
// Wait for some seconds
MstTimer.WaitForSeconds(timeoutSeconds, () =>
{
if (!isConnected)
{
timedOut = true;
OnConnectedEvent -= onConnected;
connectionCallback.Invoke(this);
}
});
}
public void WaitForConnection(Action<IClientSocket> connectionCallback)
{
WaitForConnection(connectionCallback, connectionTimeout);
}
public void AddConnectionListener(Action callback, bool invokeInstantlyIfConnected = true)
{
// Asign callback method again
OnConnectedEvent += callback;
if (IsConnected && invokeInstantlyIfConnected)
{
callback.Invoke();
}
}
public void RemoveConnectionListener(Action callback)
{
OnConnectedEvent -= callback;
}
public void AddDisconnectionListener(Action callback, bool invokeInstantlyIfDisconnected = true)
{
// Remove copy of the callback method to prevent double invocation
OnDisconnectedEvent -= callback;
// Asign callback method again
OnDisconnectedEvent += callback;
if (!IsConnected && invokeInstantlyIfDisconnected)
{
callback.Invoke();
}
}
public void RemoveDisconnectionListener(Action callback)
{
OnDisconnectedEvent -= callback;
}
public IPacketHandler SetHandler(IPacketHandler handler)
{
handlers[handler.OpCode] = handler;
return handler;
}
public IPacketHandler SetHandler(short opCode, IncommingMessageHandler handlerMethod)
{
var handler = new PacketHandler(opCode, handlerMethod);
SetHandler(handler);
return handler;
}
public void RemoveHandler(IPacketHandler handler)
{
// But only if this exact handler
if (handlers.TryGetValue(handler.OpCode, out IPacketHandler previousHandler) && previousHandler != handler)
{
return;
}
handlers.Remove(handler.OpCode);
}
public void Reconnect()
{
Disconnect();
Connect(ConnectionIp, ConnectionPort);
}
public void Update()
{
if (webSocket == null)
{
return;
}
byte[] data = webSocket.Recv();
while (data != null)
{
Peer.HandleDataReceived(data, 0);
data = webSocket.Recv();
}
bool wasConnected = IsConnected;
IsConnected = webSocket.IsConnected;
// Check if status changed
if (wasConnected != IsConnected)
{
SetStatus(IsConnected ? ConnectionStatus.Connected : ConnectionStatus.Disconnected);
}
}
public IClientSocket Connect(string ip, int port)
{
return Connect(ip, port, connectionTimeout);
}
public IClientSocket Connect(string ip, int port, float timeoutSeconds)
{
connectionTimeout = timeoutSeconds;
ConnectionIp = ip;
ConnectionPort = port;
if (webSocket != null && webSocket.IsConnected)
{
webSocket.Close();
}
IsConnected = false;
SetStatus(ConnectionStatus.Connecting);
if (Peer != null)
{
Peer.OnMessageReceivedEvent -= HandleMessage;
Peer.Dispose();
}
if (UseSsl)
{
webSocket = new WebSocket(new Uri($"wss://{ip}:{port}/msf"));
}
else
{
webSocket = new WebSocket(new Uri($"ws://{ip}:{port}/msf"));
}
Peer = new PeerWs(webSocket);
Peer.OnMessageReceivedEvent += HandleMessage;
MstUpdateRunner.Instance.Add(this);
MstUpdateRunner.Instance.StartCoroutine(webSocket.Connect());
return this;
}
public void Disconnect()
{
if (webSocket != null)
{
webSocket.Close();
}
if (Peer != null)
{
Peer.Dispose();
}
IsConnected = false;
SetStatus(ConnectionStatus.Disconnected);
}
}
} | 29.077399 | 119 | 0.492227 | [
"MIT"
] | itsnotyoutoday/MST | Assets/MasterServerToolkit/Networking/Scripts/ClientSocketWs.cs | 9,394 | C# |
using System;
[Serializable]
public struct PotionEffect
{
public double IncreaseMaxHp { get; set; }
public double IncreaseMaxEp { get; set; }
public double IncreaseAttDmg { get; set; }
public double IncreaseDefPer { get; set; }
public double IncreaseCritDmg { get; set; }
public double IncreaseCritPer { get; set; }
public double IncreaseIgnoreDef { get; set; }
public double IncreaseGold { get; set; }
public double IncreaseExp { get; set; }
public int InBattleTurn { get; set; }
public double InBattleMaxHp { get; set; }
public double InBattleMaxEp { get; set; }
public double InBattleAttDmg { get; set; }
public double InBattleDefPer { get; set; }
public double InBattleCritDmg { get; set; }
public double InBattleCritPer { get; set; }
public double InBattleIgnoreDef { get; set; }
public double HealHp { get; set; }
public double HealEp { get; set; }
} | 32.071429 | 47 | 0.707127 | [
"Apache-2.0"
] | hellun205/Goguma | Game/Object/Inventory/Item/Consume/PotionEffect.cs | 898 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Zammad.Client.Core;
using Zammad.Client.Resources;
using Zammad.Client.Services;
namespace Zammad.Client
{
public class OrganizationClient : ZammadClient, IOrganizationService
{
public OrganizationClient(ZammadAccount account)
: base(account)
{
}
#region IOrganizationService
public Task<IList<Organization>> GetOrganizationListAsync()
{
return GetAsync<IList<Organization>>("/api/v1/organizations");
}
public Task<IList<Organization>> GetOrganizationListAsync(int page, int count)
{
return GetAsync<IList<Organization>>("/api/v1/organizations", $"page={page},per_page={count}");
}
public Task<IList<Organization>> SearchOrganizationAsync(string query, int limit)
{
return GetAsync<IList<Organization>>("/api/v1/organizations/search", $"query={query}&limit={limit}&expand=true");
}
public Task<Organization> GetOrganizationAsync(int id)
{
return GetAsync<Organization>($"/api/v1/organizations/{id}");
}
public Task<Organization> CreateOrganizationAsync(Organization organization)
{
return PostAsync<Organization>("/api/v1/organizations", organization);
}
public Task<Organization> UpdateOrganizationAsync(int id, Organization organization)
{
return PutAsync<Organization>($"/api/v1/organizations/{id}", organization);
}
public Task<bool> DeleteOrganizationAsync(int id)
{
return DeleteAsync($"/api/v1/organizations/{id}");
}
#endregion
}
}
| 30.491228 | 125 | 0.643268 | [
"Apache-2.0"
] | MarvinKlar/Zammad-Client | src/Zammad.Client/OrganizationClient.cs | 1,740 | C# |
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.IdentityFramework;
using Abp.Linq.Extensions;
using Abp.Runtime.Caching;
using AutoMapper;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Snow.Template.Authorization.Users;
using Snow.Template.Authorization.Roles.Dto;
namespace Snow.Template.Authorization.Roles
{
[AbpAuthorize(PermissionNames.Pages_Administration_Roles)]
public class RoleAppService : TemplateAppServiceBase, IRoleAppService
{
private readonly RoleManager _roleManager;
private readonly UserManager _userManager;
private readonly IRepository<Role> _roleRepository;
private readonly IMapper _mapper;
private readonly ICacheManager _cache;
public RoleAppService(IRepository<Role> repository, RoleManager roleManager, UserManager userManager, IMapper mapper)
{
_roleManager = roleManager;
_userManager = userManager;
_mapper = mapper;
_roleRepository = repository;
}
public async Task<PagedResultDto<RoleListDto>> GetPagedAsync(GetRolesInput input)
{
var query = GetRolesFilteredQuery(input);
var userCount = await query.CountAsync();
var users = await query
.OrderBy(input.Sorting)
.PageBy(input)
.ToListAsync();
var userListDtos = _mapper.Map<List<RoleListDto>>(users);
return new PagedResultDto<RoleListDto>(
userCount,
userListDtos
);
}
[AbpAuthorize(PermissionNames.Pages_Administration_Roles_Create,
PermissionNames.Pages_Administration_Roles_Edit)]
public async Task<GetRoleForEditOutput> GetForEditAsync(NullableIdDto input)
{
var permissions = PermissionManager.GetAllPermissions();
RoleEditDto roleEditDto;
List<FlatPermissionDto> flatPermissions = _mapper.Map<List<FlatPermissionDto>>(permissions);
if (input.Id.HasValue) //Editing existing role?
{
var role = await _roleManager.GetRoleByIdAsync(input.Id.Value);
string[] grantedPermissionNames = (await _roleManager.GetGrantedPermissionsAsync(role)).Select(p => p.Name).ToArray();
foreach (FlatPermissionDto flatPermission in flatPermissions)
{
if (grantedPermissionNames.Contains(flatPermission.Name))
{
flatPermission.IsSelected = true;
}
}
roleEditDto = _mapper.Map<RoleEditDto>(role);
}
else
{
roleEditDto = new RoleEditDto();
}
return new GetRoleForEditOutput
{
Role = roleEditDto,
Permissions = flatPermissions.OrderBy(p => p.Name).ToList(),
};
}
public async Task<ListResultDto<RoleListDto>> GetListAsync(GetRolesInput input)
{
var roles = await _roleManager
.Roles
.WhereIf(
!input.Permission.IsNullOrWhiteSpace(),
r => r.Permissions.Any(rp => rp.Name == input.Permission && rp.IsGranted)
)
.ToListAsync();
return new ListResultDto<RoleListDto>(_mapper.Map<List<RoleListDto>>(roles));
}
[AbpAuthorize(PermissionNames.Pages_Administration_Roles_Create, PermissionNames.Pages_Administration_Roles_Edit)]
public async Task CreateOrUpdateAsync(CreateOrUpdateRoleInput input)
{
if (input.Role.Id.HasValue)
{
await UpdateAsync(input);
}
else
{
await CreateAsync(input);
}
}
[AbpAuthorize(PermissionNames.Pages_Administration_Roles_Create)]
protected virtual async Task CreateAsync(CreateOrUpdateRoleInput input)
{
var role = _mapper.Map<Role>(input.Role);
role.SetNormalizedName();
CheckErrors(await _roleManager.CreateAsync(role));
if (input.GrantedPermissions.Any())
{
var grantedPermissions = PermissionManager
.GetAllPermissions()
.Where(p => input.GrantedPermissions.Contains(p.Name))
.ToList();
await _roleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
}
}
[AbpAuthorize(PermissionNames.Pages_Administration_Roles_Edit)]
protected virtual async Task UpdateAsync(CreateOrUpdateRoleInput input)
{
Debug.Assert(input.Role.Id != null, "input.Role.Id != null");
var role = await _roleManager.GetRoleByIdAsync(input.Role.Id.Value);
_mapper.Map(input.Role, role);
CheckErrors(await _roleManager.UpdateAsync(role));
var grantedPermissions = PermissionManager
.GetAllPermissions()
.Where(p => input.GrantedPermissions.Contains(p.Name))
.ToList();
await _roleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
}
[AbpAuthorize(PermissionNames.Pages_Administration_Roles_Delete)]
public async Task DeleteAsync(EntityDto<int> input)
{
var role = await _roleManager.FindByIdAsync(input.Id.ToString());
var users = await _userManager.GetUsersInRoleAsync(role.NormalizedName);
foreach (var user in users)
{
CheckErrors(await _userManager.RemoveFromRoleAsync(user, role.NormalizedName));
}
CheckErrors(await _roleManager.DeleteAsync(role));
}
public Task<ListResultDto<PermissionDto>> GetAllPermissionsAsync()
{
var permissions = PermissionManager.GetAllPermissions();
return Task.FromResult(new ListResultDto<PermissionDto>(
ObjectMapper.Map<List<PermissionDto>>(permissions).OrderBy(p => p.DisplayName).ToList()
));
}
/// <summary>
/// 获取用户过滤查询
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private IQueryable<Role> GetRolesFilteredQuery(IGetRolesInput input)
{
return _roleRepository.GetAll();
}
}
} | 36.074468 | 134 | 0.615305 | [
"MIT"
] | snowchenlei/AbpCustomerAuth | aspnet-core/src/Snow.Template.Application/Authorization/Roles/RoleAppService.cs | 6,800 | C# |
namespace ET
{
public class LoginFinish_RemoveLoginUI: AEvent<EventType.LoginFinish>
{
protected override async ETTask Run(EventType.LoginFinish args)
{
args.ZoneScene.GetComponent<FGUIComponent>().Remove(FGUILogin.UIResName);
await ETTask.CompletedTask;
//await UIHelper.Remove(args.ZoneScene, UIType.UILogin);
}
}
}
| 21.25 | 76 | 0.761765 | [
"MIT"
] | jameshuh/ET | Unity/Assets/HotfixView/FairyGUI/Logic/UILogin/Handler/LoginFinish_RemoveLoginUI.cs | 342 | C# |
// Copyright (c) MicroElements. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace MicroElements.FileStorage.Abstractions
{
public static class StorageEngineExtensions
{
public static bool IsExists(this IStorageProvider storageProvider, string location)
{
return storageProvider.GetFileMetadata(location).IsExists;
}
}
}
| 32.357143 | 101 | 0.730684 | [
"MIT"
] | micro-elements/MicroElements.FileStorage | src/MicroElements.FileStorage/Abstractions/StorageEngineExtensions.cs | 455 | C# |
using DotNetRevolution.Core.Domain;
using DotNetRevolution.Core.Tests.Mock;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.ObjectModel;
using System.Linq;
namespace DotNetRevolution.Core.Tests.Domain
{
[TestClass]
public class DomainEventHandlerFactoryTests
{
private IDomainEventHandlerFactory _factory;
[TestInitialize]
public void Init()
{
var catalog = new DomainEventCatalog(new Collection<DomainEventEntry>
{
new DomainEventEntry(typeof(DomainEvent1), typeof(MockDomainEventHandler<DomainEvent1>)),
new DomainEventEntry(typeof(DomainEvent2), typeof(MockReusableDomainEventHandler<DomainEvent2>))
});
_factory = new DomainEventHandlerFactory(catalog);
}
[TestMethod]
public void HasCatalog()
{
Assert.IsTrue(_factory.Catalog != null);
}
[TestMethod]
public void CanGetHandlerForRegisteredDomainEvent()
{
Assert.IsNotNull(_factory.GetHandlers(typeof(DomainEvent1)));
}
[TestMethod]
public void CanGetCachedHandler()
{
var handlers = _factory.GetHandlers(typeof(DomainEvent2));
var cachedHandlers = _factory.GetHandlers(typeof(DomainEvent2));
Assert.AreEqual(handlers.Count, cachedHandlers.Count);
Assert.AreEqual(handlers.DomainEventType, cachedHandlers.DomainEventType);
Assert.IsTrue(handlers.Except(cachedHandlers).Count() == 0);
}
[TestMethod]
public void AssertHandlerDoesNotCache()
{
var handler = _factory.GetHandlers(typeof(DomainEvent1));
Assert.AreNotEqual(handler, _factory.GetHandlers(typeof(DomainEvent1)));
}
[TestMethod]
public void CannotGetHandlerForUnregisteredDomainEvent()
{
Assert.IsTrue(_factory.GetHandlers(typeof(object)).Count == 0);
}
}
}
| 31.307692 | 112 | 0.646683 | [
"MIT"
] | DotNetRevolution/DotNetRevolution-Framework | tests/DotNetRevolution.Core.Tests/Domain/DomainEventHandlerFactoryTests.cs | 2,037 | C# |
using Abp.AspNetCore.Mvc.Controllers;
using Abp.IdentityFramework;
using Microsoft.AspNetCore.Identity;
namespace MyProject.Controllers
{
public abstract class MyProjectControllerBase: AbpController
{
protected MyProjectControllerBase()
{
LocalizationSourceName = MyProjectConsts.LocalizationSourceName;
}
protected void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}
| 25.35 | 76 | 0.710059 | [
"MIT"
] | CadeXu/ABP | abpMySql/aspnet-core/src/MyProject.Web.Core/Controllers/MyProjectControllerBase.cs | 507 | C# |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.Core;
namespace ICSharpCode.SharpDevelop
{
/// <summary>
/// A wrapper around commonly used System.IO methods
/// for accessing the file system. Allows mocking file system access in unit tests.
/// </summary>
[SDService("SD.FileSystem", FallbackImplementation = typeof(EmptyFileSystem))]
public interface IFileSystem : IReadOnlyFileSystem
{
/// <inheritdoc cref="System.IO.File.Delete"/>
void Delete(FileName path);
/// <inheritdoc cref="System.IO.File.CopyFile"/>
void CopyFile(FileName source, FileName destination, bool overwrite = false);
/// <inheritdoc cref="System.IO.Directory.Delete"/>
void CreateDirectory(DirectoryName path);
/// <inheritdoc cref="System.IO.File.OpenWrite"/>
Stream OpenWrite(FileName fileName);
}
public interface IReadOnlyFileSystem
{
/// <inheritdoc cref="System.IO.File.Exists"/>
bool FileExists(FileName path);
/// <inheritdoc cref="System.IO.Directory.Exists"/>
bool DirectoryExists(DirectoryName path);
/// <inheritdoc cref="System.IO.File.OpenRead"/>
Stream OpenRead(FileName fileName);
/// <inheritdoc cref="System.IO.File.OpenText"/>
TextReader OpenText(FileName fileName);
/// <summary>
/// Retrieves the list of files in the specified directory.
/// </summary>
/// <param name="directory">The directory to search in.</param>
/// <param name="searchPattern">The search pattern used to filter the result list.
/// For example: "*.exe".
/// This method does not use 8.3 patterns; so "*.htm" will not match ".html".</param>
/// <param name="searchOptions">
/// Options that influence the search.
/// </param>
/// <returns>An enumerable that iterates through the directory contents</returns>
/// <exception cref="IOExcption">The directory does not exist / access is denied.</exception>
IEnumerable<FileName> GetFiles(DirectoryName directory, string searchPattern = "*", DirectorySearchOptions searchOptions = DirectorySearchOptions.None);
}
[Flags]
public enum DirectorySearchOptions
{
/// <summary>
/// Search top directory only; skip hidden files.
/// </summary>
None = 0,
/// <summary>
/// Include hidden files/subdirectories.
/// </summary>
IncludeHidden = 1,
/// <summary>
/// Perform a recursive search into subdirectories.
/// </summary>
IncludeSubdirectories = 2
}
public static class FileSystemExtensions
{
public static string ReadAllText(this IReadOnlyFileSystem fileSystem, FileName fileName)
{
using (var reader = fileSystem.OpenText(fileName)) {
return reader.ReadToEnd();
}
}
}
sealed class EmptyFileSystem : IFileSystem
{
void IFileSystem.Delete(FileName path)
{
throw new FileNotFoundException();
}
void IFileSystem.CopyFile(FileName source, FileName destination, bool overwrite)
{
throw new FileNotFoundException();
}
void IFileSystem.CreateDirectory(DirectoryName path)
{
throw new NotSupportedException();
}
Stream IFileSystem.OpenWrite(FileName fileName)
{
throw new NotSupportedException();
}
bool IReadOnlyFileSystem.FileExists(FileName path)
{
return false;
}
bool IReadOnlyFileSystem.DirectoryExists(DirectoryName path)
{
return false;
}
Stream IReadOnlyFileSystem.OpenRead(FileName fileName)
{
throw new FileNotFoundException();
}
TextReader IReadOnlyFileSystem.OpenText(FileName fileName)
{
throw new FileNotFoundException();
}
IEnumerable<FileName> IReadOnlyFileSystem.GetFiles(DirectoryName directory, string searchPattern, DirectorySearchOptions searchOptions)
{
return Enumerable.Empty<FileName>();
}
}
}
| 32.218543 | 154 | 0.730319 | [
"MIT"
] | TetradogOther/SharpDevelop | src/Main/Base/Project/Services/IFileSystem.cs | 4,867 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;
namespace Common.Authentication.Test
{
public class AzureRMProfileTests
{
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void ProfileSerializeDeserializeWorks()
{
var dataStore = new MockDataStore();
AzureSession.DataStore = dataStore;
var profilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile);
var currentProfile = new AzureRMProfile(profilePath);
var tenantId = Guid.NewGuid().ToString();
var environment = new AzureEnvironment
{
Name = "testCloud",
Endpoints = { { AzureEnvironment.Endpoint.ActiveDirectory, "http://contoso.com" } }
};
var account = new AzureAccount
{
Id = "me@contoso.com",
Type = AzureAccount.AccountType.User,
Properties = { { AzureAccount.Property.Tenants, tenantId } }
};
var sub = new AzureSubscription
{
Account = account.Id,
Environment = environment.Name,
Id = new Guid(),
Name = "Contoso Test Subscription",
Properties = { { AzureSubscription.Property.Tenants, tenantId } }
};
var tenant = new AzureTenant
{
Id = new Guid(tenantId),
Domain = "contoso.com"
};
currentProfile.Context = new AzureContext(sub, account, environment, tenant);
currentProfile.Environments[environment.Name] = environment;
currentProfile.Context.TokenCache = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 };
AzureRMProfile deserializedProfile;
// Round-trip the exception: Serialize and de-serialize with a BinaryFormatter
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
// "Save" object state
bf.Serialize(ms, currentProfile);
// Re-use the same stream for de-serialization
ms.Seek(0, 0);
// Replace the original exception with de-serialized one
deserializedProfile = (AzureRMProfile)bf.Deserialize(ms);
}
Assert.NotNull(deserializedProfile);
var jCurrentProfile = currentProfile.ToString();
var jDeserializedProfile = deserializedProfile.ToString();
Assert.Equal(jCurrentProfile, jDeserializedProfile);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void SavingProfileWorks()
{
string expected = @"{
""Environments"": {
""testCloud"": {
""Name"": ""testCloud"",
""OnPremise"": false,
""Endpoints"": {
""ActiveDirectory"": ""http://contoso.com""
}
}
},
""Context"": {
""Account"": {
""Id"": ""me@contoso.com"",
""Type"": 1,
""Properties"": {
""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
}
},
""Subscription"": {
""Id"": ""00000000-0000-0000-0000-000000000000"",
""Name"": ""Contoso Test Subscription"",
""Environment"": ""testCloud"",
""Account"": ""me@contoso.com"",
""State"": ""Enabled"",
""Properties"": {
""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
}
},
""Environment"": {
""Name"": ""testCloud"",
""OnPremise"": false,
""Endpoints"": {
""ActiveDirectory"": ""http://contoso.com""
}
},
""Tenant"": {
""Id"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"",
""Domain"": ""contoso.com""
},
""TokenCache"": ""AQIDBAUGCAkA""
}
}";
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile);
var dataStore = new MockDataStore();
AzureSession.DataStore = dataStore;
AzureRMProfile profile = new AzureRMProfile(path);
var tenantId = new Guid("3c0ff8a7-e8bb-40e8-ae66-271343379af6");
var environment = new AzureEnvironment
{
Name = "testCloud",
Endpoints = { { AzureEnvironment.Endpoint.ActiveDirectory, "http://contoso.com" } }
};
var account = new AzureAccount
{
Id = "me@contoso.com",
Type = AzureAccount.AccountType.User,
Properties = { { AzureAccount.Property.Tenants, tenantId.ToString() } }
};
var sub = new AzureSubscription
{
Account = account.Id,
Environment = environment.Name,
Id = new Guid(),
Name = "Contoso Test Subscription",
State = "Enabled",
Properties = { { AzureSubscription.Property.Tenants, tenantId.ToString() } }
};
var tenant = new AzureTenant
{
Id = tenantId,
Domain = "contoso.com"
};
profile.Context = new AzureContext(sub, account, environment, tenant);
profile.Environments[environment.Name] = environment;
profile.Context.TokenCache = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 };
profile.Save();
string actual = dataStore.ReadFileAsText(path);
Assert.Equal(expected, actual);
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void LoadingProfileWorks()
{
string contents = @"{
""Environments"": {
""testCloud"": {
""Name"": ""testCloud"",
""OnPremise"": false,
""Endpoints"": {
""ActiveDirectory"": ""http://contoso.com""
}
}
},
""Context"": {
""TokenCache"": ""AQIDBAUGCAkA"",
""Account"": {
""Id"": ""me@contoso.com"",
""Type"": 1,
""Properties"": {
""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
}
},
""Subscription"": {
""Id"": ""00000000-0000-0000-0000-000000000000"",
""Name"": ""Contoso Test Subscription"",
""Environment"": ""testCloud"",
""Account"": ""me@contoso.com"",
""Properties"": {
""Tenants"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6""
}
},
""Environment"": {
""Name"": ""testCloud"",
""OnPremise"": false,
""Endpoints"": {
""ActiveDirectory"": ""http://contoso.com""
}
},
""Tenant"": {
""Id"": ""3c0ff8a7-e8bb-40e8-ae66-271343379af6"",
""Domain"": ""contoso.com""
}
}
}";
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile);
var dataStore = new MockDataStore();
AzureSession.DataStore = dataStore;
dataStore.WriteFile(path, contents);
var profile = new AzureRMProfile(path);
Assert.Equal(4, profile.Environments.Count);
Assert.Equal("3c0ff8a7-e8bb-40e8-ae66-271343379af6", profile.Context.Tenant.Id.ToString());
Assert.Equal("contoso.com", profile.Context.Tenant.Domain);
Assert.Equal("00000000-0000-0000-0000-000000000000", profile.Context.Subscription.Id.ToString());
Assert.Equal("testCloud", profile.Context.Environment.Name);
Assert.Equal("me@contoso.com", profile.Context.Account.Id);
Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 }, profile.Context.TokenCache);
Assert.Equal(path, profile.ProfilePath);
}
}
}
| 38.787879 | 110 | 0.542076 | [
"MIT"
] | Peter-Schneider/azure-powershell | src/Common/Commands.Common.Authentication.Test/AzureRMProfileTests.cs | 8,732 | C# |
using DotNetNuke.Services.Localization;
using System;
using System.Web;
using System.ComponentModel;
using Microsoft.VisualBasic;
using System.Web.UI.WebControls;
using System.Collections;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Data.SqlClient;
using System.Data;
using DotNetNuke.UI.UserControls;
//------------------------------------------------------------------------------
// <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 DNNStuff.SQLViewPro
{
public partial class EditConnection
{
///<summary>
///lblConnectionName control.
///</summary>
///<remarks>
///Auto-generated field.
///To modify move field declaration from designer file to code-behind file.
///</remarks>
protected LabelControl lblConnectionName;
///<summary>
///txtName control.
///</summary>
///<remarks>
///Auto-generated field.
///To modify move field declaration from designer file to code-behind file.
///</remarks>
protected System.Web.UI.WebControls.TextBox txtName;
///<summary>
///lblConnectionString control.
///</summary>
///<remarks>
///Auto-generated field.
///To modify move field declaration from designer file to code-behind file.
///</remarks>
protected LabelControl lblConnectionString;
///<summary>
///txtConnectionString control.
///</summary>
///<remarks>
///Auto-generated field.
///To modify move field declaration from designer file to code-behind file.
///</remarks>
protected System.Web.UI.WebControls.TextBox txtConnectionString;
///<summary>
///vldConnectionStringValid control.
///</summary>
///<remarks>
///Auto-generated field.
///To modify move field declaration from designer file to code-behind file.
///</remarks>
protected System.Web.UI.WebControls.CustomValidator vldConnectionStringValid;
///<summary>
///cmdUpdate control.
///</summary>
///<remarks>
///Auto-generated field.
///To modify move field declaration from designer file to code-behind file.
///</remarks>
protected System.Web.UI.WebControls.LinkButton cmdUpdate;
///<summary>
///cmdCancel control.
///</summary>
///<remarks>
///Auto-generated field.
///To modify move field declaration from designer file to code-behind file.
///</remarks>
protected System.Web.UI.WebControls.LinkButton cmdCancel;
}
}
| 26.080808 | 80 | 0.660341 | [
"MIT"
] | UpendoVentures/dnnstuff.sqlviewpro | EditConnection.ascx.designer.cs | 2,582 | C# |
using SAAI.Properties;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
namespace SAAI
{
/// <summary>
/// SettingsDialog allows the user to enter/edit the application wide settings.
/// This includes the ip address/port of the AI.
/// </summary>
public partial class SettingsDialog : Form
{
public SettingsDialog()
{
InitializeComponent();
aiLocationListView.Sorting = SortOrder.Ascending;
// The older (pre 1-6-1) version may have used the old registry format.
// If so, get it, but delete it.
string oldIPAddress = Storage.GetGlobalString("DeepStackIPAddress");
if (!string.IsNullOrEmpty(oldIPAddress))
{
int aiPort = Storage.GetGlobalInt("DeepStackPort");
AILocation location = new AILocation(Guid.NewGuid(), oldIPAddress, aiPort);
Storage.RemoveGlobalValue("DeepStackIPAddress"); // get rid of the old format
Storage.RemoveGlobalValue("DeepStackPort");
}
List<AILocation> locations = Storage.GetAILocations();
foreach (var location in locations)
{
ListViewItem item = new ListViewItem(new string[] { location.IPAddress, location.Port.ToString() });
aiLocationListView.Items.Add(item);
item.Tag = location;
}
double snapshot = Storage.GetGlobalDouble("FrameInterval");
if (snapshot != 0.0)
{
snapshotNumeric.Value = (decimal)snapshot;
}
int maxEvent = Storage.GetGlobalInt("MaxEventTime");
if (maxEvent != 0)
{
maxEventNumeric.Value = maxEvent;
}
int eventInterval = Storage.GetGlobalInt("EventInterval");
if (eventInterval != 0)
{
eventIntervalNumeric.Value = eventInterval;
}
// Database Stuff
string customConnectionString = Storage.GetGlobalString("CustomDatabaseConnectionString");
if (string.IsNullOrEmpty(customConnectionString))
{
ConnectionStringText.Text = Storage.GetGlobalString("DBConnectionString"); // the fully formatted one that is in use!
}
}
private void OkButton_Click(object sender, EventArgs e)
{
Storage.SetGlobalDouble("FrameInterval", (double)snapshotNumeric.Value);
Storage.SetGlobalInt("MaxEventTime", (int)maxEventNumeric.Value);
Storage.SetGlobalInt("EventInterval", (int)eventIntervalNumeric.Value);
DialogResult = DialogResult.OK;
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
private void AddButton_Click(object sender, EventArgs e)
{
using (AILocationDialog dlg = new AILocationDialog())
{
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK)
{
ListViewItem item = new ListViewItem(new string[] { dlg.Location.IPAddress, dlg.Location.Port.ToString() });
item.Tag = dlg.Location;
aiLocationListView.Items.Add(item);
}
}
DialogResult = DialogResult.None;
}
private void RemoveButton_Click(object sender, EventArgs e)
{
if (aiLocationListView.SelectedItems.Count > 0)
{
int index = aiLocationListView.SelectedIndices[0];
AILocation location = (AILocation) aiLocationListView.Items[index].Tag;
Storage.RemoveAILocation(location.ID.ToString());
AILocation.Refresh();
aiLocationListView.Items.RemoveAt(index);
}
}
private void OnActivate(object sender, EventArgs e)
{
if (aiLocationListView.SelectedItems.Count > 0)
{
int index = aiLocationListView.SelectedIndices[0];
ListViewItem item = aiLocationListView.Items[index];
AILocation location = (AILocation)item.Tag;
using (AILocationDialog dlg = new AILocationDialog(location))
{
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK)
{
aiLocationListView.Items[index].SubItems[0].Text = dlg.Location.IPAddress;
aiLocationListView.Items[index].SubItems[1].Text = dlg.Location.Port.ToString();
}
}
}
}
// This does not just get the exiting value, it reforms it from the base components!
private void GetDefaultButton_Click(object sender, EventArgs e)
{
ConnectionStringText.Text = Storage.GetGlobalString("DBConnectionString"); // the one we use
Storage.RemoveGlobalValue("CustomDatabaseConnectionString"); // nuke any custom stuff the user set.
}
private void UseCustomButton_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(ConnectionStringText.Text))
{
Storage.SetGlobalString("CustomDatabaseConnectionString", ConnectionStringText.Text); // His custom string stored here so we can get it back (unless nuked)!
Storage.SetGlobalString("DBConnectionString", ConnectionStringText.Text); // This is the one actually used!
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show(this, "This button re-reads the AI information from storage. This can be useful if the status of your AI server(s) has changed", "Refresh AI Information", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
AILocation.Refresh();
}
}
}
}
| 34.944444 | 226 | 0.651122 | [
"MIT"
] | Ken98045/On-Guard | src/AIDisplay/Forms/SettingsDialog.cs | 5,663 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lykke.Service.EthereumCore.Core.Repositories
{
public interface INewEthereumContract
{
string Abi { get; set; }
string ByteCode { get; set; }
}
public interface IEthereumContract : INewEthereumContract
{
string ContractAddress { get; set; }
}
public class EthereumContract : IEthereumContract
{
public string ContractAddress { get; set; }
public string Abi { get; set; }
public string ByteCode { get; set; }
}
public interface IEthereumContractRepository
{
Task SaveAsync(IEthereumContract transferContract);
Task<IEthereumContract> GetAsync(string contractAddress);
}
}
| 25.612903 | 65 | 0.680101 | [
"MIT"
] | JTOne123/EthereumApiDotNetCore | src/Lykke.Service.EthereumCore.Core/Repositories/IEthereumContractRepository.cs | 796 | C# |
// Copyright (c) Josef Pihrt. 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.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Roslynator.CodeFixes;
namespace Roslynator.CSharp.CodeFixes
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RemoveDuplicateModifierCodeFixProvider))]
[Shared]
public class RemoveDuplicateModifierCodeFixProvider : BaseCodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(CompilerDiagnosticIdentifiers.DuplicateModifier); }
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
if (!Settings.IsEnabled(CodeFixIdentifiers.RemoveDuplicateModifier))
return;
SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false);
if (!TryFindToken(root, context.Span.Start, out SyntaxToken token))
return;
foreach (Diagnostic diagnostic in context.Diagnostics)
{
switch (diagnostic.Id)
{
case CompilerDiagnosticIdentifiers.DuplicateModifier:
{
ModifiersCodeFixRegistrator.RemoveModifier(
context,
diagnostic,
token.Parent,
token,
additionalKey: CodeFixIdentifiers.RemoveDuplicateModifier);
break;
}
}
}
}
}
}
| 36.72549 | 160 | 0.601708 | [
"Apache-2.0"
] | IanKemp/Roslynator | src/CodeFixes/CSharp/CodeFixes/RemoveDuplicateModifierCodeFixProvider.cs | 1,875 | C# |
using FFMpegCore.FFMPEG.Enums;
namespace FFMpegCore.FFMPEG.Argument
{
/// <summary>
/// Represents speed parameter
/// </summary>
public class SpeedArgument : Argument<Speed>
{
public SpeedArgument()
{
}
public SpeedArgument(Speed value) : base(value) { }
/// <inheritdoc/>
public override string GetStringValue()
{
return $"-preset {Value.ToString().ToLower()}";
}
}
}
| 21.130435 | 59 | 0.549383 | [
"MIT"
] | liuyl1992/FFMpegCore | FFMpegCore/FFMPEG/Argument/Atoms/SpeedArgument.cs | 488 | C# |
// <auto-generated />
using System;
using Company.WebApplication1.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Company.WebApplication1.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.0-preview1")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider")
.HasMaxLength(128);
b.Property<string>("Name")
.HasMaxLength(128);
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 35.164557 | 125 | 0.489921 | [
"Apache-2.0"
] | 0xced/AspNetCore | src/Templating/src/Microsoft.DotNet.Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Data/SqlServer/00000000000000_CreateIdentitySchema.Designer.cs | 8,334 | C# |
// Copyright (c) 2017 Andrew Vardeman. Published under the MIT license.
// See license.txt in the FileSharper distribution or repository for the
// full text of the license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
namespace FileSharperCore.Processors.Shell
{
public class OpenContainingFolderProcessor : SingleFileProcessorBase
{
private HashSet<string> m_OpenedFolders = new HashSet<string>();
public override string Name => "Open containing folder";
public override string Category => "Shell";
public override string Description => "Opens the folder containing the file";
public override object Parameters => null;
public override void LocalInit()
{
m_OpenedFolders.Clear();
}
protected internal override ProcessingResult Process(FileInfo file, string[] values,
CancellationToken token)
{
ProcessingResultType type = ProcessingResultType.Failure;
string message = "Success";
if (!m_OpenedFolders.Contains(file.DirectoryName))
{
try
{
System.Diagnostics.Process.Start(file.DirectoryName);
m_OpenedFolders.Add(file.DirectoryName);
type = ProcessingResultType.Success;
}
catch (Exception ex)
{
message = ex.Message;
RunInfo.ExceptionInfos.Enqueue(new ExceptionInfo(ex, file));
}
}
return new ProcessingResult(type, message, new FileInfo[] { file });
}
}
}
| 32.788462 | 92 | 0.607038 | [
"MIT"
] | adv12/FileSharper | src/FileSharper/FileSharperCore/Processors/Shell/OpenContainingFolderProcessor.cs | 1,705 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <ToDo>
/// check code.
/// </ToDo>
public class CharacterHolder : MonoBehaviour {
public Text CharacterName;
public RawImage CharacterImage;
public RawImage CharacterRank;
public RawImage CharacterFaction;
public Text CharacterRankName;
public Text CharacterType;
public Button CharacterUpgrade;
public Button CharacterCareerSwitch;
public Button CharacterEditName;
public Button EditEnd;
public Dropdown cSwitch;
public Toggle ToggleGold;
public InputField Rename;
//public List<Assault_Team> assault_teams;
private bool isEdit = false;
public void Edit(){
Debug.Log (isEdit);
Rename.gameObject.SetActive (true);
}
void Update(){
if (!isEdit) {
//Debug.Log (isEdit);
}
}
}
| 18.636364 | 46 | 0.754878 | [
"MIT"
] | jengske/HeroesAndGeneralsManager | Scripts/CharacterScripts/CharacterHolder.cs | 822 | C# |
using HaloEzAPI.Model.Response.MetaData.HaloWars2.Shared;
namespace HaloEzAPI.Model.Response.MetaData.HaloWars2.Cards
{
public class HW2StartingArmyDisplayInfo : Details
{
}
} | 23.5 | 59 | 0.781915 | [
"MIT"
] | BadDub/Halo-API | HaloEzAPI/Model/Response/MetaData/HaloWars2/Cards/HW2StartingArmyDisplayInfo.cs | 188 | C# |
using HarSharp;
using JBlam.HarClient.Tests.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Mime;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace JBlam.HarClient.Tests.Content
{
[TestClass]
public class ResponseContentBehaviour
{
static async Task<Har> GetContent(HttpContent content)
{
const string requestPath = "/" + nameof(ResponseContentBehaviour) + "/" + nameof(GetContent);
var mockHandler = new MockServerHandler
{
Responses =
{
{
requestPath,
HttpMethod.Get,
new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = content }
}
}
};
var sut = new HarMessageHandler(mockHandler);
var client = new HttpClient(sut) { BaseAddress = MockServerHandler.BaseUri };
(await client.GetAsync(requestPath)).EnsureSuccessStatusCode();
return await sut.CreateHarAsync();
}
static void AssertIsMimeType(string expectedMediaType, Encoding? expectedEncoding, string actualMimeType)
{
if (expectedEncoding == null)
{
// The charset must be not emitted
Assert.AreEqual(expectedMediaType, actualMimeType, "Media type did not match the expected value");
}
else
{
// Spec:
// > *mimeType [string]* - MIME type of the response text (value of the Content-Type
// > response header). The charset attribute of the MIME type is included (if
// > available).
//
// Since the mock HTTP handler will always produce a content-type value, the test
// should fail if the HAR doesn't represent content-type in the `mimeType` field.
var match = Regex.Match(actualMimeType, @"^(.*); charset=(.*)$");
Assert.IsTrue(match.Success, "MIME type {0} was not well-formed", actualMimeType);
var (actualMediaType, actualCharSet) = (match.Groups[1].Value, match.Groups[2].Value);
Assert.AreEqual(expectedMediaType, actualMediaType, "Media type did not match the expected value");
Assert.AreEqual(expectedEncoding.WebName, actualCharSet, "CharSet did not match the expected value");
}
}
[TestMethod]
public void StringContentHeadersProduceExpectedMimeType()
{
var content = new StringContent("Plain text");
Assert.AreEqual("text/plain; charset=utf-8", content.Headers.ContentType.ToString());
Assert.AreEqual("text/plain", content.Headers.ContentType.MediaType);
Assert.AreEqual("utf-8", content.Headers.ContentType.CharSet);
}
[TestMethod]
public async Task LogsAsciiPlain()
{
const string expectedHarContentValue = "Plain text";
var content = new StringContent(expectedHarContentValue);
var har = await GetContent(content);
var harContent = har.Log.Entries.First().Response.Content;
Assert.IsNotNull(harContent, "No content was recorded in the HAR");
AssertIsMimeType(MediaTypeNames.Text.Plain, Encoding.UTF8, harContent.MimeType);
Assert.AreEqual(expectedHarContentValue, harContent.Text);
Assert.AreEqual(expectedHarContentValue.Length, harContent.Size);
Assert.IsNull(harContent.Encoding, "Unexpected not-null Encoding value for text response");
}
[TestMethod]
public async Task LogsAsciiJson()
{
const string expectedMediaType = MediaTypeNames.Application.Json;
const string expectedJson = "{ \"content\": \"yes\" }";
var content = new StringContent(expectedJson, Encoding.UTF8, expectedMediaType);
var harContent = (await GetContent(content)).Log.Entries.First().Response.Content;
Assert.IsNotNull(harContent, "No content was recorded in the HAR");
AssertIsMimeType(expectedMediaType, Encoding.UTF8, harContent.MimeType);
Assert.AreEqual(expectedJson, harContent.Text);
Assert.AreEqual(expectedJson.Length, harContent.Size);
Assert.IsNull(harContent.Encoding, "Unexpected not-null Encoding value for text response");
}
[TestMethod]
public async Task LogsMultibyteUtf8()
{
// This is a string containing Unicode which has a multibyte UTF8 representation. It
// also requires surrogate pairs in UTF-16.
// The string does not change under different Unicode normalisations, which is
// important when making assetions about the Size property.
const string stringValue = "Unicode: 👍 很好";
var content = new StringContent(stringValue);
var harContent = (await GetContent(content)).Log.Entries.First().Response.Content;
Assert.IsNotNull(harContent, "No content was recorded in the HAR");
AssertIsMimeType(MediaTypeNames.Text.Plain, Encoding.UTF8, harContent.MimeType);
// The spec is weird when it comes to this point:
// > *text [string, optional]* - Response body sent from the server or loaded from the
// > browser cache. This field is populated with textual content only. The text field
// > is either HTTP decoded text or a encoded (e.g. "base64") representation of the
// > response body. Leave out this field if the information is not available.
// > *encoding [string, optional]* (new in 1.2) - Encoding used for response text field
// > e.g "base64". Leave out this field if the text field is HTTP decoded (decompressed
// > & unchunked), than trans-coded from its original character set into UTF-8.
//
// This implies that the `text` property will be "interpreted as UTF-8", unless
// `encoding` is "base64" (or some other not-null value).
//
// However, HAR must be valid JSON. The JSON spec says that all "unicode escapes" must
// be FOUR hex digits, implying that JSON will interpret unicode escape points as
// UTF-16:
// > character
// > '0020'. '10FFFF' - '"' - '\'
// > '\' escape
// >
// > escape
// > '"'
// > '\'
// > '/'
// > 'b'
// > 'f'
// > 'n'
// > 'r'
// > 't'
// > 'u' hex hex hex hex
//
// The Firefox HAR sample produces both direct characters, and UTF-16 escapes. It's
// unclear at this time what influences the choice. This library will only produce
// direct characters.
Assert.AreEqual(stringValue, harContent.Text);
Assert.AreEqual(Encoding.UTF8.GetByteCount(stringValue), harContent.Size);
}
/// <summary>
/// Asserts that the HAR object representation contains characters which are illegal in
/// JSON. The serialiser is in charge of ensuring they are properly escaped.
/// </summary>
/// <returns>A Task which resolves when the test is complete</returns>
/// <remarks>
/// Escaping behaviour is asserted in
/// <seealso cref="HarSerialisationBehaviour.IllegalJsonCharactersAreEscaped"/>
/// </remarks>
[TestMethod]
public async Task ObjectRepresentationContainsIllegalJsonCharacters()
{
const string textNeedingEscapes = "String with newlines:\r\nand tabs:\t backspaces:\b null:\0 and other control chars:\u0003;\u0019;\u001f and quotes:\"";
var httpContent = new StringContent(textNeedingEscapes);
var harContent = (await GetContent(httpContent)).Log.Entries.First().Response.Content;
Assert.IsNotNull(harContent, "No content was recorded in the HAR");
AssertIsMimeType(MediaTypeNames.Text.Plain, Encoding.UTF8, harContent.MimeType);
// Size refers to the encoded length; all chars are 1-byte in UTF-8
Assert.AreEqual(textNeedingEscapes.Length, harContent.Size);
Assert.AreEqual(textNeedingEscapes, harContent.Text);
}
[TestMethod]
public async Task LogsBinaryImage()
{
var imageBytes = new byte[]
{
// smallest possible GIF
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00,
0x00, 0xff, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
0x01, 0x00, 0x00, 0x02, 0x00, 0x3b,
};
var imageHttpContent = new ByteArrayContent(imageBytes);
imageHttpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(MediaTypeNames.Image.Gif);
var harContent = (await GetContent(imageHttpContent)).Log.Entries.First().Response.Content;
Assert.IsNotNull(harContent, "No content was recorded in the HAR");
AssertIsMimeType(MediaTypeNames.Image.Gif, null, harContent.MimeType);
// Size should equal the *content* size, not the size of the *HAR's representation*
// of the content.
Assert.AreEqual(imageBytes.Length, harContent.Size, "Unexpected content size reported");
Assert.AreEqual("base64", harContent.Encoding, "Binary image data was unexpectedly not base64-encoded for the HAR");
Assert.AreEqual(Convert.ToBase64String(imageBytes), harContent.Text);
}
[TestMethod]
public async Task LogsForResponseMissingContentTypeHeader()
{
var bytes = new byte[] { (byte)'a', (byte)'b', (byte)'c', (byte)'d' };
var harContent = (await GetContent(new ByteArrayContent(bytes))).Log.Entries.First().Response.Content;
Assert.IsNotNull(harContent, "No content was recorded in the HAR");
Assert.AreEqual(bytes.Length, harContent.Size, "Unexpected content size reported");
Assert.AreEqual("base64", harContent.Encoding, "Unknown format data was unexpectedly not base64-encoded for the HAR");
Assert.AreEqual(Convert.ToBase64String(bytes), harContent.Text);
}
[TestMethod]
public async Task LogsSvgImageAsText()
{
const string svgText = @"<svg xmlns=""http://www.w3.org/2000/svg"" encoding=""utf-8""></svg>";
var httpContent = new StringContent(svgText, Encoding.UTF8, "image/svg+xml");
// charset appears to be legal according to https://tools.ietf.org/html/rfc7231#section-3.1.1.2
// but does not appear to be emitted in practice.
httpContent.Headers.ContentType.CharSet = null;
var harContent = (await GetContent(httpContent)).Log.Entries.First().Response.Content;
Assert.IsNotNull(harContent, "No content was recorded in the HAR");
Assert.IsNull(harContent.Encoding, "HAR unexpectedly re-encoded the SVG text");
AssertIsMimeType("image/svg+xml", null, harContent.MimeType);
Assert.AreEqual(svgText, harContent.Text);
}
[TestMethod]
public async Task ResponseHarIncludesContentHeaders()
{
var har = await GetContent(new StringContent("Hello this is dog"));
var harResponse = har.Log.Entries.First().Response;
Assert.IsTrue(harResponse.Headers.Any(h => h.Name.Equals("content-type", StringComparison.InvariantCultureIgnoreCase)));
}
}
}
| 52.902655 | 166 | 0.616929 | [
"MIT"
] | jblam/HarClient | HarClient.Tests/Content/ResponseContentBehaviour.cs | 11,965 | C# |
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Buffer<T>
{
public int Size { get { return elements.Count; } }
private Queue<T> elements;
private int bufferSize;
private int counter;
private int correctionTollerance;
public Buffer(int bufferSize, int correctionTollerance)
{
this.bufferSize = bufferSize;
this.correctionTollerance = correctionTollerance;
elements = new Queue<T>();
}
public void Add(T element)
{
elements.Enqueue(element);
}
public T[] Get()
{
int size = elements.Count - 1;
if (size == bufferSize)
{
counter = 0;
}
if (size > bufferSize)
{
if (counter < 0)
{
counter = 0;
}
counter++;
if (counter > correctionTollerance)
{
int amount = elements.Count - bufferSize;
T[] temp = new T[amount];
for (int i = 0; i < amount; i++)
{
temp[i] = elements.Dequeue();
}
return temp;
}
}
if (size < bufferSize)
{
if (counter > 0)
{
counter = 0;
}
counter--;
if (-counter > correctionTollerance)
{
return new T[0];
}
}
if (elements.Any())
{
return new T[] { elements.Dequeue() };
}
return new T[0];
}
}
| 20.443038 | 59 | 0.448916 | [
"MIT"
] | Vytek/EmbeddedFPSExample | EmbeddedFPSClient/Assets/Scripts/shared/Buffer.cs | 1,617 | C# |
/*
* This class was auto-generated from the API references found at
* https://epayments-api.developer-ingenico.com/s2sapi/v1/
*/
using Ingenico.Connect.Sdk.Domain.Mandates.Definitions;
namespace Ingenico.Connect.Sdk.Domain.Payment.Definitions
{
public class SepaDirectDebitPaymentProduct771SpecificInput : AbstractSepaDirectDebitPaymentProduct771SpecificInput
{
public string ExistingUniqueMandateReference { get; set; } = null;
public CreateMandateWithReturnUrl Mandate { get; set; } = null;
}
}
| 33.125 | 118 | 0.766038 | [
"MIT"
] | AlexXx777/connect-sdk-dotnet | connect-sdk-dotnet/Ingenico/Connect/Sdk/Domain/Payment/Definitions/SepaDirectDebitPaymentProduct771SpecificInput.cs | 530 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Starter.Web.Vue.API.Users
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public DateTime CreatedAt { get; set; }
}
}
| 21.25 | 47 | 0.635294 | [
"MIT"
] | vyrotek/dotnet-starter | src/Starter.Web.Vue/API/Users/User.cs | 342 | C# |
// InpDateTimeOptionTests.cs
// By: Adam Renaud
// Created: 2019-09-18
using Droplet.Core.Inp.Exceptions;
using Droplet.Core.Inp.Options;
using Droplet.Core.Inp.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
using Xunit.Abstractions;
namespace Droplet.Core.Inp.Tests.Options
{
/// <summary>
/// Tests for the <see cref="InpDateTimeOption"/> and inheritors
/// </summary>
public class InpDateTimeOptionTests : FileTestsBase
{
#region Constructor
/// <summary>
/// Default Constructor
/// </summary>
/// <param name="logger"></param>
public InpDateTimeOptionTests(ITestOutputHelper logger) : base(logger)
{
}
#endregion
#region Start DateTime Tests
/// <summary>
/// Testing the parsing of the <see cref="StartDateTimeOption"/>
/// </summary>
/// <param name="value">A string from an inp file that holds the data
/// to the start date and the start time</param>
/// <param name="expectedValue">The expected <see cref="DateTime"/> that the parser
/// should build</param>
[Theory]
[ClassData(typeof(StartDateTimeParserTestData))]
public void StartDateTimeParserTests(string value, DateTime expectedValue)
=> Assert.Equal(expectedValue,
SetupProject(value).Database.GetOption<StartDateTimeOption>().Value);
/// <summary>
/// Testing the <see cref="IInpEntity.ToInpString"/> override for the <see cref="StartDateTimeOption"/> class
/// </summary>
/// <param name="expectedString">The expected <see cref="string"/></param>
/// <param name="value">The value that will be used to construct the <see cref="StartDateTimeOption"/></param>
[Theory]
[ClassData(typeof(StartDateTimeToInpStringTestData))]
public void StartDateTime_ToInpStringMethod_ShoudMatchValue(string expectedString, DateTime value)
=> Assert.Equal(expectedString, new StartDateTimeOption(value).ToInpString());
/// <summary>
/// Test Data for the <see cref="StartDateTimeParserTests(string, DateTime)"/> tests
/// </summary>
private class StartDateTimeParserTestData : IEnumerable<object[]>
{
/// <summary>
/// A string from an inp file
/// and the expected <see cref="DateTime"/> that the
/// parser should create
/// </summary>
/// <returns></returns>
public IEnumerator<object[]> GetEnumerator()
{
// With start time
yield return new object[]
{
@"[OPTIONS]
START_DATE 07/28/2019
START_TIME 01:12:50
",
new DateTime(2019, 07, 28, 1, 12, 50)
};
// Without start time
yield return new object[]
{
@"[OPTIONS]
START_DATE 07/28/2019
",
new DateTime(2019, 07, 28, 0, 0, 0)
};
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
/// <summary>
/// Test data for the <see cref="StartDateTime_ToInpStringMethod_ShoudMatchValue(string, DateTime)"/>
/// Tests
/// </summary>
private class StartDateTimeToInpStringTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[]
{
@"START_DATE 07/28/2019
START_TIME 01:12:50",
new DateTime(2019, 07, 28, 1, 12, 50)
};
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
#endregion
#region Report StartDate Time Tests
/// <summary>
/// Testing the parsing of the <see cref="ReportStartDateTimeOption"/>
/// class.
/// </summary>
/// <param name="value">A string from an inp file that holds the data to
/// the Report Start Date and Time</param>
/// <param name="expectedValue">The expected <see cref="DateTime"/> that the
/// Parser should create from the <paramref name="value"/> passed</param>
[Theory]
[ClassData(typeof(ReportStartDateTimeParserTestData))]
public void ReportStartDateTimeParser_ValidString_ShouldMatchExpected(string value, DateTime expectedValue)
=> Assert.Equal(expectedValue,
SetupProject(value).Database.GetOption<ReportStartDateTimeOption>().Value);
/// <summary>
/// Testing the parsing of <see cref="ReportStartDateTimeOption"/> when an invalid string
/// is passed to it for either the start date or the start time
/// </summary>
/// <param name="value"></param>
[Theory]
[InlineData("[OPTIONS]\nREPORT_START_DATE 07/28/2019\nREPORT_START_TIME INVALID\n")]
[InlineData("[OPTIONS]\nREPORT_START_DATE INVALID\nREPORT_START_TIME 00:00:00\n")]
public void ReportStartDateTimeParser_InvalidString_ShouldThrowInpFileException(string value)
=> Assert.Throws<InpFileException>(() => SetupProject(value));
/// <summary>
/// Testing the <see cref="IInpEntity.ToInpString"/> method override for the <see cref="ReportStartDateTimeOption"/>
/// class
/// </summary>
/// <param name="expectedString">The expected <see cref="string"/></param>
/// <param name="value">The value that will be used to create the <see cref="ReportStartDateTimeOption"/></param>
[Theory]
[ClassData(typeof(ReportStartDateTimeToInpStringTestData))]
public void ReportStartDateTime_ToInpString_ShouldMatchExpected(string expectedString, DateTime value)
=> Assert.Equal(expectedString, new ReportStartDateTimeOption(value).ToInpString());
/// <summary>
/// Test Data for the <see cref="ReportStartDateTimeParser_ValidString_ShouldMatchExpected(string, DateTime)"/> tests
/// </summary>
private class ReportStartDateTimeParserTestData : IEnumerable<object[]>
{
/// <summary>
/// Returns the <see cref="string"/> and expected <see cref="DateTime"/>
/// for the test
/// </summary>
/// <returns>Returns: a string and a DateTime for the test</returns>
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[]
{
@"[OPTIONS]
REPORT_START_DATE 07/28/2019
REPORT_START_TIME 00:00:00
",
new DateTime(2019, 07, 28, 0, 0, 0)
};
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
/// <summary>
/// Test data for the <see cref="ReportStartDateTime_ToInpString_ShouldMatchExpected(string, DateTime)"/>
/// Tests
/// </summary>
private class ReportStartDateTimeToInpStringTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[]
{
@"REPORT_START_DATE 07/28/2019
REPORT_START_TIME 00:00:00",
new DateTime(2019, 07, 28, 0, 0, 0)
};
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
#endregion
#region EndDateTime Tests
/// <summary>
/// A valid <see cref="EndDateTimeOption"/> inp string
/// </summary>
private const string EndDateTimeValidInpString = @"[OPTIONS]
END_DATE 07/28/2019
END_TIME 06:00:00
";
/// <summary>
/// Invalid <see cref="EndDateTimeOption"/> inp string that has an invalid
/// end time
/// </summary>
private const string EndDateTimeString_InvalidEndTime = @"[OPTIONS]
END_DATE 07/28/2019
END_TIME INVALID
";
/// <summary>
/// Invalid <see cref="EndDateTimeOption"/> inp string that is missing the
/// End Time
/// </summary>
private const string EndDateTimeString_MissingEndTime = @"[OPTIONS]
END_DATE 07/28/2019
";
/// <summary>
/// Invalid <see cref="EndDateTimeOption"/> inp string that has an invalid
/// end date
/// </summary>
private const string EndDateTimeString_InvalidEndDate = @"[OPTIONS]
END_DATE INVALID
END_TIME 06:00:00
";
/// <summary>
/// Invalid <see cref="EndDateTimeOption"/> inp string that is missing the start date
/// </summary>
private const string EndDateTimeString_MissingEndDate = @"[OPTIONS]
END_TIME 06:00:00
";
/// <summary>
/// Tests the parsing of the <see cref="EndDateTimeOption"/> option
/// </summary>
/// <param name="value">A string from an inp file that represents a date and a time</param>
/// <param name="expectedDateTime">The expected date time</param>
[Theory]
[ClassData(typeof(EndDateTimeParserTesData))]
public void EndDateTimeParser_ValidString_ShouldMatchExpected(string value, DateTime expectedDateTime)
=> Assert.Equal(expectedDateTime,
SetupProject(value).Database.GetOption<EndDateTimeOption>().Value);
/// <summary>
/// Testing the parsing of the <see cref="EndDateTimeOption"/> when
/// and invalid string is passed
/// </summary>
/// <param name="value">The invalid string</param>
[Theory]
// [InlineData(EndDateTimeString_MissingEndTime)] // TODO: Fix these failing tests if required
[InlineData(EndDateTimeString_InvalidEndDate)]
// [InlineData(EndDateTimeString_MissingEndDate)] // TODO: Fix these failing tests if required
[InlineData(EndDateTimeString_InvalidEndTime)]
public void EndDateTimeParser_InvalidString_ShouldThrowInpFileException(string value)
=> Assert.Throws<InpFileException>(() => SetupProject(value));
/// <summary>
/// Testing
/// </summary>
/// <param name="value"></param>
[Theory]
[ClassData(typeof(EndDateTimeToInpStringTestData))]
public void EndDateTimeToInpString_ValidString_ShouldMatchValue(DateTime value, string expected)
=> Assert.Equal(expected, new EndDateTimeOption(value).ToInpString());
/// <summary>
/// Test data for the <see cref="EndDateTimeParserTesData"/>
/// </summary>
private class EndDateTimeParserTesData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[]
{
EndDateTimeValidInpString,
new DateTime(2019, 07, 28, 6, 0, 0)
};
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
/// <summary>
/// Private class that holds test data for the <see cref="EndDateTimeParser_ValidString_ShouldMatchExpected(DateTime, string)"/> tests
/// </summary>
private class EndDateTimeToInpStringTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
// Standard string test
yield return new object[]
{
new DateTime(2019, 07, 28, 6, 0, 0),
@"END_DATE 07/28/2019
END_TIME 06:00:00"
};
// Testing without end time
yield return new object[]
{
new DateTime(2019, 07, 28),
@"END_DATE 07/28/2019
END_TIME 00:00:00"
};
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
#endregion
#region Sweeping Date Time Tests
/// <summary>
/// Testing the parsing of the <see cref="SweepingStartDateTimeOption"/>
/// Option
/// </summary>
/// <param name="value">A string from an inp file that contains the option</param>
/// <param name="expectedValue">The expected value from the option</param>
[Theory]
[ClassData(typeof(SweepingStartDateTimeParserTestData))]
public void SweepingStartDateTimeParserTests(string value, DateTime expectedValue)
=> Assert.Equal(expectedValue, SetupProject(value)
.Database
.GetOption<SweepingStartDateTimeOption>().Value);
/// <summary>
/// Testing the public override of the <see cref="IInpEntity.ToInpString"/>
/// as implemented for the <see cref="SweepingStartDateTimeOption"/> class
/// </summary>
/// <param name="expectedString">The expected string</param>
/// <param name="value">The value that will be used to construct the <see cref="SweepingStartDateTimeOption"/></param>
[Theory]
[ClassData(typeof(SweepingStartDateTimeParserTestData))]
public void SweepingStartDateTime_ToInpString_ShouldMatchExpected(string expectedString, DateTime value)
=> Assert.Equal(PruneInpString(expectedString, OptionsHeader), new SweepingStartDateTimeOption(value).ToInpString());
/// <summary>
/// Test data for the <see cref="SweepingStartDateTimeParserTests(string, DateTime)"/>
/// tests
/// </summary>
private class SweepingStartDateTimeParserTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[]
{
@"[OPTIONS]
SWEEP_START 01/01
",
new DateTime(DateTime.Now.Year, 1, 1)
};
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
/// <summary>
/// Testing the parsing of the <see cref="SweepingEndDateTimeOption"/>
/// </summary>
/// <param name="value">A <see cref="string"/> from an inp file that
/// contains a <see cref="SweepingEndDateTimeOption"/> that will be parsed</param>
/// <param name="expectedValue">The expected <see cref="DateTime"/> that the parser should
/// produced from the <paramref name="value"/></param>
[Theory]
[ClassData(typeof(SweepingEndDateTimeParserTestData))]
public void SweepingEndDateTimeParserTests(string value, DateTime expectedValue)
=> Assert.Equal(expectedValue, SetupProject(value).Database
.GetOption<SweepingEndDateTimeOption>().Value);
/// <summary>
/// Testing the override of the <see cref="IInpEntity.ToInpString"/> as implemented for
/// the <see cref="SweepingEndDateTimeOption"/>
/// </summary>
/// <param name="expectedValue">The expected value</param>
/// <param name="value">The value that will be used to
/// construct the <see cref="SweepingEndDateTimeOption"/></param>
[Theory]
[ClassData(typeof(SweepingEndDateTimeParserTestData))]
public void SweepingEndDateTime_ToInpString_ShouldMatchExpected(string expectedValue, DateTime value)
=> Assert.Equal(PruneInpString(expectedValue, OptionsHeader), new SweepingEndDateTimeOption(value).ToInpString());
/// <summary>
/// Test data for the <see cref="SweepingEndDateTimeParserTests(string, DateTime)"/>
/// tests
/// </summary>
private class SweepingEndDateTimeParserTestData : IEnumerable<object[]>
{
public IEnumerator<object[]> GetEnumerator()
{
yield return new object[]
{
@"[OPTIONS]
SWEEP_END 12/31
",
new DateTime(DateTime.Now.Year, 12, 31)
};
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
#endregion
}
}
| 38.933806 | 142 | 0.586132 | [
"MIT"
] | rena0157/Droplet | tests/Droplet.Core.Inp.Tests/Options/InpDateTimeOptionTests.cs | 16,471 | C# |
using UnityEditor.ShaderGraph;
namespace UnityEditor.Rendering.HighDefinition
{
static class CreateHDLitShaderGraph
{
[MenuItem("Assets/Create/Shader/HDRP/Lit Graph", false, 208)]
public static void CreateMaterialGraph()
{
GraphUtil.CreateNewGraph(new HDLitMasterNode());
}
}
}
| 24.857143 | 70 | 0.646552 | [
"MIT"
] | JesusGarciaValadez/RenderStreamingHDRP | RenderStreamingHDRP/Library/PackageCache/com.unity.render-pipelines.high-definition@8.2.0/Editor/Material/Lit/ShaderGraph/CreateHDLitShaderGraph.cs | 348 | C# |
//
// Copyright 2012-2016, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Android.Content;
using Android.Runtime;
using Java.IO;
using Java.Security;
using Javax.Security.Auth.Callback;
using Javax.Crypto;
#if ! AZURE_MOBILE_SERVICES
namespace Xamarin.Auth
#else
namespace Xamarin.Auth._MobileServices
#endif
{
/// <summary>
/// AccountStore that uses a KeyStore of PrivateKeys protected by a fixed password
/// in a private region of internal storage.
/// </summary>
internal partial class AndroidAccountStore : AccountStore
{
Context context;
KeyStore ks;
KeyStore.PasswordProtection prot;
static readonly object fileLock = new object();
const string FileName = "Xamarin.Social.Accounts";
static char[] Password;
// mc++
// NOTE security hole! Left for backwards compatibility
// PR56
static readonly char[] PasswordHardCoded = "3295043EA18CA264B2C40E0B72051DEF2D07AD2B4593F43DDDE1515A7EC32617".ToCharArray();
static readonly char[] PasswordHardCodedOriginal = "System.Char[]".ToCharArray();
public AndroidAccountStore(Context context)
: this(context, new string(PasswordHardCoded))
{
return;
}
/// <summary>
/// Initializes a new instance of the <see cref="Xamarin.Auth.AndroidAccountStore"/> class
/// with a KeyStore password provided by the application.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="password">KeyStore Password.</param>
public AndroidAccountStore(Context context, string password)
{
if (password == null)
{
throw new ArgumentNullException("password");
}
Password = password.ToCharArray();
this.context = context;
ks = KeyStore.GetInstance(KeyStore.DefaultType);
prot = new KeyStore.PasswordProtection(Password);
try
{
lock (fileLock)
{
if (!this.FileExists(context, FileName))
{
LoadEmptyKeyStore(Password);
}
else
{
using (var s = context.OpenFileInput(FileName))
{
ks.Load(s, Password);
}
}
}
}
catch (FileNotFoundException)
{
LoadEmptyKeyStore(Password);
}
catch (Java.IO.IOException ex)
{
if (ex.Message == "KeyStore integrity check failed.")
{
// Migration scenario: this exception means that the keystore could not be opened
// with the app provided password, so there is probably an existing keystore
// that was encoded with the old hard coded password, which was deprecated.
// We'll try to open the keystore with the old password, and migrate the contents
// to a new one that will be encoded with the new password.
//MigrateKeyStore(context);
try
{
//try with the original password
MigrateKeyStore(context, PasswordHardCodedOriginal);
}
catch (System.Exception)
{
//migrate using the default
MigrateKeyStore(context);
}
}
}
}
public override IEnumerable<Account> FindAccountsForService(string serviceId)
{
return FindAccountsForServiceAsync(serviceId).Result;
}
public override void Save(Account account, string serviceId)
{
SaveAsync(account, serviceId);
}
public override void Delete(Account account, string serviceId)
{
DeleteAsync(account, serviceId);
return;
}
protected void Save()
{
lock (fileLock)
{
using (var s = context.OpenFileOutput(FileName, FileCreationMode.Private))
{
ks.Store(s, Password);
s.Flush();
s.Close();
}
}
return;
}
static string MakeAlias(Account account, string serviceId)
{
return account.Username + "-" + serviceId;
}
class SecretAccount : Java.Lang.Object, ISecretKey
{
byte[] bytes;
public SecretAccount(Account account)
{
bytes = System.Text.Encoding.UTF8.GetBytes(account.Serialize());
}
public byte[] GetEncoded()
{
return bytes;
}
public string Algorithm
{
get
{
return "RAW";
}
}
public string Format
{
get
{
return "RAW";
}
}
}
static IntPtr id_load_Ljava_io_InputStream_arrayC;
/// <summary>
/// Work around Bug https://bugzilla.xamarin.com/show_bug.cgi?id=6766
/// </summary>
void LoadEmptyKeyStore(char[] password)
{
if (id_load_Ljava_io_InputStream_arrayC == IntPtr.Zero)
{
id_load_Ljava_io_InputStream_arrayC = JNIEnv.GetMethodID(ks.Class.Handle, "load", "(Ljava/io/InputStream;[C)V");
}
IntPtr intPtr = IntPtr.Zero;
IntPtr intPtr2 = JNIEnv.NewArray(password);
JNIEnv.CallVoidMethod(ks.Handle, id_load_Ljava_io_InputStream_arrayC, new JValue[]
{
new JValue (intPtr),
new JValue (intPtr2)
});
JNIEnv.DeleteLocalRef(intPtr);
if (password != null)
{
JNIEnv.CopyArray(intPtr2, password);
JNIEnv.DeleteLocalRef(intPtr2);
}
}
public bool FileExists(Context context, String filename)
{
File file = context.GetFileStreamPath(filename);
if (file == null || !file.Exists())
{
return false;
}
return true;
}
#region Migration of key store with hard coded password
//Keep for backward compatibility
void MigrateKeyStore(Context context)
{
MigrateKeyStore(context, PasswordHardCoded);
}
/// <summary>
/// Migrates the key store.
/// </summary>
/// <param name="context">Context.</param>
/// <param name="password">Password.</param>
void MigrateKeyStore(Context context, char[] oldpassword)
{
// Moves aside the old keystore, opens it with the old hard coded password
// and copies all entries to the new keystore, secured with the app provided password
lock (fileLock)
{
// First: attempt to open the keystore with the old password
// If that succeeds, the store can be migrated
lock (fileLock)
{
using (var s = context.OpenFileInput(FileName))
{
ks.Load(s, oldpassword);
}
}
MoveKeyStoreFile(context, FileName, FileName + "Old");
LoadEmptyKeyStore(Password);
CopyKeyStoreContents(oldpassword);
context.DeleteFile(FileName + "Old");
}
}
protected void MoveKeyStoreFile(Context context, string source, string destination)
{
var input = context.OpenFileInput(source);
var output = context.OpenFileOutput(destination, FileCreationMode.Private);
byte[] buffer = new byte[1024];
int len;
while ((len = input.Read(buffer, 0, 1024)) > 0)
{
output.Write(buffer, 0, len);
}
input.Close();
output.Close();
context.DeleteFile(FileName);
}
protected void CopyKeyStoreContents(char[] oldPassword)
{
var oldKeyStore = KeyStore.GetInstance(KeyStore.DefaultType);
var oldProtection = new KeyStore.PasswordProtection(oldPassword);
using (var s = context.OpenFileInput(FileName + "Old"))
{
oldKeyStore.Load(s, oldPassword);
// Copy all aliases to a new keystore, using a different password
var aliases = oldKeyStore.Aliases();
while (aliases.HasMoreElements)
{
var alias = aliases.NextElement().ToString();
var e = oldKeyStore.GetEntry(alias, oldProtection) as KeyStore.SecretKeyEntry;
ks.SetEntry(alias, e, prot);
}
}
Save();
}
#endregion
}
}
| 34.155116 | 133 | 0.511837 | [
"Apache-2.0"
] | Abhirasmanu-Trimble/Xamarin.Auth | source/Core/Xamarin.Auth.XamarinAndroid/AccountStore/AndroidAccountStore.cs | 10,349 | 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 swf-2012-01-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SimpleWorkflow.Model
{
/// <summary>
/// Contains the response data from the DescribeDomain operation.
/// </summary>
public partial class DescribeDomainResult : AmazonWebServiceResponse
{
private DomainDetail _domainDetail;
// Gets and sets the DomainDetail member
public DomainDetail DomainDetail
{
get { return this._domainDetail; }
set { this._domainDetail = value; }
}
// Check to see if DomainDetail property is set
internal bool IsSetDomainDetail()
{
return this._domainDetail != null;
}
}
} | 30.36 | 101 | 0.689723 | [
"Apache-2.0"
] | ermshiperete/aws-sdk-net | AWSSDK_DotNet35/Amazon.SimpleWorkflow/Model/DescribeDomainResult.cs | 1,518 | C# |
using System;
using System.Collections.Generic;
using Windows.Foundation;
namespace Windows.UI.Xaml.Automation.Peers
{
public partial class LoopingSelectorItemDataAutomationPeer
{
internal LoopingSelectorItemDataAutomationPeer(
DependencyObject pItem,
LoopingSelectorAutomationPeer pOwner)
{
_itemIndex = -1;
InitializeImpl(pItem, pOwner);
}
void InitializeImpl(
DependencyObject pItem,
LoopingSelectorAutomationPeer pOwner)
{
//AutomationPeerFactory spInnerFactory;
//AutomationPeer spInnerInstance;
//DependencyObject spInnerInspectable;
//LoopingSelectorItemDataAutomationPeerGenerated.InitializeImpl(pItem, pOwner);
//(wf.GetActivationFactory(
// wrl_wrappers.Hstring(RuntimeClass_Microsoft_UI_Xaml_Automation_Peers_AutomationPeer),
// &spInnerFactory));
//(spInnerFactory.CreateInstance(
// (LoopingSelectorItemDataAutomationPeer)(this),
// &spInnerInspectable,
// &spInnerInstance));
//(SetComposableBasePointers(
// spInnerInspectable,
// spInnerFactory));
SetParent(pOwner);
SetItem(pItem);
}
void SetParent(LoopingSelectorAutomationPeer pOwner)
{
AutomationPeer spThisAsAP;
//(QueryInterface(
// __uuidof(AutomationPeer),
// &spThisAsAP));
spThisAsAP = this;
//LoopingSelectorAutomationPeer(pOwner).AsWeak(_wrParent);
_wrParent = new WeakReference<LoopingSelectorAutomationPeer>(pOwner);
if (pOwner is { })
{
AutomationPeer spLSAsAP;
//pOwner.QueryInterface<AutomationPeer>(spLSAsAP);
spLSAsAP = pOwner;
// NOTE: This causes an addmost likely, I think that's a good idea.
spThisAsAP.SetParent(spLSAsAP);
}
else
{
spThisAsAP.SetParent(null);
}
}
public void SetItem(DependencyObject pItem)
{
_tpItem = pItem;
}
internal void
GetItem(out DependencyObject ppItem)
{
ppItem = null;
//_tpItem.CopyTo(ppItem);
ppItem = _tpItem;
}
public void SetItemIndex(int index)
{
_itemIndex = index;
}
void ThrowElementNotAvailableException()
{
//return UIA_E_INVALIDOPERATION;
throw new InvalidOperationException();
}
void GetContainerAutomationPeer(
out AutomationPeer ppContainer)
{
ppContainer = null;
LoopingSelectorAutomationPeer spParent = default;
//_wrParent.As(spParent);
//spParent = _wrParent;
//if (spParent is {})
if(_wrParent?.TryGetTarget(out spParent) ?? false)
{
LoopingSelectorItemAutomationPeer spLSIAP;
spParent.GetContainerAutomationPeerForItem(_tpItem, out spLSIAP);
if (spLSIAP == null)
{
// If the item has not been realized, spLSIAP will be null.
// Realize the item on demand now and try again
Realize();
spParent.GetContainerAutomationPeerForItem(_tpItem, out spLSIAP);
}
if (spLSIAP is { })
{
//spLSIAP.CopyTo(ppContainer);
ppContainer = spLSIAP;
}
}
}
void
RealizeImpl()
{
LoopingSelectorAutomationPeer spParent = default;
//_wrParent.As(spParent);
//if (spParent && _tpItem)
if(_wrParent?.TryGetTarget(out spParent) ?? false)
{
spParent.RealizeItemAtIndex(_itemIndex);
}
}
#region Method forwarders
protected override object GetPatternCore(PatternInterface patternInterface)
{
DependencyObject returnValue = default;
if (patternInterface == PatternInterface.VirtualizedItem)
{
returnValue = (LoopingSelectorItemDataAutomationPeer)this;
//AddRef();
}
else
{
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetPattern(patternInterface) as DependencyObject;
}
else
{
//LoopingSelectorItemDataAutomationPeerGenerated.GetPatternCoreImpl(patternInterface, out returnValue);
}
}
return returnValue;
}
protected override string GetAcceleratorKeyCore()
{
string returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetAcceleratorKey();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override string GetAccessKeyCore()
{
string returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetAccessKey();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override AutomationControlType GetAutomationControlTypeCore()
{
AutomationControlType returnValue;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetAutomationControlType();
}
else
{
returnValue = AutomationControlType.ListItem;
}
return returnValue;
}
protected override string GetAutomationIdCore()
{
string returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetAutomationId();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override Rect GetBoundingRectangleCore()
{
Rect returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetBoundingRectangle();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override IList<AutomationPeer> GetChildrenCore()
{
IList<AutomationPeer> returnValue;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetChildren();
}
else
{
returnValue = null;
}
return returnValue;
}
protected override string GetClassNameCore()
{
string returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetClassName();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override Point GetClickablePointCore()
{
Point returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetClickablePoint();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override string GetHelpTextCore()
{
string returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetHelpText();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override string GetItemStatusCore()
{
string returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetItemStatus();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override string GetItemTypeCore()
{
string returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetItemType();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override AutomationPeer GetLabeledByCore()
{
AutomationPeer returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetLabeledBy();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override string GetLocalizedControlTypeCore()
{
string returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetLocalizedControlType();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override string GetNameCore()
{
string returnValue = default;
if (_tpItem is { })
{
returnValue = AutomationHelper.GetPlainText(_tpItem);
}
return returnValue;
}
protected override AutomationOrientation GetOrientationCore()
{
AutomationOrientation returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetOrientation();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override AutomationLiveSetting GetLiveSettingCore()
{
AutomationLiveSetting returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetLiveSetting();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override IReadOnlyList<AutomationPeer> GetControlledPeersCore()
{
IReadOnlyList<AutomationPeer> returnValue;
returnValue = null;
return returnValue;
}
protected override bool HasKeyboardFocusCore()
{
bool returnValue;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.HasKeyboardFocus();
}
else
{
returnValue = false;
}
return returnValue;
}
protected override bool IsContentElementCore()
{
bool returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.IsContentElement();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override bool IsControlElementCore()
{
bool returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.IsControlElement();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override bool IsEnabledCore()
{
bool returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.IsEnabled();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override bool IsKeyboardFocusableCore()
{
bool returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.IsKeyboardFocusable();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override bool IsOffscreenCore()
{
bool returnValue;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.IsOffscreen();
}
else
{
returnValue = true;
}
return returnValue;
}
protected override bool IsPasswordCore()
{
bool returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.IsPassword();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override bool IsRequiredForFormCore()
{
bool returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.IsRequiredForForm();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override void SetFocusCore()
{
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
spAutomationPeer.SetFocus();
}
}
protected override IList<AutomationPeerAnnotation> GetAnnotationsCore()
{
IList<AutomationPeerAnnotation> returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetAnnotations();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override int GetPositionInSetCore()
{
int returnValue = -1;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetPositionInSet();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override int GetSizeOfSetCore()
{
int returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetSizeOfSet();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override int GetLevelCore()
{
int returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetLevel();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override AutomationLandmarkType GetLandmarkTypeCore()
{
AutomationLandmarkType returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetLandmarkType();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
protected override string GetLocalizedLandmarkTypeCore()
{
string returnValue = default;
AutomationPeer spAutomationPeer;
GetContainerAutomationPeer(out spAutomationPeer);
if (spAutomationPeer is { })
{
returnValue = spAutomationPeer.GetLocalizedLandmarkType();
}
else
{
ThrowElementNotAvailableException();
}
return returnValue;
}
#endregion
}
}
| 21.498563 | 108 | 0.714629 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UI/UI/Xaml/Controls/Primitives/LoopingSelector/LoopingSelectorItemDataAutomationPeer_Partial.cs | 14,963 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.HDInsight.Cmdlet.PSCmdlets
{
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using Commands.BaseCommandInterfaces;
using Commands.CommandInterfaces;
using DataObjects;
using GetAzureHDInsightClusters;
using GetAzureHDInsightClusters.Extensions;
using ServiceLocation;
/// <summary>
/// Represents the New-AzureHDInsightConfig Power Shell Cmdlet.
/// </summary>
[Cmdlet(VerbsCommon.New, AzureHdInsightPowerShellConstants.AzureHDInsightHiveJobDefinition)]
[OutputType(typeof(AzureHDInsightHiveJobDefinition))]
public class NewAzureHDInsightHiveJobDefinitionCmdlet : AzureHDInsightCmdlet, INewAzureHDInsightHiveJobDefinitionBase
{
private readonly INewAzureHDInsightHiveJobDefinitionCommand command;
/// <summary>
/// Initializes a new instance of the NewAzureHDInsightHiveJobDefinitionCmdlet class.
/// </summary>
public NewAzureHDInsightHiveJobDefinitionCmdlet()
{
this.command = ServiceLocator.Instance.Locate<IAzureHDInsightCommandFactory>().CreateNewHiveDefinition();
}
/// <inheritdoc />
[Parameter(Mandatory = false, HelpMessage = "The hive arguments for the jobDetails.")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Need collections for input parameters")]
public string[] Arguments
{
get { return this.command.Arguments; }
set { this.command.Arguments = value; }
}
/// <inheritdoc />
[Parameter(Mandatory = false, HelpMessage = "The parameters for the jobDetails.")]
[Alias(AzureHdInsightPowerShellConstants.AliasParameters)]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Need collections for input parameters")]
public Hashtable Defines
{
get { return this.command.Defines; }
set { this.command.Defines = value; }
}
/// <inheritdoc />
[Parameter(Mandatory = false, HelpMessage = "The query file to run in the jobDetails.")]
[Alias(AzureHdInsightPowerShellConstants.AliasQueryFile)]
public string File
{
get { return this.command.File; }
set { this.command.File = value; }
}
/// <inheritdoc />
[Parameter(Mandatory = false, HelpMessage = "The files for the jobDetails.")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Need collections for input parameters")]
public string[] Files
{
get { return this.command.Files; }
set { this.command.Files = value; }
}
/// <inheritdoc />
[Parameter(Mandatory = false, HelpMessage = "The name of the jobDetails.")]
[Alias(AzureHdInsightPowerShellConstants.AliasJobName)]
public string JobName
{
get { return this.command.JobName; }
set { this.command.JobName = value; }
}
/// <inheritdoc />
[Parameter(Mandatory = false, HelpMessage = "The query to run in the jobDetails.")]
[Alias(AzureHdInsightPowerShellConstants.AliasQuery)]
public string Query
{
get { return this.command.Query; }
set { this.command.Query = value; }
}
/// <inheritdoc />
[Parameter(Mandatory = false, HelpMessage = "The output location to use for the job.")]
public string StatusFolder
{
get { return this.command.StatusFolder; }
set { this.command.StatusFolder = value; }
}
/// <summary>
/// Finishes the execution of the cmdlet by writing out the config object.
/// </summary>
protected override void EndProcessing()
{
if (this.File.IsNullOrEmpty() && this.Query.IsNullOrEmpty())
{
throw new PSArgumentException("Either File or Query should be specified for Hive jobs.");
}
this.command.EndProcessing().Wait();
foreach (AzureHDInsightHiveJobDefinition output in this.command.Output)
{
this.WriteObject(output);
}
this.WriteDebugLog();
}
/// <inheritdoc />
protected override void StopProcessing()
{
this.command.Cancel();
}
}
}
| 41.801527 | 149 | 0.610299 | [
"MIT"
] | Milstein/azure-sdk-tools | WindowsAzurePowershell/src/Commands/HDInsight/NewAzureHDInsightHiveJobDefinitionCmdlet.cs | 5,348 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft;
using Microsoft.VisualStudio.Threading;
using Xunit;
using Xunit.Abstractions;
internal static class TestUtilities
{
internal static Task SetAsync(this TaskCompletionSource<object?> tcs)
{
return Task.Run(() => tcs.TrySetResult(null));
}
/// <summary>
/// Runs an asynchronous task synchronously, using just the current thread to execute continuations.
/// </summary>
internal static void Run(Func<Task> func)
{
if (func is null)
{
throw new ArgumentNullException(nameof(func));
}
SynchronizationContext? prevCtx = SynchronizationContext.Current;
try
{
SynchronizationContext? syncCtx = SingleThreadedTestSynchronizationContext.New();
SynchronizationContext.SetSynchronizationContext(syncCtx);
Task? t = func();
if (t is null)
{
throw new InvalidOperationException();
}
SingleThreadedTestSynchronizationContext.IFrame? frame = SingleThreadedTestSynchronizationContext.NewFrame();
t.ContinueWith(_ => { frame.Continue = false; }, TaskScheduler.Default);
SingleThreadedTestSynchronizationContext.PushFrame(syncCtx, frame);
t.GetAwaiter().GetResult();
}
finally
{
SynchronizationContext.SetSynchronizationContext(prevCtx);
}
}
/// <summary>
/// Executes the specified function on multiple threads simultaneously.
/// </summary>
/// <typeparam name="T">The type of the value returned by the specified function.</typeparam>
/// <param name="action">The function to invoke concurrently.</param>
/// <param name="concurrency">The level of concurrency.</param>
internal static T[] ConcurrencyTest<T>(Func<T> action, int concurrency = -1)
{
Requires.NotNull(action, nameof(action));
if (concurrency == -1)
{
concurrency = Environment.ProcessorCount;
}
Skip.If(Environment.ProcessorCount < concurrency, $"The test machine does not have enough CPU cores to exercise a concurrency level of {concurrency}");
// We use a barrier to guarantee that all threads are fully ready to
// execute the provided function at precisely the same time.
// The barrier will unblock all of them together.
using (var barrier = new Barrier(concurrency))
{
var tasks = new Task<T>[concurrency];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = Task.Run(delegate
{
barrier.SignalAndWait();
return action();
});
}
Task.WaitAll(tasks);
return tasks.Select(t => t.Result).ToArray();
}
}
internal static DebugAssertionRevert DisableAssertionDialog()
{
#if NETFRAMEWORK
DefaultTraceListener? listener = Debug.Listeners.OfType<DefaultTraceListener>().FirstOrDefault();
if (listener is object)
{
listener.AssertUiEnabled = false;
}
#elif NET5_0
Trace.Listeners.Clear();
#endif
return default(DebugAssertionRevert);
}
internal static void CompleteSynchronously(this JoinableTaskFactory factory, JoinableTaskCollection collection, Task task)
{
Requires.NotNull(factory, nameof(factory));
Requires.NotNull(collection, nameof(collection));
Requires.NotNull(task, nameof(task));
factory.Run(async delegate
{
using (collection.Join())
{
await task;
}
});
}
/// <summary>
/// Forces an awaitable to yield, setting signals after the continuation has been pended and when the continuation has begun execution.
/// </summary>
/// <param name="baseAwaiter">The awaiter to extend.</param>
/// <param name="yieldingSignal">The signal to set after the continuation has been pended.</param>
/// <param name="resumingSignal">The signal to set when the continuation has been invoked.</param>
/// <returns>A new awaitable.</returns>
internal static YieldAndNotifyAwaitable YieldAndNotify(this INotifyCompletion baseAwaiter, AsyncManualResetEvent? yieldingSignal = null, AsyncManualResetEvent? resumingSignal = null)
{
Requires.NotNull(baseAwaiter, nameof(baseAwaiter));
return new YieldAndNotifyAwaitable(baseAwaiter, yieldingSignal, resumingSignal);
}
/// <summary>
/// Flood the threadpool with requests that will just block the threads
/// until the returned value is disposed of.
/// </summary>
/// <returns>A value to dispose of to unblock the threadpool.</returns>
/// <remarks>
/// This can provide a unique technique for influencing execution order
/// of synchronous code vs. async code.
/// </remarks>
internal static IDisposable StarveThreadpool()
{
ThreadPool.GetMaxThreads(out int workerThreads, out int completionPortThreads);
var disposalTokenSource = new CancellationTokenSource();
var unblockThreadpool = new ManualResetEventSlim();
for (int i = 0; i < workerThreads; i++)
{
Task.Run(
() => unblockThreadpool.Wait(disposalTokenSource.Token),
disposalTokenSource.Token);
}
return new DisposalAction(disposalTokenSource.Cancel);
}
/// <summary>
/// Executes the specified test method in its own process, offering maximum isolation from ambient noise from other threads
/// and GC.
/// </summary>
/// <param name="testClass">The instance of the test class containing the method to be run in isolation.</param>
/// <param name="testMethodName">The name of the test method.</param>
/// <param name="logger">An optional logger to forward any <see cref="ITestOutputHelper"/> output to from the isolated test runner.</param>
/// <returns>
/// A task whose result is <c>true</c> if test execution is already isolated and should therefore proceed with the body of the test,
/// or <c>false</c> after the isolated instance of the test has completed execution.
/// </returns>
/// <exception cref="Xunit.Sdk.XunitException">Thrown if the isolated test result is a Failure.</exception>
/// <exception cref="SkipException">Thrown if on a platform that we do not yet support test isolation on.</exception>
internal static Task<bool> ExecuteInIsolationAsync(object testClass, string testMethodName, ITestOutputHelper logger)
{
Requires.NotNull(testClass, nameof(testClass));
return ExecuteInIsolationAsync(testClass.GetType().FullName!, testMethodName, logger);
}
/// <summary>
/// Executes the specified test method in its own process, offering maximum isolation from ambient noise from other threads
/// and GC.
/// </summary>
/// <param name="testClassName">The full name of the test class.</param>
/// <param name="testMethodName">The name of the test method.</param>
/// <param name="logger">An optional logger to forward any <see cref="ITestOutputHelper"/> output to from the isolated test runner.</param>
/// <returns>
/// A task whose result is <c>true</c> if test execution is already isolated and should therefore proceed with the body of the test,
/// or <c>false</c> after the isolated instance of the test has completed execution.
/// </returns>
/// <exception cref="Xunit.Sdk.XunitException">Thrown if the isolated test result is a Failure.</exception>
/// <exception cref="SkipException">Thrown if on a platform that we do not yet support test isolation on.</exception>
#pragma warning disable CA1801 // Review unused parameters
internal static Task<bool> ExecuteInIsolationAsync(string testClassName, string testMethodName, ITestOutputHelper logger)
#pragma warning restore CA1801 // Review unused parameters
{
Requires.NotNullOrEmpty(testClassName, nameof(testClassName));
Requires.NotNullOrEmpty(testMethodName, nameof(testMethodName));
#if NETFRAMEWORK
const string testHostProcessName = "IsolatedTestHost.exe";
if (Process.GetCurrentProcess().ProcessName == Path.GetFileNameWithoutExtension(testHostProcessName))
{
return TplExtensions.TrueTask;
}
var startInfo = new ProcessStartInfo(
testHostProcessName,
AssemblyCommandLineArguments(
Assembly.GetExecutingAssembly().Location,
testClassName,
testMethodName))
{
RedirectStandardError = logger is object,
RedirectStandardOutput = logger is object,
CreateNoWindow = true,
UseShellExecute = false,
};
Process isolatedTestProcess = new Process
{
StartInfo = startInfo,
EnableRaisingEvents = true,
};
var processExitCode = new TaskCompletionSource<IsolatedTestHost.ExitCode>();
isolatedTestProcess.Exited += (s, e) =>
{
processExitCode.SetResult((IsolatedTestHost.ExitCode)isolatedTestProcess.ExitCode);
};
if (logger is object)
{
isolatedTestProcess.OutputDataReceived += (s, e) => logger.WriteLine(e.Data ?? string.Empty);
isolatedTestProcess.ErrorDataReceived += (s, e) => logger.WriteLine(e.Data ?? string.Empty);
}
Assert.True(isolatedTestProcess.Start());
if (logger is object)
{
isolatedTestProcess.BeginOutputReadLine();
isolatedTestProcess.BeginErrorReadLine();
}
return processExitCode.Task.ContinueWith(
t =>
{
switch (t.Result)
{
case IsolatedTestHost.ExitCode.TestSkipped:
throw new SkipException("Test skipped. See output of isolated task for details.");
case IsolatedTestHost.ExitCode.TestPassed:
default:
Assert.Equal(IsolatedTestHost.ExitCode.TestPassed, t.Result);
break;
}
return false;
},
TaskScheduler.Default);
#else
return Task.FromException<bool>(new SkipException("Test isolation is not yet supported on this platform."));
#endif
}
/// <summary>
/// Wait on a task without possibly inlining it to the current thread.
/// </summary>
/// <param name="task">The task to wait on.</param>
/// <param name="throwOriginalException"><c>true</c> to throw the original (inner) exception when the <paramref name="task"/> faults; <c>false</c> to throw <see cref="AggregateException"/>.</param>
/// <exception cref="AggregateException">Thrown if <paramref name="task"/> completes in a faulted state if <paramref name="throwOriginalException"/> is <c>false</c>.</exception>
internal static void WaitWithoutInlining(this Task task, bool throwOriginalException)
{
Requires.NotNull(task, nameof(task));
if (!task.IsCompleted)
{
// Waiting on a continuation of a task won't ever inline the predecessor (in .NET 4.x anyway).
Task? continuation = task.ContinueWith(t => { }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
continuation.Wait();
}
// Rethrow the exception if the task faulted.
if (throwOriginalException)
{
task.GetAwaiter().GetResult();
}
else
{
task.Wait();
}
}
/// <summary>
/// Wait on a task without possibly inlining it to the current thread and returns its result.
/// </summary>
/// <typeparam name="T">The type of result returned from the <paramref name="task"/>.</typeparam>
/// <param name="task">The task to wait on.</param>
/// <param name="throwOriginalException"><c>true</c> to throw the original (inner) exception when the <paramref name="task"/> faults; <c>false</c> to throw <see cref="AggregateException"/>.</param>
/// <returns>The result of the <see cref="Task{T}"/>.</returns>
/// <exception cref="AggregateException">Thrown if <paramref name="task"/> completes in a faulted state if <paramref name="throwOriginalException"/> is <c>false</c>.</exception>
internal static T GetResultWithoutInlining<T>(this Task<T> task, bool throwOriginalException = true)
{
WaitWithoutInlining(task, throwOriginalException);
return task.Result;
}
private static string AssemblyCommandLineArguments(params string[] args) => string.Join(" ", args.Select(a => $"\"{a}\""));
internal readonly struct YieldAndNotifyAwaitable
{
private readonly INotifyCompletion baseAwaiter;
private readonly AsyncManualResetEvent? yieldingSignal;
private readonly AsyncManualResetEvent? resumingSignal;
internal YieldAndNotifyAwaitable(INotifyCompletion baseAwaiter, AsyncManualResetEvent? yieldingSignal, AsyncManualResetEvent? resumingSignal)
{
Requires.NotNull(baseAwaiter, nameof(baseAwaiter));
this.baseAwaiter = baseAwaiter;
this.yieldingSignal = yieldingSignal;
this.resumingSignal = resumingSignal;
}
public YieldAndNotifyAwaiter GetAwaiter()
{
return new YieldAndNotifyAwaiter(this.baseAwaiter, this.yieldingSignal, this.resumingSignal);
}
}
internal readonly struct YieldAndNotifyAwaiter : INotifyCompletion
{
private readonly INotifyCompletion baseAwaiter;
private readonly AsyncManualResetEvent? yieldingSignal;
private readonly AsyncManualResetEvent? resumingSignal;
internal YieldAndNotifyAwaiter(INotifyCompletion baseAwaiter, AsyncManualResetEvent? yieldingSignal, AsyncManualResetEvent? resumingSignal)
{
Requires.NotNull(baseAwaiter, nameof(baseAwaiter));
this.baseAwaiter = baseAwaiter;
this.yieldingSignal = yieldingSignal;
this.resumingSignal = resumingSignal;
}
public bool IsCompleted
{
get { return false; }
}
public void OnCompleted(Action continuation)
{
YieldAndNotifyAwaiter that = this;
this.baseAwaiter.OnCompleted(delegate
{
if (that.resumingSignal is object)
{
that.resumingSignal.Set();
}
continuation();
});
if (this.yieldingSignal is object)
{
this.yieldingSignal.Set();
}
}
public void GetResult()
{
}
}
internal readonly struct DebugAssertionRevert : IDisposable
{
public void Dispose()
{
#if NETFRAMEWORK
DefaultTraceListener? listener = Debug.Listeners.OfType<DefaultTraceListener>().FirstOrDefault();
if (listener is object)
{
listener.AssertUiEnabled = true;
}
#endif
}
}
private class DisposalAction : IDisposable
{
private readonly Action disposeAction;
internal DisposalAction(Action disposeAction)
{
this.disposeAction = disposeAction;
}
public void Dispose() => this.disposeAction();
}
}
| 39.83208 | 201 | 0.643302 | [
"MIT"
] | AArnott/vs-threading | test/Microsoft.VisualStudio.Threading.Tests/TestUtilities.cs | 15,895 | C# |
using RestAPI.Data.VO;
using RestAPI.Model;
using RestAPI.Model.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace RestAPI.Repository
{
public class UserRepository : IUserRepository
{
private readonly MySQLContext _context;
public UserRepository(MySQLContext context)
{
_context = context;
}
public User ValidateCredentials(UserVO user)
{
var pass = ComputeHash(user.Password, new SHA256CryptoServiceProvider());
return _context.Users.FirstOrDefault(u => (u.UserName == user.UserName) && (u.Password == pass));
}
public User ValidateCredentials(string userName)
{
return _context.Users.SingleOrDefault(u => (u.UserName == userName));
}
public bool RevokeToken(string userName)
{
var user = _context.Users.SingleOrDefault(u => (u.UserName == userName));
if (user is null) return false;
user.RefreshToken = null;
_context.SaveChanges();
return true;
}
public User RefreshUserInfo(User user)
{
if (!_context.Users.Any(u => u.Id.Equals(user.Id))) return null;
var result = _context.Users.SingleOrDefault(p => p.Id.Equals(user.Id));
if (result != null)
{
try
{
_context.Entry(result).CurrentValues.SetValues(user);
_context.SaveChanges();
return result;
}
catch (Exception)
{
throw;
}
}
return result;
}
private string ComputeHash(string input, SHA256CryptoServiceProvider algorithm)
{
Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
return BitConverter.ToString(hashedBytes);
}
}
}
| 27.986842 | 109 | 0.566996 | [
"Apache-2.0"
] | osvaldobnu/RestWithAspnet5 | RestWithASPNET/02_Calculator/RestAPI/RestAPI/Repository/UserRepository.cs | 2,129 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime
{
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using GetEventData = System.Func<EventData>;
using static Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Extensions;
public interface IValidates
{
Task Validate(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.IEventListener listener);
}
/// <summary>
/// The IEventListener Interface defines the communication mechanism for Signaling events during a remote call.
/// </summary>
/// <remarks>
/// The interface is designed to be as minimal as possible, allow for quick peeking of the event type (<c>id</c>)
/// and the cancellation status and provides a delegate for retrieving the event details themselves.
/// </remarks>
public interface IEventListener
{
Task Signal(string id, CancellationToken token, GetEventData createMessage);
CancellationToken Token { get; }
System.Action Cancel { get; }
}
internal static partial class Extensions
{
public static Task Signal(this IEventListener instance, string id, CancellationToken token, Func<EventData> createMessage) => instance.Signal(id, token, createMessage);
public static Task Signal(this IEventListener instance, string id, CancellationToken token) => instance.Signal(id, token, () => new EventData { Id = id, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText, HttpRequestMessage request) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, RequestMessage = request, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText, HttpResponseMessage response) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, RequestMessage = response.RequestMessage, ResponseMessage = response, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText, double magnitude) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, Value = magnitude, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText, double magnitude, HttpRequestMessage request) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, RequestMessage = request, Value = magnitude, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, CancellationToken token, string messageText, double magnitude, HttpResponseMessage response) => instance.Signal(id, token, () => new EventData { Id = id, Message = messageText, RequestMessage = response.RequestMessage, ResponseMessage = response, Value = magnitude, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, CancellationToken token, HttpRequestMessage request) => instance.Signal(id, token, () => new EventData { Id = id, RequestMessage = request, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, CancellationToken token, HttpRequestMessage request, HttpResponseMessage response) => instance.Signal(id, token, () => new EventData { Id = id, RequestMessage = request, ResponseMessage = response, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, CancellationToken token, HttpResponseMessage response) => instance.Signal(id, token, () => new EventData { Id = id, RequestMessage = response.RequestMessage, ResponseMessage = response, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, CancellationToken token, EventData message) => instance.Signal(id, token, () => { message.Id = id; message.Cancel = instance.Cancel; return message; });
public static Task Signal(this IEventListener instance, string id, Func<EventData> createMessage) => instance.Signal(id, instance.Token, createMessage);
public static Task Signal(this IEventListener instance, string id) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, string messageText) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, string messageText, HttpRequestMessage request) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, RequestMessage = request, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, string messageText, HttpResponseMessage response) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, RequestMessage = response.RequestMessage, ResponseMessage = response, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, string messageText, double magnitude) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, Value = magnitude, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, string messageText, double magnitude, HttpRequestMessage request) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, RequestMessage = request, Value = magnitude, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, string messageText, double magnitude, HttpResponseMessage response) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = messageText, RequestMessage = response.RequestMessage, ResponseMessage = response, Value = magnitude, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, HttpRequestMessage request) => instance.Signal(id, instance.Token, () => new EventData { Id = id, RequestMessage = request, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, HttpRequestMessage request, HttpResponseMessage response) => instance.Signal(id, instance.Token, () => new EventData { Id = id, RequestMessage = request, ResponseMessage = response, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, HttpResponseMessage response) => instance.Signal(id, instance.Token, () => new EventData { Id = id, RequestMessage = response.RequestMessage, ResponseMessage = response, Cancel = instance.Cancel });
public static Task Signal(this IEventListener instance, string id, EventData message) => instance.Signal(id, instance.Token, () => { message.Id = id; message.Cancel = instance.Cancel; return message; });
public static Task Signal(this IEventListener instance, string id, System.Uri uri) => instance.Signal(id, instance.Token, () => new EventData { Id = id, Message = uri.ToString(), Cancel = instance.Cancel });
public static async Task AssertNotNull(this IEventListener instance, string parameterName, object value)
{
if (value == null)
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"'{parameterName}' should not be null", Parameter = parameterName, Cancel = instance.Cancel });
}
}
public static async Task AssertMinimumLength(this IEventListener instance, string parameterName, string value, int length)
{
if (value != null && value.Length < length)
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"Length of '{parameterName}' is less than {length}", Parameter = parameterName, Cancel = instance.Cancel });
}
}
public static async Task AssertMaximumLength(this IEventListener instance, string parameterName, string value, int length)
{
if (value != null && value.Length > length)
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"Length of '{parameterName}' is greater than {length}", Parameter = parameterName, Cancel = instance.Cancel });
}
}
public static async Task AssertRegEx(this IEventListener instance, string parameterName, string value, string regularExpression)
{
if (value != null && !System.Text.RegularExpressions.Regex.Match(value, regularExpression).Success)
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"'{parameterName}' does not validate against pattern /{regularExpression}/", Parameter = parameterName, Cancel = instance.Cancel });
}
}
public static async Task AssertEnum(this IEventListener instance, string parameterName, string value, params string[] values)
{
if (!values.Any(each => each.Equals(value)))
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"'{parameterName}' is not one of ({values.Aggregate((c, e) => $"'{e}',{c}")}", Parameter = parameterName, Cancel = instance.Cancel });
}
}
public static async Task AssertObjectIsValid(this IEventListener instance, string parameterName, object inst)
{
await (inst as Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.IValidates)?.Validate(instance);
}
public static async Task AssertIsLessThan<T>(this IEventListener instance, string parameterName, T? value, T max) where T : struct, System.IComparable<T>
{
if (null != value && ((T)value).CompareTo(max) >= 0)
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be less than {max} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel });
}
}
public static async Task AssertIsGreaterThan<T>(this IEventListener instance, string parameterName, T? value, T max) where T : struct, System.IComparable<T>
{
if (null != value && ((T)value).CompareTo(max) <= 0)
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be greater than {max} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel });
}
}
public static async Task AssertIsLessThanOrEqual<T>(this IEventListener instance, string parameterName, T? value, T max) where T : struct, System.IComparable<T>
{
if (null != value && ((T)value).CompareTo(max) > 0)
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be less than or equal to {max} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel });
}
}
public static async Task AssertIsGreaterThanOrEqual<T>(this IEventListener instance, string parameterName, T? value, T max) where T : struct, System.IComparable<T>
{
if (null != value && ((T)value).CompareTo(max) < 0)
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be greater than or equal to {max} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel });
}
}
public static async Task AssertIsMultipleOf(this IEventListener instance, string parameterName, Int64? value, Int64 multiple)
{
if (null != value && value % multiple != 0)
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be multiple of {multiple} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel });
}
}
public static async Task AssertIsMultipleOf(this IEventListener instance, string parameterName, double? value, double multiple)
{
if (null != value)
{
var i = (Int64)(value / multiple);
if (i != value / multiple)
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be multiple of {multiple} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel });
}
}
}
public static async Task AssertIsMultipleOf(this IEventListener instance, string parameterName, decimal? value, decimal multiple)
{
if (null != value)
{
var i = (Int64)(value / multiple);
if (i != value / multiple)
{
await instance.Signal(Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.ImageBuilder.Runtime.Events.ValidationWarning, Message = $"Value of '{parameterName}' must be multiple of {multiple} (value is {value})", Parameter = parameterName, Cancel = instance.Cancel });
}
}
}
}
/// <summary>
/// An Implementation of the IEventListener that supports subscribing to events and dispatching them
/// (used for manually using the lowlevel interface)
/// </summary>
public class EventListener : CancellationTokenSource, IEnumerable<KeyValuePair<string, Event>>, IEventListener
{
private Dictionary<string, Event> calls = new Dictionary<string, Event>();
public IEnumerator<KeyValuePair<string, Event>> GetEnumerator() => calls.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => calls.GetEnumerator();
public EventListener()
{
}
public new Action Cancel => base.Cancel;
private Event tracer;
public EventListener(params (string name, Event callback)[] initializer)
{
foreach (var each in initializer)
{
Add(each.name, each.callback);
}
}
public void Add(string name, SynchEvent callback)
{
Add(name, (message) => { callback(message); return Task.CompletedTask; });
}
public void Add(string name, Event callback)
{
if (callback != null)
{
if (string.IsNullOrEmpty(name))
{
if (calls.ContainsKey(name))
{
tracer += callback;
}
else
{
tracer = callback;
}
}
else
{
if (calls.ContainsKey(name))
{
calls[name ?? System.String.Empty] += callback;
}
else
{
calls[name ?? System.String.Empty] = callback;
}
}
}
}
public async Task Signal(string id, CancellationToken token, GetEventData createMessage)
{
using (NoSynchronizationContext)
{
if (!string.IsNullOrEmpty(id) && (calls.TryGetValue(id, out Event listener) || tracer != null))
{
var message = createMessage();
message.Id = id;
await listener?.Invoke(message);
await tracer?.Invoke(message);
if (token.IsCancellationRequested)
{
throw new OperationCanceledException($"Canceled by event {id} ", this.Token);
}
}
}
}
}
} | 77.518219 | 400 | 0.656343 | [
"MIT"
] | 3quanfeng/azure-powershell | src/ImageBuilder/generated/runtime/EventListener.cs | 18,901 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Eva.eShop.Services.Marketing.API.Model;
using MySql.Data.EntityFrameworkCore.Extensions;
namespace Eva.eShop.Services.Marketing.API.Infrastructure.EntityConfigurations
{
class RuleEntityTypeConfiguration
: IEntityTypeConfiguration<Rule>
{
public void Configure(EntityTypeBuilder<Rule> builder)
{
builder.ToTable("Rule");
builder.HasKey(r => r.Id);
builder.Property(r => r.Id)
.UseMySQLAutoIncrementColumn("rule_hilo")
.IsRequired();
builder.HasDiscriminator<int>("RuleTypeId")
.HasValue<UserProfileRule>(RuleType.UserProfileRule.Id)
.HasValue<PurchaseHistoryRule>(RuleType.PurchaseHistoryRule.Id)
.HasValue<UserLocationRule>(RuleType.UserLocationRule.Id);
builder.Property(r => r.Description)
.HasColumnName("Description")
.IsRequired();
}
}
}
| 33.15625 | 79 | 0.653157 | [
"MIT"
] | Liang-Zhinian/eShop | src/Services/Marketing/Marketing.API/Infrastructure/EntityConfigurations/RuleEntityTypeConfiguration.cs | 1,063 | C# |
namespace Lab_7
{
public enum Gender
{
Male,
Female,
Intrasex
}
} | 11.333333 | 22 | 0.470588 | [
"MIT"
] | BullFrog13/Centennial_Programming2CSharp | Labs/Lab_7/Gender.cs | 104 | C# |
using NUnit.Framework;
using PackageManager.Enums;
using PackageManager.Models;
using System;
namespace PackageManager.Tests.Models.PackageVersionTests
{
[TestFixture]
public class Minor_Should
{
[Test]
public void SetThePassedValue_IfItIsValid()
{
int major = 1;
int minor = 1;
int patch = 1;
VersionType type = VersionType.alpha;
var packageVersion = new PackageVersion(major, minor, patch, type);
Assert.AreEqual(minor, packageVersion.Minor);
}
[Test]
public void ThrowArgumentException_IfInvalidValueIsPassed()
{
int major = 1;
int minor = -1;
int patch = 1;
VersionType type = VersionType.alpha;
Assert.Throws<ArgumentException>(() => new PackageVersion(major, minor, patch, type));
}
}
}
| 25.333333 | 98 | 0.592105 | [
"MIT"
] | darindragomirow/TelerikAcademy | Module2/UnitTestingEXAMS-02.2017/PackageManager-UnitTesting2/Skeleton/AcademyPackageManager/PackageManager.Tests/Models/PackageVersionTests/Minor_Should.cs | 914 | C# |
namespace TraktNet.Objects.Get.Syncs.Activities
{
using System;
/// <summary>A collection of UTC datetimes of last activities for seasons.</summary>
public class TraktSyncSeasonsLastActivities : ITraktSyncSeasonsLastActivities
{
/// <summary>Gets or sets the UTC datetime, when a season was lastly rated.</summary>
public DateTime? RatedAt { get; set; }
/// <summary>Gets or sets the UTC datetime, when a season was lastly added to the watchlist.</summary>
public DateTime? WatchlistedAt { get; set; }
/// <summary>Gets or sets the UTC datetime, when a season was lastly commented.</summary>
public DateTime? CommentedAt { get; set; }
/// <summary>Gets or sets the UTC datetime, when a season was lastly hidden.</summary>
public DateTime? HiddenAt { get; set; }
}
}
| 40.714286 | 110 | 0.678363 | [
"MIT"
] | henrikfroehling/Trakt.NET | Source/Lib/Trakt.NET/Objects/Get/Syncs/Activities/Implementations/TraktSyncSeasonsLastActivities.cs | 857 | C# |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using DocuSign.eSign.Api;
using DocuSign.eSign.Model;
using DocuSign.eSign.Client;
using System.Reflection;
namespace DocuSign.eSign.Test
{
/// <summary>
/// Class for testing RecipientUpdateResponse
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class RecipientUpdateResponseTests
{
// TODO uncomment below to declare an instance variable for RecipientUpdateResponse
//private RecipientUpdateResponse instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of RecipientUpdateResponse
//instance = new RecipientUpdateResponse();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of RecipientUpdateResponse
/// </summary>
[Test]
public void RecipientUpdateResponseInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" RecipientUpdateResponse
//Assert.IsInstanceOfType<RecipientUpdateResponse> (instance, "variable 'instance' is a RecipientUpdateResponse");
}
/// <summary>
/// Test the property 'ErrorDetails'
/// </summary>
[Test]
public void ErrorDetailsTest()
{
// TODO unit test for the property 'ErrorDetails'
}
/// <summary>
/// Test the property 'RecipientId'
/// </summary>
[Test]
public void RecipientIdTest()
{
// TODO unit test for the property 'RecipientId'
}
/// <summary>
/// Test the property 'Tabs'
/// </summary>
[Test]
public void TabsTest()
{
// TODO unit test for the property 'Tabs'
}
}
}
| 26.494737 | 126 | 0.595153 | [
"MIT"
] | CameronLoewen/docusign-csharp-client | sdk/src/DocuSign.eSign.Test/Model/RecipientUpdateResponseTests.cs | 2,517 | C# |
using System;
using ObjCRuntime;
namespace MaterialControls {
public enum MDButtonType : uint {
Raised,
Flat,
FloatingAction
}
[Native]
public enum MDCalendarMonthSymbolsFormat : long /* nint */ {
Short = 0,
Full = 1,
ShortUppercase = 2,
FullUppercase = 3
}
[Native]
public enum MDCalendarCellStyle : long /* nint */ {
Circle = 0,
Rectangle = 1
}
[Native]
public enum MDCalendarCellState : long /* nint */ {
Normal = 0,
Selected = 1,
Placeholder = 1 << 1,
Disabled = 1 << 2,
Today = 1 << 3,
Weekend = 1 << 4,
WeekTitle = 1 << 5,
MonthTitle = 1 << 6,
Button = 1 << 7
}
[Native]
public enum MDCalendarTheme : long /* nint */ {
Light = 1,
Dark = 2
}
public enum MDProgressStyle : uint {
Circular,
Linear
}
public enum MDProgressType : uint {
Indeterminate,
Determinate,
Buffer,
QueryIndeterminateAndDeterminate
}
public enum ViewState : uint {
NORMAL,
HIGHLIGHT,
ERROR,
DISABLED
}
[Native]
public enum MDCalendarTimeMode : long /* nint */ {
MDCalendarTimeMode12H,
MDCalendarTimeMode24H
}
[Native]
public enum MDFontFamilySize : long /* nint */ {
Regular = 0,
Bold = 1,
Light = 2,
Medium = 3,
Thin = 4,
Black = 5
}
[Native]
public enum MDFontFamilyType : long /* nint */ {
Bold = 1,
Italic = 2
}
}
| 15.137931 | 61 | 0.63022 | [
"MIT"
] | AgentdesksEngine/Material-Controls-For-iOS | MaterialControls.Xamarin.Binding/Structs.cs | 1,319 | C# |
/*
* Copyright 2020 Sage Intacct, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
using Intacct.SDK.Functions.Common.Query.Comparison.GreaterThan;
using Xunit;
namespace Intacct.SDK.Tests.Functions.Common.Query.Comparison.GreaterThan
{
public class GreaterThanDecimalTest
{
[Fact]
public void ToStringTest()
{
GreaterThanDecimal condition = new GreaterThanDecimal()
{
Field = "AMOUNTDUE",
Value = 123.45M,
};
Assert.Equal("AMOUNTDUE > 123.45", condition.ToString());
}
[Fact]
public void ToStringNotTest()
{
GreaterThanDecimal condition = new GreaterThanDecimal()
{
Negate = true,
Field = "AMOUNTDUE",
Value = 123.45M,
};
Assert.Equal("NOT AMOUNTDUE > 123.45", condition.ToString());
}
}
} | 30.416667 | 80 | 0.595205 | [
"Apache-2.0"
] | Intacct/intacct-sdk-net | Intacct.SDK.Tests/Functions/Common/Query/Comparison/GreaterThan/GreaterThanDecimalTest.cs | 1,462 | C# |
/*=================================\
* CWA.DTP\CommandType.cs
*
* The Coestaris licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
*
* Created: 12.09.2017 21:45
* Last Edited: 15.09.2017 22:40:15
*=================================*/
using System;
namespace CWA.DTP.Plotter
{
enum CommandType : UInt32
{
Plotter_RefreshConfig = 0x120,
Plotter_Print_Run = 0x121,
Plotter_Print_Info = 0x122,
Plotter_Print_Abort = 0x123,
Plotter_Print_Run_Ex = 0x124,
Plotter_Move = 0x125,
Plotter_TurnEngines_On = 0x126,
Plotter_TurnEngines_Off = 0x127,
};
}
| 25.222222 | 64 | 0.602056 | [
"MIT"
] | Coestaris/PlotterControl | Lib/CWA.DTP/Plotter/Handler/CommandType.cs | 681 | C# |
using HarmonyLib;
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace PlatoTK.Content
{
internal class EventConditionsProvider : IConditionsProvider
{
public string Id => "Default";
public bool CanHandleConditions(string conditions)
{
return true;
}
public bool CheckConditions(string conditions, object caller)
{
GameLocation location = caller is GameLocation gl ? gl : Game1.currentLocation;
if (location == null)
return false;
var m = AccessTools.Method(typeof(GameLocation),"checkEventPrecondition");
return (int)m.Invoke(location, new string[] { ("9999999/" + conditions) }) > 0;
}
}
}
| 26.090909 | 91 | 0.646922 | [
"MIT"
] | Platonymous/PlatoTK | PlatoTK/Content/EventConditionsProvider.cs | 863 | C# |
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using Xenko.Core;
using Xenko.Core.IO;
using Xenko.Games;
using Xenko.Graphics.Font;
namespace Xenko.Rendering.Fonts
{
/// <summary>
/// The game system in charge of calling <see cref="FontSystem"/>.
/// </summary>
public class GameFontSystem : GameSystemBase
{
public FontSystem FontSystem { get; private set; }
public GameFontSystem(IServiceRegistry registry)
: base(registry)
{
Visible = true;
FontSystem = new FontSystem();
}
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
FontSystem.Draw();
}
protected override void LoadContent()
{
base.LoadContent();
FontSystem.Load(GraphicsDevice, Services.GetSafeServiceAs<IDatabaseFileProviderService>());
}
protected override void UnloadContent()
{
base.UnloadContent();
FontSystem.Unload();
}
}
}
| 26.12766 | 114 | 0.613192 | [
"MIT"
] | Aminator/xenko | sources/engine/Xenko.Engine/Rendering/Fonts/GameFontSystem.cs | 1,228 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.ContainerRegistry.V20190501
{
public static class GetRegistry
{
public static Task<GetRegistryResult> InvokeAsync(GetRegistryArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetRegistryResult>("azure-nextgen:containerregistry/v20190501:getRegistry", args ?? new GetRegistryArgs(), options.WithVersion());
}
public sealed class GetRegistryArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the container registry.
/// </summary>
[Input("registryName", required: true)]
public string RegistryName { get; set; } = null!;
/// <summary>
/// The name of the resource group to which the container registry belongs.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetRegistryArgs()
{
}
}
[OutputType]
public sealed class GetRegistryResult
{
/// <summary>
/// The value that indicates whether the admin user is enabled.
/// </summary>
public readonly bool? AdminUserEnabled;
/// <summary>
/// The creation date of the container registry in ISO8601 format.
/// </summary>
public readonly string CreationDate;
/// <summary>
/// The location of the resource. This cannot be changed after the resource is created.
/// </summary>
public readonly string Location;
/// <summary>
/// The URL that can be used to log into the container registry.
/// </summary>
public readonly string LoginServer;
/// <summary>
/// The name of the resource.
/// </summary>
public readonly string Name;
/// <summary>
/// The network rule set for a container registry.
/// </summary>
public readonly Outputs.NetworkRuleSetResponse? NetworkRuleSet;
/// <summary>
/// The policies for a container registry.
/// </summary>
public readonly Outputs.PoliciesResponse? Policies;
/// <summary>
/// The provisioning state of the container registry at the time the operation was called.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// The SKU of the container registry.
/// </summary>
public readonly Outputs.SkuResponse Sku;
/// <summary>
/// The status of the container registry at the time the operation was called.
/// </summary>
public readonly Outputs.StatusResponse Status;
/// <summary>
/// The properties of the storage account for the container registry. Only applicable to Classic SKU.
/// </summary>
public readonly Outputs.StorageAccountPropertiesResponse? StorageAccount;
/// <summary>
/// The tags of the resource.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// The type of the resource.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetRegistryResult(
bool? adminUserEnabled,
string creationDate,
string location,
string loginServer,
string name,
Outputs.NetworkRuleSetResponse? networkRuleSet,
Outputs.PoliciesResponse? policies,
string provisioningState,
Outputs.SkuResponse sku,
Outputs.StatusResponse status,
Outputs.StorageAccountPropertiesResponse? storageAccount,
ImmutableDictionary<string, string>? tags,
string type)
{
AdminUserEnabled = adminUserEnabled;
CreationDate = creationDate;
Location = location;
LoginServer = loginServer;
Name = name;
NetworkRuleSet = networkRuleSet;
Policies = policies;
ProvisioningState = provisioningState;
Sku = sku;
Status = status;
StorageAccount = storageAccount;
Tags = tags;
Type = type;
}
}
}
| 33.064748 | 184 | 0.604656 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/ContainerRegistry/V20190501/GetRegistry.cs | 4,596 | C# |
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Linq;
using System;
// TODO: Muokkaa tätä koodia myöhemmin.
public static class SaveLoad
{
// all saved data is turned into longs (64bit int)
public static long[] SaveData { get; set; }
// SaveData lenght
public static int SaveDataSize
{
get { return (int)Line.LineCount; }
}
public enum Line
{
Version,
Koskikeskus,
Elo,
Kirjasto,
Ranta,
Reittinyt, // 0: Koskikeskus, 1, 10, 100: Elo jne (for bpm)...
Theme,
LineCount // Always last !!!!
}
// boolean values
public const int FALSE = 0;
public const int TRUE = 1;
// filepath
public const string FILE_PATH = "/Sovellus.ph";
public static bool Find()
{
return File.Exists(Application.persistentDataPath + FILE_PATH);
}
public static void Save(TMPro.TextMeshProUGUI debugText)
{
// making string for saving
string data = "";
for (int i = 0; i < SaveData.Length; i++)
{
// adding only number value and newline
data += SaveData[i].ToString() + Environment.NewLine;
}
// write data to file
File.WriteAllText(Application.persistentDataPath + FILE_PATH, data, System.Text.Encoding.UTF8);
#region debug
data = "Saved:" + Environment.NewLine;
for (int i = 0; i < SaveData.Length; i++)
{
data += ((Line)i).ToString() + " : " + SaveData[i].ToString() + Environment.NewLine;
}
if (debugText) debugText.text = data;
#endregion
}
public static void Load(TMPro.TextMeshProUGUI debugText)
{
// converting textlines to longs
string[] lines = File.ReadAllLines(Application.persistentDataPath + FILE_PATH, System.Text.Encoding.UTF8);
for (int i = 0; i < lines.Length; i++)
{
SaveData[i] = TextToLong(lines[i]);
}
#region debug
string data = "Loaded:" + Environment.NewLine;
for (int i = 0; i < SaveData.Length; i++)
{
data += ((Line)i).ToString() + " : " + SaveData[i].ToString() + Environment.NewLine;
}
if (debugText) debugText.text = data;
#endregion
}
public static void Delete()
{
if (Find())
{
File.Delete(Application.persistentDataPath + FILE_PATH);
}
}
static long TextToLong(string text)
{
long result = 0;
char[] numbers = text.ToCharArray();
for (int i = 0; i < numbers.Length; i++)
{
result *= 10;
// number zero is value 30(hex) 48(dec) in unicode and ascii
// meaning char '0' = int 48
result += numbers[i] - 48;
}
return result;
}
}
| 26.962963 | 114 | 0.556319 | [
"MIT"
] | FromCaffeineToCode/Kuntoutussovelluss | Assets/Code/SaveLoad.cs | 2,917 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03.PCCatalog
{
class Components
{
private string name;
private string details;
private decimal price;
public Components(string name, string details, decimal price)
{
this.Name = name;
this.Details = details;
this.Price = price;
}
public Components(string name, decimal price) :
this(name,null,price)
{
}
public string Name
{
get { return this.name; }
set
{
if (string.IsNullOrEmpty(value.Trim()))
{
throw new ArgumentException("Componenct name cannot be empty.");
}
this.name = value;
}
}
public string Details
{
get { return this.details; }
set
{
if (value?.Trim().Length ==0)
{
throw new ArgumentException("Componenct details cannot be blank.");
}
this.details = value;
}
}
public decimal Price
{
get { return this.price; }
set
{
if (value < 0)
{
throw new ArgumentException("Component price can't be negative number.");
}
this.price = value;
}
}
public override string ToString()
{
var info = new StringBuilder();
string separator = "+" + new string('-', 15) + "+" + new string('-', 35) + "+";
info.AppendLine(separator);
if (this.Details != null)
{
info.AppendLine($"|{"component name",15}|{this.Name + " (" + this.Details + ")",35}|");
}
else
{
info.AppendLine($"|{"component name",15}|{this.Name,35}|");
}
info.AppendLine($"|{"",15}|{this.Price,35:C}|");
return info.ToString();
}
}
}
| 26.97561 | 103 | 0.44575 | [
"MIT"
] | evgeni-tsn/CSharp-Entity-ASP-Web-Development | 2.C#-Object-Oriented-Programming/01.OOP-Defining-Classes/03.PCCatalog/Components.cs | 2,214 | C# |
using Newtonsoft.Json;
using RabbitMqHttpApiClient.Models.Common;
namespace RabbitMqHttpApiClient.Models.QueueModel
{
public class Queue
{
[JsonProperty("memory")]
public long Memory { get; set; }
[JsonProperty("message_stats")]
public QueueMessageStats MessageStats { get; set; }
[JsonProperty("reductions")]
public long Reductions { get; set; }
[JsonProperty("reductions_details")]
public RateDetails ReductionsDetails { get; set; }
[JsonProperty("messages")]
public long Messages { get; set; }
[JsonProperty("messages_details")]
public RateDetails MessagesDetails { get; set; }
[JsonProperty("messages_ready")]
public long MessagesReady { get; set; }
[JsonProperty("messages_ready_details")]
public RateDetails MessagesReadyDetails { get; set; }
[JsonProperty("messages_unacknowledged")]
public long MessagesUnacknowledged { get; set; }
[JsonProperty("messages_unacknowledged_details")]
public RateDetails MessagesUnacknowledgedDetails { get; set; }
[JsonProperty("idle_since")]
public string IdleSince { get; set; }
[JsonProperty("consumer_utilisation")]
public double? ConsumerUtilisation { get; set; }
[JsonProperty("policy")]
public string Policy { get; set; }
[JsonProperty("exclusive_consumer_tag")]
public string ExclusiveConsumerTag { get; set; }
[JsonProperty("consumers")]
public int Consumers { get; set; }
[JsonProperty("recoverable_slaves")]
public object RecoverableSlaves { get; set; }
[JsonProperty("state")]
public string State { get; set; }
[JsonProperty("garbage_collection")]
public GarbageCollection GarbageCollection { get; set; }
[JsonProperty("messages_ram")]
public long MessagesRam { get; set; }
[JsonProperty("messages_ready_ram")]
public long MessagesReadyRam { get; set; }
[JsonProperty("messages_unacknowledged_ram")]
public long MessagesUnacknowledgedRam { get; set; }
[JsonProperty("messages_persistent")]
public long MessagesPersistent { get; set; }
[JsonProperty("message_bytes")]
public long MessageBytes { get; set; }
[JsonProperty("message_bytes_ready")]
public long MessageBytesReady { get; set; }
[JsonProperty("message_bytes_unacknowledged")]
public long MessageBytesUnacknowledged { get; set; }
[JsonProperty("message_bytes_ram")]
public long MessageBytesRam { get; set; }
[JsonProperty("message_bytes_persistent")]
public long MessageBytesPersistent { get; set; }
[JsonProperty("head_message_timestamp")]
public object HeadMessageTimestamp { get; set; }
[JsonProperty("disk_reads")]
public long DiskReads { get; set; }
[JsonProperty("disk_writes")]
public long DiskWrites { get; set; }
[JsonProperty("backing_queue_status")]
public BackingQueueStatus BackingQueueStatus { get; set; }
[JsonProperty("node")]
public string Node { get; set; }
[JsonIgnore]
[JsonProperty("arguments")]
public Arguments Arguments { get; set; }
[JsonProperty("exclusive")]
public bool Exclusive { get; set; }
[JsonProperty("auto_delete")]
public bool AutoDelete { get; set; }
[JsonProperty("durable")]
public bool Durable { get; set; }
[JsonProperty("vhost")]
public string Vhost { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
} | 30.414634 | 70 | 0.631917 | [
"MIT"
] | kuanysh-nabiyev/RabbitMqHttpApiClient | RabbitMqHttpApiClient/Models/QueueModel/Queue.cs | 3,741 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.TestPlatform.Extensions.TrxLogger
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using Microsoft.TestPlatform.Extensions.TrxLogger.ObjectModel;
using Microsoft.TestPlatform.Extensions.TrxLogger.Utility;
using Microsoft.TestPlatform.Extensions.TrxLogger.XML;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;
using Microsoft.VisualStudio.TestPlatform.Utilities;
using ObjectModel.Logging;
using TrxLoggerConstants = Microsoft.TestPlatform.Extensions.TrxLogger.Utility.Constants;
using TrxLoggerObjectModel = Microsoft.TestPlatform.Extensions.TrxLogger.ObjectModel;
using TrxLoggerResources = Microsoft.VisualStudio.TestPlatform.Extensions.TrxLogger.Resources.TrxResource;
/// <summary>
/// Logger for Generating TRX
/// </summary>
[FriendlyName(TrxLoggerConstants.FriendlyName)]
[ExtensionUri(TrxLoggerConstants.ExtensionUri)]
internal class TrxLogger : ITestLoggerWithParameters
{
#region Fields
/// <summary>
/// Cache the TRX file path
/// </summary>
private string trxFilePath;
private TrxLoggerObjectModel.TestRun testRun;
private ConcurrentDictionary<Guid, TrxLoggerObjectModel.ITestResult> results;
private ConcurrentDictionary<Guid, TrxLoggerObjectModel.ITestElement> testElements;
private ConcurrentDictionary<Guid, TestEntry> entries;
// Caching results and inner test entries for constant time lookup for inner parents.
private ConcurrentDictionary<Guid, TrxLoggerObjectModel.ITestResult> innerResults;
private ConcurrentDictionary<Guid, TestEntry> innerTestEntries;
/// <summary>
/// Specifies the run level "out" messages
/// </summary>
private StringBuilder runLevelStdOut;
// List of run level errors and warnings generated. These are logged in the Trx in the Results Summary.
private List<TrxLoggerObjectModel.RunInfo> runLevelErrorsAndWarnings;
private TrxLoggerObjectModel.TestOutcome testRunOutcome = TrxLoggerObjectModel.TestOutcome.Passed;
private int totalTests, passTests, failTests;
private DateTime testRunStartTime;
/// <summary>
/// Parameters dictionary for logger. Ex: {"LogFileName":"TestResults.trx"}.
/// </summary>
private Dictionary<string, string> parametersDictionary;
/// <summary>
/// Gets the directory under which default trx file and test results attachements should be saved.
/// </summary>
private string testResultsDirPath;
#endregion
#region ITestLogger
/// <inheritdoc/>
public void Initialize(TestLoggerEvents events, string testResultsDirPath)
{
if (events == null)
{
throw new ArgumentNullException(nameof(events));
}
if (string.IsNullOrEmpty(testResultsDirPath))
{
throw new ArgumentNullException(nameof(testResultsDirPath));
}
// Register for the events.
events.TestRunMessage += this.TestMessageHandler;
events.TestResult += this.TestResultHandler;
events.TestRunComplete += this.TestRunCompleteHandler;
this.testResultsDirPath = testResultsDirPath;
this.InitializeInternal();
}
/// <inheritdoc/>
public void Initialize(TestLoggerEvents events, Dictionary<string, string> parameters)
{
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
if (parameters.Count == 0)
{
throw new ArgumentException("No default parameters added", nameof(parameters));
}
this.parametersDictionary = parameters;
this.Initialize(events, this.parametersDictionary[DefaultLoggerParameterNames.TestRunDirectory]);
}
#endregion
#region ForTesting
internal string GetRunLevelInformationalMessage()
{
return this.runLevelStdOut.ToString();
}
internal List<TrxLoggerObjectModel.RunInfo> GetRunLevelErrorsAndWarnings()
{
return this.runLevelErrorsAndWarnings;
}
internal DateTime TestRunStartTime
{
get { return this.testRunStartTime; }
}
internal TestRun LoggerTestRun
{
get { return this.testRun; }
}
internal int TotalTestCount
{
get { return totalTests; }
}
internal int PassedTestCount
{
get { return passTests; }
}
internal int FailedTestCount
{
get { return failTests; }
}
internal int TestResultCount
{
get { return this.results.Count; }
}
internal int UnitTestElementCount
{
get { return this.testElements.Count; }
}
internal int TestEntryCount
{
get { return this.entries.Count; }
}
internal TrxLoggerObjectModel.TestOutcome TestResultOutcome
{
get { return this.testRunOutcome; }
}
#endregion
#region Event Handlers
/// <summary>
/// Called when a test message is received.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// Event args
/// </param>
public void TestMessageHandler(object sender, TestRunMessageEventArgs e)
{
ValidateArg.NotNull<object>(sender, "sender");
ValidateArg.NotNull<TestRunMessageEventArgs>(e, "e");
TrxLoggerObjectModel.RunInfo runMessage;
switch (e.Level)
{
case TestMessageLevel.Informational:
this.AddRunLevelInformationalMessage(e.Message);
break;
case TestMessageLevel.Warning:
runMessage = new TrxLoggerObjectModel.RunInfo(e.Message, null, Environment.MachineName, TrxLoggerObjectModel.TestOutcome.Warning);
this.runLevelErrorsAndWarnings.Add(runMessage);
break;
case TestMessageLevel.Error:
this.testRunOutcome = TrxLoggerObjectModel.TestOutcome.Failed;
runMessage = new TrxLoggerObjectModel.RunInfo(e.Message, null, Environment.MachineName, TrxLoggerObjectModel.TestOutcome.Error);
this.runLevelErrorsAndWarnings.Add(runMessage);
break;
default:
Debug.Fail("TrxLogger.TestMessageHandler: The test message level is unrecognized: {0}", e.Level.ToString());
break;
}
}
/// <summary>
/// Called when a test result is received.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The eventArgs.
/// </param>
public void TestResultHandler(object sender, ObjectModel.Logging.TestResultEventArgs e)
{
// Create test run
if (this.testRun == null)
CreateTestRun();
// Convert skipped test to a log entry as that is the behaviour of mstest.
if (e.Result.Outcome == ObjectModel.TestOutcome.Skipped)
this.HandleSkippedTest(e.Result);
var testType = Converter.GetTestType(e.Result);
var executionId = Converter.GetExecutionId(e.Result);
// Setting parent properties like parent result, parent test element, parent execution id.
var parentExecutionId = Converter.GetParentExecutionId(e.Result);
var parentTestResult = GetTestResult(parentExecutionId);
var parentTestElement = (parentTestResult != null) ? GetTestElement(parentTestResult.Id.TestId) : null;
// Switch to flat test results in case any parent related information is missing.
if (parentTestResult == null || parentTestElement == null || parentExecutionId == Guid.Empty)
{
parentTestResult = null;
parentTestElement = null;
parentExecutionId = Guid.Empty;
}
// Create trx test element from rocksteady test case
var testElement = GetOrCreateTestElement(executionId, parentExecutionId, testType, parentTestElement, e.Result);
// Update test links. Test Links are updated in case of Ordered test.
UpdateTestLinks(testElement, parentTestElement);
// Convert the rocksteady result to trx test result
var testResult = CreateTestResult(executionId, parentExecutionId, testType, testElement, parentTestElement, parentTestResult, e.Result);
// Update test entries
UpdateTestEntries(executionId, parentExecutionId, testElement, parentTestElement);
// Set various counts (passtests, failed tests, total tests)
this.totalTests++;
if (testResult.Outcome == TrxLoggerObjectModel.TestOutcome.Failed)
{
this.testRunOutcome = TrxLoggerObjectModel.TestOutcome.Failed;
this.failTests++;
}
else if (testResult.Outcome == TrxLoggerObjectModel.TestOutcome.Passed)
{
this.passTests++;
}
}
/// <summary>
/// Called when a test run is completed.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// Test run complete events arguments.
/// </param>
public void TestRunCompleteHandler(object sender, TestRunCompleteEventArgs e)
{
if (this.testRun != null)
{
XmlPersistence helper = new XmlPersistence();
XmlTestStoreParameters parameters = XmlTestStoreParameters.GetParameters();
XmlElement rootElement = helper.CreateRootElement("TestRun");
// Save runId/username/creation time etc.
this.testRun.Finished = DateTime.UtcNow;
helper.SaveSingleFields(rootElement, this.testRun, parameters);
// Save test settings
helper.SaveObject(this.testRun.RunConfiguration, rootElement, "TestSettings", parameters);
// Save test results
helper.SaveIEnumerable(this.results.Values, rootElement, "Results", ".", null, parameters);
// Save test definitions
helper.SaveIEnumerable(this.testElements.Values, rootElement, "TestDefinitions", ".", null, parameters);
// Save test entries
helper.SaveIEnumerable(this.entries.Values, rootElement, "TestEntries", ".", "TestEntry", parameters);
// Save default categories
List<TestListCategory> categories = new List<TestListCategory>();
categories.Add(TestListCategory.UncategorizedResults);
categories.Add(TestListCategory.AllResults);
helper.SaveList<TestListCategory>(categories, rootElement, "TestLists", ".", "TestList", parameters);
// Save summary
if (this.testRunOutcome == TrxLoggerObjectModel.TestOutcome.Passed)
{
this.testRunOutcome = TrxLoggerObjectModel.TestOutcome.Completed;
}
List<string> errorMessages = new List<string>();
List<CollectorDataEntry> collectorEntries = Converter.ToCollectionEntries(e.AttachmentSets, this.testRun, this.testResultsDirPath);
IList<String> resultFiles = Converter.ToResultFiles(e.AttachmentSets, this.testRun, this.testResultsDirPath, errorMessages);
if (errorMessages.Count > 0)
{
// Got some errors while attaching files, report them and set the outcome of testrun to be Error...
this.testRunOutcome = TrxLoggerObjectModel.TestOutcome.Error;
foreach (string msg in errorMessages)
{
RunInfo runMessage = new RunInfo(msg, null, Environment.MachineName, TrxLoggerObjectModel.TestOutcome.Error);
this.runLevelErrorsAndWarnings.Add(runMessage);
}
}
TestRunSummary runSummary = new TestRunSummary(
this.totalTests,
this.passTests + this.failTests,
this.passTests,
this.failTests,
this.testRunOutcome,
this.runLevelErrorsAndWarnings,
this.runLevelStdOut.ToString(),
resultFiles,
collectorEntries);
helper.SaveObject(runSummary, rootElement, "ResultSummary", parameters);
//Save results to Trx file
this.DeriveTrxFilePath();
this.PopulateTrxFile(this.trxFilePath, rootElement);
}
}
/// <summary>
/// populate trx file from the xmlelement
/// </summary>
/// <param name="trxFileName">
/// Trx full path
/// </param>
/// <param name="rootElement">
/// XmlElement.
/// </param>
internal virtual void PopulateTrxFile(string trxFileName, XmlElement rootElement)
{
try
{
var trxFileDirPath = Path.GetDirectoryName(trxFilePath);
if (Directory.Exists(trxFileDirPath) == false)
{
Directory.CreateDirectory(trxFileDirPath);
}
if (File.Exists(trxFilePath))
{
var overwriteWarningMsg = string.Format(CultureInfo.CurrentCulture,
TrxLoggerResources.TrxLoggerResultsFileOverwriteWarning, trxFileName);
ConsoleOutput.Instance.Warning(false, overwriteWarningMsg);
EqtTrace.Warning(overwriteWarningMsg);
}
using (var fs = File.Open(trxFileName, FileMode.Create))
{
using (XmlWriter writer = XmlWriter.Create(fs, new XmlWriterSettings { NewLineHandling = NewLineHandling.Entitize }))
{
rootElement.OwnerDocument.Save(writer);
writer.Flush();
}
}
String resultsFileMessage = String.Format(CultureInfo.CurrentCulture, TrxLoggerResources.TrxLoggerResultsFile, trxFileName);
ConsoleOutput.Instance.Information(false, resultsFileMessage);
EqtTrace.Info(resultsFileMessage);
}
catch (System.UnauthorizedAccessException fileWriteException)
{
ConsoleOutput.Instance.Error(false, fileWriteException.Message);
}
}
// Initializes trx logger cache.
private void InitializeInternal()
{
this.results = new ConcurrentDictionary<Guid, TrxLoggerObjectModel.ITestResult>();
this.innerResults = new ConcurrentDictionary<Guid, TrxLoggerObjectModel.ITestResult>();
this.testElements = new ConcurrentDictionary<Guid, ITestElement>();
this.entries = new ConcurrentDictionary<Guid,TestEntry>();
this.innerTestEntries = new ConcurrentDictionary<Guid, TestEntry>();
this.runLevelErrorsAndWarnings = new List<RunInfo>();
this.testRun = null;
this.totalTests = 0;
this.passTests = 0;
this.failTests = 0;
this.runLevelStdOut = new StringBuilder();
this.testRunStartTime = DateTime.UtcNow;
}
/// <summary>
/// Add run level informational message
/// </summary>
/// <param name="message">
/// The message.
/// </param>
private void AddRunLevelInformationalMessage(string message)
{
this.runLevelStdOut.Append(message);
}
// Handle the skipped test result
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed. Suppression is OK here.")]
private void HandleSkippedTest(ObjectModel.TestResult rsTestResult)
{
Debug.Assert(rsTestResult.Outcome == ObjectModel.TestOutcome.Skipped, "Test Result should be skipped but it is " + rsTestResult.Outcome);
ObjectModel.TestCase testCase = rsTestResult.TestCase;
string testCaseName = !string.IsNullOrEmpty(testCase.DisplayName) ? testCase.DisplayName : testCase.FullyQualifiedName;
string message = String.Format(CultureInfo.CurrentCulture, TrxLoggerResources.MessageForSkippedTests, testCaseName);
this.AddRunLevelInformationalMessage(message);
}
private void DeriveTrxFilePath()
{
if (this.parametersDictionary != null)
{
var isLogFileNameParameterExists = this.parametersDictionary.TryGetValue(TrxLoggerConstants.LogFileNameKey, out string logFileNameValue);
if (isLogFileNameParameterExists && !string.IsNullOrWhiteSpace(logFileNameValue))
{
this.trxFilePath = Path.Combine(this.testResultsDirPath, logFileNameValue);
}
else
{
this.SetDefaultTrxFilePath();
}
}
else
{
this.SetDefaultTrxFilePath();
}
}
/// <summary>
/// Sets auto generated Trx file name under test results directory.
/// </summary>
private void SetDefaultTrxFilePath()
{
var defaultTrxFileName = this.testRun.RunConfiguration.RunDeploymentRootDirectory + ".trx";
this.trxFilePath = FileHelper.GetNextIterationFileName(this.testResultsDirPath, defaultTrxFileName, false);
}
/// <summary>
/// Creates test run.
/// </summary>
private void CreateTestRun()
{
// Skip run creation if already exists.
if (testRun != null)
return;
Guid runId = Guid.NewGuid();
this.testRun = new TestRun(runId);
// We cannot rely on the StartTime for the first test result
// In case of parallel, first test result is the fastest test and not the one which started first.
// Setting Started to DateTime.Now in Intialize will make sure we include the startup cost, which was being ignored earlier.
// This is in parity with the way we set this.testRun.Finished
this.testRun.Started = this.testRunStartTime;
// Save default test settings
string runDeploymentRoot = FileHelper.ReplaceInvalidFileNameChars(this.testRun.Name);
TestRunConfiguration testrunConfig = new TestRunConfiguration("default");
testrunConfig.RunDeploymentRootDirectory = runDeploymentRoot;
this.testRun.RunConfiguration = testrunConfig;
}
/// <summary>
/// Gets test result from stored test results.
/// </summary>
/// <param name="executionId"></param>
/// <returns>Test result</returns>
private ITestResult GetTestResult(Guid executionId)
{
ITestResult testResult = null;
if (executionId != Guid.Empty)
{
this.results.TryGetValue(executionId, out testResult);
if (testResult == null)
this.innerResults.TryGetValue(executionId, out testResult);
}
return testResult;
}
/// <summary>
/// Gets test element from stored test elements.
/// </summary>
/// <param name="testId"></param>
/// <returns></returns>
private ITestElement GetTestElement(Guid testId)
{
this.testElements.TryGetValue(testId, out var testElement);
return testElement;
}
/// <summary>
/// Gets or creates test element.
/// </summary>
/// <param name="executionId"></param>
/// <param name="parentExecutionId"></param>
/// <param name="testType"></param>
/// <param name="parentTestElement"></param>
/// <param name="rockSteadyTestCase"></param>
/// <returns>Trx test element</returns>
private ITestElement GetOrCreateTestElement(Guid executionId, Guid parentExecutionId, TestType testType, ITestElement parentTestElement, ObjectModel.TestResult rockSteadyTestResult)
{
ITestElement testElement = parentTestElement;
// For scenarios like data driven tests, test element is same as parent test element.
if (parentTestElement != null && !parentTestElement.TestType.Equals(TrxLoggerConstants.OrderedTestType))
{
return testElement;
}
Guid testId = Converter.GetTestId(rockSteadyTestResult.TestCase);
// Scenario for inner test case when parent test element is not present.
var testName = rockSteadyTestResult.TestCase.DisplayName;
if (parentTestElement == null && !string.IsNullOrEmpty(rockSteadyTestResult.DisplayName))
{
testId = Guid.NewGuid();
testName = rockSteadyTestResult.DisplayName;
}
// Get test element
testElement = GetTestElement(testId);
// Create test element
if (testElement == null)
{
testElement = Converter.ToTestElement(testId, executionId, parentExecutionId, testName, testType, rockSteadyTestResult.TestCase);
testElements.TryAdd(testId, testElement);
}
return testElement;
}
/// <summary>
/// Update test links
/// </summary>
/// <param name="testElement"></param>
/// <param name="parentTestElement"></param>
private void UpdateTestLinks(ITestElement testElement, ITestElement parentTestElement)
{
if (parentTestElement != null &&
parentTestElement.TestType.Equals(TrxLoggerConstants.OrderedTestType) &&
!(parentTestElement as OrderedTestElement).TestLinks.ContainsKey(testElement.Id.Id))
{
(parentTestElement as OrderedTestElement).TestLinks.Add(testElement.Id.Id, new TestLink(testElement.Id.Id, testElement.Name, testElement.Storage));
}
}
/// <summary>
/// Creates test result
/// </summary>
/// <param name="executionId"></param>
/// <param name="parentExecutionId"></param>
/// <param name="testType"></param>
/// <param name="testElement"></param>
/// <param name="parentTestElement"></param>
/// <param name="parentTestResult"></param>
/// <param name="rocksteadyTestResult"></param>
/// <returns>Trx test result</returns>
private ITestResult CreateTestResult(Guid executionId, Guid parentExecutionId, TestType testType,
ITestElement testElement, ITestElement parentTestElement, ITestResult parentTestResult, ObjectModel.TestResult rocksteadyTestResult)
{
// Create test result
TrxLoggerObjectModel.TestOutcome testOutcome = Converter.ToOutcome(rocksteadyTestResult.Outcome);
var testResult = Converter.ToTestResult(testElement.Id.Id, executionId, parentExecutionId, testElement.Name,
this.testResultsDirPath, testType, testElement.CategoryId, testOutcome, this.testRun, rocksteadyTestResult);
// Normal result scenario
if (parentTestResult == null)
{
this.results.TryAdd(executionId, testResult);
return testResult;
}
// Ordered test inner result scenario
if (parentTestElement != null && parentTestElement.TestType.Equals(TrxLoggerConstants.OrderedTestType))
{
(parentTestResult as TestResultAggregation).InnerResults.Add(testResult);
this.innerResults.TryAdd(executionId, testResult);
return testResult;
}
// Data driven inner result scenario
if (parentTestElement != null && parentTestElement.TestType.Equals(TrxLoggerConstants.UnitTestType))
{
(parentTestResult as TestResultAggregation).InnerResults.Add(testResult);
testResult.DataRowInfo = (parentTestResult as TestResultAggregation).InnerResults.Count;
testResult.ResultType = TrxLoggerConstants.InnerDataDrivenResultType;
parentTestResult.ResultType = TrxLoggerConstants.ParentDataDrivenResultType;
return testResult;
}
return testResult;
}
/// <summary>
/// Update test entries
/// </summary>
/// <param name="executionId"></param>
/// <param name="parentExecutionId"></param>
/// <param name="testElement"></param>
/// <param name="parentTestElement"></param>
private void UpdateTestEntries(Guid executionId, Guid parentExecutionId, ITestElement testElement, ITestElement parentTestElement)
{
TestEntry te = new TestEntry(testElement.Id, TestListCategory.UncategorizedResults.Id);
te.ExecutionId = executionId;
if (parentTestElement == null)
{
this.entries.TryAdd(executionId, te);
}
else if (parentTestElement.TestType.Equals(TrxLoggerConstants.OrderedTestType))
{
te.ParentExecutionId = parentExecutionId;
var parentTestEntry = GetTestEntry(parentExecutionId);
if (parentTestEntry != null)
parentTestEntry.TestEntries.Add(te);
this.innerTestEntries.TryAdd(executionId, te);
}
}
/// <summary>
/// Gets test entry from stored test entries.
/// </summary>
/// <param name="executionId"></param>
/// <returns>Test entry</returns>
private TestEntry GetTestEntry(Guid executionId)
{
TestEntry testEntry = null;
if (executionId != Guid.Empty)
{
this.entries.TryGetValue(executionId, out testEntry);
if (testEntry == null)
this.innerTestEntries.TryGetValue(executionId, out testEntry);
}
return testEntry;
}
#endregion
}
} | 40.715339 | 189 | 0.604419 | [
"MIT"
] | saul/vstest | src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs | 27,605 | C# |
/*
--------------------------------- MIT License ---------------------------------
Copyright (c) 2019 jtsoya539
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 Newtonsoft.Json;
using Risk.API.Models;
namespace Risk.API.Entities
{
public class YArchivo : IEntity
{
[JsonProperty("contenido")]
public string Contenido { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("checksum")]
public string Checksum { get; set; }
[JsonProperty("tamano")]
public int? Tamano { get; set; }
[JsonProperty("nombre")]
public string Nombre { get; set; }
[JsonProperty("extension")]
public string Extension { get; set; }
[JsonProperty("tipo_mime")]
public string TipoMime { get; set; }
public IModel ConvertToModel()
{
return new Archivo
{
Contenido = this.Contenido,
Url = this.Url,
Checksum = this.Checksum,
Tamano = this.Tamano,
Nombre = this.Nombre,
Extension = this.Extension,
TipoMime = this.TipoMime
};
}
}
} | 37.540984 | 79 | 0.620087 | [
"MIT"
] | DamyGenius/risk | source/backend/Risk.API/Entities/YArchivo.cs | 2,290 | C# |
// 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.
namespace Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Cmdlets
{
using static Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Extensions;
using System;
/// <summary>
/// Returns daily data volume cap (quota) status for an Application Insights component.
/// </summary>
/// <remarks>
/// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/quotastatus"
/// </remarks>
[global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.InternalExport]
[global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzApplicationInsightsComponentQuotaStatus_GetViaIdentity")]
[global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20150501.IApplicationInsightsComponentQuotaStatus))]
[global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Description(@"Returns daily data volume cap (quota) status for an Application Insights component.")]
[global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Generated]
public partial class GetAzApplicationInsightsComponentQuotaStatus_GetViaIdentity : global::System.Management.Automation.PSCmdlet,
Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener
{
/// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary>
private string __correlationId = System.Guid.NewGuid().ToString();
/// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary>
private global::System.Management.Automation.InvocationInfo __invocationInfo;
/// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary>
private string __processRecordId;
/// <summary>
/// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation.
/// </summary>
private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource();
/// <summary>Wait for .NET debugger to attach</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")]
[global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter Break { get; set; }
/// <summary>The reference to the client API class.</summary>
public Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ApplicationInsightsManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Module.Instance.ClientAPI;
/// <summary>
/// The credentials, account, tenant, and subscription used for communication with Azure
/// </summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")]
[global::System.Management.Automation.ValidateNotNull]
[global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")]
[global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Azure)]
public global::System.Management.Automation.PSObject DefaultProfile { get; set; }
/// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; }
/// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; }
/// <summary>Backing field for <see cref="InputObject" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.IApplicationInsightsIdentity _inputObject;
/// <summary>Identity Parameter</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)]
[global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Path)]
public Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.IApplicationInsightsIdentity InputObject { get => this._inputObject; set => this._inputObject = value; }
/// <summary>Accessor for our copy of the InvocationInfo.</summary>
public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } }
/// <summary>
/// <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener" /> cancellation delegate. Stops the cmdlet when called.
/// </summary>
global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel;
/// <summary><see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener" /> cancellation token.</summary>
global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener.Token => _cancellationTokenSource.Token;
/// <summary>
/// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.HttpPipeline" /> that the remote call will use.
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.HttpPipeline Pipeline { get; set; }
/// <summary>The URI for the proxy server to use</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")]
[global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)]
public global::System.Uri Proxy { get; set; }
/// <summary>Credentials for a proxy server to use for the remote call</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)]
public global::System.Management.Automation.PSCredential ProxyCredential { get; set; }
/// <summary>Use the default credentials for the proxy</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")]
[global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; }
/// <summary>
/// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens
/// on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20150501.IApplicationInsightsComponentQuotaStatus">Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20150501.IApplicationInsightsComponentQuotaStatus</see>
/// from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return
/// immediately (set to true to skip further processing )</param>
partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20150501.IApplicationInsightsComponentQuotaStatus> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet)
/// </summary>
protected override void BeginProcessing()
{
var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Module.Instance.GetTelemetryId.Invoke();
if (telemetryId != "" && telemetryId != "internal")
{
__correlationId = telemetryId;
}
Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials);
if (Break)
{
Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.AttachDebugger.Break();
}
((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>Performs clean-up after the command execution</summary>
protected override void EndProcessing()
{
}
/// <summary>
/// Intializes a new instance of the <see cref="GetAzApplicationInsightsComponentQuotaStatus_GetViaIdentity" /> cmdlet class.
/// </summary>
public GetAzApplicationInsightsComponentQuotaStatus_GetViaIdentity()
{
}
/// <summary>Handles/Dispatches events during the call to the REST service.</summary>
/// <param name="id">The message id</param>
/// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param>
/// <param name="messageData">Detailed message data for the message event.</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed.
/// </returns>
async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.EventData> messageData)
{
using( NoSynchronizationContext )
{
if (token.IsCancellationRequested)
{
return ;
}
switch ( id )
{
case Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.Verbose:
{
WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.Warning:
{
WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.Information:
{
var data = messageData();
WriteInformation(data.Message, new string[]{});
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.Debug:
{
WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.Error:
{
WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) );
return ;
}
}
await Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null );
if (token.IsCancellationRequested)
{
return ;
}
WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}");
}
}
/// <summary>Performs execution of the command.</summary>
protected override void ProcessRecord()
{
((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
__processRecordId = System.Guid.NewGuid().ToString();
try
{
// work
using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token) )
{
asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token);
}
}
catch (global::System.AggregateException aggregateException)
{
// unroll the inner exceptions to get the root cause
foreach( var innerException in aggregateException.Flatten().InnerExceptions )
{
((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
}
catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null)
{
((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
finally
{
((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletProcessRecordEnd).Wait();
}
}
/// <summary>Performs execution of the command, working asynchronously if required.</summary>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
protected async global::System.Threading.Tasks.Task ProcessRecordAsync()
{
using( NoSynchronizationContext )
{
await ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName);
if (null != HttpPipelinePrepend)
{
Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend);
}
if (null != HttpPipelineAppend)
{
Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend);
}
// get the client instance
try
{
await ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
if (InputObject?.Id != null)
{
await this.Client.ComponentQuotaStatusGetViaIdentity(InputObject.Id, onOk, this, Pipeline);
}
else
{
// try to call with PATH parameters from Input Object
if (null == InputObject.ResourceGroupName)
{
ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) );
}
if (null == InputObject.SubscriptionId)
{
ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) );
}
if (null == InputObject.ResourceName)
{
ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) );
}
await this.Client.ComponentQuotaStatusGet(InputObject.ResourceGroupName ?? null, InputObject.SubscriptionId ?? null, InputObject.ResourceName ?? null, onOk, this, Pipeline);
}
await ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
catch (Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.UndeclaredResponseException urexception)
{
WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action }
});
}
finally
{
await ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletProcessRecordAsyncEnd);
}
}
}
/// <summary>Interrupts currently running code within the command.</summary>
protected override void StopProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Cancel();
base.StopProcessing();
}
/// <summary>a delegate that is called when the remote service returns 200 (OK).</summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20150501.IApplicationInsightsComponentQuotaStatus">Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20150501.IApplicationInsightsComponentQuotaStatus</see>
/// from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20150501.IApplicationInsightsComponentQuotaStatus> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnOk(responseMessage, response, ref _returnNow);
// if overrideOnOk has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// onOk - response for 200 / application/json
// (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20150501.IApplicationInsightsComponentQuotaStatus
WriteObject((await response));
}
}
}
} | 77.416918 | 507 | 0.686049 | [
"MIT"
] | AlanFlorance/azure-powershell | src/ApplicationInsights/generated/cmdlets/GetAzApplicationInsightsComponentQuotaStatus_GetViaIdentity.cs | 25,295 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4952
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ActiVizEventMonitor.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 32.903226 | 148 | 0.613725 | [
"BSD-3-Clause"
] | Shagai/Activiz | Examples/EventMonitor/CS/Properties/Settings.Designer.cs | 1,022 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Text;
using System.Threading.Tasks;
using BlogSystem.IDAL;
using BlogSystem.Models;
namespace BlogSystem.DAL
{
public class BaseService<T>:IBaseService<T> where T :BaseEntity,new()
{
private readonly BlogContext _db;
public BaseService ( BlogContext db)
{
_db = db;
}
public async Task CreateAsync(T model, bool saved = true)
{
_db.Set<T>().Add(model);
if (saved) await _db.SaveChangesAsync();
}
public async Task EditAsync(T model, bool saved = true)
{
_db.Configuration.ValidateOnSaveEnabled = false;
_db.Entry(model).State = EntityState.Modified;
if (saved)
{
await _db.SaveChangesAsync();
_db.Configuration.ValidateOnSaveEnabled = true;
}
}
public async Task RemoveAsync(Guid id, bool saved = true)
{
_db.Configuration.ValidateOnSaveEnabled = false;
var t = new T(){ Id = id};
_db.Entry(t).State = EntityState.Unchanged;
t.IsRemoved = true;
if (saved)
{
await _db.SaveChangesAsync();
_db.Configuration.ValidateOnSaveEnabled = true;
}
}
public async Task RemoveAsync(T model, bool saved = true)
{
await RemoveAsync(model.Id, saved);
}
public async Task Save()
{
await _db.SaveChangesAsync();
_db.Configuration.ValidateOnSaveEnabled = true;
}
public async Task<T> GetOneByIdAsync(Guid id)
{
return await GetAllAsync().FirstAsync(m => m.Id == id);
}
/// <summary>
/// 返回所有未被删除的数据(没有真的执行)
/// </summary>
/// <returns></returns>
public IQueryable<T> GetAllAsync()
{
return _db.Set<T>().Where(m => !m.IsRemoved).AsNoTracking();
}
public IQueryable<T> GetAllByPageAsync(int pageSize = 10, int pageIndex = 0)
{
return GetAllAsync().Skip(pageSize * pageIndex).Take(pageSize);
}
public IQueryable<T> GetAllOrderAsync(bool asc = true)
{
var datas = GetAllAsync();
datas = asc ? datas.OrderBy(m => m.CreateTime) : datas.OrderByDescending(m => m.CreateTime);
return datas ;
}
public IQueryable<T> GetAllByPageOrderAsync(int pageSize = 10, int pageIndex = 0, bool asc = true)
{
return GetAllOrderAsync(asc).Skip(pageSize * pageIndex).Take(pageSize);
}
public void Dispose()
{
_db.Dispose();
}
}
}
| 29.340206 | 107 | 0.547435 | [
"MIT"
] | zd19851231/blog_sys | BlogSystem/BlogSystem.DAL/BaseService.cs | 2,886 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Frends.Community.RabbitMQ
{
/// <summary>
/// Acknowledge type for manual operation
/// </summary>
public enum ManualAckType
{
Ack,
Nack,
NackAndRequeue,
Reject,
RejectAndRequeue
}
/// <summary>
/// Acknowledge type while reading message
/// </summary>
public enum ReadAckType
{
ManualAck,
AutoAck,
AutoNack,
AutoNackAndRequeue,
AutoReject,
AutoRejectAndRequeue
}
/// <summary>
/// Collection of read message parameters
/// </summary>
public class ReadInputParams
{
/// <summary>
/// Name of the queue
/// </summary>
[DefaultValue("sampleQueue")]
[DisplayName(@"Queue name")]
[DisplayFormat(DataFormatString = "Text")]
public string QueueName { get; set; }
/// <summary>
/// RabbitMQ host name
/// </summary>
[DefaultValue("localhost")]
[DisplayName(@"Host name")]
[DisplayFormat(DataFormatString = "Text")]
public string HostName { get; set; }
/// <summary>
/// Maximum number of messages to read
/// </summary>
[DefaultValue(1)]
[DisplayName(@"Read message count")]
public int ReadMessageCount { get; set; }
/// <summary>
/// Set acknowledgement type. AutoAck,AutoNack, AutoNackAndRequeue,AutoReject,AutoRejectAndRequeue,ManualAck.
/// </summary>
[DefaultValue(ReadAckType.AutoAck)]
[DisplayName(@"Auto ack")]
public ReadAckType AutoAck { get; set; }
/// <summary>
/// Use URI instead of a hostname
/// </summary>
[DefaultValue(false)]
[DisplayName(@"Use URI for connection")]
public bool ConnectWithURI { get; set; }
}
/// <summary>
/// Collection of write message parameters
/// </summary>
public class WriteInputParams
{
public WriteInputParams()
{
ExchangeName = String.Empty;
RoutingKey = String.Empty;
}
/// <summary>
/// Data payload
/// </summary>
[DisplayName(@"Data")]
[DisplayFormat(DataFormatString = "Expression")]
public byte[] Data { get; set; }
/// <summary>
/// Name of the exchange e.g. sampleExchange
/// </summary>
[DefaultValue("")]
[DisplayName(@"Exchange name")]
[DisplayFormat(DataFormatString = "Text")]
public string ExchangeName { get; set; }
/// <summary>
/// Name of the queue
/// </summary>
[DefaultValue("sampleQueue")]
[DisplayName(@"Queue name")]
[DisplayFormat(DataFormatString = "Text")]
public string QueueName { get; set; }
/// <summary>
/// Routing key name
/// </summary>
[DefaultValue("sampleQueue")]
[DisplayName(@"Routing key")]
[DisplayFormat(DataFormatString = "Text")]
public string RoutingKey { get; set; }
/// <summary>
/// RabbitMQ host name
/// </summary>
[DisplayName(@"Host name")]
[DisplayFormat(DataFormatString = "Text")]
public string HostName { get; set; }
/// <summary>
/// Use URI instead of a hostname
/// </summary>
[DefaultValue(false)]
[DisplayName(@"Use URI for connection")]
public bool ConnectWithURI { get; set; }
/// <summary>
/// True to declare queue when writing
/// </summary>
[DefaultValue(false)]
[DisplayName(@"True to declare queue before writing. False to not declare it")]
public bool Create { get; set; }
/// <summary>
/// Durable option when creating queue
/// </summary>
[DefaultValue(true)]
[DisplayName(@"Set durable option when creating queue")]
public bool Durable { get; set; }
}
public class WriteInputParamsString
{
public WriteInputParamsString()
{
ExchangeName = String.Empty;
RoutingKey = String.Empty;
}
/// <summary>
/// Data payload in string. Will be internally converted to byte array using UTF8.Convert method
/// </summary>
[DisplayName(@"Data")]
[DisplayFormat(DataFormatString = "Text")]
public string Data { get; set; }
/// <summary>
/// Name of the exchange
/// </summary>
[DefaultValue("sampleExchange")]
[DisplayName(@"Exchange name")]
[DisplayFormat(DataFormatString = "Text")]
public string ExchangeName { get; set; }
/// <summary>
/// Name of the queue
/// </summary>
[DefaultValue("sampleQueue")]
[DisplayName(@"Queue name")]
[DisplayFormat(DataFormatString = "Text")]
public string QueueName { get; set; }
/// <summary>
/// Routing key name
/// </summary>
[DefaultValue("sampleQueue")]
[DisplayName(@"Routing key")]
[DisplayFormat(DataFormatString = "Text")]
public string RoutingKey { get; set; }
/// <summary>
/// RabbitMQ host name
/// </summary>
[DisplayName(@"Host name")]
[DisplayFormat(DataFormatString = "Text")]
public string HostName { get; set; }
/// <summary>
/// Use URI instead of a hostname
/// </summary>
[DefaultValue(false)]
[DisplayName(@"Use URI for connection")]
public bool ConnectWithURI { get; set; }
/// <summary>
/// True to declare queue when writing
/// </summary>
[DefaultValue(false)]
[DisplayName(@"True to declare queue before writing. False to not declare it")]
public bool Create { get; set; }
/// <summary>
/// Durable option when creating queue
/// </summary>
[DefaultValue(true)]
[DisplayName(@"Set durable option when creating queue")]
public bool Durable { get; set; }
}
public class Output
{
public List<Message> Messages { get; set; } = new List<Message>();
}
public class Message
{
/// <summary>
/// Data in base64 format
/// </summary>
public string Data { get; set; }
public uint MessagesCount { get; set; }
public ulong DeliveryTag { get; set; }
}
public class MessageString
{
/// <summary>
/// Data in UTF8 string converted from byte[] array
/// </summary>
public string Data { get; set; }
public uint MessagesCount { get; set; }
public ulong DeliveryTag { get; set; }
}
public class OutputString
{
public List<MessageString> Messages { get; set; } = new List<MessageString>();
}
}
| 29.970213 | 117 | 0.557717 | [
"MIT"
] | levik-buka/Frends.Community.RabbitMQ | Frends.Community.RabbitMQ/Definitions.cs | 7,045 | C# |
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
#if WINDOWS_STOREAPP || WINDOWS_UAP
using Windows.UI.Xaml.Controls;
#endif
#if ANDROID
using Android.Views;
#endif
namespace Microsoft.Xna.Framework
{
public class GraphicsDeviceManager : IGraphicsDeviceService, IDisposable, IGraphicsDeviceManager
{
private Game _game;
private GraphicsDevice _graphicsDevice;
private int _preferredBackBufferHeight;
private int _preferredBackBufferWidth;
private SurfaceFormat _preferredBackBufferFormat;
private DepthFormat _preferredDepthStencilFormat;
private bool _preferMultiSampling;
private DisplayOrientation _supportedOrientations;
private bool _synchronizedWithVerticalRetrace = true;
private bool _drawBegun;
bool disposed;
private bool _hardwareModeSwitch = true;
#if (WINDOWS || WINDOWS_UAP) && DIRECTX
private bool _firstLaunch = true;
#endif
#if !WINRT || WINDOWS_UAP
private bool _wantFullScreen = false;
#endif
public static readonly int DefaultBackBufferHeight = 480;
public static readonly int DefaultBackBufferWidth = 800;
public GraphicsDeviceManager(Game game)
{
if (game == null)
throw new ArgumentNullException("The game cannot be null!");
_game = game;
_supportedOrientations = DisplayOrientation.Default;
#if WINDOWS || MONOMAC || DESKTOPGL
_preferredBackBufferHeight = DefaultBackBufferHeight;
_preferredBackBufferWidth = DefaultBackBufferWidth;
#else
// Preferred buffer width/height is used to determine default supported orientations,
// so set the default values to match Xna behaviour of landscape only by default.
// Note also that it's using the device window dimensions.
_preferredBackBufferWidth = Math.Max(_game.Window.ClientBounds.Height, _game.Window.ClientBounds.Width);
_preferredBackBufferHeight = Math.Min(_game.Window.ClientBounds.Height, _game.Window.ClientBounds.Width);
#endif
_preferredBackBufferFormat = SurfaceFormat.Color;
_preferredDepthStencilFormat = DepthFormat.Depth24;
_synchronizedWithVerticalRetrace = true;
// XNA would read this from the manifest, but it would always default
// to Reach unless changed. So lets mimic that without the manifest bit.
GraphicsProfile = GraphicsProfile.Reach;
if (_game.Services.GetService(typeof(IGraphicsDeviceManager)) != null)
throw new ArgumentException("Graphics Device Manager Already Present");
_game.Services.AddService(typeof(IGraphicsDeviceManager), this);
_game.Services.AddService(typeof(IGraphicsDeviceService), this);
}
~GraphicsDeviceManager()
{
Dispose(false);
}
public void CreateDevice()
{
Initialize();
OnDeviceCreated(EventArgs.Empty);
}
public bool BeginDraw()
{
if (_graphicsDevice == null)
return false;
_drawBegun = true;
return true;
}
public void EndDraw()
{
if (_graphicsDevice != null && _drawBegun)
{
_drawBegun = false;
_graphicsDevice.Present();
}
}
#region IGraphicsDeviceService Members
public event EventHandler<EventArgs> DeviceCreated;
public event EventHandler<EventArgs> DeviceDisposing;
public event EventHandler<EventArgs> DeviceReset;
public event EventHandler<EventArgs> DeviceResetting;
public event EventHandler<PreparingDeviceSettingsEventArgs> PreparingDeviceSettings;
// FIXME: Why does the GraphicsDeviceManager not know enough about the
// GraphicsDevice to raise these events without help?
internal void OnDeviceDisposing(EventArgs e)
{
EventHelpers.Raise(this, DeviceDisposing, e);
}
// FIXME: Why does the GraphicsDeviceManager not know enough about the
// GraphicsDevice to raise these events without help?
internal void OnDeviceResetting(EventArgs e)
{
EventHelpers.Raise(this, DeviceResetting, e);
}
// FIXME: Why does the GraphicsDeviceManager not know enough about the
// GraphicsDevice to raise these events without help?
internal void OnDeviceReset(EventArgs e)
{
EventHelpers.Raise(this, DeviceReset, e);
}
// FIXME: Why does the GraphicsDeviceManager not know enough about the
// GraphicsDevice to raise these events without help?
internal void OnDeviceCreated(EventArgs e)
{
EventHelpers.Raise(this, DeviceCreated, e);
}
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (_graphicsDevice != null)
{
_graphicsDevice.Dispose();
_graphicsDevice = null;
}
}
disposed = true;
}
}
#endregion
public void ApplyChanges()
{
// Calling ApplyChanges() before CreateDevice() should have no effect
if (_graphicsDevice == null)
return;
#if WINDOWS_PHONE
_graphicsDevice.GraphicsProfile = GraphicsProfile;
// Display orientation is always portrait on WP8
_graphicsDevice.PresentationParameters.DisplayOrientation = DisplayOrientation.Portrait;
#elif WINDOWS_STOREAPP || WINDOWS_UAP
// TODO: Does this need to occur here?
_game.Window.SetSupportedOrientations(_supportedOrientations);
_graphicsDevice.PresentationParameters.BackBufferFormat = _preferredBackBufferFormat;
_graphicsDevice.PresentationParameters.BackBufferWidth = _preferredBackBufferWidth;
_graphicsDevice.PresentationParameters.BackBufferHeight = _preferredBackBufferHeight;
_graphicsDevice.PresentationParameters.DepthStencilFormat = _preferredDepthStencilFormat;
// TODO: We probably should be resetting the whole device
// if this changes as we are targeting a different
// hardware feature level.
_graphicsDevice.GraphicsProfile = GraphicsProfile;
#if WINDOWS_UAP
_graphicsDevice.PresentationParameters.DeviceWindowHandle = IntPtr.Zero;
_graphicsDevice.PresentationParameters.SwapChainPanel = this.SwapChainPanel;
_graphicsDevice.PresentationParameters.IsFullScreen = _wantFullScreen;
#else
_graphicsDevice.PresentationParameters.IsFullScreen = false;
// The graphics device can use a XAML panel or a window
// to created the default swapchain target.
if (this.SwapChainBackgroundPanel != null)
{
_graphicsDevice.PresentationParameters.DeviceWindowHandle = IntPtr.Zero;
_graphicsDevice.PresentationParameters.SwapChainBackgroundPanel = this.SwapChainBackgroundPanel;
}
else
{
_graphicsDevice.PresentationParameters.DeviceWindowHandle = _game.Window.Handle;
_graphicsDevice.PresentationParameters.SwapChainBackgroundPanel = null;
}
#endif
// Update the back buffer.
_graphicsDevice.CreateSizeDependentResources();
_graphicsDevice.ApplyRenderTargets(null);
#if WINDOWS_UAP
((UAPGameWindow)_game.Window).SetClientSize(_preferredBackBufferWidth, _preferredBackBufferHeight);
#endif
#elif WINDOWS && DIRECTX
_graphicsDevice.PresentationParameters.BackBufferFormat = _preferredBackBufferFormat;
_graphicsDevice.PresentationParameters.BackBufferWidth = _preferredBackBufferWidth;
_graphicsDevice.PresentationParameters.BackBufferHeight = _preferredBackBufferHeight;
_graphicsDevice.PresentationParameters.DepthStencilFormat = _preferredDepthStencilFormat;
_graphicsDevice.PresentationParameters.PresentationInterval = _synchronizedWithVerticalRetrace ? PresentInterval.Default : PresentInterval.Immediate;
_graphicsDevice.PresentationParameters.IsFullScreen = _wantFullScreen;
// TODO: We probably should be resetting the whole
// device if this changes as we are targeting a different
// hardware feature level.
_graphicsDevice.GraphicsProfile = GraphicsProfile;
_graphicsDevice.PresentationParameters.DeviceWindowHandle = _game.Window.Handle;
// Update the back buffer.
_graphicsDevice.CreateSizeDependentResources();
_graphicsDevice.ApplyRenderTargets(null);
((MonoGame.Framework.WinFormsGamePlatform)_game.Platform).ResetWindowBounds();
#elif DESKTOPGL
var displayIndex = Sdl.Window.GetDisplayIndex (SdlGameWindow.Instance.Handle);
var displayName = Sdl.Display.GetDisplayName (displayIndex);
_graphicsDevice.PresentationParameters.BackBufferFormat = _preferredBackBufferFormat;
_graphicsDevice.PresentationParameters.BackBufferWidth = _preferredBackBufferWidth;
_graphicsDevice.PresentationParameters.BackBufferHeight = _preferredBackBufferHeight;
_graphicsDevice.PresentationParameters.DepthStencilFormat = _preferredDepthStencilFormat;
_graphicsDevice.PresentationParameters.PresentationInterval = _synchronizedWithVerticalRetrace ? PresentInterval.Default : PresentInterval.Immediate;
_graphicsDevice.PresentationParameters.IsFullScreen = _wantFullScreen;
//Set the swap interval based on if vsync is desired or not.
//See GetSwapInterval for more details
int swapInterval;
if (_synchronizedWithVerticalRetrace)
swapInterval = _graphicsDevice.PresentationParameters.PresentationInterval.GetSwapInterval();
else
swapInterval = 0;
_graphicsDevice.Context.SwapInterval = swapInterval;
_graphicsDevice.ApplyRenderTargets (null);
_game.Platform.BeginScreenDeviceChange (GraphicsDevice.PresentationParameters.IsFullScreen);
_game.Platform.EndScreenDeviceChange (displayName, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight);
#elif MONOMAC
_graphicsDevice.PresentationParameters.IsFullScreen = _wantFullScreen;
// TODO: Implement multisampling (aka anti-alising) for all platforms!
_game.applyChanges(this);
#else
#if ANDROID
// Trigger a change in orientation in case the supported orientations have changed
((AndroidGameWindow)_game.Window).SetOrientation(_game.Window.CurrentOrientation, false);
#endif
// Ensure the presentation parameter orientation and buffer size matches the window
_graphicsDevice.PresentationParameters.DisplayOrientation = _game.Window.CurrentOrientation;
// Set the presentation parameters' actual buffer size to match the orientation
bool isLandscape = (0 != (_game.Window.CurrentOrientation & (DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight)));
int w = PreferredBackBufferWidth;
int h = PreferredBackBufferHeight;
_graphicsDevice.PresentationParameters.BackBufferWidth = isLandscape ? Math.Max(w, h) : Math.Min(w, h);
_graphicsDevice.PresentationParameters.BackBufferHeight = isLandscape ? Math.Min(w, h) : Math.Max(w, h);
ResetClientBounds();
#endif
// Set the new display size on the touch panel.
//
// TODO: In XNA this seems to be done as part of the
// GraphicsDevice.DeviceReset event... we need to get
// those working.
//
TouchPanel.DisplayWidth = _graphicsDevice.PresentationParameters.BackBufferWidth;
TouchPanel.DisplayHeight = _graphicsDevice.PresentationParameters.BackBufferHeight;
#if (WINDOWS || WINDOWS_UAP) && DIRECTX
if (!_firstLaunch)
{
if (IsFullScreen)
{
_game.Platform.EnterFullScreen();
}
else
{
_game.Platform.ExitFullScreen();
}
}
_firstLaunch = false;
#endif
}
private void Initialize()
{
var presentationParameters = new PresentationParameters();
presentationParameters.DepthStencilFormat = DepthFormat.Depth24;
#if (WINDOWS || WINRT) && !DESKTOPGL
_game.Window.SetSupportedOrientations(_supportedOrientations);
presentationParameters.BackBufferFormat = _preferredBackBufferFormat;
presentationParameters.BackBufferWidth = _preferredBackBufferWidth;
presentationParameters.BackBufferHeight = _preferredBackBufferHeight;
presentationParameters.DepthStencilFormat = _preferredDepthStencilFormat;
presentationParameters.IsFullScreen = false;
#if WINDOWS_PHONE
// Nothing to do!
#elif WINDOWS_UAP
presentationParameters.DeviceWindowHandle = IntPtr.Zero;
presentationParameters.SwapChainPanel = this.SwapChainPanel;
#elif WINDOWS_STOREAPP
// The graphics device can use a XAML panel or a window
// to created the default swapchain target.
if (this.SwapChainBackgroundPanel != null)
{
presentationParameters.DeviceWindowHandle = IntPtr.Zero;
presentationParameters.SwapChainBackgroundPanel = this.SwapChainBackgroundPanel;
}
else
{
presentationParameters.DeviceWindowHandle = _game.Window.Handle;
presentationParameters.SwapChainBackgroundPanel = null;
}
#else
presentationParameters.DeviceWindowHandle = _game.Window.Handle;
#endif
#else
#if MONOMAC || DESKTOPGL
presentationParameters.IsFullScreen = _wantFullScreen;
#elif WEB
presentationParameters.IsFullScreen = false;
#else
// Set "full screen" as default
presentationParameters.IsFullScreen = true;
#endif // MONOMAC
#endif // WINDOWS || WINRT
// TODO: Implement multisampling (aka anti-alising) for all platforms!
var preparingDeviceSettingsHandler = PreparingDeviceSettings;
if (preparingDeviceSettingsHandler != null)
{
GraphicsDeviceInformation gdi = new GraphicsDeviceInformation();
gdi.GraphicsProfile = GraphicsProfile; // Microsoft defaults this to Reach.
gdi.Adapter = GraphicsAdapter.DefaultAdapter;
gdi.PresentationParameters = presentationParameters;
PreparingDeviceSettingsEventArgs pe = new PreparingDeviceSettingsEventArgs(gdi);
preparingDeviceSettingsHandler(this, pe);
presentationParameters = pe.GraphicsDeviceInformation.PresentationParameters;
GraphicsProfile = pe.GraphicsDeviceInformation.GraphicsProfile;
}
// Needs to be before ApplyChanges()
_graphicsDevice = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, GraphicsProfile, presentationParameters);
#if !MONOMAC
ApplyChanges();
#endif
// Set the new display size on the touch panel.
//
// TODO: In XNA this seems to be done as part of the
// GraphicsDevice.DeviceReset event... we need to get
// those working.
//
TouchPanel.DisplayWidth = _graphicsDevice.PresentationParameters.BackBufferWidth;
TouchPanel.DisplayHeight = _graphicsDevice.PresentationParameters.BackBufferHeight;
TouchPanel.DisplayOrientation = _graphicsDevice.PresentationParameters.DisplayOrientation;
}
public void ToggleFullScreen()
{
IsFullScreen = !IsFullScreen;
#if ((WINDOWS || WINDOWS_UAP) && DIRECTX) || DESKTOPGL
ApplyChanges();
#endif
}
#if WINDOWS_STOREAPP
[CLSCompliant(false)]
public SwapChainBackgroundPanel SwapChainBackgroundPanel { get; set; }
#endif
#if WINDOWS_UAP
[CLSCompliant(false)]
public SwapChainPanel SwapChainPanel { get; set; }
#endif
public GraphicsProfile GraphicsProfile { get; set; }
public GraphicsDevice GraphicsDevice
{
get
{
return _graphicsDevice;
}
}
public bool IsFullScreen
{
get
{
#if WINDOWS_UAP
return _wantFullScreen;
#elif WINRT
return true;
#else
if (_graphicsDevice != null)
return _graphicsDevice.PresentationParameters.IsFullScreen;
return _wantFullScreen;
#endif
}
set
{
#if WINDOWS_UAP
_wantFullScreen = value;
#elif WINRT
// Just ignore this as it is not relevant on Windows 8
#elif WINDOWS && DIRECTX
_wantFullScreen = value;
#else
_wantFullScreen = value;
if (_graphicsDevice != null)
{
_graphicsDevice.PresentationParameters.IsFullScreen = value;
#if ANDROID
ForceSetFullScreen();
#endif
}
#endif
}
}
#if ANDROID
internal void ForceSetFullScreen()
{
if (IsFullScreen)
{
Game.Activity.Window.ClearFlags(Android.Views.WindowManagerFlags.ForceNotFullscreen);
Game.Activity.Window.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.Fullscreen);
}
else
Game.Activity.Window.SetFlags(WindowManagerFlags.ForceNotFullscreen, WindowManagerFlags.ForceNotFullscreen);
}
#endif
/// <summary>
/// Gets or sets the boolean which defines how window switches from windowed to fullscreen state.
/// "Hard" mode(true) is slow to switch, but more effecient for performance, while "soft" mode(false) is vice versa.
/// The default value is <c>true</c>.
/// </summary>
public bool HardwareModeSwitch
{
get { return _hardwareModeSwitch; }
set
{
_hardwareModeSwitch = value;
}
}
public bool PreferMultiSampling
{
get
{
return _preferMultiSampling;
}
set
{
_preferMultiSampling = value;
}
}
public SurfaceFormat PreferredBackBufferFormat
{
get
{
return _preferredBackBufferFormat;
}
set
{
_preferredBackBufferFormat = value;
}
}
public int PreferredBackBufferHeight
{
get
{
return _preferredBackBufferHeight;
}
set
{
_preferredBackBufferHeight = value;
}
}
public int PreferredBackBufferWidth
{
get
{
return _preferredBackBufferWidth;
}
set
{
_preferredBackBufferWidth = value;
}
}
public DepthFormat PreferredDepthStencilFormat
{
get
{
return _preferredDepthStencilFormat;
}
set
{
_preferredDepthStencilFormat = value;
}
}
public bool SynchronizeWithVerticalRetrace
{
get
{
return _synchronizedWithVerticalRetrace;
}
set
{
_synchronizedWithVerticalRetrace = value;
}
}
public DisplayOrientation SupportedOrientations
{
get
{
return _supportedOrientations;
}
set
{
_supportedOrientations = value;
if (_game.Window != null)
_game.Window.SetSupportedOrientations(_supportedOrientations);
}
}
/// <summary>
/// This method is used by MonoGame Android to adjust the game's drawn to area to fill
/// as much of the screen as possible whilst retaining the aspect ratio inferred from
/// aspectRatio = (PreferredBackBufferWidth / PreferredBackBufferHeight)
///
/// NOTE: this is a hack that should be removed if proper back buffer to screen scaling
/// is implemented. To disable it's effect, in the game's constructor use:
///
/// graphics.IsFullScreen = true;
/// graphics.PreferredBackBufferHeight = Window.ClientBounds.Height;
/// graphics.PreferredBackBufferWidth = Window.ClientBounds.Width;
///
/// </summary>
internal void ResetClientBounds()
{
#if ANDROID
float preferredAspectRatio = (float)PreferredBackBufferWidth /
(float)PreferredBackBufferHeight;
float displayAspectRatio = (float)GraphicsDevice.DisplayMode.Width /
(float)GraphicsDevice.DisplayMode.Height;
float adjustedAspectRatio = preferredAspectRatio;
if ((preferredAspectRatio > 1.0f && displayAspectRatio < 1.0f) ||
(preferredAspectRatio < 1.0f && displayAspectRatio > 1.0f))
{
// Invert preferred aspect ratio if it's orientation differs from the display mode orientation.
// This occurs when user sets preferredBackBufferWidth/Height and also allows multiple supported orientations
adjustedAspectRatio = 1.0f / preferredAspectRatio;
}
const float EPSILON = 0.00001f;
var newClientBounds = new Rectangle();
if (displayAspectRatio > (adjustedAspectRatio + EPSILON))
{
// Fill the entire height and reduce the width to keep aspect ratio
newClientBounds.Height = _graphicsDevice.DisplayMode.Height;
newClientBounds.Width = (int)(newClientBounds.Height * adjustedAspectRatio);
newClientBounds.X = (_graphicsDevice.DisplayMode.Width - newClientBounds.Width) / 2;
}
else if (displayAspectRatio < (adjustedAspectRatio - EPSILON))
{
// Fill the entire width and reduce the height to keep aspect ratio
newClientBounds.Width = _graphicsDevice.DisplayMode.Width;
newClientBounds.Height = (int)(newClientBounds.Width / adjustedAspectRatio);
newClientBounds.Y = (_graphicsDevice.DisplayMode.Height - newClientBounds.Height) / 2;
}
else
{
// Set the ClientBounds to match the DisplayMode
newClientBounds.Width = GraphicsDevice.DisplayMode.Width;
newClientBounds.Height = GraphicsDevice.DisplayMode.Height;
}
// Ensure buffer size is reported correctly
_graphicsDevice.PresentationParameters.BackBufferWidth = newClientBounds.Width;
_graphicsDevice.PresentationParameters.BackBufferHeight = newClientBounds.Height;
// Set the veiwport so the (potentially) resized client bounds are drawn in the middle of the screen
_graphicsDevice.Viewport = new Viewport(newClientBounds.X, -newClientBounds.Y, newClientBounds.Width, newClientBounds.Height);
((AndroidGameWindow)_game.Window).ChangeClientBounds(newClientBounds);
// Touch panel needs latest buffer size for scaling
TouchPanel.DisplayWidth = newClientBounds.Width;
TouchPanel.DisplayHeight = newClientBounds.Height;
Android.Util.Log.Debug("MonoGame", "GraphicsDeviceManager.ResetClientBounds: newClientBounds=" + newClientBounds.ToString());
#endif
}
}
}
| 38.115677 | 174 | 0.634374 | [
"MIT"
] | ArmatureStudio/MonoGame | MonoGame.Framework/GraphicsDeviceManager.Legacy.cs | 25,042 | C# |
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Test.Controls
{
/// <summary>
///
/// </summary>
public partial class StateControl : UserControl
{
/// <summary>
///
/// </summary>
public StateControl()
{
InitializeComponent();
}
}
}
| 25.117647 | 102 | 0.660422 | [
"MIT"
] | billchungiii/Test2d | Test2d.UI.Wpf/Controls/StateControl.xaml.cs | 826 | C# |
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FakeItEasy;
using FluentAssertions.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using Shouldly;
using Stackage.Core.Abstractions.Metrics;
using Stackage.Core.Extensions;
namespace Stackage.Core.Tests.DefaultMiddleware.Health
{
public class child_registered_with_factory : health_scenario
{
private HttpResponseMessage _response;
private string _content;
[OneTimeSetUp]
public async Task setup_scenario()
{
_response = await TestService.GetAsync("/health");
_content = await _response.Content.ReadAsStringAsync();
}
protected override void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
base.ConfigureServices(services, configuration);
var response = A.Fake<IHealthCheckResponse>();
A.CallTo(() => response.Value).Returns(new HealthCheckResult(HealthStatus.Degraded));
services.AddSingleton<IHealthCheckResponse>(response);
services.AddHealthCheck("using-service-provider", BuildHealthCheck);
}
private static IHealthCheck BuildHealthCheck(IServiceProvider sp)
{
var response = sp.GetRequiredService<IHealthCheckResponse>();
return new StubHealthCheck {CheckHealthResponse = response.Value};
}
[Test]
public void should_return_status_code_200()
{
_response.StatusCode.ShouldBe(HttpStatusCode.OK);
}
[Test]
public void should_return_content()
{
var response = JObject.Parse(_content);
var expectedResponse = new JObject
{
["status"] = "Degraded",
["dependencies"] = new JArray
{
new JObject
{
["name"] = "using-service-provider",
["status"] = "Degraded"
}
}
};
response.Should().ContainSubtree(expectedResponse);
}
[Test]
public void should_return_content_type_json()
{
_response.Content.Headers.ContentType.MediaType.ShouldBe("application/json");
}
[Test]
public void should_write_end_metric_with_status_200()
{
var metric = (Gauge) MetricSink.Metrics.Last();
Assert.That(metric.Dimensions["statusCode"], Is.EqualTo(200));
}
// ReSharper disable once MemberCanBePrivate.Global
public interface IHealthCheckResponse
{
HealthCheckResult Value { get; }
}
}
}
| 28.255102 | 106 | 0.657638 | [
"MIT"
] | concilify/stackage-core-nuget | package/Stackage.Core.Tests/DefaultMiddleware/Health/child_registered_with_factory.cs | 2,769 | C# |
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if !UNITY_2018_3_OR_NEWER
using System;
using MessagePack;
using MessagePack.Resolvers;
using Xunit;
using Xunit.Abstractions;
public class MessagePackSerializerTypelessTests
{
private readonly ITestOutputHelper logger;
public MessagePackSerializerTypelessTests(ITestOutputHelper logger)
{
this.logger = logger;
}
[Fact]
public void SerializationOfBuiltInType()
{
byte[] msgpack = MessagePackSerializer.Typeless.Serialize("hi");
this.logger.WriteLine(MessagePackSerializer.ConvertToJson(msgpack));
Assert.Equal("hi", MessagePackSerializer.Typeless.Deserialize(msgpack));
}
[Fact]
public void SerializationOfDisallowedType()
{
var myOptions = new MyTypelessOptions();
byte[] msgpack = MessagePackSerializer.Typeless.Serialize(new MyObject { SomeValue = 5 }, myOptions);
this.logger.WriteLine(MessagePackSerializer.ConvertToJson(msgpack, myOptions));
var ex = Assert.Throws<MessagePackSerializationException>(() => MessagePackSerializer.Typeless.Deserialize(msgpack, myOptions));
Assert.IsType<TypeAccessException>(ex.InnerException);
}
[Fact]
public void OmitAssemblyVersion()
{
string json = MessagePackSerializer.ConvertToJson(MessagePackSerializer.Typeless.Serialize(new MyObject { SomeValue = 5 }));
this.logger.WriteLine(json);
Assert.Contains(ThisAssembly.AssemblyVersion, json);
json = MessagePackSerializer.ConvertToJson(MessagePackSerializer.Typeless.Serialize(new MyObject { SomeValue = 5 }, MessagePackSerializer.Typeless.DefaultOptions.WithOmitAssemblyVersion(true)));
this.logger.WriteLine(json);
Assert.DoesNotContain(ThisAssembly.AssemblyVersion, json);
}
public class MyObject
{
public object SomeValue { get; set; }
}
private class MyTypelessOptions : MessagePackSerializerOptions
{
internal MyTypelessOptions()
: base(TypelessContractlessStandardResolver.Options)
{
}
internal MyTypelessOptions(MyTypelessOptions copyFrom)
: base(copyFrom)
{
}
public override void ThrowIfDeserializingTypeIsDisallowed(Type type)
{
if (type == typeof(MyObject))
{
throw new TypeAccessException();
}
}
protected override MessagePackSerializerOptions Clone() => new MyTypelessOptions(this);
}
}
#endif
| 33.05 | 202 | 0.699319 | [
"BSD-2-Clause"
] | Alprog/MessagePack-CSharp | src/MessagePack.UnityClient/Assets/Scripts/Tests/ShareTests/MessagePackSerializerTypelessTests.cs | 2,644 | C# |
using Amazon.JSII.JsonModel.Spec;
using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace Amazon.JSII.Generator
{
public static class AssemblyExtensions
{
public static string GetNativePackageId(this Assembly assembly, string targetPackageName = null)
{
assembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
string packageId = assembly.GetNativeProperty
(
assembly.Name,
targetPackageName ?? assembly.Name,
d => d.Targets?.DotNet?.PackageId
);
if (string.IsNullOrWhiteSpace(packageId))
{
throw new ArgumentException
(
$"Assembly {assembly.Name} does not include a package id mapping for {targetPackageName ?? assembly.Name}",
nameof(assembly)
);
}
return packageId;
}
public static string GetNativeNamespace(this Assembly assembly, string targetPackageName = null)
{
assembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
string @namespace = assembly.GetNativeProperty
(
assembly.Name,
targetPackageName ?? assembly.Name,
d => d.Targets?.DotNet?.Namespace
);
if (string.IsNullOrWhiteSpace(@namespace))
{
throw new ArgumentException
(
$"Assembly {assembly.Name} does not include a namespace mapping for {targetPackageName ?? assembly.Name}",
nameof(assembly)
);
}
return @namespace;
}
public static IEnumerable<XElement> GetMsBuildProperties(this Assembly assembly)
{
yield return new XElement("TargetFramework", "netstandard2.0");
yield return new XElement("GeneratePackageOnBuild", true);
yield return new XElement("IncludeSymbols", true);
yield return new XElement("IncludeSource", true);
yield return new XElement("PackageVersion", assembly.Version);
yield return new XElement("PackageId", assembly.Targets.DotNet.PackageId);
yield return new XElement("Description", assembly.Description);
yield return new XElement("ProjectUrl", assembly.Homepage);
yield return new XElement("LicenseUrl", $"https://spdx.org/licenses/{assembly.License}.html");
yield return new XElement("Authors", $"{assembly.Author.Name}");
// TODO: Update once we have a localization story.
yield return new XElement("Language", "en-US");
if (assembly.Targets.DotNet.Title != null)
{
yield return new XElement("Title", assembly.Targets.DotNet.Title);
}
if (assembly.Targets.DotNet.SignAssembly != null)
{
yield return new XElement("SignAssembly",
new XAttribute("Condition", @"Exists('$(AssemblyOriginatorKeyFile)')"),
assembly.Targets.DotNet.SignAssembly
);
}
if (assembly.Targets.DotNet.AssemblyOriginatorKeyFile != null)
{
yield return new XElement("AssemblyOriginatorKeyFile", assembly.Targets.DotNet.AssemblyOriginatorKeyFile);
}
if (assembly.Targets.DotNet.IconUrl != null)
{
yield return new XElement("IconUrl", assembly.Targets.DotNet.IconUrl);
}
}
}
}
| 37.773196 | 127 | 0.577784 | [
"Apache-2.0"
] | floehopper/jsii | packages/jsii-dotnet-generator/src/Amazon.JSII.Generator/AssemblyExtensions.cs | 3,666 | C# |
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using smartadmiral.common;
namespace smartadmiral.files
{
public class FileCopier
{
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(string username, string domain,
IntPtr password, int logonType,
int logonProvider, ref IntPtr token);
public static bool Copy(string src, string dest, AdmiralContext context)
{
IntPtr adminToken = default(IntPtr);
WindowsImpersonationContext wic = null;
var passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(context.Password);
try
{
if (LogonUser(context.UserName, context.Hostname, passwordPtr, 9, 0, ref adminToken))
{
var widAdmin = new WindowsIdentity(adminToken);
wic = widAdmin.Impersonate();
var host = $@"\\{context.Hostname}";
dest = dest.Replace(':', '$');
dest = Path.Combine(host, dest);
File.Copy(src, dest);
return true;
}
return false;
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
wic?.Undo();
}
}
}
} | 32.511111 | 101 | 0.548872 | [
"MIT"
] | AdmiralTool/Admiral | smartadmiral.files/FileCopier.cs | 1,465 | C# |
using CryptoApisLibrary.DataTypes;
using CryptoApisLibrary.ResponseTypes.Blockchains;
using System;
namespace CryptoApisSnippets.Samples.Blockchains
{
partial class BlockchainSnippets
{
public void ImportAddressAsWalletBtc()
{
var walletName = "testImportWallet";
var password = "SECRET123456";
var privateKey = "8aeb39b5f9b0xxxxxxxc7001c1cecc112712c9448b";
var address = "mn6GtNFRPwXtW7xJqH8Afck7FbVoRi6NF1";
var manager = new CryptoManager(ApiKey);
var response = manager.Blockchains.Wallet.ImportAddressAsWallet<ImportAddressAsWalletResponse>(
NetworkCoin.BtcMainNet, walletName, password, privateKey, address);
Console.WriteLine(string.IsNullOrEmpty(response.ErrorMessage)
? "ImportAddressAsWalletBtc executed successfully, " +
$"\"{response.Payload.Addresses.Count}\" addresses were imported "
: $"ImportAddressAsWalletBtc error: {response.ErrorMessage}");
}
}
} | 37.115385 | 101 | 0.745078 | [
"MIT"
] | Crypto-APIs/.NET-Library | CryptoApisSnippets/Samples/Blockchains/Wallets/ImportAddressAsWalletBtc.cs | 967 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using FluentAssertions;
using Microsoft.CodeAnalysis.Sarif.PatternMatcher.Plugins.Security.Helpers;
using Microsoft.CodeAnalysis.Sarif.PatternMatcher.Sdk;
using Xunit;
namespace Microsoft.CodeAnalysis.Sarif.PatternMatcher.Plugins.Security.Validators
{
public class CratesApiKeyValidatorTests
{
[Fact]
public void DiscordCredentialsValidator_MockHttpTests()
{
string unknownMessage = null;
const string fingerprintText = "[secret=b]";
ValidatorBase.ReturnUnexpectedResponseCode(ref unknownMessage, HttpStatusCode.NotFound);
var testCases = new HttpMockTestCase[]
{
new HttpMockTestCase
{
Title = "Testing Valid Credentials",
HttpStatusCodes = new List<HttpStatusCode>{ HttpStatusCode.OK },
ExpectedValidationState = ValidationState.Authorized,
},
new HttpMockTestCase
{
Title = "Testing Invalid Credentials (Forbidden StatusCode)",
HttpStatusCodes = new List<HttpStatusCode>{ HttpStatusCode.Forbidden },
ExpectedValidationState = ValidationState.Unauthorized,
},
new HttpMockTestCase
{
Title = "Testing Invalid Credentials (Unauthorized StatusCode)",
HttpStatusCodes = new List<HttpStatusCode>{ HttpStatusCode.Unauthorized },
ExpectedValidationState = ValidationState.Unauthorized,
},
new HttpMockTestCase
{
Title = "Testing NotFound StatusCode",
HttpStatusCodes = new List<HttpStatusCode>{ HttpStatusCode.NotFound },
ExpectedValidationState = ValidationState.Unknown,
ExpectedMessage = unknownMessage
},
};
var sb = new StringBuilder();
var cratesApiKeyValidator = new CratesApiKeyValidator();
foreach (HttpMockTestCase testCase in testCases)
{
string message = null;
ResultLevelKind resultLevelKind = default;
var fingerprint = new Fingerprint(fingerprintText);
var keyValuePairs = new Dictionary<string, string>();
using var httpClient = new HttpClient(HttpMockHelper.Mock(testCase.HttpStatusCodes[0], null));
cratesApiKeyValidator.SetHttpClient(httpClient);
ValidationState currentState = cratesApiKeyValidator.IsValidDynamic(ref fingerprint,
ref message,
keyValuePairs,
ref resultLevelKind);
if (currentState != testCase.ExpectedValidationState)
{
sb.AppendLine($"The test case '{testCase.Title}' was expecting '{testCase.ExpectedValidationState}' but found '{currentState}'.");
}
if (message != testCase.ExpectedMessage)
{
sb.AppendLine($"The test case '{testCase.Title}' was expecting '{testCase.ExpectedMessage}' but found '{message}'.");
}
}
sb.Length.Should().Be(0, sb.ToString());
}
}
}
| 43.609195 | 150 | 0.563258 | [
"MIT"
] | microsoft/sarif-pattern-matcher | Src/Plugins/Tests.Security/Validators/SEC101_047.CratesApiKeyValidatorTests.cs | 3,796 | C# |
using Foundation.ObjectHydrator.Interfaces;
using System;
using System.Collections.Generic;
namespace Foundation.ObjectHydrator.Tests.HydratorTests
{
class InjectedGenerator:IGenerator<string>
{
private readonly Random random;
private IList<string> states = new List<string>();
public InjectedGenerator()
{
random = RandomSingleton.Instance.Random;
LoadStates();
}
private void LoadStates()
{
states = new List<string>
{
"AK",
"CA"
};
}
public string Generate()
{
return states[random.Next(0, states.Count)];
}
}
}
| 25.242424 | 61 | 0.477791 | [
"Apache-2.0"
] | PrintsCharming/ObjectHydrator | Foundation.ObjectHydrator.Tests/HydratorTests/InjectedGenerator.cs | 835 | C# |
using System;
#if __MOBILE__
namespace Xamarin.Forms.Platform.iOS
#else
namespace Xamarin.Forms.Platform.MacOS
#endif
{
public class VisualElementChangedEventArgs : ElementChangedEventArgs<VisualElement>
{
public VisualElementChangedEventArgs(VisualElement oldElement, VisualElement newElement)
: base(oldElement, newElement)
{
}
}
public class ElementChangedEventArgs<TElement> : EventArgs where TElement : Element
{
public ElementChangedEventArgs(TElement oldElement, TElement newElement)
{
OldElement = oldElement;
NewElement = newElement;
}
public TElement NewElement { get; private set; }
public TElement OldElement { get; private set; }
}
} | 22.733333 | 90 | 0.77566 | [
"MIT"
] | 07101994/Xamarin.Forms | Xamarin.Forms.Platform.iOS/ElementChangedEventArgs.cs | 682 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Transport.Libuv.Native
{
using System;
using System.Diagnostics;
using System.Net;
sealed class Tcp : TcpHandle
{
static readonly uv_alloc_cb AllocateCallback = OnAllocateCallback;
static readonly uv_read_cb ReadCallback = OnReadCallback;
readonly ReadOperation pendingRead;
NativeChannel.INativeUnsafe nativeUnsafe;
public Tcp(Loop loop, uint flags = 0 /* AF_UNSPEC */ ) : base(loop, flags)
{
this.pendingRead = new ReadOperation();
}
public void ReadStart(NativeChannel.INativeUnsafe channel)
{
Debug.Assert(channel != null);
this.Validate();
int result = NativeMethods.uv_read_start(this.Handle, AllocateCallback, ReadCallback);
NativeMethods.ThrowIfError(result);
this.nativeUnsafe = channel;
}
public void ReadStop()
{
if (this.Handle == IntPtr.Zero)
{
return;
}
// This function is idempotent and may be safely called on a stopped stream.
NativeMethods.uv_read_stop(this.Handle);
}
void OnReadCallback(int statusCode, OperationException error)
{
try
{
this.pendingRead.Complete(statusCode, error);
this.nativeUnsafe.FinishRead(this.pendingRead);
}
catch (Exception exception)
{
//Logger.Warn($"Tcp {this.Handle} read callbcak error.", exception);
}
finally
{
this.pendingRead.Reset();
}
}
static void OnReadCallback(IntPtr handle, IntPtr nread, ref uv_buf_t buf)
{
var tcp = GetTarget<Tcp>(handle);
int status = (int)nread.ToInt64();
OperationException error = null;
if (status < 0 && status != NativeMethods.EOF)
{
error = NativeMethods.CreateError((uv_err_code)status);
}
tcp.OnReadCallback(status, error);
}
protected override void OnClosed()
{
base.OnClosed();
this.pendingRead.Dispose();
this.nativeUnsafe = null;
}
void OnAllocateCallback(out uv_buf_t buf)
{
buf = this.nativeUnsafe.PrepareRead(this.pendingRead);
}
static void OnAllocateCallback(IntPtr handle, IntPtr suggestedSize, out uv_buf_t buf)
{
var tcp = GetTarget<Tcp>(handle);
tcp.OnAllocateCallback(out buf);
}
public IPEndPoint GetPeerEndPoint()
{
this.Validate();
return NativeMethods.TcpGetPeerName(this.Handle);
}
}
}
| 29.425743 | 101 | 0.567631 | [
"Apache-2.0"
] | cdy816/mars | Common/DotNettyCore/Transport/Libuv/Native/Tcp.cs | 2,974 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using IndependentResolutionRendering;
using BBTA.Interface;
using BBTA.GestionAudio;
namespace BBTA.Menus
{
public class MenuOptions : MenuArrierePlan
{
private event EventHandler ChangementVolume;
private bool initierAudio;
//Lettrage-------------------------------------------------------------------
private Texture2D lettrage;
private SpriteFont police;
//Boutons menu--------------------------------------------------------------------------------
private Bouton btnValider;
private Bouton btnDefaut;
private Bouton btnAnnuler;
//Bouton de selection des touches------------------------------------------------------------
private BoutonClicEtEcris btnGauche;
private BoutonClicEtEcris btnDroite;
private BoutonClicEtEcris btnSaut;
private BoutonClicEtEcris btnTir;
private BoutonClicEtEcris btnPause;
//Boutons de sélection du volume-------------------------------------------------------------
private Slider sliderEffet;
private Slider sliderMusique;
//Si on est en train d'enregistrer une nouvelle touche---------------------------------------
private bool enAttente;
private BoutonClicEtEcris boutonEnAttente;
private EtatJeu prochainEtat;
private Option.Option OptionJeu;
public void InitControlAudio(GestionMusique gestionnaireMusique, GestionSon gestionnaireSon)
{
if (initierAudio == false)
{
ChangementVolume += gestionnaireMusique.ChangementVolume;
ChangementVolume += gestionnaireSon.ChangementVolume;
ChangementVolume(Game1.chargeurOption.OptionActive.InformationSonore, EventArgs.Empty);
initierAudio = true;
}
}
/// <summary>
/// Constructeur de base pour la classe MenuOption
/// </summary>
/// <param name="game"></param>
public MenuOptions(Game game)
: base(game)
{
prochainEtat = EtatJeu.Options;
OptionJeu = Game1.chargeurOption.OptionActive;
}
/// <summary>
/// Chargement des textures du menu option
/// </summary>
protected override void LoadContent()
{
//Lettrage
lettrage = Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\lettrageOption");
police = Game.Content.Load<SpriteFont>(@"Police\ComicSan");
//Sliders
sliderEffet = new Slider(Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\ArrierePlanSlider"), new Vector2(900, 225),
Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\BarreSlider"),
Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\btnSlider"),
(float)OptionJeu.InformationSonore.EffetSonore / 100);
sliderMusique = new Slider(Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\ArrierePlanSlider"), new Vector2(900, 325),
Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\BarreSlider"),
Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\btnSlider"),
(float)OptionJeu.InformationSonore.Musique / 100);
//Bouton menus
btnValider = new Bouton(Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\btnValider"), new Vector2(1175, 600), null);
btnValider.Clic += new EventHandler(btnValider_Clic);
btnDefaut = new Bouton(Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\btnDefaut"), new Vector2(1175, 700), null);
btnDefaut.Clic += new EventHandler(btnDefaut_Clic);
btnAnnuler = new Bouton(Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\btnAnnuler"), new Vector2(1175, 800), null);
btnAnnuler.Clic += new EventHandler(btnAnnuler_Clic);
//Bouton Configuration
btnGauche = new BoutonClicEtEcris(Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\btnClickNTypeGauche"), new Vector2(226, 500),
null, OptionJeu.InformationTouche.Gauche, police);
btnGauche.Clic += new EventHandler(btnConfigTouche_Clic);
btnDroite = new BoutonClicEtEcris(Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\btnClickNTypeDroite"), new Vector2(655, 500),
null, OptionJeu.InformationTouche.Droite, police);
btnDroite.Clic += new EventHandler(btnConfigTouche_Clic);
btnSaut = new BoutonClicEtEcris(Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\btnClickNTypeSaut"), new Vector2(226, 574),
null, OptionJeu.InformationTouche.Saut, police);
btnSaut.Clic += new EventHandler(btnConfigTouche_Clic);
btnTir = new BoutonClicEtEcris(Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\btnClickNTypeTir"), new Vector2(655, 574),
null, OptionJeu.InformationTouche.Tir, police);
btnTir.Clic += new EventHandler(btnConfigTouche_Clic);
btnPause = new BoutonClicEtEcris(Game.Content.Load<Texture2D>(@"Ressources\Menus\Options\btnClickNTypePause"), new Vector2(226, 648),
null, OptionJeu.InformationTouche.Pause, police);
btnPause.Clic += new EventHandler(btnConfigTouche_Clic);
base.LoadContent();
}
//Évênement pour les boutons de configuration
void btnConfigTouche_Clic(object sender, EventArgs e)
{
if (!enAttente)
{
BoutonClicEtEcris boutonTouche = sender as BoutonClicEtEcris;
if (boutonTouche != null)
{
enAttente = true;
boutonEnAttente = boutonTouche;
boutonTouche.EcouteTouche += new EventInput.KeyEventHandler(EventInput_KeyDown);
EventInput.EventInput.KeyDown += new EventInput.KeyEventHandler(EventInput_KeyDown);
}
}
}
//
void EventInput_KeyDown(object sender, EventInput.KeyEventArgs e)
{
boutonEnAttente.Touche = e.KeyCode;
boutonEnAttente.EcouteTouche -= new EventInput.KeyEventHandler(EventInput_KeyDown);
EventInput.EventInput.KeyDown -= new EventInput.KeyEventHandler(EventInput_KeyDown);
boutonEnAttente = null;
enAttente = false;
}
//Évênement bouton valider
void btnValider_Clic(object sender, EventArgs e)
{
Enregistrement(); //Teste pour enregistrer les nouveaux paramètres dans les fichiers
prochainEtat = EtatJeu.Accueil;
}
//Évênement bouton pour mettre les options par défaut
void btnDefaut_Clic(object sender, EventArgs e)
{
RetourDefaut();
}
//Annule les changment fait aux sliders et aux boutons de configurations
void btnAnnuler_Clic(object sender, EventArgs e)
{
sliderEffet.DeplacementPourcentage((float)OptionJeu.InformationSonore.EffetSonore / 100);
sliderMusique.DeplacementPourcentage((float)OptionJeu.InformationSonore.Musique / 100);
btnDroite.Touche = Game1.chargeurOption.OptionActive.InformationTouche.Droite;
btnGauche.Touche = Game1.chargeurOption.OptionActive.InformationTouche.Gauche;
btnPause.Touche = Game1.chargeurOption.OptionActive.InformationTouche.Pause;
btnSaut.Touche = Game1.chargeurOption.OptionActive.InformationTouche.Saut;
btnTir.Touche = Game1.chargeurOption.OptionActive.InformationTouche.Tir;
prochainEtat = EtatJeu.Accueil;
}
/// <summary>
/// Mise à jour des éléments du menu option
/// </summary>
/// <param name="gameTime"></param>
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
//Sliders
sliderEffet.Deplacement();
sliderMusique.Deplacement();
//Options
OptionJeu.InformationSonore.EffetSonore = sliderEffet.ObtenirPourcentage();
OptionJeu.InformationSonore.Musique = sliderMusique.ObtenirPourcentage();
//Boutons
btnValider.Update(null);
btnDefaut.Update(null);
btnAnnuler.Update(null);
//Boutons clics et ecris
btnGauche.Update(null);
btnDroite.Update(null);
btnSaut.Update(null);
btnTir.Update(null);
btnPause.Update(null);
}
public EtatJeu ObtenirEtat()
{
return prochainEtat;
}
public void RemiseAZeroEtat()
{
prochainEtat = EtatJeu.Options;
}
/// <summary>
/// Affichage des éléments du menu options
/// </summary>
/// <param name="gameTime"></param>
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, Resolution.getTransformationMatrix());
spriteBatch.Draw(lettrage, Vector2.Zero, Color.White);
sliderEffet.Draw(spriteBatch);
sliderMusique.Draw(spriteBatch);
btnValider.Draw(spriteBatch);
btnDefaut.Draw(spriteBatch);
btnAnnuler.Draw(spriteBatch);
btnGauche.Draw(spriteBatch);
btnDroite.Draw(spriteBatch);
btnSaut.Draw(spriteBatch);
btnTir.Draw(spriteBatch);
btnPause.Draw(spriteBatch);
spriteBatch.End();
}
/// <summary>
/// Enregistre les modifications faites par l'utilisateur dans un fichier xml
/// </summary>
private void Enregistrement()
{
OptionJeu.InformationSonore.EffetSonore = sliderEffet.ObtenirPourcentage();
OptionJeu.InformationSonore.Musique = sliderMusique.ObtenirPourcentage();
OptionJeu.InformationTouche.Droite = btnDroite.Touche;
OptionJeu.InformationTouche.Gauche = btnGauche.Touche;
OptionJeu.InformationTouche.Pause = btnPause.Touche;
OptionJeu.InformationTouche.Saut = btnSaut.Touche;
OptionJeu.InformationTouche.Tir = btnTir.Touche;
Game1.chargeurOption.EnregistrementUtilisateur(ref OptionJeu);
//ChangementVolume(Game1.chargeurOption.OptionActive.InformationSonore, EventArgs.Empty);
}
/// <summary>
/// Remet par défaut les options de l'utilsiateur
/// </summary>
private void RetourDefaut()
{
sliderEffet.DeplacementPourcentage((float)Game1.chargeurOption.OptionDefaut.InformationSonore.EffetSonore / 100);
sliderMusique.DeplacementPourcentage((float)Game1.chargeurOption.OptionDefaut.InformationSonore.Musique / 100);
btnDroite.Touche = Game1.chargeurOption.OptionDefaut.InformationTouche.Droite;
btnGauche.Touche = Game1.chargeurOption.OptionDefaut.InformationTouche.Gauche;
btnPause.Touche = Game1.chargeurOption.OptionDefaut.InformationTouche.Pause;
btnSaut.Touche = Game1.chargeurOption.OptionDefaut.InformationTouche.Saut;
btnTir.Touche = Game1.chargeurOption.OptionDefaut.InformationTouche.Tir;
}
}
}
| 43.444853 | 147 | 0.616654 | [
"BSD-3-Clause"
] | Tri125/BBTA_MonoGame | BBTA_MonoGame/BBTA_MonoGame/Classe/Menus/MenuOptions.cs | 11,834 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WinActiveTool
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 20.5 | 65 | 0.585366 | [
"MIT"
] | KangXieXK/FileUpLoadDownloadToSqlServer | WinActiveTool/Program.cs | 473 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Xunit;
using Xunit.Abstractions;
namespace Dotnet.CodeGen.Tests
{
public class PackAndUseTests : IDisposable
{
const string PACKAGE_NAME = "Dotnet.CodeGen";
const string COMMAND_NAME = "dotnet-codegen";
private readonly ITestOutputHelper _output;
private readonly string _tmpOutput;
private readonly string _solutionFolder;
public PackAndUseTests(ITestOutputHelper output)
{
_output = output;
_solutionFolder = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "../../../../.."));
_tmpOutput = Path.Combine(_solutionFolder, "_testsnugetpakage." + Path.GetRandomFileName());
}
public void Dispose()
{
if (Directory.Exists(_tmpOutput))
Directory.Delete(_tmpOutput, true);
UninstallTool(_output, _solutionFolder, _tmpOutput);
}
[Fact]
public void Should_pack_install_unistall()
{
ListTools(_output, _solutionFolder, _tmpOutput);
UninstallTool(_output, _solutionFolder, _tmpOutput);
PackTool(_output, _solutionFolder, _tmpOutput);
InstallTool(_output, _solutionFolder, _tmpOutput);
ListTools(_output, _solutionFolder, _tmpOutput);
}
[IgnoreOnLinuxFact]
public void Should_pack_install_tool_execute()
{
UninstallTool(_output, _solutionFolder, _tmpOutput);
PackTool(_output, _solutionFolder, _tmpOutput);
InstallTool(_output, _solutionFolder, _tmpOutput);
var outputPath = Path.GetRandomFileName();
try
{
using (var process = Process.Start(new ProcessStartInfo
{
FileName = COMMAND_NAME,
Arguments = $"\"./_samples/test1/schema.json\" \"./_samples/test1/template\" \"{outputPath}\"",
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
}))
{
process.WaitForExit();
_output.WriteLine(process.StandardOutput.ReadToEnd());
_output.WriteLine(process.StandardError.ReadToEnd());
if (process.ExitCode != 0)
throw new Exception($"Failed : '{process.StandardError.ReadToEnd()}'");
}
}
finally
{
if (Directory.Exists(outputPath))
Directory.Delete(outputPath, true);
}
}
internal static void InstallTool(ITestOutputHelper output, string solutionFolder, string folder)
{
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "dotnet",
Arguments = $"tool install -g {PACKAGE_NAME} --add-source {folder}",
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
WorkingDirectory = solutionFolder
}))
{
process.WaitForExit();
if (process.ExitCode != 0)
throw new Exception($"Failed : '{process.StandardError.ReadToEnd()}'");
}
}
internal static void ListTools(ITestOutputHelper output, string solutionFolder, string folder)
{
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "dotnet",
Arguments = $"tool list -g",
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
}))
{
process.WaitForExit();
if (process.ExitCode != 0)
throw new Exception($"Failed : '{process.StandardError.ReadToEnd()}'");
output.WriteLine($"Tools list : '\n{process.StandardOutput.ReadToEnd()}\n'");
}
}
internal static void UninstallTool(ITestOutputHelper output, string solutionFolder, string folder)
{
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "dotnet",
Arguments = $"tool uninstall -g {PACKAGE_NAME}",
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
WorkingDirectory = solutionFolder
}))
{
process.WaitForExit();
// Errors are ignored
}
}
internal static void PackTool(ITestOutputHelper output, string solutionFolder, string folder)
{
using (var process = Process.Start(new ProcessStartInfo
{
FileName = "dotnet",
Arguments = $"pack ./src/{PACKAGE_NAME}/{PACKAGE_NAME}.csproj --configuration Release --output {folder}",
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
WorkingDirectory = solutionFolder
}))
{
process.WaitForExit();
if (process.ExitCode != 0)
{
output.WriteLine($"{process.StandardOutput.ReadToEnd()}");
throw new Exception($"Failed : '{process.StandardError.ReadToEnd()}'");
}
}
}
}
}
| 36.762821 | 121 | 0.544725 | [
"Apache-2.0"
] | thomasraynal/dotnet-codegen | tests/Dotnet.CodeGen.Tests/PackAndUseTests.cs | 5,737 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Check2.Models;
namespace Check2.Controllers
{
[Authorize]
public class AccountController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Isso não conta falhas de login em relação ao bloqueio de conta
// Para permitir que falhas de senha acionem o bloqueio da conta, altere para shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Tentativa de login inválida.");
return View(model);
}
}
//
// GET: /Account/VerifyCode
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
{
// Exija que o usuário efetue login via nome de usuário/senha ou login externo
if (!await SignInManager.HasBeenVerifiedAsync())
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// O código a seguir protege de ataques de força bruta em relação aos códigos de dois fatores.
// Se um usuário inserir códigos incorretos para uma quantidade especificada de tempo, então a conta de usuário
// será bloqueado por um período especificado de tempo.
// Você pode configurar os ajustes de bloqueio da conta em IdentityConfig
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(model.ReturnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Código inválido.");
return View(model);
}
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// Para obter mais informações sobre como habilitar a confirmação da conta e redefinição de senha, visite https://go.microsoft.com/fwlink/?LinkID=320771
// Enviar um email com este link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirmar sua conta", "Confirme sua conta clicando <a href=\"" + callbackUrl + "\">aqui</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// Se chegamos até aqui e houver alguma falha, exiba novamente o formulário
return View(model);
}
//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(userId, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Não revelar que o usuário não existe ou não está confirmado
return View("ForgotPasswordConfirmation");
}
// Para obter mais informações sobre como habilitar a confirmação da conta e redefinição de senha, visite https://go.microsoft.com/fwlink/?LinkID=320771
// Enviar um email com este link
// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Redefinir senha", "Redefina sua senha, clicando <a href=\"" + callbackUrl + "\">aqui</a>");
// return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// Se chegamos até aqui e houver alguma falha, exiba novamente o formulário
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Não revelar que o usuário não existe
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation()
{
return View();
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Solicitar um redirecionamento para o provedor de logon externo
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/SendCode
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
{
var userId = await SignInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
// Gerar o token e enviá-lo
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
return View("Error");
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Faça logon do usuário com este provedor de logon externo se o usuário já tiver um logon
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// Se o usuário não tiver uma conta, solicite que o usuário crie uma conta
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Obter as informações sobre o usuário do provedor de logon externo
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
if (_signInManager != null)
{
_signInManager.Dispose();
_signInManager = null;
}
}
base.Dispose(disposing);
}
#region Auxiliares
// Usado para proteção XSRF ao adicionar logons externos
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
}
} | 37.045361 | 173 | 0.539712 | [
"MIT"
] | athena272/Mentoria | Controllers/AccountController.cs | 18,026 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Cdn.Inputs
{
/// <summary>
/// Defines the parameters for QueryString match conditions
/// </summary>
public sealed class QueryStringMatchConditionParametersArgs : Pulumi.ResourceArgs
{
[Input("matchValues")]
private InputList<string>? _matchValues;
/// <summary>
/// The match value for the condition of the delivery rule
/// </summary>
public InputList<string> MatchValues
{
get => _matchValues ?? (_matchValues = new InputList<string>());
set => _matchValues = value;
}
/// <summary>
/// Describes if this is negate condition or not
/// </summary>
[Input("negateCondition")]
public Input<bool>? NegateCondition { get; set; }
[Input("odataType", required: true)]
public Input<string> OdataType { get; set; } = null!;
/// <summary>
/// Describes operator to be matched
/// </summary>
[Input("operator", required: true)]
public InputUnion<string, Pulumi.AzureNative.Cdn.QueryStringOperator> Operator { get; set; } = null!;
[Input("transforms")]
private InputList<Union<string, Pulumi.AzureNative.Cdn.Transform>>? _transforms;
/// <summary>
/// List of transforms
/// </summary>
public InputList<Union<string, Pulumi.AzureNative.Cdn.Transform>> Transforms
{
get => _transforms ?? (_transforms = new InputList<Union<string, Pulumi.AzureNative.Cdn.Transform>>());
set => _transforms = value;
}
public QueryStringMatchConditionParametersArgs()
{
}
}
}
| 32.322581 | 115 | 0.616766 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Cdn/Inputs/QueryStringMatchConditionParametersArgs.cs | 2,004 | C# |
#pragma checksum "C:\Users\merve bilgiç\Source\Repos\merveBILGIC\KombniyApp\KombniyAppAccount\Views\Shared\_Layout.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "266a12e94271e40d223514d318f168a7fe2cde42"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__Layout), @"mvc.1.0.view", @"/Views/Shared/_Layout.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\merve bilgiç\Source\Repos\merveBILGIC\KombniyApp\KombniyAppAccount\Views\_ViewImports.cshtml"
using KombniyAppAccount;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\merve bilgiç\Source\Repos\merveBILGIC\KombniyApp\KombniyAppAccount\Views\_ViewImports.cshtml"
using KombniyApp.Core.Models;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\Users\merve bilgiç\Source\Repos\merveBILGIC\KombniyApp\KombniyAppAccount\Views\_ViewImports.cshtml"
using KombniyApp.Core.Manage;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "C:\Users\merve bilgiç\Source\Repos\merveBILGIC\KombniyApp\KombniyAppAccount\Views\_ViewImports.cshtml"
using KombniyApp.Core.Repository;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "C:\Users\merve bilgiç\Source\Repos\merveBILGIC\KombniyApp\KombniyAppAccount\Views\_ViewImports.cshtml"
using KombniyApp.Core.Services;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"266a12e94271e40d223514d318f168a7fe2cde42", @"/Views/Shared/_Layout.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"2b9e7b0206103215518dd409bfeed9c6fc2e46b9", @"/Views/_ViewImports.cshtml")]
public class Views_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("stylesheet"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/bootstrap/dist/css/bootstrap.min.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/css/site.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("nav-link text-dark"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-area", "", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Gallery", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Image", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Upload", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Styling", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Home", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery/dist/jquery.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_12 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_13 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/js/site.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
private global::Syncfusion.EJ2.ScriptRenderer __Syncfusion_EJ2_ScriptRenderer;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("<!DOCTYPE html>\r\n<html lang=\"en\">\r\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "266a12e94271e40d223514d318f168a7fe2cde429110", async() => {
WriteLiteral("\r\n <meta charset=\"utf-8\" />\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\r\n <title>");
#nullable restore
#line 6 "C:\Users\merve bilgiç\Source\Repos\merveBILGIC\KombniyApp\KombniyAppAccount\Views\Shared\_Layout.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
#nullable disable
WriteLiteral(" - KombniyApp</title>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "266a12e94271e40d223514d318f168a7fe2cde429778", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "266a12e94271e40d223514d318f168a7fe2cde4210956", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n <link rel=\"stylesheet\" href=\"https://cdn.syncfusion.com/ej2/material.css\"/>\r\n \r\n");
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "266a12e94271e40d223514d318f168a7fe2cde4212935", async() => {
WriteLiteral(@"
<header>
<nav class=""navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"">
<div class=""container"">
<a class=""navbar-brand"" >KombinyApp </a>
<button class=""navbar-toggler"" type=""button"" data-toggle=""collapse"" data-target="".navbar-collapse"" aria-controls=""navbarSupportedContent""
aria-expanded=""false"" aria-label=""Toggle navigation"">
<span class=""navbar-toggler-icon""></span>
</button>
<div class=""navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"">
<ul class=""navbar-nav flex-grow-1"">
<li class=""nav-item"">
");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "266a12e94271e40d223514d318f168a7fe2cde4213999", async() => {
WriteLiteral("Galeri");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_6.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </li>\r\n <li class=\"nav-item\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "266a12e94271e40d223514d318f168a7fe2cde4215840", async() => {
WriteLiteral("Fotoraf yükleme");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_7.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_8.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </li>\r\n <li class=\"nav-item\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "266a12e94271e40d223514d318f168a7fe2cde4217690", async() => {
WriteLiteral("Styling Paketleri");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_9.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_6.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </li>\r\n </ul>\r\n </div>\r\n </div>\r\n </nav>\r\n </header>\r\n <div class=\"container\">\r\n <main role=\"main\" class=\"pb-3\">\r\n ");
#nullable restore
#line 39 "C:\Users\merve bilgiç\Source\Repos\merveBILGIC\KombniyApp\KombniyAppAccount\Views\Shared\_Layout.cshtml"
Write(RenderBody());
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </main>\r\n </div>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("ejs-scripts", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "266a12e94271e40d223514d318f168a7fe2cde4219957", async() => {
}
);
__Syncfusion_EJ2_ScriptRenderer = CreateTagHelper<global::Syncfusion.EJ2.ScriptRenderer>();
__tagHelperExecutionContext.Add(__Syncfusion_EJ2_ScriptRenderer);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n\r\n <footer class=\"border-top footer text-muted\">\r\n <div class=\"container\">\r\n © 2020 - KombinyApp - ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "266a12e94271e40d223514d318f168a7fe2cde4221001", async() => {
WriteLiteral("ANA SAYFA");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_10.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_10);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_6.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n </footer>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "266a12e94271e40d223514d318f168a7fe2cde4222687", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_11);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "266a12e94271e40d223514d318f168a7fe2cde4223788", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_12);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "266a12e94271e40d223514d318f168a7fe2cde4224889", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_13.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_13);
#nullable restore
#line 51 "C:\Users\merve bilgiç\Source\Repos\merveBILGIC\KombniyApp\KombniyAppAccount\Views\Shared\_Layout.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true;
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
#nullable restore
#line 52 "C:\Users\merve bilgiç\Source\Repos\merveBILGIC\KombniyApp\KombniyAppAccount\Views\Shared\_Layout.cshtml"
Write(RenderSection("Scripts", required: false));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n\r\n\r\n");
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n</html>\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 79.955056 | 384 | 0.725583 | [
"MIT"
] | merveBILGIC/KombiniyApp | KombniyAppAccount/obj/Debug/netcoreapp3.1/Razor/Views/Shared/_Layout.cshtml.g.cs | 28,475 | C# |
namespace CarDealer.Web.Controllers
{
using CarDealer.Data.Models;
using CarDealer.Web.Models.AccountModels;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
[Authorize]
[Route("[controller]/[action]")]
public class AccountController : Controller
{
private readonly UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
private readonly ILogger _logger;
public AccountController(
UserManager<User> userManager,
SignInManager<User> signInManager,
ILogger<AccountController> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[TempData]
public string ErrorMessage { get; set; }
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToAction(nameof(Lockout));
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
return View(model);
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> LoginWith2fa(bool rememberMe, string returnUrl = null)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load two-factor authentication user.");
}
var model = new LoginWith2faModel { RememberMe = rememberMe };
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginWith2fa(LoginWith2faModel model, bool rememberMe, string returnUrl = null)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);
var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, model.RememberMachine);
if (result.Succeeded)
{
_logger.LogInformation("User with ID {UserId} logged in with 2fa.", user.Id);
return RedirectToLocal(returnUrl);
}
else if (result.IsLockedOut)
{
_logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
return RedirectToAction(nameof(Lockout));
}
else
{
_logger.LogWarning("Invalid authenticator code entered for user with ID {UserId}.", user.Id);
ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
return View();
}
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> LoginWithRecoveryCode(string returnUrl = null)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load two-factor authentication user.");
}
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginWithRecoveryCode(LoginWithRecoveryCodeModel model, string returnUrl = null)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new ApplicationException($"Unable to load two-factor authentication user.");
}
var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty);
var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);
if (result.Succeeded)
{
_logger.LogInformation("User with ID {UserId} logged in with a recovery code.", user.Id);
return RedirectToLocal(returnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
return RedirectToAction(nameof(Lockout));
}
else
{
_logger.LogWarning("Invalid recovery code entered for user with ID {UserId}", user.Id);
ModelState.AddModelError(string.Empty, "Invalid recovery code entered.");
return View();
}
}
[HttpGet]
[AllowAnonymous]
public IActionResult Lockout()
{
return View();
}
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new User { UserName = model.Username, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation("User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ErrorMessage = $"Error from external provider: {remoteError}";
return RedirectToAction(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.IsLockedOut)
{
return RedirectToAction(nameof(Lockout));
}
else
{
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLogin", new ExternalLoginModel { Email = email });
}
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
throw new ApplicationException("Error loading external login information during confirmation.");
}
var user = new User { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(nameof(ExternalLogin), model);
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{userId}'.");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
return RedirectToAction(nameof(ForgotPasswordConfirmation));
}
return View(model);
}
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
if (code == null)
{
throw new ApplicationException("A code must be supplied for password reset.");
}
var model = new ResetPasswordModel { Code = code };
return View(model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null)
{
return RedirectToAction(nameof(ResetPasswordConfirmation));
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(ResetPasswordConfirmation));
}
AddErrors(result);
return View();
}
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
[HttpGet]
public IActionResult AccessDenied()
{
return View();
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| 34.922374 | 153 | 0.555178 | [
"MIT"
] | ivanrk/CarDealerSystem | CarDealer.Web/Controllers/AccountController.cs | 15,298 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
/*
namespace project_api.Models
{
public class Taak
{
#region Properties
public int Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 5)]
public string Naam { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime TaakStartDatum { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime TaakEindDatum { get; set; }
[Required]
[StringLength(15, MinimumLength = 5)]
public string Categorie { get; set; }
[Required]
public string Prioriteit { get; set; }
[Required]
public string Status { get; set; }
#endregion
#region Constructors
public Taak() {
}
public Taak(string naam, DateTime taakStartDatum, DateTime taakEindDatum, string categorie, string prioriteit, string status)
{
Naam = naam;
TaakStartDatum = taakStartDatum;
TaakEindDatum = taakEindDatum;
Categorie = categorie;
Prioriteit = prioriteit;
Status = status;
}
#endregion
}
}
*/ | 25.173077 | 133 | 0.588235 | [
"MIT"
] | christofremeysen-git/mobile-application-development-android | project-api/Models/Taak.cs | 1,309 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.NetApp
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PoolsOperations operations.
/// </summary>
internal partial class PoolsOperations : IServiceOperations<AzureNetAppFilesManagementClient>, IPoolsOperations
{
/// <summary>
/// Initializes a new instance of the PoolsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PoolsOperations(AzureNetAppFilesManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AzureNetAppFilesManagementClient
/// </summary>
public AzureNetAppFilesManagementClient Client { get; private set; }
/// <summary>
/// Describe all Capacity Pools
/// </summary>
/// <remarks>
/// List all capacity pools in the NetApp Account
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the NetApp account
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<CapacityPool>>> ListWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ApiVersion != null)
{
if (Client.ApiVersion.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1);
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<CapacityPool>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<CapacityPool>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Describe a Capacity Pool
/// </summary>
/// <remarks>
/// Get details of the specified capacity pool
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the NetApp account
/// </param>
/// <param name='poolName'>
/// The name of the capacity pool
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<CapacityPool>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string poolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (poolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "poolName");
}
if (poolName != null)
{
if (poolName.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "poolName", 64);
}
if (poolName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "poolName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(poolName, "^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,63}$"))
{
throw new ValidationException(ValidationRules.Pattern, "poolName", "^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,63}$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ApiVersion != null)
{
if (Client.ApiVersion.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1);
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("poolName", poolName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{poolName}", System.Uri.EscapeDataString(poolName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<CapacityPool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<CapacityPool>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or Update the specified capacity pool within the resource group
/// </summary>
/// <remarks>
/// Create or Update a capacity pool
/// </remarks>
/// <param name='body'>
/// Capacity pool object supplied in the body of the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the NetApp account
/// </param>
/// <param name='poolName'>
/// The name of the capacity pool
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<CapacityPool>> CreateOrUpdateWithHttpMessagesAsync(CapacityPool body, string resourceGroupName, string accountName, string poolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<CapacityPool> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(body, resourceGroupName, accountName, poolName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Update a capacity pool
/// </summary>
/// <remarks>
/// Patch the specified capacity pool
/// </remarks>
/// <param name='body'>
/// Capacity pool object supplied in the body of the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the NetApp account
/// </param>
/// <param name='poolName'>
/// The name of the capacity pool
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<CapacityPool>> UpdateWithHttpMessagesAsync(CapacityPoolPatch body, string resourceGroupName, string accountName, string poolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<CapacityPool> _response = await BeginUpdateWithHttpMessagesAsync(body, resourceGroupName, accountName, poolName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete a capacity pool
/// </summary>
/// <remarks>
/// Delete the specified capacity pool
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the NetApp account
/// </param>
/// <param name='poolName'>
/// The name of the capacity pool
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string poolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, accountName, poolName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Create or Update the specified capacity pool within the resource group
/// </summary>
/// <remarks>
/// Create or Update a capacity pool
/// </remarks>
/// <param name='body'>
/// Capacity pool object supplied in the body of the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the NetApp account
/// </param>
/// <param name='poolName'>
/// The name of the capacity pool
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<CapacityPool>> BeginCreateOrUpdateWithHttpMessagesAsync(CapacityPool body, string resourceGroupName, string accountName, string poolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
if (body != null)
{
body.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (poolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "poolName");
}
if (poolName != null)
{
if (poolName.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "poolName", 64);
}
if (poolName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "poolName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(poolName, "^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,63}$"))
{
throw new ValidationException(ValidationRules.Pattern, "poolName", "^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,63}$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ApiVersion != null)
{
if (Client.ApiVersion.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1);
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("poolName", poolName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{poolName}", System.Uri.EscapeDataString(poolName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<CapacityPool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<CapacityPool>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<CapacityPool>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Update a capacity pool
/// </summary>
/// <remarks>
/// Patch the specified capacity pool
/// </remarks>
/// <param name='body'>
/// Capacity pool object supplied in the body of the operation.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the NetApp account
/// </param>
/// <param name='poolName'>
/// The name of the capacity pool
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<CapacityPool>> BeginUpdateWithHttpMessagesAsync(CapacityPoolPatch body, string resourceGroupName, string accountName, string poolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (poolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "poolName");
}
if (poolName != null)
{
if (poolName.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "poolName", 64);
}
if (poolName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "poolName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(poolName, "^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,63}$"))
{
throw new ValidationException(ValidationRules.Pattern, "poolName", "^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,63}$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ApiVersion != null)
{
if (Client.ApiVersion.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1);
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("poolName", poolName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{poolName}", System.Uri.EscapeDataString(poolName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<CapacityPool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<CapacityPool>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete a capacity pool
/// </summary>
/// <remarks>
/// Delete the specified capacity pool
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='accountName'>
/// The name of the NetApp account
/// </param>
/// <param name='poolName'>
/// The name of the capacity pool
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string poolName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (resourceGroupName != null)
{
if (resourceGroupName.Length > 90)
{
throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90);
}
if (resourceGroupName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$");
}
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (poolName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "poolName");
}
if (poolName != null)
{
if (poolName.Length > 64)
{
throw new ValidationException(ValidationRules.MaxLength, "poolName", 64);
}
if (poolName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "poolName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(poolName, "^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,63}$"))
{
throw new ValidationException(ValidationRules.Pattern, "poolName", "^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,63}$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ApiVersion != null)
{
if (Client.ApiVersion.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1);
}
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("poolName", poolName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{poolName}", System.Uri.EscapeDataString(poolName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Describe all Capacity Pools
/// </summary>
/// <remarks>
/// List all capacity pools in the NetApp Account
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<CapacityPool>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<CapacityPool>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<CapacityPool>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 45.872985 | 307 | 0.553753 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/netapp/Microsoft.Azure.Management.NetApp/src/Generated/PoolsOperations.cs | 71,149 | C# |
using GDAPI.Objects.DataStructures;
using System;
namespace GDAPI.Objects.Reflection
{
/// <summary>Represents a dictionary of <seealso cref="FirstWideCachedTypeInfo{TTypeKey, TPropertyKey}"/> objects.</summary>
/// <typeparam name="TTypeKey">The type of the key that the type returns.</typeparam>
/// <typeparam name="TPropertyKey">The type of the key that the type's properties return.</typeparam>
public class CachedTypeInfoDictionary<TTypeKey, TPropertyKey> : DoubleKeyedObjectDictionary<TTypeKey, Type, FirstWideCachedTypeInfo<TTypeKey, TPropertyKey>>
{
/// <summary>Initializes a new instance of the <seealso cref="CachedTypeInfoDictionary{TTypeKey, TPropertyKey}"/> class.</summary>
public CachedTypeInfoDictionary() : base() { }
/// <summary>Initializes a new instance of the <seealso cref="CachedTypeInfoDictionary{TTypeKey, TPropertyKey}"/> class.</summary>
/// <param name="d">The dictionary to initialize this dictionary out of.</param>
public CachedTypeInfoDictionary(CachedTypeInfoDictionary<TTypeKey, TPropertyKey> d) : base(d) { }
// TODO: Add more constructors if necessary
}
}
| 61.526316 | 160 | 0.734816 | [
"MIT"
] | AlFasGD/GDAPI | GDAPI/GDAPI/Objects/Reflection/CachedTypeInfoDictionary.cs | 1,171 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using Eto.Forms;
using Quartz.Util;
using Serilog.Core;
using SteamKit2;
using SteamKit2.GC;
using SteamKit2.GC.CSGO.Internal;
using SteamKit2.GC.TF2.Internal;
using SteamKit2.Internal;
using Titan.Json;
using Titan.Logging;
using Titan.MatchID.Live;
using Titan.Sentry;
using Titan.UI;
using Titan.UI._2FA;
using Titan.Util;
namespace Titan.Account.Impl
{
public class ProtectedAccount : TitanAccount
{
private Logger _log;
private int _reconnects;
private SteamConfiguration _steamConfig;
private Sentry.Sentry _sentry;
private SharedSecret _sharedSecretGenerator;
private string _authCode;
private string _2FactorCode;
private LoginKey _loginKey;
private SteamClient _steamClient;
private SteamUser _steamUser;
private SteamFriends _steamFriends;
private SteamGameCoordinator _gameCoordinator;
private CallbackManager _callbacks;
private TitanHandler _titanHandle;
private PrimitiveFreeGamesRequestHandler _freeGamesHandler;
public Result Result { get; private set; } = Result.Unknown;
public ProtectedAccount(JsonAccounts.JsonAccount json) : base(json)
{
_log = LogCreator.Create("GC - " + json.Username + (!Titan.Instance.Options.Secure ? " (Protected)" : ""));
_steamConfig = SteamConfiguration.Create(builder =>
{
builder.WithConnectionTimeout(TimeSpan.FromMinutes(1));
var key = Titan.Instance.WebHandle.GetKey();
if (!string.IsNullOrEmpty(key))
{
builder.WithWebAPIKey(key);
_log.Debug("Initializing with preloaded API key.");
}
else
{
_log.Debug("Initializing without API key.");
}
});
_sentry = new Sentry.Sentry(this);
_loginKey = new LoginKey(this);
_steamClient = new SteamClient(_steamConfig);
_callbacks = new CallbackManager(_steamClient);
_steamUser = _steamClient.GetHandler<SteamUser>();
_steamFriends = _steamClient.GetHandler<SteamFriends>();
_gameCoordinator = _steamClient.GetHandler<SteamGameCoordinator>();
// This clause excludes SteamKit debug mode as that mode is handeled seperately.
// Normal debug mode doesn't equal SteamKit debug mode.
if (Titan.Instance.Options.Debug)
{
_titanHandle = new TitanHandler();
_steamClient.AddHandler(_titanHandle);
// Initialize debug network sniffer when debug mode is enabled
var dir = new DirectoryInfo(Path.Combine(Titan.Instance.DebugDirectory.ToString(), json.Username));
if (!dir.Exists)
{
dir.Create();
}
_steamClient.DebugNetworkListener = new NetHookNetworkListener(
dir.ToString()
);
}
if (!string.IsNullOrWhiteSpace(JsonAccount.SharedSecret))
{
_sharedSecretGenerator = new SharedSecret(this);
}
_log.Debug("Successfully initialized account object for " + json.Username + ".");
}
public override Result Start()
{
Thread.CurrentThread.Name = JsonAccount.Username + " - " + (_reportInfo != null ? "Report" : "Commend");
_freeGamesHandler = new PrimitiveFreeGamesRequestHandler(OnFreeLicenseResponse);
_steamClient.AddHandler(_freeGamesHandler);
_callbacks.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
_callbacks.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
_callbacks.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
_callbacks.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
_callbacks.Subscribe<SteamGameCoordinator.MessageCallback>(OnGCMessage);
_callbacks.Subscribe<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth);
_callbacks.Subscribe<SteamUser.LoginKeyCallback>(OnNewLoginKey);
IsRunning = true;
_steamClient.Connect();
while (IsRunning)
{
_callbacks.RunWaitAllCallbacks(TimeSpan.FromMilliseconds(500));
}
return Result;
}
public override void Stop()
{
_reportInfo = null;
_commendInfo = null;
_liveGameInfo = null;
if (_steamFriends.GetPersonaState() != EPersonaState.Offline)
{
_steamFriends.SetPersonaState(EPersonaState.Offline);
}
if (_steamUser.SteamID != null)
{
_steamUser.LogOff();
}
if (_steamClient.IsConnected)
{
_steamClient.Disconnect();
}
IsRunning = false;
Titan.Instance.ThreadManager.FinishBotting(this);
}
////////////////////////////////////////////////////
// STEAM WEB INTERFACE
////////////////////////////////////////////////////
public override async void LoginWebInterface(ulong steamID)
{
if (!IsAuthenticated)
{
SteamUser.WebAPIUserNonceCallback callback;
try
{
callback = await _steamUser.RequestWebAPIUserNonce();
}
catch (Exception ex)
{
_log.Error(ex, "Unable to request Web API Nonce. Titan won't be able to execute Web API actions.");
return;
}
if (string.IsNullOrWhiteSpace(callback?.Nonce))
{
_log.Error("Received empty Web API Nonce. Titan won't be able to execute Web API actions.");
return;
}
var sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString()));
var sessionKey = CryptoHelper.GenerateRandomBlock(32);
byte[] cryptedSessionKey;
using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(_steamClient.Universe)))
{
cryptedSessionKey = rsa.Encrypt(sessionKey);
}
var loginKey = new byte[callback.Nonce.Length];
Array.Copy(Encoding.ASCII.GetBytes(callback.Nonce), loginKey, callback.Nonce.Length);
// AES encrypt the login key with our session key
var cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);
if (!Titan.Instance.WebHandle.AuthentificateUser(
steamID, cryptedLoginKey, cryptedSessionKey, out var result
))
{
_log.Error("Failed to authentificate with Web API Nonce. " +
"Titan won't be able to execute Web API actions.");
return;
}
var token = result["token"].Value;
var secureToken = result["tokensecure"].Value;
if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(secureToken))
{
_log.Error("Failed to authentificate with Web API Nonce. " +
"Titan won't be able to execute Web API actions.");
return;
}
Cookies.Add("sessionid", sessionID);
Cookies.Add("steamLogin", token);
Cookies.Add("steamLoginSecure", secureToken);
if (!Titan.Instance.Options.Secure)
{
_log.Debug("Authorized with Steam Web API. Session ID: {id}", sessionID);
}
_log.Information("Successfully authorized with Steam Web API.");
IsAuthenticated = true;
}
}
public override async void JoinSteamGroup(uint groupID = 28495194)
{
if (IsAuthenticated)
{
var headers = new Dictionary<string, string>
{
{ "sessionID", Cookies.TryGetAndReturn("sessionid") },
{ "action", "join" }
};
var response = await Titan.Instance.HttpClient.PostAsync(
"https://steamcommunity.com/gid/" + groupID, new FormUrlEncodedContent(headers)
);
_log.Debug(await response.Content.ReadAsStringAsync());
}
}
////////////////////////////////////////////////////
// CALLBACKS
////////////////////////////////////////////////////
public override void OnConnected(SteamClient.ConnectedCallback callback)
{
_log.Debug("Successfully connected to Steam. Logging in...");
byte[] hash = null;
if (_sentry.Exists())
{
_log.Debug("Found previous Sentry file. Hashing it and sending it to Steam...");
hash = _sentry.Hash();
}
else
{
_log.Debug("No Sentry file found. Titan will ask for a confirmation code...");
}
var loginID = RandomUtil.RandomUInt32();
string loginKey = null;
if (_loginKey.Exists())
{
loginKey = _loginKey.GetLastKey();
}
if (!Titan.Instance.Options.Secure)
{
_log.Debug("Logging in with Auth Code: {a} / 2FA Code {b} / Hash: {c} / LoginID: {d} / LoginKey: {e}",
_authCode, _2FactorCode, hash != null ? Convert.ToBase64String(hash) : null, loginID, loginKey);
}
_steamUser.LogOn(new SteamUser.LogOnDetails
{
Username = JsonAccount.Username,
Password = loginKey == null ? JsonAccount.Password : null,
AuthCode = _authCode,
TwoFactorCode = _2FactorCode,
SentryFileHash = hash,
LoginID = loginID,
ShouldRememberPassword = true,
LoginKey = loginKey
});
}
public override void OnDisconnected(SteamClient.DisconnectedCallback callback)
{
_reconnects++;
if (_reconnects <= 5 && !callback.UserInitiated &&
(Result != Result.Success && Result != Result.AlreadyLoggedInSomewhereElse || IsRunning))
{
_log.Debug("Disconnected from Steam. Retrying in 5 seconds... ({Count}/5)", _reconnects);
Thread.Sleep(TimeSpan.FromSeconds(5));
_steamClient.Connect();
}
else
{
_log.Debug("Successfully disconnected from Steam.");
IsRunning = false;
}
}
public override void OnLoggedOn(SteamUser.LoggedOnCallback callback)
{
switch (callback.Result)
{
case EResult.OK:
_log.Debug("Successfully logged in. Requesting license for {id}...", GetAppID());
_steamFriends.SetPersonaState(EPersonaState.Online);
/*if (!Titan.Instance.Options.NoSteamGroup)
{
LoginWebInterface(callback.ClientSteamID);
JoinSteamGroup(); // https://steamcommunity.com/groups/TitanReportBot
return;
}*/
var requestLicense = new ClientMsgProtobuf<CMsgClientRequestFreeLicense>(EMsg.ClientRequestFreeLicense);
requestLicense.Body.appids.Add(GetAppID());
_steamClient.Send(requestLicense);
break;
case EResult.AccountLoginDeniedNeedTwoFactor:
if (!string.IsNullOrWhiteSpace(JsonAccount.SharedSecret))
{
_log.Debug("A shared secret has been provided: automatically generating it...");
_2FactorCode = _sharedSecretGenerator.GenerateCode();
}
else
{
_log.Information("Opening UI form to get the 2FA Steam Guard App Code...");
Application.Instance.Invoke(() => Titan.Instance.UIManager.ShowForm(
UIType.TwoFactorAuthentification, new _2FAForm(this)
));
while (string.IsNullOrEmpty(_2FactorCode))
{
/* Wait until we receive the Steam Guard code from the UI */
}
}
if (!Titan.Instance.Options.Secure)
{
_log.Information("Received 2FA Code: {Code}", _2FactorCode);
}
break;
case EResult.AccountLogonDenied:
_log.Information("Opening UI form to get the Auth Token from EMail...");
Application.Instance.Invoke(() => Titan.Instance.UIManager.ShowForm(
UIType.TwoFactorAuthentification, new _2FAForm(this, callback.EmailDomain)
));
while (string.IsNullOrEmpty(_authCode))
{
/* Wait until we receive the Auth Token from the UI */
}
if (!Titan.Instance.Options.Secure)
{
_log.Information("Received Auth Token: {Code}", _authCode);
}
break;
case EResult.ServiceUnavailable:
_log.Error("Steam is currently offline. Please try again later.");
Stop();
break;
case EResult.RateLimitExceeded:
_log.Error("Steam Rate Limit has been reached. Please try it again in a few minutes...");
Result = Result.RateLimit;
Stop();
break;
case EResult.TwoFactorCodeMismatch:
case EResult.TwoFactorActivationCodeMismatch:
case EResult.Invalid:
_log.Error("Invalid Steam Guard code provided. Reasking after reconnecting.");
_authCode = null;
_2FactorCode = null;
break;
default:
_log.Error("Unable to logon to account: {Result}: {ExtendedResult}", callback.Result, callback.ExtendedResult);
Stop();
break;
}
}
public override void OnLoggedOff(SteamUser.LoggedOffCallback callback)
{
if (callback.Result == EResult.LoggedInElsewhere || callback.Result == EResult.AlreadyLoggedInElsewhere)
{
Result = Result.AlreadyLoggedInSomewhereElse;
}
if (Result == Result.AlreadyLoggedInSomewhereElse)
{
_log.Warning("Account is already logged on somewhere else. Skipping...");
}
else
{
_log.Debug("Successfully logged off from Steam: {Result}", callback.Result);
}
}
public void OnMachineAuth(SteamUser.UpdateMachineAuthCallback callback)
{
_log.Debug("Updating Steam sentry file...");
if (_sentry.Save(callback.Offset, callback.Data, callback.BytesToWrite, out var hash, out var size))
{
_steamUser.SendMachineAuthResponse(new SteamUser.MachineAuthDetails
{
JobID = callback.JobID,
FileName = callback.FileName,
BytesWritten = callback.BytesToWrite,
FileSize = size,
Offset = callback.Offset,
Result = EResult.OK,
LastError = 0,
OneTimePassword = callback.OneTimePassword,
SentryFileHash = hash
});
_log.Information("Successfully updated Steam sentry file.");
}
else
{
_log.Error("Could not save sentry file. Titan will ask again for Steam Guard code on next attempt.");
}
}
public void OnNewLoginKey(SteamUser.LoginKeyCallback callback)
{
if (!Titan.Instance.Options.Secure)
{
_log.Debug("Received new login key: {key}", callback.LoginKey);
}
_loginKey.Save(callback.LoginKey);
_steamUser.AcceptNewLoginKey(callback);
}
public override void OnFreeLicenseResponse(ClientMsgProtobuf<CMsgClientRequestFreeLicenseResponse> payload)
{
if (!payload.Body.granted_appids.Contains(GetAppID()))
{
// We already own it, let's continue
}
_log.Debug("Successfully acquired license for app. Starting game...");
var playGames = new ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed);
playGames.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed
{
game_id = GetAppID()
});
_steamClient.Send(playGames);
Thread.Sleep(TimeSpan.FromSeconds(2));
_log.Debug("Successfully registered app {game}. Sending client hello to gc services.", GetAppID());
switch (GetAppID())
{
case CSGO_APPID:
{
var clientHello = new ClientGCMsgProtobuf<SteamKit2.GC.CSGO.Internal.CMsgClientHello>(
(uint) SteamKit2.GC.CSGO.Internal.EGCBaseClientMsg.k_EMsgGCClientHello
);
_gameCoordinator.Send(clientHello, GetAppID());
break;
}
case TF2_APPID:
{
var clientInit = new ClientGCMsgProtobuf<CMsgTFClientInit>(
(uint) ETFGCMsg.k_EMsgGC_TFClientInit
)
{
Body =
{
client_version = 4478108, // up2date as of 17th may 2018
client_versionSpecified = true,
language = 0, // We are english
languageSpecified = true
}
};
_gameCoordinator.Send(clientInit, GetAppID());
var clientHello = new ClientGCMsgProtobuf<SteamKit2.GC.TF2.Internal.CMsgClientHello>(
(uint) SteamKit2.GC.TF2.Internal.EGCBaseClientMsg.k_EMsgGCClientHello
);
_gameCoordinator.Send(clientHello, GetAppID());
break;
}
}
}
public override void OnClientWelcome(IPacketGCMsg msg)
{
switch (GetAppID())
{
case CSGO_APPID:
{
var welcome = new ClientGCMsgProtobuf<SteamKit2.GC.CSGO.Internal.CMsgClientWelcome>(msg);
_log.Debug("Received welcome from CS:GO GC version {v} (Connected to {loc}). " +
"Sending hello the CS:GO's matchmaking service.",
welcome.Body.version, welcome.Body.location.country);
var mmHello = new ClientGCMsgProtobuf<CMsgGCCStrike15_v2_MatchmakingClient2GCHello>(
(uint) ECsgoGCMsg.k_EMsgGCCStrike15_v2_MatchmakingClient2GCHello
);
_gameCoordinator.Send(mmHello, GetAppID());
break;
}
case TF2_APPID:
{
var welcome = new ClientGCMsgProtobuf<SteamKit2.GC.TF2.Internal.CMsgClientWelcome>(msg);
_log.Debug("Received welcome from TF2 GC version {v}. Sending report...",
welcome.Body.version);
_gameCoordinator.Send(GetReportPayload(), GetAppID());
break;
}
}
}
public override void OnMatchmakingHelloResponse(IPacketGCMsg msg)
{
var response = new ClientGCMsgProtobuf<CMsgGCCStrike15_v2_MatchmakingGC2ClientHello>(msg);
if (response.Body.penalty_reasonSpecified)
{
Cooldown cooldown = response.Body.penalty_reason;
_log.Error("This account has received a {type} cooldown: {reason}",
cooldown.Permanent ? "global" : "temporary", cooldown.Reason);
if (cooldown.Permanent)
{
_log.Error("This ban is permanent. Botting with banned accounts is not possible.");
}
else
{
var penalty = TimeSpan.FromSeconds(response.Body.penalty_seconds);
var time = penalty.Minutes >= 60 ? penalty.Hours + " Hours" : penalty.Minutes + " Minutes";
_log.Error("This ban will end in {end}. Botting with banned accounts is not possible.", time);
}
Result = Result.AccountBanned;
Stop();
return;
}
// When the CS:GO GC sends a vac_banned (type 2) but not a penalty_reason (type 0)
// the account has received a yellow "This account has been banned by Overwatch"
// banner in-game and has no longer the ability to report or commend.
if (response.Body.vac_bannedSpecified && !response.Body.penalty_reasonSpecified &&
response.Body.vac_banned == 2 && !response.Body.penalty_secondsSpecified)
{
_log.Error("This account has been banned by Valve Anti Cheat. Botting with banned " +
"accounts is not possible.");
Result = Result.AccountBanned;
Stop();
return;
}
var type = _liveGameInfo != null ? "Live Game Request" : (_reportInfo != null ? "Report" : "Commend");
_log.Debug("Received hello from CS:GO matchmaking services. Authenticated as {id}. Sending {type}.",
response.Body.account_id, type);
if (_liveGameInfo != null)
{
_gameCoordinator.Send(GetLiveGamePayload(), GetAppID());
}
else if (_reportInfo != null)
{
if (_reportInfo.GameServerID != 0)
{
_log.Debug("Additional game server ID provided, registering with Steam...");
_gameCoordinator.Send(GetClientGamesPlayedPayload(), GetAppID());
Thread.Sleep(TimeSpan.FromSeconds(2));
_log.Debug("Successfully registered playing on server. Sending report...");
}
_gameCoordinator.Send(GetReportPayload(), GetAppID());
}
else
{
_gameCoordinator.Send(GetCommendPayload(), GetAppID());
}
}
public override void OnReportResponse(IPacketGCMsg msg)
{
switch (GetAppID())
{
case CSGO_APPID:
{
var response = new ClientGCMsgProtobuf<CMsgGCCStrike15_v2_ClientReportResponse>(msg);
if (_reportInfo != null)
{
_log.Information("Successfully reported. Confirmation ID: {ID}", response.Body.confirmation_id);
}
else
{
_log.Information("Successfully commended {Target} with {Pretty}.",
_commendInfo.SteamID.ConvertToUInt64(), _commendInfo.ToPrettyString());
}
break;
}
case TF2_APPID:
{
var response = new ClientGCMsgProtobuf<SteamKit2.GC.TF2.Internal.CMsgGCReportAbuseResponse>(msg);
if (!response.Body.error_messageSpecified)
{
_log.Information("Successfully reported {target}. Received result: {result}",
response.Body.target_steam_id, response.Body.result);
}
else
{
_log.Error("Failed to report target. Received result {result} with error {msg}.",
response.Body.result, response.Body.error_message);
Result = Result.TimedOut;
Stop();
return;
}
break;
}
}
Result = Result.Success;
Stop();
}
public override void OnCommendResponse(IPacketGCMsg msg)
{
_log.Information("Successfully commended target {Target} with {Pretty}.",
_commendInfo.SteamID.ConvertToUInt64(), _commendInfo.ToPrettyString());
Result = Result.Success;
Stop();
}
public override void OnLiveGameRequestResponse(IPacketGCMsg msg)
{
var response = new ClientGCMsgProtobuf<CMsgGCCStrike15_v2_MatchList>(msg);
if (response.Body.matches.Count >= 1)
{
var matchInfos = response.Body.matches.Select(match => new MatchInfo
{
MatchID = match.matchid,
MatchTime = match.matchtime,
WatchableMatchInfo = match.watchablematchinfo,
RoundsStats = match.roundstatsall
}
).ToList();
MatchInfo = matchInfos[0]; // TODO: Maybe change this into a better than meme than just using the 0 index
_log.Information("Received live game Match ID: {MatchID}", MatchInfo.MatchID);
Result = Result.Success;
}
else
{
MatchInfo = new MatchInfo
{
MatchID = 8,
MatchTime = 0,
WatchableMatchInfo = null,
RoundsStats = null
};
Result = Result.NoMatches;
}
Stop();
}
public void FeedWithAuthToken(string authToken)
{
_authCode = authToken;
}
public void FeedWith2FACode(string twofactorCode)
{
_2FactorCode = twofactorCode;
}
public override uint GetReporterAccountID()
{
return _steamClient.SteamID.AccountID;
}
}
}
| 37.893817 | 131 | 0.507325 | [
"MIT"
] | Marc3842h/Titan | Titan/Account/Impl/ProtectedAccount.cs | 28,195 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.