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 ALE.ETLBox; using ALE.ETLBox.ConnectionManager; using ALE.ETLBox.ControlFlow; using ALE.ETLBox.DataFlow; using ALE.ETLBox.Helper; using ALE.ETLBox.Logging; using ALE.ETLBoxTests.Fixtures; using System; using System.Collections.Generic; using Xunit; namespace ALE.ETLBoxTests.DataFlowTests { [Collection("DataFlow")] public class DbSourceTableDefinitionTests { public static IEnumerable<object[]> Connections => Config.AllSqlConnections("DataFlow"); public DbSourceTableDefinitionTests(DataFlowDatabaseFixture dbFixture) { } public class MySimpleRow { public long Col1 { get; set; } public string Col2 { get; set; } } [Theory, MemberData(nameof(Connections))] public void WithTableDefinition(IConnectionManager connection) { //Arrange TwoColumnsTableFixture source2Columns = new TwoColumnsTableFixture(connection, "Source"); source2Columns.InsertTestData(); TwoColumnsTableFixture dest2Columns = new TwoColumnsTableFixture(connection, "Destination"); //Act DbSource<MySimpleRow> source = new DbSource<MySimpleRow>() { SourceTableDefinition = source2Columns.TableDefinition, ConnectionManager = connection }; DbDestination<MySimpleRow> dest = new DbDestination<MySimpleRow>() { DestinationTableDefinition = dest2Columns.TableDefinition, ConnectionManager = connection }; source.LinkTo(dest); source.Execute(); dest.Wait(); //Assert dest2Columns.AssertTestData(); } } }
30.929825
104
0.633579
[ "MIT" ]
SipanOhanyan/etlbox
TestsETLBox/src/DataFlowTests/DBSource/DBSourceTableDefinitionTests.cs
1,763
C#
namespace ProcessTests.Api.Components.Health { using System.Net; using System.Reflection; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; [ApiController] [AllowAnonymous] [Route("api/[controller]")] [Produces("application/json")] public class HealthController : ControllerBase { private readonly IWebHostEnvironment _webHostEnvironment; public HealthController(IWebHostEnvironment webHostEnvironment) => _webHostEnvironment = webHostEnvironment; private static string ApiVersion => Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion ?? string.Empty; /// <summary> /// Endpoint to verify server's responsiveness. /// </summary> /// <response code="200"> Server is responsive </response> /// <response code="424"> Server is unresponsive </response> [HttpGet] [ProducesResponseType(typeof(HealthStateDto), (int)HttpStatusCode.OK)] public IActionResult Health() { var healthState = new HealthStateDto { Name = _webHostEnvironment.ApplicationName, Environment = _webHostEnvironment.EnvironmentName, ApiVersion = ApiVersion, IsHealthy = true }; return StatusCode((int)HttpStatusCode.OK, healthState); } } }
35.431818
142
0.632457
[ "MIT" ]
TomaszSynak/ProcessTests
Projects/ProcessTests.Api/Components/Health/HealthController.cs
1,561
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("UnitTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnitTest")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("029135c3-4251-4648-9b90-136e79b9f8d3")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.324324
56
0.712914
[ "MIT" ]
D15190304050/WpfGames
UnitTest/Properties/AssemblyInfo.cs
1,278
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace WebMarket.Models.AdministrationModels { public class EditUserViewModel { public string Id { get; set; } [Required] public string UserName { get; set; } [Required] [EmailAddress] public string Email { get; set; } public decimal Money { get; set; } public List<string> Claims { get; set; } public List<string> Roles { get; set; } public EditUserViewModel() { Claims = new List<string>(); Roles = new List<string>(); } } }
23.633333
48
0.603667
[ "MIT" ]
DewhiteE/WebMarket
WebMarket/Models/AdministrationModels/EditUserViewModel.cs
711
C#
using System; using System.Collections.Generic; using Xms.Core.Context; using Xms.Business.Filter.Domain; using Xms.Core; namespace Xms.Business.Filter { public interface IFilterRuleFinder { FilterRule FindById(Guid id); List<FilterRule> FindAll(); List<FilterRule> Query(Func<QueryDescriptor<FilterRule>, QueryDescriptor<FilterRule>> container); List<FilterRule> QueryByEntityId(Guid entityid, string eventName, RecordState? recordState); PagedList<FilterRule> QueryPaged(Func<QueryDescriptor<FilterRule>, QueryDescriptor<FilterRule>> container); PagedList<FilterRule> QueryPaged(Func<QueryDescriptor<FilterRule>, QueryDescriptor<FilterRule>> container, Guid solutionId, bool existInSolution); } }
42.222222
154
0.761842
[ "MIT" ]
feilingdeng/xms
Libraries/Business/Xms.Business.Filter/IFilterRuleFinder.cs
762
C#
using System; using DemoParser.Parser.Components.Abstract; using DemoParser.Utils; using DemoParser.Utils.BitStreams; namespace DemoParser.Parser.Components.Messages.UserMessages { public class Fade : UserMessage { public float Duration; public ushort HoldTime; // yeah idk what this is about public FadeFlags Flags; public byte R, G, B, A; public Fade(SourceDemo? demoRef) : base(demoRef) {} protected override void Parse(ref BitStreamReader bsr) { Duration = bsr.ReadUShort() / (float)(1 << 9); // might be useful: #define SCREENFADE_FRACBITS 9 HoldTime = bsr.ReadUShort(); Flags = (FadeFlags)bsr.ReadUShort(); R = bsr.ReadByte(); G = bsr.ReadByte(); B = bsr.ReadByte(); A = bsr.ReadByte(); } internal override void WriteToStreamWriter(BitStreamWriter bsw) { throw new NotImplementedException(); } public override void PrettyWrite(IPrettyWriter iw) { iw.AppendLine($"duration: {Duration}"); iw.AppendLine($"hold time: {HoldTime}"); iw.AppendLine($"flags: {Flags}"); iw.Append($"RGBA: {R:D3}, {G:D3}, {B:D3}, {A:D3}"); } } [Flags] public enum FadeFlags : ushort { None = 0, FadeIn = 1, FadeOut = 1 << 1, Modulate = 1 << 2, // Modulate (don't blend) StayOut = 1 << 3, // ignores the duration, stays faded out until new ScreenFade message received Purge = 1 << 4 // Purges all other fades, replacing them with this one } }
26.981132
99
0.670629
[ "MIT" ]
UncraftedName/UncraftedDemoParser
DemoParser/src/Parser/Components/Messages/UserMessages/Fade.cs
1,430
C#
using System.Text.RegularExpressions; namespace Microsoft.Recognizers.Text.DateTime.Utilities { public interface IDateTimeUtilityConfiguration { Regex AgoRegex { get; } Regex LaterRegex { get; } Regex InConnectorRegex { get; } Regex SinceYearSuffixRegex { get; } Regex WithinNextPrefixRegex { get; } Regex RangeUnitRegex { get; } Regex TimeUnitRegex { get; } Regex DateUnitRegex { get; } Regex AmDescRegex { get; } Regex PmDescRegex { get; } Regex AmPmDescRegex { get; } Regex CommonDatePrefixRegex { get; } } }
20.75
56
0.593373
[ "MIT" ]
AzureMentor/Recognizers-Text
.NET/Microsoft.Recognizers.Text.DateTime/Utilities/IDateTimeUtilityConfiguration.cs
666
C#
namespace Wareh.Controllers { using System.Data.Entity; using System.Linq; using System.Web.Mvc; using Models; using ViewModels; using System.Web; using System.IO; using System; public class ProductController : Controller { [HttpGet] [Authorize] public ActionResult Index() { using (var db = new ApplicationDbContext()) { var products = db.Products.Include(m => m.Manufacturer).Include(s => s.Suppliers).ToList(); return View(products); } } [HttpGet] [Authorize] public ActionResult Create() { using (var db = new ApplicationDbContext()) { var manufacturers = db.Manufacturers.ToList(); var suppliers = db.Suppliers.ToList(); var viewModel = new ProductViewModel { Manufacturers = manufacturers, Suppliers = suppliers }; return View(viewModel); } } [HttpPost] [Authorize] public ActionResult Create(ProductViewModel productViewModel, HttpPostedFileBase file, int[] selectedSuppliers) { string imagePath = String.Empty; if (ModelState.IsValid) { if (file != null && file.ContentLength > 0) try { string path = Path.Combine(Server.MapPath("~/Content/Images/Upload"), Path.GetFileName(file.FileName)); imagePath = "Content/Images/Upload/" + Path.GetFileName(file.FileName); file.SaveAs(path); ViewBag.Message = "File uploaded successfully"; } catch (Exception ex) { ViewBag.Message = "ERROR:" + ex.Message.ToString(); } else { ViewBag.Message = "You have not specified a file."; } using (var db = new ApplicationDbContext()) { //var suppliers = new HashSet<Supplier>(); var suppliers = db.Suppliers.Where(s => selectedSuppliers.Contains(s.Id)).ToList(); var product = new Product { Name = productViewModel.Product.Name, Image = imagePath, Barcode = productViewModel.Product.Barcode, ManufacturerId = productViewModel.Product.ManufacturerId, Suppliers = suppliers, }; db.Products.Add(product); db.SaveChanges(); return RedirectToAction("Index"); } } using (var db = new ApplicationDbContext()) { var manufacturers = db.Manufacturers.ToList(); var suppliers = db.Suppliers.ToList(); var viewModel = new ProductViewModel { Manufacturers = manufacturers, Suppliers = suppliers, Product = productViewModel.Product }; return View(viewModel); } } [HttpGet] [Authorize] public ActionResult Edit(int? id) { using (var db = new ApplicationDbContext()) { var product = db.Products.Find(id); if (product == null) { RedirectToAction("Index"); } var manufacturers = db.Manufacturers.ToList(); var suppliers = db.Suppliers.ToList(); var viewModel = new ProductViewModel(); viewModel.Product = product; viewModel.Manufacturers = manufacturers; viewModel.Suppliers = suppliers; viewModel.SelectedSuppliers = product.Suppliers.Select(s => s.Id).ToList(); return View(viewModel); } } [HttpPost] [Authorize] public ActionResult Edit(ProductViewModel productViewModel, HttpPostedFileBase file, int[] selectedSuppliers) { string imagePath = String.Empty; int? id = int.Parse(RouteData.Values["Id"].ToString()); if (id == null) { return RedirectToAction("Index"); } using (var db = new ApplicationDbContext()) { var suppliers = db.Suppliers.Where(s => selectedSuppliers.Contains(s.Id)).ToList(); var product = db.Products.Find(id); for (var i = 0; i < product.Suppliers.Count; i++) { product.Suppliers.Remove(product.Suppliers[i]); } //product.Id = (int)id; product.Name = productViewModel.Product.Name; product.Barcode = productViewModel.Product.Barcode; product.ManufacturerId = productViewModel.Product.ManufacturerId; product.Suppliers = suppliers; if (ModelState.IsValid) { if (file != null && file.ContentLength > 0) try { string path = Path.Combine(Server.MapPath("~/Content/Images/Upload"), Path.GetFileName(file.FileName)); imagePath = "Content/Images/Upload/" + Path.GetFileName(file.FileName); file.SaveAs(path); ViewBag.Message = "File uploaded successfully"; } catch (Exception ex) { ViewBag.Message = "ERROR:" + ex.Message.ToString(); } else { ViewBag.Message = "You have not specified a file."; } product.Image = imagePath; db.SaveChanges(); return RedirectToAction("Index"); } var manufacturers = db.Manufacturers.ToList(); suppliers = db.Suppliers.ToList(); productViewModel.Manufacturers = manufacturers; productViewModel.Suppliers = suppliers; } return View(productViewModel); } [HttpGet] [Authorize] public ActionResult Details(int? id) { using (var db = new ApplicationDbContext()) { var product = db.Products.Include(m => m.Manufacturer) .Include(s => s.Suppliers) .SingleOrDefault(p => p.Id == id); if (product == null) { RedirectToAction("Index"); } return View(product); } } } }
33.04
119
0.452785
[ "MIT" ]
ninetensfive/wareh
Wareh/Controllers/ProductController.cs
7,436
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace librarysample { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddCors(options => { options.AddPolicy("AllowBookEditor", builder => builder.WithOrigins("http://localhost:3000").AllowAnyMethod().AllowAnyHeader()); }); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseCors("AllowBookEditor"); app.UseMvc(); } } }
36.42
112
0.630972
[ "Apache-2.0" ]
CaveJ/NetCoreBasicRestServer
Startup.cs
1,823
C#
using UnityEngine; using Lean.Common; #if UNITY_EDITOR using UnityEditor; #endif namespace Lean.Gui { /// <summary>This component allows you to draw a UI element between two points in the scene (e.g. 3D objects). /// NOTE: To see the line you also need to add a <b>Graphic</b> to your line GameObject, like <b>LeanBox</b> or <b>Image</b>.</summary> [ExecuteInEditMode] [DisallowMultipleComponent] [RequireComponent(typeof(RectTransform))] [HelpURL(LeanGui.HelpUrlPrefix + "LeanLine")] [AddComponentMenu(LeanGui.ComponentMenuPrefix + "Line")] public class LeanLine : MonoBehaviour { /// <summary>The camera rendering the target transform/position. /// None/Null = The <b>MainCamera</b> will be used.</summary> public Camera WorldCamera { set { worldCamera = value; } get { return worldCamera; } } [SerializeField] private Camera worldCamera; /// <summary>The start point of the <b>RectTransform</b> will be placed at this anchor point.</summary> public LeanAnchor AnchorA { get { if (anchorA == null) anchorA = new LeanAnchor(); return anchorA; } } [SerializeField] private LeanAnchor anchorA; /// <summary>The end point of the <b>RectTransform</b> will be placed at this anchor point.</summary> public LeanAnchor AnchorB { get { if (anchorB == null) anchorB = new LeanAnchor(); return anchorB; } } [SerializeField] private LeanAnchor anchorB; [System.NonSerialized] private RectTransform cachedRectTransform; [System.NonSerialized] private bool cachedRectTransformSet; /// <summary>This method forces the <b>RectTransform</b> settings to update based on the current line settings. /// NOTE: This is automatically called in <b>LateUpdate</b>, but you can manually call it if you have modified it after this, but before the canvas is drawn.</summary> [ContextMenu("Update Line")] public void UpdateLine() { var canvas = gameObject.GetComponentInParent<Canvas>(); if (canvas != null) { if (cachedRectTransformSet == false) { cachedRectTransform = GetComponent<RectTransform>(); cachedRectTransformSet = true; } var canvasRectTransform = canvas.transform as RectTransform; var pointA = default(Vector3); var pointB = default(Vector3); var pointAValid = AnchorA.TryGetPoint(canvasRectTransform, ref pointA, worldCamera); var pointBValid = AnchorB.TryGetPoint(canvasRectTransform, ref pointB, worldCamera); if (pointAValid == true || pointBValid == true) { var pointV = pointB - pointA; var pointM = (pointA + pointB) * 0.5f; // Position in middle SetPosition(cachedRectTransform, pointM); // Stretch to pointV var sizeDelta = cachedRectTransform.sizeDelta; var scaleFactor = canvas.scaleFactor; sizeDelta.y = pointV.magnitude; if (scaleFactor != 0.0f) { sizeDelta.y /= scaleFactor; } cachedRectTransform.sizeDelta = sizeDelta; // Rotate to pointV var angle = Mathf.Atan2(pointV.x, pointV.y) * Mathf.Rad2Deg; cachedRectTransform.localRotation = Quaternion.Euler(0.0f, 0.0f, -angle); } else { // Position outside view SetPosition(cachedRectTransform, new Vector3(100000.0f, 100000.0f)); cachedRectTransform.sizeDelta = Vector2.zero; } } } protected virtual void LateUpdate() { UpdateLine(); } private static void SetPosition(RectTransform rectTransform, Vector3 position) { rectTransform.position = position; // NOTE: This is required to force the RectTransform position to update on some versions of the UI?! rectTransform.anchoredPosition3D = rectTransform.anchoredPosition3D; } #if UNITY_EDITOR [MenuItem("GameObject/Lean/GUI/Line", false, 1)] private static void CreateLine() { Selection.activeObject = LeanHelper.CreateElement<LeanLine>(Selection.activeTransform); } #endif } } #if UNITY_EDITOR namespace Lean.Gui { [CanEditMultipleObjects] [CustomEditor(typeof(LeanLine))] public class LeanLine_Editor : Common.LeanInspector<LeanLine> { private static bool expandDetail; private static bool expandRadius; protected override void DrawInspector() { Draw("worldCamera", "The camera rendering the target transform/position.\n\nNone/Null = The MainCamera will be used."); EditorGUILayout.Separator(); Draw("anchorA", "The start point of the RectTransform will be placed at this anchor point."); Draw("anchorB", "The end point of the RectTransform will be placed at this anchor point."); } } } #endif
33.688889
169
0.710642
[ "MIT" ]
DrScatman/vr-mod
Assets/Lean/GUI Shapes/Scripts/LeanLine.cs
4,550
C#
using System; using System.Collections.Generic; namespace DevAchievements.Domain.UnitTests { public class AvailableAchievementProvider : IAchievementProvider { #region IAchievementProvider implementation public void CheckAvailability () { } public bool Enabled { get { return true; } } public bool IsAvailable { get { return true; } } public bool Exists (DeveloperAccountAtIssuer account) { return true; } public IList<Achievement> GetAchievements (DeveloperAccountAtIssuer account) { if (account.Username.Equals ("DeveloperWithAchievements")) { return new List<Achievement> () { new Achievement () { Name = "Achievement One", Issuer = new AchievementIssuer("Issuer One") } }; } return new List<Achievement> (); } public AchievementIssuer[] SupportedIssuers { get { return new AchievementIssuer[] { new AchievementIssuer("Test") }; } } #endregion } }
19.230769
85
0.658
[ "MIT" ]
giacomelli/DevAchievements
src/DevAchievements.Domain.UnitTests/Stubs/TwoAvailableAchievementProvider.cs
1,000
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. // This code was generated by an automated template. using Mosa.Compiler.Framework; namespace Mosa.Platform.x86.Instructions { /// <summary> /// MovLoad8 /// </summary> /// <seealso cref="Mosa.Platform.x86.X86Instruction" /> public sealed class MovLoad8 : X86Instruction { public override int ID { get { return 244; } } internal MovLoad8() : base(1, 2) { } public override bool IsMemoryRead { get { return true; } } public override void Emit(InstructionNode node, BaseCodeEmitter emitter) { System.Diagnostics.Debug.Assert(node.ResultCount == 1); System.Diagnostics.Debug.Assert(node.OperandCount == 2); if ((node.Operand1.IsCPURegister && node.Operand1.Register.RegisterCode == 5) && node.Operand2.IsConstantZero) { emitter.OpcodeEncoder.AppendByte(0x8A); emitter.OpcodeEncoder.Append2Bits(0b01); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(0b101); emitter.OpcodeEncoder.AppendByte(0x00); return; } if ((node.Operand1.IsCPURegister && node.Operand1.Register.RegisterCode == 5) && node.Operand2.IsCPURegister) { emitter.OpcodeEncoder.AppendByte(0x8A); emitter.OpcodeEncoder.Append2Bits(0b01); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(0b100); emitter.OpcodeEncoder.Append2Bits(0b00); emitter.OpcodeEncoder.Append3Bits(node.Operand2.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(0b101); emitter.OpcodeEncoder.AppendByte(0x00); return; } if ((node.Operand1.IsCPURegister && node.Operand1.Register.RegisterCode == 4) && node.Operand2.IsConstantZero) { emitter.OpcodeEncoder.AppendByte(0x8A); emitter.OpcodeEncoder.Append2Bits(0b00); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(0b100); emitter.OpcodeEncoder.Append2Bits(0b00); emitter.OpcodeEncoder.Append3Bits(0b100); emitter.OpcodeEncoder.Append3Bits(0b100); return; } if ((node.Operand1.IsCPURegister && node.Operand1.Register.RegisterCode == 4) && (node.Operand2.IsConstant && node.Operand2.ConstantSignedInteger >= -128 && node.Operand2.ConstantSignedInteger <= 127)) { emitter.OpcodeEncoder.AppendByte(0x8A); emitter.OpcodeEncoder.Append2Bits(0b01); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(0b100); emitter.OpcodeEncoder.Append2Bits(0b00); emitter.OpcodeEncoder.Append3Bits(0b100); emitter.OpcodeEncoder.Append3Bits(0b100); emitter.OpcodeEncoder.Append8BitImmediate(node.Operand2); return; } if ((node.Operand1.IsCPURegister && node.Operand1.Register.RegisterCode == 4) && node.Operand2.IsConstant) { emitter.OpcodeEncoder.AppendByte(0x8A); emitter.OpcodeEncoder.Append2Bits(0b10); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(0b100); emitter.OpcodeEncoder.Append8BitImmediate(node.Operand2); return; } if (node.Operand1.IsCPURegister && node.Operand2.IsCPURegister) { emitter.OpcodeEncoder.AppendByte(0x8A); emitter.OpcodeEncoder.Append2Bits(0b00); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(0b100); emitter.OpcodeEncoder.Append2Bits(0b00); emitter.OpcodeEncoder.Append3Bits(node.Operand2.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(node.Operand1.Register.RegisterCode); return; } if (node.Operand1.IsCPURegister && node.Operand2.IsConstantZero) { emitter.OpcodeEncoder.AppendByte(0x8A); emitter.OpcodeEncoder.Append2Bits(0b00); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(node.Operand1.Register.RegisterCode); return; } if (node.Operand1.IsCPURegister && (node.Operand2.IsConstant && node.Operand2.ConstantSignedInteger >= -128 && node.Operand2.ConstantSignedInteger <= 127)) { emitter.OpcodeEncoder.AppendByte(0x8A); emitter.OpcodeEncoder.Append2Bits(0b01); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(node.Operand1.Register.RegisterCode); emitter.OpcodeEncoder.Append8BitImmediate(node.Operand2); return; } if (node.Operand1.IsCPURegister && node.Operand2.IsConstant) { emitter.OpcodeEncoder.AppendByte(0x8A); emitter.OpcodeEncoder.Append2Bits(0b10); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(node.Operand1.Register.RegisterCode); emitter.OpcodeEncoder.Append32BitImmediate(node.Operand2); return; } if (node.Operand1.IsConstant && node.Operand2.IsConstantZero) { emitter.OpcodeEncoder.AppendByte(0x8A); emitter.OpcodeEncoder.Append2Bits(0b00); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(0b101); emitter.OpcodeEncoder.Append32BitImmediate(node.Operand1); return; } if (node.Operand1.IsConstant && node.Operand2.IsConstant) { emitter.OpcodeEncoder.AppendByte(0x8A); emitter.OpcodeEncoder.Append2Bits(0b00); emitter.OpcodeEncoder.Append3Bits(node.Result.Register.RegisterCode); emitter.OpcodeEncoder.Append3Bits(0b101); emitter.OpcodeEncoder.Append32BitImmediateWithOffset(node.Operand1, node.Operand2); return; } throw new Compiler.Common.Exceptions.CompilerException("Invalid Opcode"); } } }
37.506579
204
0.755832
[ "BSD-3-Clause" ]
kthompson/MOSA-Project
Source/Mosa.Platform.x86/Instructions/MovLoad8.cs
5,701
C#
using UnityEngine; using System.Collections; public class BushHealthScript : HealthScript { public string nameOfLeafPool; public GameObject dropOnKill; private BoxCollider2D _collider; private GameObjectPool _leafPool; GameObject leafs; private void Start () { _collider = GetComponent<BoxCollider2D>(); _leafPool = GameObject.Find(nameOfLeafPool).GetComponent<GameObjectPool>(); if(_leafPool == null) Debug.Log("WTF no leafPool found. How will bushes die awesomely?"); } public override void InflictDamage(float value) { currentHealth -= value; if(currentHealth <= 0) { Kill(); } } public override void Kill() { _collider.enabled = false; GetComponent<Renderer>().enabled = false; if(_leafPool != null) { leafs = _leafPool.GetObjectFromPool(); leafs.transform.position = transform.position; leafs.transform.Rotate(new Vector3(0,0,Random.Range(0,360))); leafs.GetComponent<Animator>().Play("leafs_scattering"); leafs.SetActive(true); } if(dropOnKill) { GameObject dropped = (GameObject)Instantiate(dropOnKill); dropped.transform.position = transform.position; } Invoke("RemoveBush", 1); } void RemoveBush () { if(_leafPool != null) _leafPool.ReturnObjectToPool(leafs); Destroy(gameObject); } }
19.681818
77
0.713626
[ "MIT" ]
alectyre/ElfQuest
Assets/Scripts/BushHealthScript.cs
1,301
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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. * 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 TencentCloud.Cpdp.V20190820.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class QueryReconciliationDocumentRequest : AbstractModel { /// <summary> /// String(22),商户号 /// </summary> [JsonProperty("MrchCode")] public string MrchCode{ get; set; } /// <summary> /// STRING(10),文件类型(充值文件-CZ; 提现文件-TX; 交易文件-JY; 余额文件-YE; 合约文件-HY) /// </summary> [JsonProperty("FileType")] public string FileType{ get; set; } /// <summary> /// STRING(8),文件日期(格式:20190101) /// </summary> [JsonProperty("FileDate")] public string FileDate{ get; set; } /// <summary> /// STRING(1027),保留域 /// </summary> [JsonProperty("ReservedMsg")] public string ReservedMsg{ get; set; } /// <summary> /// STRING(12),接入环境,默认接入沙箱环境。接入正式环境填"prod" /// </summary> [JsonProperty("Profile")] public string Profile{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "MrchCode", this.MrchCode); this.SetParamSimple(map, prefix + "FileType", this.FileType); this.SetParamSimple(map, prefix + "FileDate", this.FileDate); this.SetParamSimple(map, prefix + "ReservedMsg", this.ReservedMsg); this.SetParamSimple(map, prefix + "Profile", this.Profile); } } }
32.083333
83
0.610823
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Cpdp/V20190820/Models/QueryReconciliationDocumentRequest.cs
2,444
C#
namespace _05.ClosestTwoPoints { using System; using System.Collections.Generic; using System.Linq; public class ClosestTwoPoints { public static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var points = new List<Point>(); for (var i = 0; i < n; i++) { var currentPoint = ReadPoint(); points.Add(currentPoint); } var minDistance = double.MaxValue; Point firstPointResult = null; Point secondPointResult = null; for (int first = 0; first < points.Count; first++) { for (int second = first + 1; second < points.Count; second++) { var firstPoint = points[first]; var secondPoint = points[second]; var distance = CalculateDistance(firstPoint, secondPoint); if (distance < minDistance) { minDistance = distance; firstPointResult = firstPoint; secondPointResult = secondPoint; } } } Console.WriteLine($"{minDistance:F3}"); Console.WriteLine(firstPointResult.PrintPoint()); Console.WriteLine(secondPointResult.PrintPoint()); } public static Point ReadPoint() { var inputCoordinats = Console.ReadLine() .Split() .Select(int.Parse) .ToArray(); var point = new Point(inputCoordinats[0], inputCoordinats[1]); return point; } public static double CalculateDistance(Point firstPoint, Point secondPoint) { var diffX = firstPoint.X - secondPoint.X; var diffY = firstPoint.Y - secondPoint.Y; var powX = Math.Pow(diffX, 2); var powY = Math.Pow(diffY, 2); return Math.Sqrt(powX + powY); } } }
30.422535
84
0.480556
[ "MIT" ]
stoyanov7/SoftwareUniversity
TechnologiesFundamentals/ProgrammingFundamentals-Extended/ObjectsAndSimpleClasses-Lab/05.ClosestTwoPoints/05.ClosestTwoPoints/ClosestTwoPoints.cs
2,162
C#
using System.Collections.Generic; using System.ComponentModel; namespace Frontend.Core.Model.Paths.Interfaces { public interface IRequiredItemBase : INotifyPropertyChanged { string FriendlyName { get; } string SelectedValue { get; set; } string TagName { get; } string InternalTagName { get; } string Description { get; } IList<IAlternativePath> AlternativePaths { get; } string DefaultValue { get; } bool IsMandatory { get; } bool IsValid { get; } bool IsHidden { get; } } }
30.894737
64
0.618399
[ "MIT" ]
Deinos65/paradoxGameConverters
Frontend/ParadoxConverters.Frontend/Frontend.Core/Model/Paths/Interfaces/IRequiredItemBase.cs
589
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using RikardWeb.Controllers; using Microsoft.Extensions.Configuration; using RikardWeb.Options; using RikardLib.AspLog; using RikardWeb.Services; using Microsoft.Extensions.WebEncoders; using System.Text.Unicode; using System.Text.Encodings.Web; using RikardLib.AspCron; using RikardWeb.Lib.News; using RikardLib.Log; using RikardWeb.Lib.Db.Options; using RikardWeb.Lib.News.Services; using RikardWeb.Lib.Db.Service; using Microsoft.AspNetCore.Identity; using RikardWeb.Lib.Identity; using RikardLib.AspSmsRu.SmsRu.Options; using SmsRu; using RikardWeb.Policy; using Microsoft.AspNetCore.Authorization; using Microsoft.CodeAnalysis.CSharp; using RikardWeb.Lib.Adverts.Options; using RikardWeb.Lib.Adverts.Service; using RikardWeb.Lib.Adverts; namespace RikardWeb { public class Startup { private Logger logger = new Logger(); public IConfigurationRoot Configuration { get; private set; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("rikard_settings.json", optional: true); Configuration = builder.Build(); } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure<InfoOptions>(Configuration.GetSection("Info")); services.Configure<DatabaseOptions>(Configuration.GetSection("Database")); services.Configure<SmsRuOptions>(Configuration.GetSection("SmsRu")); services.Configure<AdvertsOptions>(Configuration.GetSection("Adverts")); services.AddAspLogger(); services.AddSendEmailService(); services.AddSmsRu(); services.AddMongoDbService(); services.AddNewsDatabaseService(); services.AddAdvertsDatabaseService(); services.AddCron(); services.AddMongoIdentity(); services.Configure<IdentityOptions>(o => { o.SignIn.RequireConfirmedEmail = true; o.SignIn.RequireConfirmedPhoneNumber = true; o.Password.RequireNonAlphanumeric = false; o.Password.RequireUppercase = false; o.Password.RequireLowercase = false; o.Password.RequireDigit = false; o.Password.RequiredLength = 5; o.User.RequireUniqueEmail = true; o.User.AllowedUserNameCharacters = string.Empty; o.Cookies.ApplicationCookie.AutomaticAuthenticate = true; o.Cookies.ApplicationCookie.AutomaticChallenge = true; o.Cookies.ApplicationCookie.LoginPath = "/Profile/Login"; o.Cookies.ApplicationCookie.AccessDeniedPath = "/error/403"; }); services.AddMvc() .AddRazorOptions(options => options.ParseOptions = new CSharpParseOptions(LanguageVersion.CSharp7)); services.AddViewRender(); services.AddDistributedMemoryCache(); services.AddSession(options => { options.CookieName = ".RikardRu.Session"; options.IdleTimeout = TimeSpan.FromSeconds(10); }); services.AddAuthorization(opt => { opt.AddPolicy("Paid", pb => pb.AddRequirements(new IsUserPaid(new TimeSpan(1, 0, 0, 0)))); }); services.AddSingleton<IAuthorizationHandler, IsUserPadAuthorizationHandler>(); services.Configure<WebEncoderOptions>(options => { options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { //loggerFactory.AddAspLogger(); loggerFactory.AddConsole(); loggerFactory.AddDebug(); app.UseDeveloperExceptionPage(); app.UseBrowserLink(); app.UseStatusCodePages(); } else { app.UseExceptionHandler("/error/server_exception"); app.UseStatusCodePagesWithReExecute("/error/{0}"); } app.UseStaticFiles(); app.UseIdentity(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "newsList", template: "News/NewsList/{page:int}", defaults: new { controller = "News", action=nameof(NewsController.NewsList) }); routes.MapRoute( name: "newsArticle", template: "News/NewsArticle/{article:guid}", defaults: new { controller = "News", action = nameof(NewsController.NewsArticle) }); routes.MapRoute( name: "errors", template: "error/{errid}", defaults: new { controller = "Errors", action = "ShowError" }); routes.MapRoute( name: "default", template: "{controller}/{action}", defaults: new { controller = "Adverts", action = "RentList" }); }); /** * Automatically start services **/ app.ApplicationServices.GetService<ISendEmailService>(); app.ApplicationServices.GetService<IMongoDbService>(); app.ApplicationServices.GetService<INewsDatabaseService>(); app.ApplicationServices.GetService<IAdvertsDatabaseService>(); app.ApplicationServices.GetService<IUserStore<IdentityUser>>(); app.ApplicationServices.GetService<IRoleStore<IdentityRole>>(); app.ApplicationServices.GetService<ISmsRuService>(); app.ApplicationServices.GetService<IUsersService<IdentityUser>>(); /** * Initialize cron service **/ var cron = app.ApplicationServices.GetService<ICronService>(); if(!env.IsDevelopment()) { //cron.AddJob("*/5 * * * *", () => Task.Run(async () => await // NewsUpdater.RunNewsUpdater()).GetAwaiter().GetResult(), "NewsUpdate"); //cron.AddJob("*/1 * * * *", () => Task.Run(async () => await // NewsTweeter.RunNewsTweeter()).GetAwaiter().GetResult(), "NewsTweeter"); cron.AddJob("0 */6 * * *", () => { if(AdvertsDatabase.Instance != null) { AdvertsDatabase.Instance.RunAdvertsUpdater(); } }, "AdvertsUpdate"); } } } }
40.28877
122
0.596761
[ "MIT" ]
wapxmas/rikard-csharp-net-core
RealEstate/RikardWeb/Startup.cs
7,536
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.DiskPool.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Extensions; /// <summary>Lists available Disk Pool Skus in an Azure location.</summary> /// <remarks> /// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.StoragePool/locations/{location}/diskPoolZones" /// </remarks> [global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.InternalExport] [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzDiskPoolZone_List")] [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IDiskPoolZoneInfo))] [global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Description(@"Lists available Disk Pool Skus in an Azure location.")] [global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Generated] public partial class GetAzDiskPoolZone_List : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.DiskPool Client => Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <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>Backing field for <see cref="Location" /> property.</summary> private string _location; /// <summary>The location of the resource.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The location of the resource.")] [Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Info( Required = true, ReadOnly = false, Description = @"The location of the resource.", SerializedName = @"location", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.ParameterCategory.Path)] public string Location { get => this._location; set => this._location = value; } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary>Backing field for <see cref="SubscriptionId" /> property.</summary> private string[] _subscriptionId; /// <summary>The ID of the target subscription.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] [Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Info( Required = true, ReadOnly = false, Description = @"The ID of the target subscription.", SerializedName = @"subscriptionId", PossibleTypes = new [] { typeof(string) })] [Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.DefaultInfo( Name = @"", Description =@"", Script = @"(Get-AzContext).Subscription.Id")] [global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Category(global::Microsoft.Azure.PowerShell.Cmdlets.DiskPool.ParameterCategory.Path)] public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } /// <summary> /// <c>overrideOnDefault</c> will be called before the regular onDefault 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.DiskPool.Models.Api20210401Preview.IError" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IError> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <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.DiskPool.Models.Api20210401Preview.IDiskPoolZoneListResult" /// /> 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.DiskPool.Models.Api20210401Preview.IDiskPoolZoneListResult> 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() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary> /// Intializes a new instance of the <see cref="GetAzDiskPoolZone_List" /> cmdlet class. /// </summary> public GetAzDiskPoolZone_List() { } /// <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.DiskPool.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.Information: { var data = messageData(); WriteInformation(data, new[] { data.Message }); return ; } case Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.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.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { foreach( var SubscriptionId in this.SubscriptionId ) { await ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await this.Client.DiskPoolZonesList(SubscriptionId, Location, onOk, onDefault, this, Pipeline); await ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } } catch (Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,Location=Location}) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary> /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). /// </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.DiskPool.Models.Api20210401Preview.IError" /// /> 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 onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IError> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnDefault(responseMessage, response, ref _returnNow); // if overrideOnDefault has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // Error Response : default var code = (await response)?.Code; var message = (await response)?.Message; if ((null == code || null == message)) { // Unrecognized Response. Create an error record based on what we have. var ex = new Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Models.Api20210401Preview.IError>(responseMessage, await response); WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, Location=Location }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } }); } else { WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, Location=Location }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } }); } } } /// <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.DiskPool.Models.Api20210401Preview.IDiskPoolZoneListResult" /// /> 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.DiskPool.Models.Api20210401Preview.IDiskPoolZoneListResult> 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 // response should be returning an array of some kind. +Pageable // pageable / value / nextLink var result = await response; WriteObject(result.Value,true); if (result.NextLink != null) { if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) { requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Method.Get ); await ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.DiskPool.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await this.Client.DiskPoolZonesList_Call(requestMessage, onOk, onDefault, this, Pipeline); } } } } } }
72.921717
463
0.666413
[ "MIT" ]
AzureSDKAutomation/azure-powershell
src/DiskPool/generated/cmdlets/GetAzDiskPoolZone_List.cs
28,482
C#
using System; namespace DaHo.Library.Utilities { public struct Time { public int Hours { get; set; } public int Minutes { get; set; } public Time(int hours, int minutes) { Hours = hours; Minutes = minutes; } public override string ToString() => $"{Hours}h {Minutes}m"; public static Time FromHours(decimal hours) { var timespan = TimeSpan.FromHours((double)hours); return new Time((int)timespan.TotalHours, timespan.Minutes); } public static Time FromMinutes(decimal minutes) { var timespan = TimeSpan.FromMinutes((double)minutes); return new Time((int)timespan.TotalHours, timespan.Minutes); } public static Time FromSeconds(decimal seconds) { var timespan = TimeSpan.FromSeconds((double)seconds); return new Time((int)timespan.TotalHours, timespan.Minutes); } public bool Equals(Time other) { return this.Hours == other.Hours && this.Minutes == other.Minutes; } public override bool Equals(object obj) { if (obj is Time time) return Equals(time); return false; } public override int GetHashCode() { return HashCode .Of(Hours) .And(Minutes); } public static bool operator ==(Time left, Time right) { return left.Equals(right); } public static bool operator !=(Time left, Time right) { return !(left == right); } } }
24.869565
72
0.529138
[ "MIT" ]
Davee02/DaHo.Library
src/DaHo.Library.Utilities/Time.cs
1,718
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Inventory_System { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26.814815
71
0.624309
[ "MIT" ]
galexbh/Inventory_System
Program.cs
724
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Abp.Authorization.Users; using Abp.Domain.Services; using Abp.IdentityFramework; using Abp.Runtime.Session; using Abp.UI; using myEventCloud.Authorization.Roles; using myEventCloud.MultiTenancy; namespace myEventCloud.Authorization.Users { public class UserRegistrationManager : DomainService { public IAbpSession AbpSession { get; set; } private readonly TenantManager _tenantManager; private readonly UserManager _userManager; private readonly RoleManager _roleManager; private readonly IPasswordHasher<User> _passwordHasher; public UserRegistrationManager( TenantManager tenantManager, UserManager userManager, RoleManager roleManager, IPasswordHasher<User> passwordHasher) { _tenantManager = tenantManager; _userManager = userManager; _roleManager = roleManager; _passwordHasher = passwordHasher; AbpSession = NullAbpSession.Instance; } public async Task<User> RegisterAsync(string name, string surname, string emailAddress, string userName, string plainPassword, bool isEmailConfirmed) { CheckForTenant(); var tenant = await GetActiveTenantAsync(); var user = new User { TenantId = tenant.Id, Name = name, Surname = surname, EmailAddress = emailAddress, IsActive = true, UserName = userName, IsEmailConfirmed = isEmailConfirmed, Roles = new List<UserRole>() }; user.SetNormalizedNames(); foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync()) { user.Roles.Add(new UserRole(tenant.Id, user.Id, defaultRole.Id)); } await _userManager.InitializeOptionsAsync(tenant.Id); CheckErrors(await _userManager.CreateAsync(user, plainPassword)); await CurrentUnitOfWork.SaveChangesAsync(); return user; } private void CheckForTenant() { if (!AbpSession.TenantId.HasValue) { throw new InvalidOperationException("Can not register host users!"); } } private async Task<Tenant> GetActiveTenantAsync() { if (!AbpSession.TenantId.HasValue) { return null; } return await GetActiveTenantAsync(AbpSession.TenantId.Value); } private async Task<Tenant> GetActiveTenantAsync(int tenantId) { var tenant = await _tenantManager.FindByIdAsync(tenantId); if (tenant == null) { throw new UserFriendlyException(L("UnknownTenantId{0}", tenantId)); } if (!tenant.IsActive) { throw new UserFriendlyException(L("TenantIdIsNotActive{0}", tenantId)); } return tenant; } protected virtual void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
30.663717
157
0.603463
[ "MIT" ]
lyzr2507/myEventCloud
aspnet-core/src/myEventCloud.Core/Authorization/Users/UserRegistrationManager.cs
3,467
C#
using System; using System.IO; using Newtonsoft.Json; namespace Login.Proxy.Config { internal class LoginProxyConfig { private static Lazy<LoginProxyConfig> _instance = new Lazy<LoginProxyConfig>(ReadProxyConfig); public static LoginProxyConfig Values => _instance.Value; private static string ConfigFilePath = Path.Combine(Directory.GetCurrentDirectory(), "Config", "Login.Proxy.Config.json"); private LoginProxyConfig() { } private static LoginProxyConfig ReadProxyConfig() { return JsonConvert.DeserializeObject<LoginProxyConfig>(File.ReadAllText(ConfigFilePath)); } public RedisSettings RedisSettings { get; set; } } internal class RedisSettings { public string RedisConnectionString { get; set; } public string AuthenticateFrontEndRequestsChannel { get; set; } public string AuthenticateFrontEndResponsesChannel { get; set; } public string AuthenticateBackEndRequestsChannel { get; set; } public string AuthenticateBackEndResponsesChannel { get; set; } public string CreateUserRequestsChannel { get; set; } } }
29.073171
130
0.693792
[ "MIT" ]
burak3000/LoginServiceInRedisAndDotnetFive
Login.Proxy/Config/LoginProxyConfig.cs
1,194
C#
using DiscordV.Models; using DiscordV.Core; using System.Threading.Tasks; namespace DiscordVTest { class Program { static void Main(string[] args) => new Program().Run().GetAwaiter().GetResult(); async Task Run() { Message message = new Message() { username = "test", content = "mdr", avatar_url = "https://cdn.iconverticons.com/files/png/9feca6582f22e9a7_256x256.png" }; await Webhooks.SendWebhook<Message>(message); } } }
24.166667
99
0.543103
[ "MIT" ]
Lulzboat-Mods/DiscordV
DiscordVTest/Program.cs
582
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Xamarin.Forms.Xaml.XamlResourceIdAttribute("MobilSemProjekt.View___Kopi.CreateUserPage.xaml", "View - Kopi/CreateUserPage.xaml", typeof(global::MobilSemProjekt.View.CreateUserPage))] namespace MobilSemProjekt.View { [global::Xamarin.Forms.Xaml.XamlFilePathAttribute("View - Kopi\\CreateUserPage.xaml")] public partial class CreateUserPage : global::Xamarin.Forms.ContentPage { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")] private global::Xamarin.Forms.Label CreateUserNameLabel; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")] private global::Xamarin.Forms.Entry CreateUserNameEntry; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")] private global::Xamarin.Forms.Label CreatePasswordLabel; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")] private global::Xamarin.Forms.Entry CreatePasswordEntry; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")] private global::Xamarin.Forms.Entry CreatePasswordConfirmationEntry; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")] private global::Xamarin.Forms.Button CreateAccountButton; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")] private void InitializeComponent() { global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(CreateUserPage)); CreateUserNameLabel = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Label>(this, "CreateUserNameLabel"); CreateUserNameEntry = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Entry>(this, "CreateUserNameEntry"); CreatePasswordLabel = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Label>(this, "CreatePasswordLabel"); CreatePasswordEntry = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Entry>(this, "CreatePasswordEntry"); CreatePasswordConfirmationEntry = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Entry>(this, "CreatePasswordConfirmationEntry"); CreateAccountButton = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Button>(this, "CreateAccountButton"); } } }
63.530612
201
0.688725
[ "Apache-2.0" ]
akhegr/Skoleprojekter
4. semester projekt/MobilSemProjekt/MobilSemProjekt/MobilSemProjekt/MobilSemProjekt/obj/Debug/netstandard2.0/View - Kopi/CreateUserPage.xaml.g.cs
3,113
C#
// Copyright (c) 2008-2012, Lex Li // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // - Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to // endorse or promote products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER // IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* * Created by SharpDevelop. * User: lextm * Date: 2008/10/2 * Time: 18:31 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Lextm.SharpSnmpLib.Mib { /// <summary> /// MIB assembler. /// </summary> public class Assembler { private readonly ObjectTree _tree; private readonly string _folder; /// <summary> /// Folder. /// </summary> public string Folder { get { return _folder; } } /// <summary> /// Tree. /// </summary> [CLSCompliant(false)] public IObjectTree Tree { get { return _tree; } } internal ObjectTree RealTree { get { return _tree; } } internal ICollection<string> Modules { get { return _tree.LoadedModules; } } /// <summary> /// Creates an instance of <see cref="Assembler"/>. /// </summary> /// <param name="folder">Folder.</param> public Assembler(string folder) { _folder = Path.GetFullPath(folder); if (!Directory.Exists(_folder)) { Directory.CreateDirectory(_folder); } string[] files = Directory.GetFiles(_folder, "*.module"); _tree = new ObjectTree(files); } /// <summary> /// Assemblers modules. /// </summary> /// <param name="modules">Modules.</param> public void Assemble(IEnumerable<IModule> modules) { RealTree.Import(modules); RealTree.Refresh(); foreach (MibModule module in modules.Cast<MibModule>().Where(module => !Tree.PendingModules.Contains(module.Name))) { PersistModuleToFile(Folder, module, Tree); } } private static void PersistModuleToFile(string folder, IModule module, IObjectTree tree) { string fileName = Path.Combine(folder, module.Name + ".module"); using (StreamWriter writer = new StreamWriter(fileName)) { writer.Write("#"); foreach (string dependent in module.Dependents) { writer.Write(dependent); writer.Write(','); } writer.WriteLine(); foreach (IEntity entity in module.Entities) { IDefinition node = tree.Find(module.Name, entity.Name); if (node == null) { continue; } uint[] id = node.GetNumericalForm(); /* 0: id * 1: type * 2: name * 3: parent name */ writer.WriteLine(ObjectIdentifier.Convert(id) + "," + entity.GetType() + "," + entity.Name + "," + entity.Parent); } writer.Close(); } } } }
34.048611
134
0.560473
[ "BSD-3-Clause" ]
3rdandUrban-dev/Nuxleus
src/external/sharpsnmp/SharpSnmpLib/Mib/Assembler.cs
4,903
C#
using NowWhat.Shared.Constants.Permission; using Microsoft.AspNetCore.Authorization; using System.Linq; using System.Threading.Tasks; namespace NowWhat.Server.Permission { internal class PermissionAuthorizationHandler : AuthorizationHandler<PermissionRequirement> { public PermissionAuthorizationHandler() { } protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) { if (context.User == null) { await Task.CompletedTask; } var permissions = context.User.Claims.Where(x => x.Type == ApplicationClaimTypes.Permission && x.Value == requirement.Permission && x.Issuer == "LOCAL AUTHORITY"); if (permissions.Any()) { context.Succeed(requirement); await Task.CompletedTask; } } } }
35.366667
132
0.568332
[ "MIT" ]
zoldacic/NoNonense
src/Server/Permission/PermissionAuthorizationHandler.cs
1,063
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Internal; namespace Microsoft.AspNetCore.Identity; /// <summary> /// Creates a new instance of a persistence store for roles. /// </summary> /// <typeparam name="TRole">The type of the class representing a role.</typeparam> /// <typeparam name="TKey">The type of the primary key for a role.</typeparam> /// <typeparam name="TUserRole">The type of the class representing a user role.</typeparam> /// <typeparam name="TRoleClaim">The type of the class representing a role claim.</typeparam> public abstract class RoleStoreBase<TRole, TKey, TUserRole, TRoleClaim> : IQueryableRoleStore<TRole>, IRoleClaimStore<TRole> where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> where TUserRole : IdentityUserRole<TKey>, new() where TRoleClaim : IdentityRoleClaim<TKey>, new() { /// <summary> /// Constructs a new instance of <see cref="RoleStoreBase{TRole, TKey, TUserRole, TRoleClaim}"/>. /// </summary> /// <param name="describer">The <see cref="IdentityErrorDescriber"/>.</param> public RoleStoreBase(IdentityErrorDescriber describer) { if (describer == null) { throw new ArgumentNullException(nameof(describer)); } ErrorDescriber = describer; } private bool _disposed; /// <summary> /// Gets or sets the <see cref="IdentityErrorDescriber"/> for any error that occurred with the current operation. /// </summary> public IdentityErrorDescriber ErrorDescriber { get; set; } /// <summary> /// Creates a new role in a store as an asynchronous operation. /// </summary> /// <param name="role">The role to create in the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public abstract Task<IdentityResult> CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a role in a store as an asynchronous operation. /// </summary> /// <param name="role">The role to update in the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public abstract Task<IdentityResult> UpdateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role to delete from the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public abstract Task<IdentityResult> DeleteAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the ID for a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose ID should be returned.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the ID of the role.</returns> public virtual Task<string> GetRoleIdAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(ConvertIdToString(role.Id)); } /// <summary> /// Gets the name of a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose name should be returned.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the name of the role.</returns> public virtual Task<string> GetRoleNameAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(role.Name); } /// <summary> /// Sets the name of a role in the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose name should be set.</param> /// <param name="roleName">The name of the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetRoleNameAsync(TRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } role.Name = roleName; return Task.CompletedTask; } /// <summary> /// Converts the provided <paramref name="id"/> to a strongly typed key object. /// </summary> /// <param name="id">The id to convert.</param> /// <returns>An instance of <typeparamref name="TKey"/> representing the provided <paramref name="id"/>.</returns> public virtual TKey ConvertIdFromString(string id) { if (id == null) { return default(TKey); } return (TKey)TypeDescriptor.GetConverter(typeof(TKey)).ConvertFromInvariantString(id); } /// <summary> /// Converts the provided <paramref name="id"/> to its string representation. /// </summary> /// <param name="id">The id to convert.</param> /// <returns>An <see cref="string"/> representation of the provided <paramref name="id"/>.</returns> public virtual string ConvertIdToString(TKey id) { if (id.Equals(default(TKey))) { return null; } return id.ToString(); } /// <summary> /// Finds the role who has the specified ID as an asynchronous operation. /// </summary> /// <param name="id">The role ID to look for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that result of the look up.</returns> public abstract Task<TRole> FindByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Finds the role who has the specified normalized name as an asynchronous operation. /// </summary> /// <param name="normalizedName">The normalized role name to look for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that result of the look up.</returns> public abstract Task<TRole> FindByNameAsync(string normalizedName, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a role's normalized name as an asynchronous operation. /// </summary> /// <param name="role">The role whose normalized name should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the name of the role.</returns> public virtual Task<string> GetNormalizedRoleNameAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(role.NormalizedName); } /// <summary> /// Set a role's normalized name as an asynchronous operation. /// </summary> /// <param name="role">The role whose normalized name should be set.</param> /// <param name="normalizedName">The normalized name to set</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetNormalizedRoleNameAsync(TRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } role.NormalizedName = normalizedName; return Task.CompletedTask; } /// <summary> /// Throws if this class has been disposed. /// </summary> protected void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } } /// <summary> /// Dispose the stores /// </summary> public void Dispose() => _disposed = true; /// <summary> /// Get the claims associated with the specified <paramref name="role"/> as an asynchronous operation. /// </summary> /// <param name="role">The role whose claims should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the claims granted to a role.</returns> public abstract Task<IList<Claim>> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Adds the <paramref name="claim"/> given to the specified <paramref name="role"/>. /// </summary> /// <param name="role">The role to add the claim to.</param> /// <param name="claim">The claim to add to the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public abstract Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Removes the <paramref name="claim"/> given from the specified <paramref name="role"/>. /// </summary> /// <param name="role">The role to remove the claim from.</param> /// <param name="claim">The claim to remove from the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public abstract Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// A navigation property for the roles the store contains. /// </summary> public abstract IQueryable<TRole> Roles { get; } /// <summary> /// Creates a entity representing a role claim. /// </summary> /// <param name="role">The associated role.</param> /// <param name="claim">The associated claim.</param> /// <returns>The role claim entity.</returns> protected virtual TRoleClaim CreateRoleClaim(TRole role, Claim claim) => new TRoleClaim { RoleId = role.Id, ClaimType = claim.Type, ClaimValue = claim.Value }; }
48.299625
154
0.681994
[ "MIT" ]
AndrewTriesToCode/aspnetcore
src/Identity/Extensions.Stores/src/RoleStoreBase.cs
12,896
C#
using System; using DNTProfiler.ServiceLayer.Contracts; using DNTProfiler.TestEFContext.DataLayer; using DNTProfiler.TestEFContext.Domain; namespace DNTProfiler.WebFormsTest { public partial class WebForm2 : BasePage { public IUnitOfWork UoW { set; get; } public IProductService ProductService { set; get; } public ICategoryService CategoryService { set; get; } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { bindToCategories(); } } private void bindToCategories() { ddlCategories.DataTextField = "Name"; ddlCategories.DataValueField = "Id"; ddlCategories.DataSource = CategoryService.GetAllCategories(); ddlCategories.DataBind(); } protected void btnAdd_Click(object sender, EventArgs e) { var product = new Product { Name = txtName.Text, Price = int.Parse(txtPrice.Text), CategoryId = int.Parse(ddlCategories.SelectedItem.Value) }; ProductService.AddNewProduct(product); UoW.SaveAllChanges(); Response.Redirect("~/Default.aspx"); } } }
30.162791
74
0.588281
[ "Apache-2.0" ]
Mohsenbahrzadeh/DNTProfiler
Tests/DNTProfiler.WebFormsTest/AddProduct.aspx.cs
1,299
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace Eaf.Notifications { /// <summary> /// Used to manage notification definitions. /// </summary> public interface INotificationDefinitionManager { /// <summary> /// Adds the specified notification definition. /// </summary> void Add(NotificationDefinition notificationDefinition); /// <summary> /// Gets a notification definition by name. Throws exception if there is no notification /// definition with given name. /// </summary> NotificationDefinition Get(string name); /// <summary> /// Gets all notification definitions. /// </summary> IReadOnlyList<NotificationDefinition> GetAll(); /// <summary> /// Gets all available notification definitions for given user. /// </summary> /// <param name="user">User.</param> IReadOnlyList<NotificationDefinition> GetAllAvailable(UserIdentifier user); /// <summary> /// Gets all available notification definitions for given user. /// </summary> /// <param name="user">User.</param> Task<IReadOnlyList<NotificationDefinition>> GetAllAvailableAsync(UserIdentifier user); /// <summary> /// Gets a notification definition by name. Returns null if there is no notification /// definition with given name. /// </summary> NotificationDefinition GetOrNull(string name); /// <summary> /// Checks if given notification ( <paramref name="name"/>) is available for given user. /// </summary> bool IsAvailable(string name, UserIdentifier user); /// <summary> /// Checks if given notification ( <paramref name="name"/>) is available for given user. /// </summary> Task<bool> IsAvailableAsync(string name, UserIdentifier user); /// <summary> /// Remove notification with given name /// </summary> /// <param name="name"></param> void Remove(string name); } }
34.721311
96
0.614731
[ "MIT" ]
afonsoft/EAF
src/Eaf/Notifications/INotificationDefinitionManager.cs
2,120
C#
using System.IO; using Aspose.Pdf.Facades; using System; namespace Aspose.Pdf.Examples.CSharp.AsposePDF.Bookmarks { public class GetBookmarkPageNumber { public static void Run() { // ExStart:GetBookmarkPageNumber // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Bookmarks(); // Create PdfBookmarkEditor PdfBookmarkEditor bookmarkEditor = new PdfBookmarkEditor(); // Open PDF file bookmarkEditor.BindPdf(dataDir + "GetBookmarks.pdf"); // Extract bookmarks Aspose.Pdf.Facades.Bookmarks bookmarks = bookmarkEditor.ExtractBookmarks(); foreach (Aspose.Pdf.Facades.Bookmark bookmark in bookmarks) { string strLevelSeprator = string.Empty; for (int i = 1; i < bookmark.Level; i++) { strLevelSeprator += "----"; } Console.WriteLine("{0}Title: {1}", strLevelSeprator, bookmark.Title); Console.WriteLine("{0}Page Number: {1}", strLevelSeprator, bookmark.PageNumber); Console.WriteLine("{0}Page Action: {1}", strLevelSeprator, bookmark.Action); } // ExEnd:GetBookmarkPageNumber } } }
37.222222
96
0.586567
[ "MIT" ]
Swisscard/Aspose.PDF-for-.NET
Examples/CSharp/AsposePDF/Bookmarks/GetBookmarkPageNumber.cs
1,340
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed class SymbolLoader { private readonly NameManager _nameManager; public PredefinedMembers PredefinedMembers { get; } private GlobalSymbolContext GlobalSymbolContext { get; } public ErrorHandling ErrorContext { get; } public SymbolTable RuntimeBinderSymbolTable { get; private set; } public SymbolLoader() { GlobalSymbolContext globalSymbols = new GlobalSymbolContext(new NameManager()); _nameManager = globalSymbols.GetNameManager(); PredefinedMembers = new PredefinedMembers(this); ErrorContext = new ErrorHandling(globalSymbols); GlobalSymbolContext = globalSymbols; Debug.Assert(GlobalSymbolContext != null); } public ErrorHandling GetErrorContext() { return ErrorContext; } public GlobalSymbolContext GetGlobalSymbolContext() { return GlobalSymbolContext; } public MethodSymbol LookupInvokeMeth(AggregateSymbol pAggDel) { Debug.Assert(pAggDel.AggKind() == AggKindEnum.Delegate); for (Symbol pSym = LookupAggMember(NameManager.GetPredefinedName(PredefinedName.PN_INVOKE), pAggDel, symbmask_t.MASK_ALL); pSym != null; pSym = LookupNextSym(pSym, pAggDel, symbmask_t.MASK_ALL)) { if (pSym is MethodSymbol meth && meth.isInvoke()) { return meth; } } return null; } public NameManager GetNameManager() { return _nameManager; } public PredefinedTypes GetPredefindTypes() { return GlobalSymbolContext.GetPredefTypes(); } public TypeManager GetTypeManager() { return TypeManager; } public TypeManager TypeManager { get { return GlobalSymbolContext.TypeManager; } } public PredefinedMembers getPredefinedMembers() { return PredefinedMembers; } public BSYMMGR getBSymmgr() { return GlobalSymbolContext.GetGlobalSymbols(); } public SymFactory GetGlobalSymbolFactory() { return GlobalSymbolContext.GetGlobalSymbolFactory(); } public AggregateSymbol GetPredefAgg(PredefinedType pt) => GetTypeManager().GetPredefAgg(pt); public AggregateType GetPredefindType(PredefinedType pt) => GetPredefAgg(pt).getThisType(); public Symbol LookupAggMember(Name name, AggregateSymbol agg, symbmask_t mask) { return getBSymmgr().LookupAggMember(name, agg, mask); } public Symbol LookupNextSym(Symbol sym, ParentSymbol parent, symbmask_t kindmask) { return BSYMMGR.LookupNextSym(sym, parent, kindmask); } // It would be nice to make this a virtual method on typeSym. public AggregateType GetAggTypeSym(CType typeSym) { Debug.Assert(typeSym != null); Debug.Assert(typeSym is AggregateType || typeSym is TypeParameterType || typeSym is ArrayType || typeSym is NullableType); switch (typeSym.GetTypeKind()) { case TypeKind.TK_AggregateType: return (AggregateType)typeSym; case TypeKind.TK_ArrayType: return GetPredefindType(PredefinedType.PT_ARRAY); case TypeKind.TK_TypeParameterType: return ((TypeParameterType)typeSym).GetEffectiveBaseClass(); case TypeKind.TK_NullableType: return ((NullableType)typeSym).GetAts(); } Debug.Assert(false, "Bad typeSym!"); return null; } private bool IsBaseInterface(CType pDerived, CType pBase) { Debug.Assert(pDerived != null); Debug.Assert(pBase != null); if (!pBase.isInterfaceType()) { return false; } if (!(pDerived is AggregateType atsDer)) { return false; } while (atsDer != null) { TypeArray ifacesAll = atsDer.GetIfacesAll(); for (int i = 0; i < ifacesAll.Count; i++) { if (AreTypesEqualForConversion(ifacesAll[i], pBase)) { return true; } } atsDer = atsDer.GetBaseClass(); } return false; } public bool IsBaseClassOfClass(CType pDerived, CType pBase) { Debug.Assert(pDerived != null); Debug.Assert(pBase != null); // This checks to see whether derived is a class, and if so, // if base is a base class of derived. if (!pDerived.isClassType()) { return false; } return IsBaseClass(pDerived, pBase); } private bool IsBaseClass(CType pDerived, CType pBase) { Debug.Assert(pDerived != null); Debug.Assert(pBase != null); // A base class has got to be a class. The derived type might be a struct. if (!(pBase is AggregateType atsBase && atsBase.isClassType())) { return false; } if (pDerived is NullableType derivedNub) { pDerived = derivedNub.GetAts(); } if (!(pDerived is AggregateType atsDer)) { return false; } AggregateType atsCur = atsDer.GetBaseClass(); while (atsCur != null) { if (atsCur == atsBase) { return true; } atsCur = atsCur.GetBaseClass(); } return false; } private bool HasCovariantArrayConversion(ArrayType pSource, ArrayType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return (pSource.rank == pDest.rank) && pSource.IsSZArray == pDest.IsSZArray && HasImplicitReferenceConversion(pSource.GetElementType(), pDest.GetElementType()); } public bool HasIdentityOrImplicitReferenceConversion(CType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (AreTypesEqualForConversion(pSource, pDest)) { return true; } return HasImplicitReferenceConversion(pSource, pDest); } private bool AreTypesEqualForConversion(CType pType1, CType pType2) { return pType1.Equals(pType2); } private bool HasArrayConversionToInterface(ArrayType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (!pSource.IsSZArray) { return false; } if (!pDest.isInterfaceType()) { return false; } // * From a single-dimensional array type S[] to IList<T> or IReadOnlyList<T> and their base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // We only have six interfaces to check. IList<T>, IReadOnlyList<T> and their bases: // * The base interface of IList<T> is ICollection<T>. // * The base interface of ICollection<T> is IEnumerable<T>. // * The base interface of IEnumerable<T> is IEnumerable. // * The base interface of IReadOnlyList<T> is IReadOnlyCollection<T>. // * The base interface of IReadOnlyCollection<T> is IEnumerable<T>. if (pDest.isPredefType(PredefinedType.PT_IENUMERABLE)) { return true; } AggregateType atsDest = (AggregateType)pDest; AggregateSymbol aggDest = atsDest.getAggregate(); if (!aggDest.isPredefAgg(PredefinedType.PT_G_ILIST) && !aggDest.isPredefAgg(PredefinedType.PT_G_ICOLLECTION) && !aggDest.isPredefAgg(PredefinedType.PT_G_IENUMERABLE) && !aggDest.isPredefAgg(PredefinedType.PT_G_IREADONLYCOLLECTION) && !aggDest.isPredefAgg(PredefinedType.PT_G_IREADONLYLIST)) { return false; } Debug.Assert(atsDest.GetTypeArgsAll().Count == 1); CType pSourceElement = pSource.GetElementType(); CType pDestTypeArgument = atsDest.GetTypeArgsAll()[0]; return HasIdentityOrImplicitReferenceConversion(pSourceElement, pDestTypeArgument); } private bool HasImplicitReferenceConversion(CType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); // The implicit reference conversions are: // * From any reference type to Object. if (pSource.IsRefType() && pDest.isPredefType(PredefinedType.PT_OBJECT)) { return true; } // * From any class type S to any class type T provided S is derived from T. if (pSource.isClassType() && pDest.isClassType() && IsBaseClass(pSource, pDest)) { return true; } // ORIGINAL RULES: // // * From any class type S to any interface type T provided S implements T. // if (pSource.isClassType() && pDest.isInterfaceType() && IsBaseInterface(pSource, pDest)) // { // return true; // } // // * from any interface type S to any interface type T, provided S is derived from T. // if (pSource.isInterfaceType() && pDest.isInterfaceType() && IsBaseInterface(pSource, pDest)) // { // return true; // } // VARIANCE EXTENSIONS: // * From any class type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (pSource.isClassType() && pDest.isInterfaceType() && HasAnyBaseInterfaceConversion(pSource, pDest)) { return true; } if (pSource.isInterfaceType() && pDest.isInterfaceType() && HasAnyBaseInterfaceConversion(pSource, pDest)) { return true; } if (pSource.isInterfaceType() && pDest.isInterfaceType() && pSource != pDest && HasInterfaceConversion(pSource as AggregateType, pDest as AggregateType)) { return true; } if (pSource is ArrayType arrSource) { // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (pDest is ArrayType arrDest && HasCovariantArrayConversion(arrSource, arrDest)) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (pDest.isPredefType(PredefinedType.PT_ARRAY) || IsBaseInterface(GetPredefindType(PredefinedType.PT_ARRAY), pDest)) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (HasArrayConversionToInterface(arrSource, pDest)) { return true; } } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate if (pSource.isDelegateType() && (pDest.isPredefType(PredefinedType.PT_MULTIDEL) || pDest.isPredefType(PredefinedType.PT_DELEGATE) || IsBaseInterface(GetPredefindType(PredefinedType.PT_MULTIDEL), pDest))) { return true; } // VARIANCE EXTENSION: // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (pSource.isDelegateType() && pDest.isDelegateType() && HasDelegateConversion(pSource as AggregateType, pDest as AggregateType)) { return true; } // * From the null literal to any reference type // NOTE: We extend the specification here. The C# 3.0 spec does not describe // a "null type". Rather, it says that the null literal is typeless, and is // convertible to any reference or nullable type. However, the C# 2.0 and 3.0 // implementations have a "null type" which some expressions other than the // null literal may have. (For example, (null??null), which is also an // extension to the specification.) if (pSource is NullType) { if (pDest.IsRefType() || pDest is NullableType) { return true; } } // * Implicit conversions involving type parameters that are known to be reference types. return pSource is TypeParameterType srcParType && HasImplicitReferenceTypeParameterConversion(srcParType, pDest); } private bool HasImplicitReferenceTypeParameterConversion( TypeParameterType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (!pSource.IsRefType()) { // Not a reference conversion. return false; } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. AggregateType pEBC = pSource.GetEffectiveBaseClass(); if (pDest == pEBC) { return true; } // * From T to any base class of C. if (IsBaseClass(pEBC, pDest)) { return true; } // * From T to any interface implemented by C. if (IsBaseInterface(pEBC, pDest)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I. TypeArray pInterfaces = pSource.GetInterfaceBounds(); for (int i = 0; i < pInterfaces.Count; ++i) { if (pInterfaces[i] == pDest) { return true; } } // * From T to a type parameter U, provided T depends on U. return pDest is TypeParameterType typeParamDest && pSource.DependsOn(typeParamDest); } private bool HasAnyBaseInterfaceConversion(CType pDerived, CType pBase) { if (!pBase.isInterfaceType()) { return false; } if (!(pDerived is AggregateType atsDer)) { return false; } AggregateType atsBase = (AggregateType)pBase; while (atsDer != null) { foreach (AggregateType iface in atsDer.GetIfacesAll().Items) { if (HasInterfaceConversion(iface, atsBase)) { return true; } } atsDer = atsDer.GetBaseClass(); } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceConversion(AggregateType pSource, AggregateType pDest) { Debug.Assert(pSource != null && pSource.isInterfaceType()); Debug.Assert(pDest != null && pDest.isInterfaceType()); return HasVariantConversion(pSource, pDest); } ////////////////////////////////////////////////////////////////////////////// private bool HasDelegateConversion(AggregateType pSource, AggregateType pDest) { Debug.Assert(pSource != null && pSource.isDelegateType()); Debug.Assert(pDest != null && pDest.isDelegateType()); return HasVariantConversion(pSource, pDest); } ////////////////////////////////////////////////////////////////////////////// private bool HasVariantConversion(AggregateType pSource, AggregateType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (pSource == pDest) { return true; } AggregateSymbol pAggSym = pSource.getAggregate(); if (pAggSym != pDest.getAggregate()) { return false; } TypeArray pTypeParams = pAggSym.GetTypeVarsAll(); TypeArray pSourceArgs = pSource.GetTypeArgsAll(); TypeArray pDestArgs = pDest.GetTypeArgsAll(); Debug.Assert(pTypeParams.Count == pSourceArgs.Count); Debug.Assert(pTypeParams.Count == pDestArgs.Count); for (int iParam = 0; iParam < pTypeParams.Count; ++iParam) { CType pSourceArg = pSourceArgs[iParam]; CType pDestArg = pDestArgs[iParam]; // If they're identical then this one is automatically good, so skip it. if (pSourceArg == pDestArg) { continue; } TypeParameterType pParam = (TypeParameterType)pTypeParams[iParam]; if (pParam.Invariant) { return false; } if (pParam.Covariant) { if (!HasImplicitReferenceConversion(pSourceArg, pDestArg)) { return false; } } if (pParam.Contravariant) { if (!HasImplicitReferenceConversion(pDestArg, pSourceArg)) { return false; } } } return true; } private bool HasImplicitBoxingTypeParameterConversion( TypeParameterType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (pSource.IsRefType()) { // Not a boxing conversion; both source and destination are references. return false; } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. AggregateType pEBC = pSource.GetEffectiveBaseClass(); if (pDest == pEBC) { return true; } // * From T to any base class of C. if (IsBaseClass(pEBC, pDest)) { return true; } // * From T to any interface implemented by C. if (IsBaseInterface(pEBC, pDest)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I. TypeArray pInterfaces = pSource.GetInterfaceBounds(); for (int i = 0; i < pInterfaces.Count; ++i) { if (pInterfaces[i] == pDest) { return true; } } // * The conversion from T to a type parameter U, provided T depends on U, is not // classified as a boxing conversion because it is not guaranteed to box. // (If both T and U are value types then it is an identity conversion.) return false; } private bool HasImplicitTypeParameterBaseConversion( TypeParameterType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); if (HasImplicitReferenceTypeParameterConversion(pSource, pDest)) { return true; } if (HasImplicitBoxingTypeParameterConversion(pSource, pDest)) { return true; } return pDest is TypeParameterType typeParamDest && pSource.DependsOn(typeParamDest); } public bool HasImplicitBoxingConversion(CType pSource, CType pDest) { Debug.Assert(pSource != null); Debug.Assert(pDest != null); // Certain type parameter conversions are classified as boxing conversions. if (pSource is TypeParameterType srcParType && HasImplicitBoxingTypeParameterConversion(srcParType, pDest)) { return true; } // The rest of the boxing conversions only operate when going from a value type // to a reference type. if (!pSource.IsValType() || !pDest.IsRefType()) { return false; } // A boxing conversion exists from a nullable type to a reference type // if and only if a boxing conversion exists from the underlying type. if (pSource is NullableType nubSource) { return HasImplicitBoxingConversion(nubSource.GetUnderlyingType(), pDest); } // A boxing conversion exists from any non-nullable value type to object, // to System.ValueType, and to any interface type implemented by the // non-nullable value type. Furthermore, an enum type can be converted // to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, // so we can just check here. if (IsBaseClass(pSource, pDest)) { return true; } if (HasAnyBaseInterfaceConversion(pSource, pDest)) { return true; } return false; } public bool HasBaseConversion(CType pSource, CType pDest) { // By a "base conversion" we mean: // // * an identity conversion // * an implicit reference conversion // * an implicit boxing conversion // * an implicit type parameter conversion // // In other words, these are conversions that can be made to a base // class, base interface or co/contravariant type without any change in // representation other than boxing. A conversion from, say, int to double, // is NOT a "base conversion", because representation is changed. A conversion // from, say, lambda to expression tree is not a "base conversion" because // do not have a type. // // The existence of a base conversion depends solely upon the source and // destination types, not the source expression. // // This notion is not found in the spec but it is useful in the implementation. if (pSource is AggregateType && pDest.isPredefType(PredefinedType.PT_OBJECT)) { // If we are going from any aggregate type (class, struct, interface, enum or delegate) // to object, we immediately return true. This may seem like a mere optimization -- // after all, if we have an aggregate then we have some kind of implicit conversion // to object. // // However, it is not a mere optimization; this introduces a control flow change // in error reporting scenarios for unresolved type forwarders. If a type forwarder // cannot be resolved then the resulting type symbol will be an aggregate, but // we will not be able to classify it into class, struct, etc. // // We know that we will have an error in this case; we do not wish to compound // that error by giving a spurious "you cannot convert this thing to object" // error, which, after all, will go away when the type forwarding problem is // fixed. return true; } if (HasIdentityOrImplicitReferenceConversion(pSource, pDest)) { return true; } if (HasImplicitBoxingConversion(pSource, pDest)) { return true; } return pSource is TypeParameterType srcParType && HasImplicitTypeParameterBaseConversion(srcParType, pDest); } public bool IsBaseAggregate(AggregateSymbol derived, AggregateSymbol @base) { Debug.Assert(!derived.IsEnum() && !@base.IsEnum()); if (derived == @base) return true; // identity. // refactoring error tolerance: structs and delegates can be base classes in error scenarios so // we cannot filter on whether or not the base is marked as sealed. if (@base.IsInterface()) { // Search the direct and indirect interfaces via ifacesAll, going up the base chain... while (derived != null) { foreach (AggregateType iface in derived.GetIfacesAll().Items) { if (iface.getAggregate() == @base) return true; } derived = derived.GetBaseAgg(); } return false; } // base is a class. Just go up the base class chain to look for it. while (derived.GetBaseClass() != null) { derived = derived.GetBaseClass().getAggregate(); if (derived == @base) return true; } return false; } internal void SetSymbolTable(SymbolTable symbolTable) { RuntimeBinderSymbolTable = symbolTable; } } }
38.292047
134
0.536364
[ "MIT" ]
AlexGhiondea/corefx
src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Symbols/SymbolLoader.cs
29,370
C#
using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace AuthenticodeExaminer { /// <summary> /// An interface for low-level information about Authenticode signature. /// </summary> public interface ICmsSignature { /// <summary> /// Gets the hashing digest algorithm of the signature. /// </summary> Oid? DigestAlgorithm { get; } /// <summary> /// Gets the signing algorithm of the signature. /// </summary> Oid? HashEncryptionAlgorithm { get; } /// <summary> /// Provides a list of unsigned, or unauthenticated, attributes in the current signature. /// </summary> IReadOnlyList<CryptographicAttributeObject> UnsignedAttributes { get; } /// <summary> /// Provides a list of signed, or authenticated, attributes in the current signature. /// </summary> IReadOnlyList<CryptographicAttributeObject> SignedAttributes { get; } /// <summary> /// Gets the X509 certificate used in the signature. /// </summary> X509Certificate2? Certificate { get; } /// <summary> /// Gets a list of sub-signatures, such as nested signatures or counter signatures. /// </summary> /// <returns>A read only list of immediate nested signatures.</returns> IReadOnlyList<ICmsSignature> GetNestedSignatures(); /// <summary> /// Gets the kind of the signature. For more details, see <see cref="SignatureKind"/>. /// </summary> SignatureKind Kind { get; } /// <summary> /// Gets a list of additional certificates in the signature used to assist in chain /// building to the <see cref="Certificate"/>. /// </summary> X509Certificate2Collection AdditionalCertificates { get; } /// <summary> /// Gets a <see cref="HashAlgorithmName"/> representation of the <see cref="DigestAlgorithm"/>. /// </summary> HashAlgorithmName DigestAlgorithmName { get; } /// <summary> /// Provides the raw value of the content of the signature. /// </summary> byte[]? Content { get; } /// <summary> /// Get the serial number of the certificate used to sign the signature. /// </summary> byte[] SerialNumber { get; } /// <summary> /// Gets the signature. /// </summary> ReadOnlyMemory<byte> Signature { get; } } }
34.118421
103
0.601234
[ "MIT" ]
Lakritzator/AuthenticodeExaminer
src/AuthenticodeExaminer/ICmsSignature.cs
2,595
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace HackathonProject.Models { using System; using System.Collections.Generic; public partial class Result_HIG { public int Id { get; set; } public string MobileNumber { get; set; } } }
32.190476
86
0.492604
[ "MIT" ]
abinesh-ragupathy/DDA-Housing-Scheme
HackathonProject/Models/Result_HIG.cs
676
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _10.PairsByDifference { class PairsByDifference { public static void Main() { int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int difference = int.Parse(Console.ReadLine()); int pairs = 0; for (int i = 0; i < arr.Length-1; i++) { for (int j = i+1; j < arr.Length; j++) { if (Math.Abs(arr[i] - arr[j]) == difference) { pairs++; } } } Console.WriteLine(pairs); } } }
24.806452
82
0.456437
[ "MIT" ]
KristiyanSevov/SoftUni-Programming-Fundamentals
Exercises/06. Arrays-Exercises/10. PairsByDifference/PairsByDifference.cs
771
C#
#Tue Nov 30 21:55:11 EST 2021 lib/com.ibm.ws.org.jboss.classfilewriter_1.2.59.jar=6892241c0dd4e9d194bc275878f26e5e dev/api/ibm/schema/ibm-managed-bean-bnd_1_0.xsd=3b0b778a121ff7c6c28f9e72afd96488 dev/spi/ibm/javadoc/com.ibm.websphere.appserver.spi.cdi_1.1-javadoc.zip=d3ba55dc49da0b0898ecba7e0be69e15 lib/com.ibm.ws.cdi.interfaces_1.0.59.jar=e8333f9376fb043dbb0780d8e19903b9 lib/com.ibm.ws.cdi.internal_1.0.59.jar=41dc4fbab6f4441384b0d710d5092f38 lib/com.ibm.ws.org.jboss.logging_1.0.59.jar=914f3ec45d8f62ef49d234ae8d448362 dev/api/third-party/com.ibm.websphere.appserver.thirdparty.cdi-2.0_1.0.59.jar=d249186470c303b0378a5183740f2429 lib/com.ibm.ws.cdi.2.0.weld_1.0.59.jar=ac096663737a2d59e2f13603932df787 lib/com.ibm.ws.org.jboss.jdeparser.1.0.0_1.0.59.jar=c420f679779b735bb9477f83556bf190 dev/api/spec/com.ibm.websphere.javaee.jaxws.2.2_1.0.59.jar=f1cb3020bcd99fccff723f8d91efcbc2 lib/features/com.ibm.websphere.appserver.cdi-2.0.mf=c1a7b682f36ddc69118eb7ce013b5c52 dev/api/ibm/schema/ibm-managed-bean-bnd_1_1.xsd=788164a7a6ea3fb24bb6106a48a9068b lib/com.ibm.ws.managedobject_1.0.59.jar=056779243f4b0da44fd43b7f745756fb dev/spi/ibm/com.ibm.websphere.appserver.spi.cdi_1.1.59.jar=1d081f782f2937de3017064256cb31ef lib/com.ibm.ws.org.jboss.weld3_1.0.59.jar=158374eb8217185d8840594d46854e77 lib/com.ibm.ws.cdi.weld_1.0.59.jar=959347c8882341068fdec1627aa2a570 dev/api/spec/com.ibm.websphere.javaee.jaxb.2.2_1.0.59.jar=048c178fb99f340d9e301c1637b491a1
76.263158
110
0.855763
[ "MIT" ]
johnojacob99/CSC480-21F
frontend/target/liberty/wlp/lib/features/checksums/com.ibm.websphere.appserver.cdi-2.0.cs
1,449
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; namespace LibrarySystem.Models { [MetadataType(typeof(BookMetadata))] public partial class Book { } public class BookMetadata { [Key] public int Id { get; set; } [Required] [StringLength(150)] public string Title { get; set; } [Required] [StringLength(200)] public string Author { get; set; } [StringLength(20)] public string ISBN { get; set; } [StringLength(100)] public string Url { get; set; } public string Description { get; set; } } }
20.054054
47
0.609164
[ "MIT" ]
Valersd/LibrarySystemMvc
LibrarySystem.Models/Models/Book.cs
744
C#
using System; using System.Collections.Generic; using System.Text; namespace IocServiceDemo { /// <summary> /// 服务提供者接口类 /// </summary> public interface IDemoServiceProvider { /// <summary> /// 获取服务 /// </summary> /// <returns></returns> IDemoService GetService(); /// <summary> /// 获取指定服务 /// </summary> /// <typeparam name="T">服务类型</typeparam> /// <returns></returns> IDemoService GetService<T>() where T : class; } }
20.576923
53
0.530841
[ "Apache-2.0" ]
Lc3586/Microservice
src/Applications/SimpleApi/IocServiceDemo/IDemoServiceProvider.cs
581
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Opsgenie.Inputs { public sealed class IntegrationActionIgnoreFilterConditionArgs : Pulumi.ResourceArgs { [Input("expectedValue")] public Input<string>? ExpectedValue { get; set; } [Input("field", required: true)] public Input<string> Field { get; set; } = null!; [Input("key")] public Input<string>? Key { get; set; } [Input("not")] public Input<bool>? Not { get; set; } [Input("operation", required: true)] public Input<string> Operation { get; set; } = null!; /// <summary> /// Integer value that defines in which order the action will be performed. Default: `1`. /// </summary> [Input("order")] public Input<int>? Order { get; set; } public IntegrationActionIgnoreFilterConditionArgs() { } } }
29.073171
97
0.623322
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-opsgenie
sdk/dotnet/Inputs/IntegrationActionIgnoreFilterConditionArgs.cs
1,192
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace rpi.server { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } } }
27.658537
106
0.667549
[ "MIT" ]
AgostonAttila/netacademia-lenyugozo-csharp
rpi.server/Startup.cs
1,136
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace Blog.Models { public class Article { [Key] public int Id { get; set; } [Required] [StringLength(20)] public string Title { get; set; } public string Content { get; set; } [ForeignKey("Author")] public string AuthorId { get; set; } public virtual ApplicationUser Author { get; set; } public bool IsAuthor(string name) { return (this.Author.UserName.Equals(name)); } } }
22.677419
59
0.621622
[ "MIT" ]
AlexanderVlaskovski/SoftwareTechnologies-SoftUni
09.CSharp net framework Blog/Blog/Blog/Models/Article.cs
705
C#
using System; using System.Collections.Generic; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Controllers; using JsonApiDotNetCore.Exceptions; using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Internal.Queries.Parsing; using JsonApiDotNetCore.Models.Annotation; using JsonApiDotNetCore.Queries; using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.QueryStrings; using JsonApiDotNetCore.RequestServices.Contracts; using Microsoft.Extensions.Primitives; namespace JsonApiDotNetCore.Internal.QueryStrings { public class IncludeQueryStringParameterReader : QueryStringParameterReader, IIncludeQueryStringParameterReader { private readonly IJsonApiOptions _options; private readonly IncludeParser _includeParser; private IncludeExpression _includeExpression; private string _lastParameterName; public IncludeQueryStringParameterReader(ICurrentRequest currentRequest, IResourceContextProvider resourceContextProvider, IJsonApiOptions options) : base(currentRequest, resourceContextProvider) { _options = options ?? throw new ArgumentNullException(nameof(options)); _includeParser = new IncludeParser(resourceContextProvider, ValidateSingleRelationship); } private void ValidateSingleRelationship(RelationshipAttribute relationship, ResourceContext resourceContext, string path) { if (!relationship.CanInclude) { throw new InvalidQueryStringParameterException(_lastParameterName, "Including the requested relationship is not allowed.", path == relationship.PublicName ? $"Including the relationship '{relationship.PublicName}' on '{resourceContext.ResourceName}' is not allowed." : $"Including the relationship '{relationship.PublicName}' in '{path}' on '{resourceContext.ResourceName}' is not allowed."); } } /// <inheritdoc/> public bool IsEnabled(DisableQueryAttribute disableQueryAttribute) { return !disableQueryAttribute.ContainsParameter(StandardQueryStringParameters.Include); } /// <inheritdoc/> public bool CanRead(string parameterName) { return parameterName == "include"; } /// <inheritdoc/> public void Read(string parameterName, StringValues parameterValue) { _lastParameterName = parameterName; try { _includeExpression = GetInclude(parameterValue); } catch (QueryParseException exception) { throw new InvalidQueryStringParameterException(parameterName, "The specified include is invalid.", exception.Message, exception); } } private IncludeExpression GetInclude(string parameterValue) { return _includeParser.Parse(parameterValue, RequestResource, _options.MaximumIncludeDepth); } /// <inheritdoc/> public IReadOnlyCollection<ExpressionInScope> GetConstraints() { var expressionInScope = _includeExpression != null ? new ExpressionInScope(null, _includeExpression) : new ExpressionInScope(null, IncludeExpression.Empty); return new[] {expressionInScope}; } } }
39.545455
155
0.682759
[ "MIT" ]
bjornharrtell/JsonApiDotNetCore
src/JsonApiDotNetCore/Internal/QueryStrings/IncludeQueryStringParameterReader.cs
3,480
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ancestry.Daisy.Tests.Daisy.Component.SilverBulletHandlers { using System.Text.RegularExpressions; using Ancestry.Daisy.Statements; using Ancestry.Daisy.Tests.Daisy.Component.Controllers; using Ancestry.Daisy.Tests.Daisy.Component.Domain; public class TimestampBeforeSilverBulletStatement : IStatementDefinition { public Type ScopeType { get { return typeof(Transaction); } } public string Name { get { return "HasTransaction"; } } public Type TransformsScopeTo { get { return null; } } public ILinkedStatement Link(string statement) { var match = Regex.Match(statement, @"Timestamp before (\d*) year ago"); if (!match.Success) return null; return new Linked(this, int.Parse(match.Groups[1].Value)); } private class Linked : GenericLink { public int Years { get; set; } public Linked(IStatementDefinition def, int years) : base(def) { Years = years; } public override bool Execute(InvokationContext context) { var controller = new TransactionController(); Initializer(controller, context); return controller.TimestampBeforeYearsAgo(Years); } } } }
30.5625
83
0.630539
[ "MIT" ]
erikhejl/Daisy
Tests/Daisy/Component/SilverBulletHandlers/TimestampBeforeSilverBulletStatement.cs
1,469
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using TMPro; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class TechTreeNav : MonoBehaviour { public static TechTreeNav instance; public GameObject chrSelect; public GameObject chrRW; public GameObject glossary; public GameObject techSelect; public GameObject techNext; public GameObject techRW; public Image buttonImg; public Sprite battleInactive; public GameObject selectTag; public GameObject inactive; private Unit clickedUnit; private PlayerMeta player; // Start is called before the first frame update void Awake() { instance = this; RefreshSelect(); Color mainColor = HelperScripts.GetColorByFaction(BaseSaver.GetPlayer().faction); mainColor.a = .8f; GetComponent<Image>().color = mainColor; techSelect.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = ""; selectTag.SetActive(false); techNext.SetActive(false); } public void RefreshSelect(){ if (GameMeta.RosterNeedsUpgrade()) { buttonImg.color = new Color(1,.35f,.35f); } else { buttonImg.color = Color.white; } foreach (Transform child in chrSelect.transform) { Destroy(child.gameObject); } player = BaseSaver.GetPlayer(); List<Unit> units = new List<Unit>(player.characters.Reverse()); for(int i = 0; i < units.Count; i++){ PopulateRw(units[i], i); } if (units.Count > 3) { inactive.SetActive(true); List<Unit> inact = new List<Unit>(); for(int i = 3; i < units.Count; i++){ inact.Add(units[i]); } inactive.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = ClassNode.GetClassBonusString(inact.ToArray()); } else { inactive.SetActive(false); } } void RefreshTech(){ foreach (Transform child in techSelect.transform.GetChild(1)) { Destroy(child.gameObject); } foreach (Transform child in techNext.transform.GetChild(2)) { Destroy(child.gameObject); } } void PopulateRw(Unit unt, int idx){ GameObject nwRow = Instantiate(chrRW, chrSelect.transform); nwRow.GetComponent<TechTreeUnitWrap>().unit = unt; nwRow.GetComponent<TechTreeUnitWrap>().Refresh(); RefreshMainPanel(nwRow, unt, idx); if (idx > 2) { //Reserves nwRow.GetComponent<Image>().sprite = battleInactive; } UnityEngine.Events.UnityAction action1 = () => { instance.CharClicked(unt); }; nwRow.GetComponent<Button>().onClick.AddListener(action1); } static void RefreshMainPanel(GameObject panel, Unit unit, int unitIdx){ Debug.Log("RefreshMainPanel: " + unit.characterMoniker); panel.SetActive(true); foreach(Transform child in panel.transform){ if (child.name.Equals("CharImg")) { UnitProxy unt = ClassNode.ComputeClassBaseUnit(instance.player.faction, unit.GetUnitType(), instance.glossary.GetComponent<Glossary>()); child.GetComponent<Image>().sprite = unt.transform.GetChild(0).GetComponent<SpriteRenderer>().sprite; } if (child.name.Equals("CharName")) { child.GetComponent<TextMeshProUGUI>().text = unit.characterMoniker; } if (child.name.Equals("CharType")) { child.GetComponent<TextMeshProUGUI>().text = unit.GetCurrentClass().ClassName(); } if (child.name.Equals("HPImg")) { child.GetChild(0).GetComponent<TextMeshProUGUI>().text = unit.GetMaxHP().ToString(); } if (child.name.Equals("Lineup")) { if (unitIdx > 2) { //Reserves child.GetComponent<Image>().color = Color.red; child.GetChild(0).GetComponent<TextMeshProUGUI>().text = "Inactive"; } else { //Roster child.GetComponent<Image>().color = Color.green; child.GetChild(0).GetComponent<TextMeshProUGUI>().text = "Battle Ready"; } } if (child.name.Equals("ExpImg")) { string expStr = "*"; if(unit.GetLvl() >= unit.GetCurrentClass().GetWhenToUpgrade()){ Debug.Log("Rotate!"); child.eulerAngles = new Vector3(0,0,-25); iTween.RotateTo(child.gameObject,iTween.Hash( "z", 25, "time", 5, "easetype", "easeInOutSine", "looptype","pingpong" )); iTween.ScaleTo(child.gameObject,iTween.Hash( "x", 1.3, "y", 1.3, "time", 2, "easetype", "easeInOutSine", "looptype","pingpong" )); } else { expStr = unit.GetLvl().ToString(); } child.GetChild(0).GetComponent<TextMeshProUGUI>().text = expStr; } if (child.name.Equals("Stats")) { foreach (Transform t in child.transform) { if (t.name.Equals("Move")) { RefreshSkillPnl(t, unit.GetMoveSpeed().ToString()); } if (t.name.Equals("AtkPwr")) { RefreshSkillPnl(t, unit.GetAttack().ToString()); } if (t.name.Equals("AtkRng")) { RefreshSkillPnl(t, unit.GetAtkRange().ToString()); } } } if (child.name.Equals("Turn")) { foreach (Transform t in child.transform) { if (t.name.Equals("MvTrn")) { RefreshSkillPnl(t, unit.GetTurnMoves().ToString()); } if (t.name.Equals("AtkTrn")) { RefreshSkillPnl(t, unit.GetTurnAttacks().ToString()); } } } } } public void UpgradeSelected(ClassNode cNode){ if (clickedUnit != null) { clickedUnit = cNode.UpgradeCharacter(clickedUnit); clickedUnit.SetCurrentClass(cNode.GetType().ToString()); PlayerMeta player = BaseSaver.GetPlayer(); Unit unt = player.characters.Where(chr => chr.characterName.Equals(clickedUnit.characterName)).First(); List<Unit> nwRoster = new List<Unit>(); foreach(Unit rUnt in player.characters){ if (rUnt.characterMoniker.Equals(clickedUnit.characterMoniker)) { nwRoster.Add(clickedUnit); } else { nwRoster.Add(rUnt); } } player.characters = nwRoster.ToArray(); BaseSaver.PutPlayer(player); RefreshSelect(); CharClicked(clickedUnit); } } //void Flush(){ // foreach (Transform child in techSelect.transform) // { // Destroy(child.gameObject); // } // foreach (Transform child in techNext.transform) // { // Destroy(child.gameObject); // } //} public void CharClicked(Unit unt){ clickedUnit = unt; RefreshTech(); Debug.Log("Clicked: " + unt.characterMoniker); PlayerMeta player = BaseSaver.GetPlayer(); IterateThroughTreeUp(unt.GetCurrentClass()); IterateThroughTreeDown(unt.GetLvl(), unt.GetCurrentClass()); //UnitProxy unt = ClassNode.ComputeClassBaseUnit(instance.player.faction, unt.GetUnitType(), instance.glossary.GetComponent<Glossary>()); string lvlupstr = unt.GetCurrentClass().GetWhenToUpgrade() == StaticClassRef.LEVEL4 ? "Fully Upgraded" : "Next lvl at: " + unt.GetCurrentClass().GetWhenToUpgrade().ToString(); techSelect.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = lvlupstr; selectTag.SetActive(true); selectTag.transform.GetChild(0).GetComponent<Image>().sprite = ClassNode.ComputeClassBaseUnit(instance.player.faction, unt.GetUnitType(), instance.glossary.GetComponent<Glossary>()) .transform.GetChild(0).GetComponent<SpriteRenderer>().sprite; selectTag.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = unt.characterMoniker; selectTag.transform.GetChild(2).GetComponent<TextMeshProUGUI>().text = unt.GetCurrentClass().ClassName(); } void IterateThroughTreeUp(ClassNode parent){ if (parent != null) { GameObject nwRow = Instantiate(techRW, techSelect.transform.GetChild(1)); RefreshTechPanel(nwRow, parent); IterateThroughTreeUp(parent.GetParent()); } } void IterateThroughTreeDown(int lvl, ClassNode parent){ if (parent != null && lvl >= parent.GetWhenToUpgrade()) { techNext.SetActive(true); foreach(ClassNode nd in parent.GetChildren()){ GameObject nwRow = Instantiate(techRW, techNext.transform.GetChild(2)); RefreshTechPanel(nwRow, nd); UnityEngine.Events.UnityAction action = () => { instance.UpgradeSelected(nd); }; nwRow.GetComponent<Button>().onClick.AddListener(action); } } else { techNext.SetActive(false); } } void RefreshTechPanel(GameObject panel, ClassNode clss){ Debug.Log("RefreshTechPanel: " + clss.ClassName()); foreach(Transform child in panel.transform){ if (child.name.Equals("Class")) { child.GetComponent<TextMeshProUGUI>().text = clss.ClassName(); } if (child.name.Equals("Image")) { child.GetChild(0).GetComponent<TextMeshProUGUI>().text = clss.GetWhenToUpgrade().ToString(); } if (child.name.Equals("Desc")) { child.GetComponent<TextMeshProUGUI>().text = clss.ClassDesc(); } } } static void RefreshSkillPnl(Transform pnl, string val){ foreach (Transform t in pnl) { if (t.name.Equals("Val")) { t.GetChild(0).GetComponent<TextMeshProUGUI>().text = val; } } } public void SaveAndReturn(){ SavePosition(); SceneManager.LoadScene("MapScene"); } public void SavePosition(){ PlayerMeta player = BaseSaver.GetPlayer(); List<Unit> units = new List<Unit>(); foreach (Transform child in chrSelect.transform) { foreach (Transform chld in child) { foreach(Unit unt in player.characters){ if (chld.name.Equals("CharName") && chld.GetComponent<TextMeshProUGUI>().text.Equals(unt.characterMoniker)) { if (!units.Where(un => un.characterMoniker.Equals(unt.characterMoniker)).Any()) { units.Add(unt); } } } } } units.Reverse(); player.characters = units.ToArray(); //player.characters.Reverse(); Debug.Log("Player Units: " + player.characters.Length.ToString()); BaseSaver.PutPlayer(player); } }
38.443038
190
0.535644
[ "MIT" ]
BradZzz/EldersQuest
Assets/Scripts/TechTree/TechTreeNav.cs
12,150
C#
// -------------------------------------------------------------------------------------------------- // <copyright file="Order.cs" company="FluentPOS"> // Copyright (c) FluentPOS. All rights reserved. // The core team: Mukesh Murugan (iammukeshm), Chhin Sras (chhinsras), Nikolay Chebotov (unchase). // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using FluentPOS.Shared.Core.Domain; using FluentPOS.Shared.DTOs.People.Customers; namespace FluentPOS.Modules.Sales.Core.Entities { public class Order : BaseEntity { public DateTime TimeStamp { get; private set; } public Guid CustomerId { get; private set; } public string CustomerName { get; private set; } public string CustomerPhone { get; private set; } public string CustomerEmail { get; private set; } public decimal SubTotal { get; private set; } public decimal Tax { get; private set; } public decimal Discount { get; private set; } public decimal Total { get; private set; } public bool IsPaid { get; private set; } public string Note { get; private set; } public virtual ICollection<Product> Products { get; private set; } = new List<Product>(); public static Order InitializeOrder() { return new Order() { TimeStamp = DateTime.Now }; } public void AddCustomer(GetCustomerByIdResponse customer) { this.CustomerId = customer.Id; this.CustomerName = customer.Name; this.CustomerEmail = customer.Email; this.CustomerPhone = customer.Phone; } public void AddProduct(Product product) { this.Products.Add(product); } internal void AddProduct(Guid productId, string name, int quantity, decimal rate, decimal tax) { this.Products.Add(new Product() { ProductId = productId, Quantity = quantity, Tax = tax * quantity, Price = quantity * rate, Total = (quantity * rate) + (tax * quantity) }); } } }
32.986111
102
0.559158
[ "MIT" ]
Asad-360/fluentpos
src/server/Modules/Sales/Modules.Sales.Core/Entities/Order.cs
2,375
C#
using System; using System.Collections.Generic; using System.Linq; using ShapeWorld.Library; namespace ShapeWorld.Client { class Program { static void Main(string[] args) { PlayWithRectangle(); } static void PlayWithRectangle() { var r = new Rectangle(); var sq = new Square(); //var s = new Shape(); Shape s1 = r; Shape s2 = sq; sq.Length = 10; sq.Width = 11; //r.Edges = 10; Console.WriteLine(s1.Edges); System.Console.WriteLine(r.Edges); System.Console.WriteLine(s2.Area()); } static void PlayWithShapes() { // 1-d Shape[] arrShapes1 = new Shape[10]; var arrShapes2 = new Shape[]{ new Rectangle(), new Square(), new Triangle()}; var item1 = arrShapes1[9]; arrShapes2[0] = item1; // m-d Shape[,] arrShapes3 = new Shape[2,2]; var arrShapes4 = new Shape[,] { {new Rectangle(), new Square()}, {new Triangle(), new Triangle()} }; var item2 = arrShapes3[1,0]; arrShapes4[1,1] = item2; // jagged Shape[][] arrShapes5 = new Shape[2][]; var arrShapes6 = new Shape[][]{ new Rectangle[2], new Square[] { new Rectangle() as Square, new Square(), new Square()}}; var item3 = arrShapes5[1][0]; arrShapes6[1][0] = item3; // List List<Shape> lsShapes1 = new List<Shape>(); var lsShapes2 = new List<Shape> { new Rectangle(), new Square(), new Triangle()}; var item4 = lsShapes1[8]; var item5 = lsShapes1.ElementAt(8); lsShapes2.Add(item4); lsShapes2[10] = item5; // Dictionary Dictionary<string, List<Shape>> diShapes1 = new Dictionary<string, List<Shape>>(); var diShapes2 = new Dictionary<string, List<Shape>> { {"a", new List<Shape>()}, {"b", new List<Shape>(){ new Rectangle(), new Square()}} }; var item6 = diShapes1["a"]; var item7 = diShapes1.Keys.ElementAt(1); diShapes2.Add("b", item6); //fail diShapes2["b"] = diShapes1[item7]; } } }
25.180723
127
0.566507
[ "MIT" ]
brandonmarcum/Week1Test
ShapeWorld/ShapeWorld.Client/Program.cs
2,092
C#
//------------------------------------------------------------------------------ // <copyright file="_NativeSSPI.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System.Runtime.InteropServices; using System.Net.Sockets; // // used to define the interface for security to use. // internal interface SSPIInterface { SecurityPackageInfoClass[] SecurityPackages { get; set; } int EnumerateSecurityPackages(out int pkgnum, out IntPtr arrayptr); int FreeContextBuffer(IntPtr contextBuffer); int AcquireCredentialsHandle( string principal, string moduleName, int usage, int logonID, AuthIdentity authdata, int keyCallback, int keyArgument, ref long handle, ref long timestamp); int AcquireCredentialsHandle( string principal, string moduleName, int usage, int logonID, int keyCallback, int keyArgument, ref long handle, ref long timestamp); int AcquireCredentialsHandle( string principal, string moduleName, int usage, int logonID, ref SChannelCred authdata, int keyCallback, int keyArgument, ref long handle, ref long timestamp); int FreeCredentialsHandle(ref long handle); // // we have two interfaces to this method call. // we will use the first one when we want to pass in a null // for the "context" and "inputBuffer" parameters // int InitializeSecurityContext( ref long credentialHandle, IntPtr context, string targetName, int requirements, int reservedI, int endianness, IntPtr inputBuffer, int reservedII, ref long newContext, ref SecurityBufferDescriptor outputBuffer, ref int attributes, ref long timestamp); int InitializeSecurityContext( ref long credentialHandle, ref long context, string targetName, int requirements, int reservedI, int endianness, ref SecurityBufferDescriptor inputBuffer, int reservedII, ref long newContext, ref SecurityBufferDescriptor outputBuffer, ref int attributes, ref long timestamp); int DeleteSecurityContext(ref long handle); int EncryptMessage(ref long contextHandle, int qualityOfProtection, ref SecurityBufferDescriptor input, int sequenceNumber); int DecryptMessage(ref long contextHandle, int qualityOfProtection, ref SecurityBufferDescriptor input, int sequenceNumber); int SealMessage(ref long contextHandle, int qualityOfProtection, ref SecurityBufferDescriptor input, int sequenceNumber); int UnsealMessage(ref long contextHandle, ref SecurityBufferDescriptor input, int qualityOfProtection, int sequenceNumber); SecurityStatus QueryContextAttributes(ref long ContextHandle, int ulAttribute, ref IntPtr name); int QueryContextAttributes(ref long phContext, int attribute, IntPtr buffer); int QueryCredentialAttributes(ref long phContext, int attribute, IntPtr buffer); #if SERVER_SIDE_SSPI int RevertSecurityContext(ref long phContext); int ImpersonateSecurityContext(ref long phContext); int AcceptSecurityContext( ref long credentialHandle, int context, int inputBuffer, int requirements, int endianness, ref long newContext, ref SecurityBufferDescriptor outputBuffer, out int attributes, out long timestamp); int AcceptSecurityContext( ref long credentialHandle, ref long context, ref SecurityBufferDescriptor inputBuffer, int requirements, int endianness, ref long newContext, ref SecurityBufferDescriptor outputBuffer, out int attributes, out long timestamp); #endif // SERVER_SIDE_SSPI } // SSPI Interface // ****************** // for SSL connections, use Schannel on Win9x, NT we don't care, // since its the same DLL // ****************** internal class SSPISecureChannelType : SSPIInterface { private static SecurityPackageInfoClass[] m_SecurityPackages; public SecurityPackageInfoClass[] SecurityPackages { get { return m_SecurityPackages; } set { m_SecurityPackages = value; } } public int EnumerateSecurityPackages(out int pkgnum, out IntPtr arrayptr) { GlobalLog.Print("SSPISecureChannelType::EnumerateSecurityPackages()"); if ( ComNetOS.IsWin9x ) { GlobalLog.Print(" calling UnsafeNclNativeMethods.NativeSSLWin9xSSPI.EnumerateSecurityPackagesA()"); return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.EnumerateSecurityPackagesA( out pkgnum, out arrayptr ); } else { GlobalLog.Print(" calling UnsafeNclNativeMethods.NativeNTSSPI.EnumerateSecurityPackagesW()"); return UnsafeNclNativeMethods.NativeNTSSPI.EnumerateSecurityPackagesW( out pkgnum, out arrayptr ); } } public int FreeContextBuffer(IntPtr contextBuffer) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.FreeContextBuffer(contextBuffer); } else { return UnsafeNclNativeMethods.NativeNTSSPI.FreeContextBuffer(contextBuffer); } } public int AcquireCredentialsHandle(string principal, string moduleName, int usage, int logonID, AuthIdentity authdata, int keyCallback, int keyArgument, ref long handle, ref long timestamp) { GlobalLog.Print("ComNetOS.IsWin9x = " + ComNetOS.IsWin9x); GlobalLog.Print("module name = " + moduleName); if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.AcquireCredentialsHandleA( principal, moduleName, usage, logonID, ref authdata, keyCallback, keyArgument, ref handle, ref timestamp ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.AcquireCredentialsHandleW( principal, moduleName, usage, logonID, ref authdata, keyCallback, keyArgument, ref handle, ref timestamp ); } } public int AcquireCredentialsHandle(string principal, string moduleName, int usage, int logonID, int keyCallback, int keyArgument, ref long handle, ref long timestamp) { GlobalLog.Print("ComNetOS.IsWin9x = " + ComNetOS.IsWin9x); GlobalLog.Print("module name = " + moduleName); if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.AcquireCredentialsHandleA( principal, moduleName, usage, logonID, IntPtr.Zero, keyCallback, keyArgument, ref handle, ref timestamp ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.AcquireCredentialsHandleW( principal, moduleName, usage, logonID, IntPtr.Zero, keyCallback, keyArgument, ref handle, ref timestamp ); } } public int AcquireCredentialsHandle(string principal, string moduleName, int usage, int logonID, ref SChannelCred authdata, int keyCallback, int keyArgument, ref long handle, ref long timestamp) { GlobalLog.Enter("SSPISecureChannelType::AcquireCredentialsHandle#3"); GlobalLog.Print("calling UnsafeNclNativeMethods.Native"+(ComNetOS.IsWin9x ? "SSLWin9x" : "NT")+"SSPI.AcquireCredentialsHandle()"); GlobalLog.Print(" principal = \"" + principal + "\""); GlobalLog.Print(" moduleName = \"" + moduleName + "\""); GlobalLog.Print(" usage = 0x" + String.Format("{0:x}", usage)); GlobalLog.Print(" logonID = 0x" + String.Format("{0:x}", logonID)); GlobalLog.Print(" authdata = " + authdata); GlobalLog.Print(" keyCallback = " + keyCallback); GlobalLog.Print(" keyArgument = " + keyArgument); GlobalLog.Print(" handle = {ref}"); GlobalLog.Print(" timestamp = {ref}"); authdata.DebugDump(); int result; if ( ComNetOS.IsWin9x ) { result = UnsafeNclNativeMethods.NativeSSLWin9xSSPI.AcquireCredentialsHandleA( principal, moduleName, usage, logonID, ref authdata, keyCallback, keyArgument, ref handle, ref timestamp ); } else { result = UnsafeNclNativeMethods.NativeNTSSPI.AcquireCredentialsHandleW( principal, moduleName, usage, logonID, ref authdata, keyCallback, keyArgument, ref handle, ref timestamp ); } GlobalLog.Leave("SSPISecureChannelType::AcquireCredentialsHandle#3", result); return result; } public int FreeCredentialsHandle(ref long handle) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.FreeCredentialsHandle(ref handle); } else { return UnsafeNclNativeMethods.NativeNTSSPI.FreeCredentialsHandle(ref handle); } } // // we have two interfaces to this method call. // we will use the first one when we want to pass in a null // for the "context" and "inputBuffer" parameters // public int InitializeSecurityContext( ref long credentialHandle, IntPtr context, string targetName, int requirements, int reservedI, int endianness, IntPtr inputBuffer, int reservedII, ref long newContext, ref SecurityBufferDescriptor outputBuffer, ref int attributes, ref long timestamp) { #if TRAVE GlobalLog.Enter("SSPISecureChannelType::InitializeSecurityContext#1()"); GlobalLog.Print("calling UnsafeNclNativeMethods.Native"+(ComNetOS.IsWin9x ? "SSLWin9x" : "NT")+"SSPI.InitializeSecurityContext()"); GlobalLog.Print(" credentialHandle = " + String.Format("0x{0:x}", credentialHandle)); GlobalLog.Print(" context = " + String.Format("0x{0:x}", context)); GlobalLog.Print(" targetName = \"" + targetName + "\""); GlobalLog.Print(" requirements = " + String.Format("0x{0:x}", requirements) + " [" + SecureChannel.MapInputContextAttributes(requirements) + "]"); GlobalLog.Print(" reservedI = " + String.Format("0x{0:x}", reservedI)); GlobalLog.Print(" endianness = " + String.Format("0x{0:x}", endianness)); GlobalLog.Print(" inputBuffer = " + String.Format("0x{0:x}", inputBuffer)); GlobalLog.Print(" reservedII = " + String.Format("0x{0:x}", reservedII)); GlobalLog.Print(" newContext = {ref}"); GlobalLog.Print(" outputBuffer = {ref}"); GlobalLog.Print(" attributes = {ref}"); GlobalLog.Print(" timestamp = {ref}"); #endif int result; if ( ComNetOS.IsWin9x ) { result = UnsafeNclNativeMethods.NativeSSLWin9xSSPI.InitializeSecurityContextA( ref credentialHandle, context, targetName, requirements, reservedI, endianness, inputBuffer, reservedII, ref newContext, ref outputBuffer, ref attributes, ref timestamp ); } else { result = UnsafeNclNativeMethods.NativeNTSSPI.InitializeSecurityContextW( ref credentialHandle, context, targetName, requirements, reservedI, endianness, inputBuffer, reservedII, ref newContext, ref outputBuffer, ref attributes, ref timestamp ); } #if TRAVE GlobalLog.Print("InitializeSecurityContext() returns " + SecureChannel.MapSecurityStatus((uint)result)); if (result >= 0) { GlobalLog.Print(" newContext = " + String.Format("0x{0:x}", newContext)); GlobalLog.Print(" outputBuffer = " + outputBuffer); GlobalLog.Print(" attributes = " + String.Format("0x{0:x}", attributes) + " [" + SecureChannel.MapOutputContextAttributes(attributes) + "]"); GlobalLog.Print(" timestamp = " + String.Format("0x{0:x}", timestamp)); outputBuffer.DebugDump(); } GlobalLog.Leave("SSPISecureChannelType::InitializeSecurityContext#1()", String.Format("0x{0:x}", result)); #endif return result; } public int InitializeSecurityContext( ref long credentialHandle, ref long context, string targetName, int requirements, int reservedI, int endianness, ref SecurityBufferDescriptor inputBuffer, int reservedII, ref long newContext, ref SecurityBufferDescriptor outputBuffer, ref int attributes, ref long timestamp) { #if TRAVE GlobalLog.Enter("SSPISecureChannelType::InitializeSecurityContext#2()"); GlobalLog.Print("calling UnsafeNclNativeMethods.Native"+(ComNetOS.IsWin9x ? "SSLWin9x" : "NT")+"SSPI.InitializeSecurityContext()"); GlobalLog.Print(" credentialHandle = " + String.Format("0x{0:x}", credentialHandle)); GlobalLog.Print(" context = " + String.Format("0x{0:x}", context)); GlobalLog.Print(" targetName = \"" + targetName + "\""); GlobalLog.Print(" requirements = " + String.Format("0x{0:x}", requirements) + " [" + SecureChannel.MapInputContextAttributes(requirements) + "]"); GlobalLog.Print(" reservedI = " + String.Format("0x{0:x}", reservedI)); GlobalLog.Print(" endianness = " + String.Format("0x{0:x}", endianness)); GlobalLog.Print(" inputBuffer = " + inputBuffer); GlobalLog.Print(" reservedII = " + String.Format("0x{0:x}", reservedII)); GlobalLog.Print(" newContext = {ref}"); GlobalLog.Print(" outputBuffer = {ref}"); GlobalLog.Print(" attributes = {ref}"); GlobalLog.Print(" timestamp = {ref}"); inputBuffer.DebugDump(); #endif int result; if ( ComNetOS.IsWin9x ) { result = UnsafeNclNativeMethods.NativeSSLWin9xSSPI.InitializeSecurityContextA( ref credentialHandle, ref context, targetName, requirements, reservedI, endianness, ref inputBuffer, reservedII, ref newContext, ref outputBuffer, ref attributes, ref timestamp ); } else { result = UnsafeNclNativeMethods.NativeNTSSPI.InitializeSecurityContextW( ref credentialHandle, ref context, targetName, requirements, reservedI, endianness, ref inputBuffer, reservedII, ref newContext, ref outputBuffer, ref attributes, ref timestamp ); } #if TRAVE GlobalLog.Print("InitializeSecurityContext() returns " + SecureChannel.MapSecurityStatus((uint)result)); if (result >= 0) { GlobalLog.Print(" newContext = " + String.Format("0x{0:x}", newContext)); GlobalLog.Print(" outputBuffer = " + outputBuffer); GlobalLog.Print(" attributes = " + String.Format("0x{0:x}", attributes) + " [" + SecureChannel.MapOutputContextAttributes(attributes) + "]"); GlobalLog.Print(" timestamp = " + String.Format("0x{0:x}", timestamp)); outputBuffer.DebugDump(); } GlobalLog.Leave("SSPISecureChannelType::InitializeSecurityContext#2()", String.Format("0x{0:x}", result)); #endif return result; } public int DeleteSecurityContext(ref long handle) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.DeleteSecurityContext(ref handle); } else { return UnsafeNclNativeMethods.NativeNTSSPI.DeleteSecurityContext(ref handle); } } public int EncryptMessage(ref long contextHandle, int qualityOfProtection, ref SecurityBufferDescriptor input, int sequenceNumber) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.EncryptMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.EncryptMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } } public int DecryptMessage(ref long contextHandle, int qualityOfProtection, ref SecurityBufferDescriptor input, int sequenceNumber) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.DecryptMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.DecryptMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } } public int SealMessage(ref long contextHandle, int qualityOfProtection, ref SecurityBufferDescriptor input, int sequenceNumber) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.SealMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.SealMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } } public int UnsealMessage(ref long contextHandle, ref SecurityBufferDescriptor input, int qualityOfProtection, int sequenceNumber) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.UnsealMessage( ref contextHandle, ref input, qualityOfProtection, sequenceNumber ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.UnsealMessage( ref contextHandle, ref input, qualityOfProtection, sequenceNumber ); } } public SecurityStatus QueryContextAttributes(ref long ContextHandle, int ulAttribute, ref IntPtr name) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.QueryContextAttributes( ref ContextHandle, ulAttribute, ref name ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.QueryContextAttributes( ref ContextHandle, ulAttribute, ref name ); } } public int QueryContextAttributes(ref long phContext, int attribute, IntPtr buffer) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.QueryContextAttributes( ref phContext, attribute, buffer ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.QueryContextAttributes( ref phContext, attribute, buffer ); } } public int QueryCredentialAttributes(ref long phContext, int attribute, IntPtr buffer) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.QueryCredentialAttributes( ref phContext, attribute, buffer ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.QueryCredentialAttributes( ref phContext, attribute, buffer ); } } #if SERVER_SIDE_SSPI public int RevertSecurityContext(ref long phContext) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.RevertSecurityContext(ref phContext); } else { return UnsafeNclNativeMethods.NativeNTSSPI.RevertSecurityContext(ref phContext); } } public int ImpersonateSecurityContext(ref long phContext) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.ImpersonateSecurityContext(ref phContext); } else { return UnsafeNclNativeMethods.NativeNTSSPI.ImpersonateSecurityContext(ref phContext); } } public int AcceptSecurityContext( ref long credentialHandle, int context, int inputBuffer, int requirements, int endianness, ref long newContext, ref SecurityBufferDescriptor outputBuffer, out int attributes, out long timestamp) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.AcceptSecurityContext( ref credentialHandle, context, inputBuffer, requirements, endianness, ref newContext, ref outputBuffer, out attributes, out timestamp ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.AcceptSecurityContext( ref credentialHandle, context, inputBuffer, requirements, endianness, ref newContext, ref outputBuffer, out attributes, out timestamp ); } } public int AcceptSecurityContext( ref long credentialHandle, ref long context, ref SecurityBufferDescriptor inputBuffer, int requirements, int endianness, ref long newContext, ref SecurityBufferDescriptor outputBuffer, out int attributes, out long timestamp) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeSSLWin9xSSPI.AcceptSecurityContext( ref credentialHandle, ref context, ref inputBuffer, requirements, endianness, ref newContext, ref outputBuffer, out attributes, out timestamp ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.AcceptSecurityContext( ref credentialHandle, ref context, ref inputBuffer, requirements, endianness, ref newContext, ref outputBuffer, out attributes, out timestamp ); } } #endif // SERVER_SIDE_SSPI } // ************* // For Authenticiation like Kerberos or NTLM // ************* internal class SSPIAuthType : SSPIInterface { private static SecurityPackageInfoClass[] m_SecurityPackages; public SecurityPackageInfoClass[] SecurityPackages { get { return m_SecurityPackages; } set { m_SecurityPackages = value; } } public int EnumerateSecurityPackages(out int pkgnum, out IntPtr arrayptr) { GlobalLog.Print("SSPIAuthType::EnumerateSecurityPackages()"); if ( ComNetOS.IsWin9x ) { GlobalLog.Print(" calling UnsafeNclNativeMethods.NativeAuthWin9xSSPI.EnumerateSecurityPackagesA()"); return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.EnumerateSecurityPackagesA( out pkgnum, out arrayptr ); } else { GlobalLog.Print(" calling UnsafeNclNativeMethods.NativeNTSSPI.EnumerateSecurityPackagesW()"); return UnsafeNclNativeMethods.NativeNTSSPI.EnumerateSecurityPackagesW( out pkgnum, out arrayptr ); } } public int FreeContextBuffer(IntPtr contextBuffer) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.FreeContextBuffer(contextBuffer); } else { return UnsafeNclNativeMethods.NativeNTSSPI.FreeContextBuffer(contextBuffer); } } public int AcquireCredentialsHandle(string principal, string moduleName, int usage, int logonID, AuthIdentity authdata, int keyCallback, int keyArgument, ref long handle, ref long timestamp ) { GlobalLog.Print("SSPIAuthType::AcquireCredentialsHandle#1(" + principal + ", " + moduleName + ", " + usage + ", " + logonID + ", " + authdata + ", " + keyCallback + ", " + keyArgument + ", " + "ref handle" + ", " + "ref timestamp" + ")" ); if (ComNetOS.IsWin9x) { GlobalLog.Print("calling AuthWin95SSPI"); GlobalLog.Print("mod name = " + moduleName); int err = UnsafeNclNativeMethods.NativeAuthWin9xSSPI.AcquireCredentialsHandleA( principal, moduleName, usage, logonID, ref authdata, keyCallback, keyArgument, ref handle, ref timestamp ); GlobalLog.Print("UnsafeNclNativeMethods.NativeAuthWin9xSSPI::AcquireCredentialsHandleA() returns 0x" + String.Format("{0:x}", err) + ", handle = 0x" + String.Format("{0:x}", handle)); return err; } else { GlobalLog.Print("calling UnsafeNclNativeMethods.NativeNTSSPI::AcquireCredentialsHandleW()"); int err = UnsafeNclNativeMethods.NativeNTSSPI.AcquireCredentialsHandleW(principal, moduleName, usage, logonID, ref authdata, keyCallback, keyArgument, ref handle, ref timestamp ); GlobalLog.Print("UnsafeNclNativeMethods.NativeNTSSPI::AcquireCredentialsHandleW() returns 0x" + String.Format("{0:x}", err) + ", handle = 0x" + String.Format("{0:x}", handle) + ", timestamp = 0x" + String.Format("{0:x}", timestamp) ); return err; } } public int AcquireCredentialsHandle(string principal, string moduleName, int usage, int logonID, int keyCallback, int keyArgument, ref long handle, ref long timestamp ) { GlobalLog.Print("SSPIAuthType::AcquireCredentialsHandle#1(" + principal + ", " + moduleName + ", " + usage + ", " + logonID + ", " + keyCallback + ", " + keyArgument + ", " + "ref handle" + ", " + "ref timestamp" + ")" ); if (ComNetOS.IsWin9x) { GlobalLog.Print("calling AuthWin95SSPI"); GlobalLog.Print("mod name = " + moduleName); int err = UnsafeNclNativeMethods.NativeAuthWin9xSSPI.AcquireCredentialsHandleA( principal, moduleName, usage, logonID, IntPtr.Zero, keyCallback, keyArgument, ref handle, ref timestamp ); GlobalLog.Print("UnsafeNclNativeMethods.NativeAuthWin9xSSPI::AcquireCredentialsHandleA() returns 0x" + String.Format("{0:x}", err) + ", handle = 0x" + String.Format("{0:x}", handle)); return err; } else { GlobalLog.Print("calling UnsafeNclNativeMethods.NativeNTSSPI::AcquireCredentialsHandleW()"); int err = UnsafeNclNativeMethods.NativeNTSSPI.AcquireCredentialsHandleW(principal, moduleName, usage, logonID, IntPtr.Zero, keyCallback, keyArgument, ref handle, ref timestamp ); GlobalLog.Print("UnsafeNclNativeMethods.NativeNTSSPI::AcquireCredentialsHandleW() returns 0x" + String.Format("{0:x}", err) + ", handle = 0x" + String.Format("{0:x}", handle) + ", timestamp = 0x" + String.Format("{0:x}", timestamp) ); return err; } } public int AcquireCredentialsHandle(string principal, string moduleName, int usage, int logonID, ref SChannelCred authdata, int keyCallback, int keyArgument, ref long handle, ref long timestamp) { GlobalLog.Print("SSPIAuthType::AcquireCredentialsHandle#2()"); GlobalLog.Print("module name = " + moduleName); if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.AcquireCredentialsHandleA( principal, moduleName, usage, logonID, ref authdata, keyCallback, keyArgument, ref handle, ref timestamp ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.AcquireCredentialsHandleW( principal, moduleName, usage, logonID, ref authdata, keyCallback, keyArgument, ref handle, ref timestamp ); } } public int FreeCredentialsHandle(ref long handle) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.FreeCredentialsHandle(ref handle); } else { return UnsafeNclNativeMethods.NativeNTSSPI.FreeCredentialsHandle(ref handle); } } // // we have two interfaces to this method call. // we will use the first one when we want to pass in a null // for the "context" and "inputBuffer" parameters // public int InitializeSecurityContext( ref long credentialHandle, IntPtr context, string targetName, int requirements, int reservedI, int endianness, IntPtr inputBuffer, int reservedII, ref long newContext, ref SecurityBufferDescriptor outputBuffer, ref int attributes, ref long timestamp) { GlobalLog.Print("SSPIAuthType::InitializeSecurityContext#1()"); GlobalLog.Print("calling UnsafeNclNativeMethods.NativeNTSSPI.InitializeSecurityContextW()"); GlobalLog.Print(" credentialHandle = 0x" + String.Format("{0:x}", credentialHandle)); GlobalLog.Print(" context = 0x" + String.Format("{0:x}", context)); GlobalLog.Print(" targetName = " + targetName); GlobalLog.Print(" requirements = 0x" + String.Format("{0:x}", requirements)); GlobalLog.Print(" reservedI = 0x" + String.Format("{0:x}", reservedI)); GlobalLog.Print(" endianness = " + endianness.ToString()); GlobalLog.Print(" inputBuffer = {ref} 0x" + String.Format("{0:x}", inputBuffer)); GlobalLog.Print(" reservedII = " + reservedII); GlobalLog.Print(" newContext = {ref} 0x" + String.Format("{0:x}", newContext)); GlobalLog.Print(" outputBuffer = {ref}"); GlobalLog.Print(" attributes = {ref} " + attributes.ToString()); GlobalLog.Print(" timestamp = {ref} 0x" + String.Format("{0:x}", timestamp)); if ( ComNetOS.IsWin9x ) { GlobalLog.Print("calling UnsafeNclNativeMethods.NativeSSLWin9xSSPI.InitializeSecurityContextA()"); return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.InitializeSecurityContextA( ref credentialHandle, context, targetName, requirements, reservedI, endianness, inputBuffer, reservedII, ref newContext, ref outputBuffer, ref attributes, ref timestamp ); } else { GlobalLog.Print("calling UnsafeNclNativeMethods.NativeNTSSPI.InitializeSecurityContextW()"); return UnsafeNclNativeMethods.NativeNTSSPI.InitializeSecurityContextW( ref credentialHandle, context, targetName, requirements, reservedI, endianness, inputBuffer, reservedII, ref newContext, ref outputBuffer, ref attributes, ref timestamp ); } } public int InitializeSecurityContext(ref long credentialHandle, ref long context, string targetName, int requirements, int reservedI, int endianness, ref SecurityBufferDescriptor inputBuffer, int reservedII, ref long newContext, ref SecurityBufferDescriptor outputBuffer, ref int attributes, ref long timestamp ) { GlobalLog.Print("SSPIAuthType::InitializeSecurityContext#2()"); if ( ComNetOS.IsWin9x ) { GlobalLog.Print("calling UnsafeNclNativeMethods.NativeSSLWin9xSSPI.InitializeSecurityContextA()"); return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.InitializeSecurityContextA( ref credentialHandle, ref context, targetName, requirements, reservedI, endianness, ref inputBuffer, reservedII, ref newContext, ref outputBuffer, ref attributes, ref timestamp ); } else { GlobalLog.Print("calling UnsafeNclNativeMethods.NativeNTSSPI.InitializeSecurityContextW()"); GlobalLog.Print(" credentialHandle = 0x" + String.Format("{0:x}", credentialHandle)); GlobalLog.Print(" context = 0x" + String.Format("{0:x}", context)); GlobalLog.Print(" targetName = " + targetName); GlobalLog.Print(" requirements = 0x" + String.Format("{0:x}", requirements)); GlobalLog.Print(" reservedI = 0x" + String.Format("{0:x}", reservedI)); GlobalLog.Print(" endianness = " + endianness); GlobalLog.Print(" inputBuffer = {ref}"); GlobalLog.Print(" reservedII = " + reservedII); GlobalLog.Print(" newContext = {ref}"); GlobalLog.Print(" outputBuffer = {ref}"); GlobalLog.Print(" attributes = {ref}"); GlobalLog.Print(" timestamp = {ref}"); int error = UnsafeNclNativeMethods.NativeNTSSPI.InitializeSecurityContextW( ref credentialHandle, ref context, targetName, requirements, reservedI, endianness, ref inputBuffer, reservedII, ref newContext, ref outputBuffer, ref attributes, ref timestamp ); GlobalLog.Print("UnsafeNclNativeMethods.NativeNTSSPI.InitializeSecurityContextW() returns 0x" + String.Format("{0:x}", error)); return error; } } public int DeleteSecurityContext(ref long handle) { if (ComNetOS.IsWin9x) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.DeleteSecurityContext(ref handle); } else { GlobalLog.Print("SSPIAuthType::DeleteSecurityContext(0x" + String.Format("{0:x}", handle) + ")"); return UnsafeNclNativeMethods.NativeNTSSPI.DeleteSecurityContext(ref handle); } } public int EncryptMessage(ref long contextHandle, int qualityOfProtection, ref SecurityBufferDescriptor input, int sequenceNumber) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.EncryptMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.EncryptMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } } public int DecryptMessage(ref long contextHandle, int qualityOfProtection, ref SecurityBufferDescriptor input, int sequenceNumber) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.DecryptMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.DecryptMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } } public int SealMessage(ref long contextHandle, int qualityOfProtection, ref SecurityBufferDescriptor input, int sequenceNumber) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.SealMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.SealMessage( ref contextHandle, qualityOfProtection, ref input, sequenceNumber ); } } public int UnsealMessage(ref long contextHandle, ref SecurityBufferDescriptor input, int qualityOfProtection, int sequenceNumber) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.UnsealMessage( ref contextHandle, ref input, qualityOfProtection, sequenceNumber ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.UnsealMessage( ref contextHandle, ref input, qualityOfProtection, sequenceNumber ); } } public SecurityStatus QueryContextAttributes(ref long ContextHandle, int ulAttribute, ref IntPtr name) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.QueryContextAttributes( ref ContextHandle, ulAttribute, ref name ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.QueryContextAttributes( ref ContextHandle, ulAttribute, ref name ); } } public int QueryContextAttributes(ref long phContext, int attribute, IntPtr buffer) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.QueryContextAttributes( ref phContext, attribute, buffer ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.QueryContextAttributes( ref phContext, attribute, buffer ); } } public int QueryCredentialAttributes(ref long phContext, int attribute, IntPtr buffer) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.QueryCredentialAttributes( ref phContext, attribute, buffer ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.QueryCredentialAttributes( ref phContext, attribute, buffer ); } } #if SERVER_SIDE_SSPI public int RevertSecurityContext(ref long phContext) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.RevertSecurityContext(ref phContext); } else { return UnsafeNclNativeMethods.NativeNTSSPI.RevertSecurityContext(ref phContext); } } public int ImpersonateSecurityContext(ref long phContext) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.ImpersonateSecurityContext(ref phContext); } else { return UnsafeNclNativeMethods.NativeNTSSPI.ImpersonateSecurityContext(ref phContext); } } public int AcceptSecurityContext( ref long credentialHandle, int context, int inputBuffer, int requirements, int endianness, ref long newContext, ref SecurityBufferDescriptor outputBuffer, out int attributes, out long timestamp) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.AcceptSecurityContext( ref credentialHandle, context, inputBuffer, requirements, endianness, ref newContext, ref outputBuffer, out attributes, out timestamp ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.AcceptSecurityContext( ref credentialHandle, context, inputBuffer, requirements, endianness, ref newContext, ref outputBuffer, out attributes, out timestamp ); } } public int AcceptSecurityContext( ref long credentialHandle, ref long context, ref SecurityBufferDescriptor inputBuffer, int requirements, int endianness, ref long newContext, ref SecurityBufferDescriptor outputBuffer, out int attributes, out long timestamp) { if ( ComNetOS.IsWin9x ) { return UnsafeNclNativeMethods.NativeAuthWin9xSSPI.AcceptSecurityContext( ref credentialHandle, ref context, ref inputBuffer, requirements, endianness, ref newContext, ref outputBuffer, out attributes, out timestamp ); } else { return UnsafeNclNativeMethods.NativeNTSSPI.AcceptSecurityContext( ref credentialHandle, ref context, ref inputBuffer, requirements, endianness, ref newContext, ref outputBuffer, out attributes, out timestamp ); } } #endif // SERVER_SIDE_SSPI } // SSPIAuthType // need a global so we can pass the interfaces as variables, // is there a better way? internal class GlobalSSPI { public static SSPIInterface SSPIAuth = new SSPIAuthType(); public static SSPIInterface SSPISecureChannel = new SSPISecureChannelType(); } } // namespace System.Net
46.155907
200
0.381188
[ "Unlicense" ]
bestbat/Windows-Server
com/netfx/src/framework/net/system/net/_nativesspi.cs
67,203
C#
using System; namespace RX { internal class DisposeToken : IDisposable { public Action DisposeAction; public void Dispose() => DisposeAction?.Invoke(); } }
16.909091
57
0.639785
[ "MIT" ]
RPGameStudio/events
Runtime/DisposeToken.cs
188
C#
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq.Expressions; using System.Net.Http; using System.Reflection; using System.Threading.Tasks; using System.Xml.Linq; using FluentAssertions.Collections; using FluentAssertions.Common; using FluentAssertions.Data; #if !NETSTANDARD2_0 using FluentAssertions.Events; #endif using FluentAssertions.Numeric; using FluentAssertions.Primitives; using FluentAssertions.Reflection; using FluentAssertions.Specialized; using FluentAssertions.Streams; using FluentAssertions.Types; using FluentAssertions.Xml; using JetBrains.Annotations; namespace FluentAssertions { /// <summary> /// Contains extension methods for custom assertions in unit tests. /// </summary> [DebuggerNonUserCode] public static class AssertionExtensions { private static readonly AggregateExceptionExtractor Extractor = new(); /// <summary> /// Invokes the specified action on a subject so that you can chain it /// with any of the assertions from <see cref="ActionAssertions"/> /// </summary> /// <exception cref="ArgumentNullException"><paramref name="subject"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception> [Pure] public static Action Invoking<T>(this T subject, Action<T> action) { Guard.ThrowIfArgumentIsNull(subject, nameof(subject)); Guard.ThrowIfArgumentIsNull(action, nameof(action)); return () => action(subject); } /// <summary> /// Invokes the specified action on a subject so that you can chain it /// with any of the assertions from <see cref="FunctionAssertions{T}"/> /// </summary> /// <exception cref="ArgumentNullException"><paramref name="subject"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception> [Pure] public static Func<TResult> Invoking<T, TResult>(this T subject, Func<T, TResult> action) { Guard.ThrowIfArgumentIsNull(subject, nameof(subject)); Guard.ThrowIfArgumentIsNull(action, nameof(action)); return () => action(subject); } /// <summary> /// Invokes the specified action on a subject so that you can chain it /// with any of the assertions from <see cref="NonGenericAsyncFunctionAssertions"/> /// </summary> [Pure] public static Func<Task> Awaiting<T>(this T subject, Func<T, Task> action) { return () => action(subject); } /// <summary> /// Invokes the specified action on a subject so that you can chain it /// with any of the assertions from <see cref="GenericAsyncFunctionAssertions{TResult}"/> /// </summary> [Pure] public static Func<Task<TResult>> Awaiting<T, TResult>(this T subject, Func<T, Task<TResult>> action) { return () => action(subject); } /// <summary> /// Invokes the specified action on a subject so that you can chain it /// with any of the assertions from <see cref="NonGenericAsyncFunctionAssertions"/> /// </summary> [Pure] public static Func<Task> Awaiting<T>(this T subject, Func<T, ValueTask> action) { return () => action(subject).AsTask(); } /// <summary> /// Invokes the specified action on a subject so that you can chain it /// with any of the assertions from <see cref="GenericAsyncFunctionAssertions{TResult}"/> /// </summary> [Pure] public static Func<Task<TResult>> Awaiting<T, TResult>(this T subject, Func<T, ValueTask<TResult>> action) { return () => action(subject).AsTask(); } /// <summary> /// Provides methods for asserting the execution time of a method or property. /// </summary> /// <param name="subject">The object that exposes the method or property.</param> /// <param name="action">A reference to the method or property to measure the execution time of.</param> /// <returns> /// Returns an object for asserting that the execution time matches certain conditions. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="subject"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception> [MustUseReturnValue /* do not use Pure because this method executes the action before returning to the caller */] public static MemberExecutionTime<T> ExecutionTimeOf<T>(this T subject, Expression<Action<T>> action, StartTimer createTimer = null) { Guard.ThrowIfArgumentIsNull(subject, nameof(subject)); Guard.ThrowIfArgumentIsNull(action, nameof(action)); createTimer ??= () => new StopwatchTimer(); return new MemberExecutionTime<T>(subject, action, createTimer); } /// <summary> /// Provides methods for asserting the execution time of an action. /// </summary> /// <param name="action">An action to measure the execution time of.</param> /// <returns> /// Returns an object for asserting that the execution time matches certain conditions. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception> [MustUseReturnValue /* do not use Pure because this method executes the action before returning to the caller */] public static ExecutionTime ExecutionTime(this Action action, StartTimer createTimer = null) { createTimer ??= () => new StopwatchTimer(); return new(action, createTimer); } /// <summary> /// Provides methods for asserting the execution time of an async action. /// </summary> /// <param name="action">An async action to measure the execution time of.</param> /// <returns> /// Returns an object for asserting that the execution time matches certain conditions. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception> [MustUseReturnValue /* do not use Pure because this method executes the action before returning to the caller */] public static ExecutionTime ExecutionTime(this Func<Task> action) { return new(action, () => new StopwatchTimer()); } /// <summary> /// Returns an <see cref="ExecutionTimeAssertions"/> object that can be used to assert the /// current <see cref="FluentAssertions.Specialized.ExecutionTime"/>. /// </summary> [Pure] public static ExecutionTimeAssertions Should(this ExecutionTime executionTime) { return new ExecutionTimeAssertions(executionTime); } /// <summary> /// Returns an <see cref="AssemblyAssertions"/> object that can be used to assert the /// current <see cref="Assembly"/>. /// </summary> [Pure] public static AssemblyAssertions Should(this Assembly assembly) { return new AssemblyAssertions(assembly); } /// <summary> /// Returns an <see cref="XDocumentAssertions"/> object that can be used to assert the /// current <see cref="XElement"/>. /// </summary> [Pure] public static XDocumentAssertions Should(this XDocument actualValue) { return new XDocumentAssertions(actualValue); } /// <summary> /// Returns an <see cref="XElementAssertions"/> object that can be used to assert the /// current <see cref="XElement"/>. /// </summary> [Pure] public static XElementAssertions Should(this XElement actualValue) { return new XElementAssertions(actualValue); } /// <summary> /// Returns an <see cref="XAttributeAssertions"/> object that can be used to assert the /// current <see cref="XAttribute"/>. /// </summary> [Pure] public static XAttributeAssertions Should(this XAttribute actualValue) { return new XAttributeAssertions(actualValue); } /// <summary> /// Returns an <see cref="StreamAssertions"/> object that can be used to assert the /// current <see cref="Stream"/>. /// </summary> [Pure] public static StreamAssertions Should(this Stream actualValue) { return new StreamAssertions(actualValue); } /// <summary> /// Returns an <see cref="BufferedStreamAssertions"/> object that can be used to assert the /// current <see cref="BufferedStream"/>. /// </summary> [Pure] public static BufferedStreamAssertions Should(this BufferedStream actualValue) { return new BufferedStreamAssertions(actualValue); } /// <summary> /// Forces enumerating a collection. Should be used to assert that a method that uses the /// <c>yield</c> keyword throws a particular exception. /// </summary> [Pure] public static Action Enumerating(this Func<IEnumerable> enumerable) { return () => ForceEnumeration(enumerable); } /// <summary> /// Forces enumerating a collection. Should be used to assert that a method that uses the /// <c>yield</c> keyword throws a particular exception. /// </summary> [Pure] public static Action Enumerating<T>(this Func<IEnumerable<T>> enumerable) { return () => ForceEnumeration(enumerable); } /// <summary> /// Forces enumerating a collection of the provided <paramref name="subject"/>. /// Should be used to assert that a method that uses the <c>yield</c> keyword throws a particular exception. /// </summary> /// <param name="subject">The object that exposes the method or property.</param> /// <param name="enumerable">A reference to the method or property to force enumeration of.</param> public static Action Enumerating<T, TResult>(this T subject, Func<T, IEnumerable<TResult>> enumerable) { return () => ForceEnumeration(subject, enumerable); } private static void ForceEnumeration(Func<IEnumerable> enumerable) { foreach (object _ in enumerable()) { // Do nothing } } private static void ForceEnumeration<T>(T subject, Func<T, IEnumerable> enumerable) { foreach (object _ in enumerable(subject)) { // Do nothing } } /// <summary> /// Returns an <see cref="ObjectAssertions"/> object that can be used to assert the /// current <see cref="object"/>. /// </summary> [Pure] public static ObjectAssertions Should(this object actualValue) { return new ObjectAssertions(actualValue); } /// <summary> /// Returns an <see cref="BooleanAssertions"/> object that can be used to assert the /// current <see cref="bool"/>. /// </summary> [Pure] public static BooleanAssertions Should(this bool actualValue) { return new BooleanAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableBooleanAssertions"/> object that can be used to assert the /// current nullable <see cref="bool"/>. /// </summary> [Pure] public static NullableBooleanAssertions Should(this bool? actualValue) { return new NullableBooleanAssertions(actualValue); } /// <summary> /// Returns an <see cref="HttpResponseMessageAssertions"/> object that can be used to assert the /// current <see cref="HttpResponseMessage"/>. /// </summary> [Pure] public static HttpResponseMessageAssertions Should(this HttpResponseMessage actualValue) { return new HttpResponseMessageAssertions(actualValue); } /// <summary> /// Returns an <see cref="GuidAssertions"/> object that can be used to assert the /// current <see cref="Guid"/>. /// </summary> [Pure] public static GuidAssertions Should(this Guid actualValue) { return new GuidAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableGuidAssertions"/> object that can be used to assert the /// current nullable <see cref="Guid"/>. /// </summary> [Pure] public static NullableGuidAssertions Should(this Guid? actualValue) { return new NullableGuidAssertions(actualValue); } /// <summary> /// Returns an <see cref="GenericCollectionAssertions{T}"/> object that can be used to assert the /// current <see cref="IEnumerable{T}"/>. /// </summary> [Pure] public static GenericCollectionAssertions<T> Should<T>(this IEnumerable<T> actualValue) { return new GenericCollectionAssertions<T>(actualValue); } /// <summary> /// Returns an <see cref="StringCollectionAssertions"/> object that can be used to assert the /// current <see cref="IEnumerable{T}"/>. /// </summary> [Pure] public static StringCollectionAssertions Should(this IEnumerable<string> @this) { return new StringCollectionAssertions(@this); } /// <summary> /// Returns an <see cref="GenericDictionaryAssertions{TCollection, TKey, TValue}"/> object that can be used to assert the /// current <see cref="IDictionary{TKey, TValue}"/>. /// </summary> [Pure] public static GenericDictionaryAssertions<IDictionary<TKey, TValue>, TKey, TValue> Should<TKey, TValue>(this IDictionary<TKey, TValue> actualValue) { return new GenericDictionaryAssertions<IDictionary<TKey, TValue>, TKey, TValue>(actualValue); } /// <summary> /// Returns an <see cref="GenericDictionaryAssertions{TCollection, TKey, TValue}"/> object that can be used to assert the /// current <see cref="IEnumerable{T}"/> of <see cref="KeyValuePair{TKey, TValue}"/>. /// </summary> [Pure] public static GenericDictionaryAssertions<IEnumerable<KeyValuePair<TKey, TValue>>, TKey, TValue> Should<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> actualValue) { return new GenericDictionaryAssertions<IEnumerable<KeyValuePair<TKey, TValue>>, TKey, TValue>(actualValue); } /// <summary> /// Returns an <see cref="GenericDictionaryAssertions{TCollection, TKey, TValue}"/> object that can be used to assert the /// current <typeparamref name="TCollection"/>. /// </summary> [Pure] public static GenericDictionaryAssertions<TCollection, TKey, TValue> Should<TCollection, TKey, TValue>(this TCollection actualValue) where TCollection : IEnumerable<KeyValuePair<TKey, TValue>> { return new GenericDictionaryAssertions<TCollection, TKey, TValue>(actualValue); } /// <summary> /// Returns a <see cref="DataColumnAssertions"/> object that can be used to assert the /// current <see cref="DataColumn"/>. /// </summary> [Pure] public static DataColumnAssertions Should(this DataColumn actualValue) { return new DataColumnAssertions(actualValue); } /// <summary> /// Returns an <see cref="DateTimeAssertions"/> object that can be used to assert the /// current <see cref="DateTime"/>. /// </summary> [Pure] public static DateTimeAssertions Should(this DateTime actualValue) { return new DateTimeAssertions(actualValue); } /// <summary> /// Returns an <see cref="DateTimeOffsetAssertions"/> object that can be used to assert the /// current <see cref="DateTimeOffset"/>. /// </summary> [Pure] public static DateTimeOffsetAssertions Should(this DateTimeOffset actualValue) { return new DateTimeOffsetAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableDateTimeAssertions"/> object that can be used to assert the /// current nullable <see cref="DateTime"/>. /// </summary> [Pure] public static NullableDateTimeAssertions Should(this DateTime? actualValue) { return new NullableDateTimeAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableDateTimeOffsetAssertions"/> object that can be used to assert the /// current nullable <see cref="DateTimeOffset"/>. /// </summary> [Pure] public static NullableDateTimeOffsetAssertions Should(this DateTimeOffset? actualValue) { return new NullableDateTimeOffsetAssertions(actualValue); } /// <summary> /// Returns an <see cref="ComparableTypeAssertions{T}"/> object that can be used to assert the /// current <see cref="IComparable{T}"/>. /// </summary> [Pure] public static ComparableTypeAssertions<T> Should<T>(this IComparable<T> comparableValue) { return new ComparableTypeAssertions<T>(comparableValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="int"/>. /// </summary> [Pure] public static NumericAssertions<int> Should(this int actualValue) { return new NumericAssertions<int>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="int"/>. /// </summary> [Pure] public static NullableNumericAssertions<int> Should(this int? actualValue) { return new NullableNumericAssertions<int>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="uint"/>. /// </summary> [Pure] public static NumericAssertions<uint> Should(this uint actualValue) { return new NumericAssertions<uint>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="uint"/>. /// </summary> [Pure] public static NullableNumericAssertions<uint> Should(this uint? actualValue) { return new NullableNumericAssertions<uint>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="decimal"/>. /// </summary> [Pure] public static NumericAssertions<decimal> Should(this decimal actualValue) { return new NumericAssertions<decimal>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="decimal"/>. /// </summary> [Pure] public static NullableNumericAssertions<decimal> Should(this decimal? actualValue) { return new NullableNumericAssertions<decimal>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="byte"/>. /// </summary> [Pure] public static NumericAssertions<byte> Should(this byte actualValue) { return new NumericAssertions<byte>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="byte"/>. /// </summary> [Pure] public static NullableNumericAssertions<byte> Should(this byte? actualValue) { return new NullableNumericAssertions<byte>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="sbyte"/>. /// </summary> [Pure] public static NumericAssertions<sbyte> Should(this sbyte actualValue) { return new NumericAssertions<sbyte>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="sbyte"/>. /// </summary> [Pure] public static NullableNumericAssertions<sbyte> Should(this sbyte? actualValue) { return new NullableNumericAssertions<sbyte>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="short"/>. /// </summary> [Pure] public static NumericAssertions<short> Should(this short actualValue) { return new NumericAssertions<short>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="short"/>. /// </summary> [Pure] public static NullableNumericAssertions<short> Should(this short? actualValue) { return new NullableNumericAssertions<short>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="ushort"/>. /// </summary> [Pure] public static NumericAssertions<ushort> Should(this ushort actualValue) { return new NumericAssertions<ushort>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="ushort"/>. /// </summary> [Pure] public static NullableNumericAssertions<ushort> Should(this ushort? actualValue) { return new NullableNumericAssertions<ushort>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="long"/>. /// </summary> [Pure] public static NumericAssertions<long> Should(this long actualValue) { return new NumericAssertions<long>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="long"/>. /// </summary> [Pure] public static NullableNumericAssertions<long> Should(this long? actualValue) { return new NullableNumericAssertions<long>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="ulong"/>. /// </summary> [Pure] public static NumericAssertions<ulong> Should(this ulong actualValue) { return new NumericAssertions<ulong>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="ulong"/>. /// </summary> [Pure] public static NullableNumericAssertions<ulong> Should(this ulong? actualValue) { return new NullableNumericAssertions<ulong>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="float"/>. /// </summary> [Pure] public static NumericAssertions<float> Should(this float actualValue) { return new NumericAssertions<float>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="float"/>. /// </summary> [Pure] public static NullableNumericAssertions<float> Should(this float? actualValue) { return new NullableNumericAssertions<float>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="double"/>. /// </summary> [Pure] public static NumericAssertions<double> Should(this double actualValue) { return new NumericAssertions<double>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="double"/>. /// </summary> [Pure] public static NullableNumericAssertions<double> Should(this double? actualValue) { return new NullableNumericAssertions<double>(actualValue); } /// <summary> /// Returns an <see cref="StringAssertions"/> object that can be used to assert the /// current <see cref="string"/>. /// </summary> [Pure] public static StringAssertions Should(this string actualValue) { return new StringAssertions(actualValue); } /// <summary> /// Returns an <see cref="SimpleTimeSpanAssertions"/> object that can be used to assert the /// current <see cref="TimeSpan"/>. /// </summary> [Pure] public static SimpleTimeSpanAssertions Should(this TimeSpan actualValue) { return new SimpleTimeSpanAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableSimpleTimeSpanAssertions"/> object that can be used to assert the /// current nullable <see cref="TimeSpan"/>. /// </summary> [Pure] public static NullableSimpleTimeSpanAssertions Should(this TimeSpan? actualValue) { return new NullableSimpleTimeSpanAssertions(actualValue); } /// <summary> /// Returns a <see cref="TypeAssertions"/> object that can be used to assert the /// current <see cref="System.Type"/>. /// </summary> [Pure] public static TypeAssertions Should(this Type subject) { return new TypeAssertions(subject); } /// <summary> /// Returns a <see cref="TypeAssertions"/> object that can be used to assert the /// current <see cref="Type"/>. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="typeSelector"/> is <c>null</c>.</exception> [Pure] public static TypeSelectorAssertions Should(this TypeSelector typeSelector) { Guard.ThrowIfArgumentIsNull(typeSelector, nameof(typeSelector)); return new TypeSelectorAssertions(typeSelector.ToArray()); } /// <summary> /// Returns a <see cref="FluentAssertions.Types.MethodBaseAssertions{TSubject, TAssertions}"/> object /// that can be used to assert the current <see cref="MethodInfo"/>. /// </summary> /// <seealso cref="TypeAssertions"/> [Pure] public static ConstructorInfoAssertions Should(this ConstructorInfo constructorInfo) { return new ConstructorInfoAssertions(constructorInfo); } /// <summary> /// Returns a <see cref="MethodInfoAssertions"/> object that can be used to assert the current <see cref="MethodInfo"/>. /// </summary> /// <seealso cref="TypeAssertions"/> [Pure] public static MethodInfoAssertions Should(this MethodInfo methodInfo) { return new MethodInfoAssertions(methodInfo); } /// <summary> /// Returns a <see cref="MethodInfoSelectorAssertions"/> object that can be used to assert the methods returned by the /// current <see cref="MethodInfoSelector"/>. /// </summary> /// <seealso cref="TypeAssertions"/> /// <exception cref="ArgumentNullException"><paramref name="methodSelector"/> is <c>null</c>.</exception> [Pure] public static MethodInfoSelectorAssertions Should(this MethodInfoSelector methodSelector) { Guard.ThrowIfArgumentIsNull(methodSelector, nameof(methodSelector)); return new MethodInfoSelectorAssertions(methodSelector.ToArray()); } /// <summary> /// Returns a <see cref="PropertyInfoAssertions"/> object that can be used to assert the /// current <see cref="PropertyInfoSelector"/>. /// </summary> /// <seealso cref="TypeAssertions"/> [Pure] public static PropertyInfoAssertions Should(this PropertyInfo propertyInfo) { return new PropertyInfoAssertions(propertyInfo); } /// <summary> /// Returns a <see cref="PropertyInfoSelectorAssertions"/> object that can be used to assert the properties returned by the /// current <see cref="PropertyInfoSelector"/>. /// </summary> /// <seealso cref="TypeAssertions"/> /// <exception cref="ArgumentNullException"><paramref name="propertyInfoSelector"/> is <c>null</c>.</exception> [Pure] public static PropertyInfoSelectorAssertions Should(this PropertyInfoSelector propertyInfoSelector) { Guard.ThrowIfArgumentIsNull(propertyInfoSelector, nameof(propertyInfoSelector)); return new PropertyInfoSelectorAssertions(propertyInfoSelector.ToArray()); } /// <summary> /// Returns a <see cref="ActionAssertions"/> object that can be used to assert the /// current <see cref="System.Action"/>. /// </summary> [Pure] public static ActionAssertions Should(this Action action) { return new ActionAssertions(action, Extractor); } /// <summary> /// Returns a <see cref="NonGenericAsyncFunctionAssertions"/> object that can be used to assert the /// current <see cref="System.Func{Task}"/>. /// </summary> [Pure] public static NonGenericAsyncFunctionAssertions Should(this Func<Task> action) { return new NonGenericAsyncFunctionAssertions(action, Extractor); } /// <summary> /// Returns a <see cref="GenericAsyncFunctionAssertions{T}"/> object that can be used to assert the /// current <see><cref>System.Func{Task{T}}</cref></see>. /// </summary> [Pure] public static GenericAsyncFunctionAssertions<T> Should<T>(this Func<Task<T>> action) { return new GenericAsyncFunctionAssertions<T>(action, Extractor); } /// <summary> /// Returns a <see cref="FunctionAssertions{T}"/> object that can be used to assert the /// current <see cref="System.Func{T}"/>. /// </summary> [Pure] public static FunctionAssertions<T> Should<T>(this Func<T> func) { return new FunctionAssertions<T>(func, Extractor); } /// <summary> /// Returns a <see cref="TaskCompletionSourceAssertions{T}"/> object that can be used to assert the /// current <see cref="TaskCompletionSource{T}"/>. /// </summary> [Pure] public static TaskCompletionSourceAssertions<T> Should<T>(this TaskCompletionSource<T> tcs) { return new TaskCompletionSourceAssertions<T>(tcs); } #if !NETSTANDARD2_0 /// <summary> /// Starts monitoring <paramref name="eventSource"/> for its events. /// </summary> /// <param name="eventSource">The object for which to monitor the events.</param> /// <param name="utcNow"> /// An optional delegate that returns the current date and time in UTC format. /// Will revert to <see cref="DateTime.UtcNow"/> if no delegate was provided. /// </param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="eventSource"/> is Null.</exception> public static IMonitor<T> Monitor<T>(this T eventSource, Func<DateTime> utcNow = null) { return new EventMonitor<T>(eventSource, utcNow ?? (() => DateTime.UtcNow)); } #endif /// <summary> /// Safely casts the specified object to the type specified through <typeparamref name="TTo"/>. /// </summary> /// <remarks> /// Has been introduced to allow casting objects without breaking the fluent API. /// </remarks> /// <typeparam name="TTo">The <see cref="Type"/> to cast <paramref name="subject"/> to</typeparam> [Pure] public static TTo As<TTo>(this object subject) { return subject is TTo to ? to : default; } #region Prevent chaining on AndConstraint /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should<TSubject, TAssertions>(this ReferenceTypeAssertions<TSubject, TAssertions> _) where TAssertions : ReferenceTypeAssertions<TSubject, TAssertions> { InvalidShouldCall(); } /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should<TAssertions>(this BooleanAssertions<TAssertions> _) where TAssertions : BooleanAssertions<TAssertions> { InvalidShouldCall(); } /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should<TAssertions>(this DateTimeAssertions<TAssertions> _) where TAssertions : DateTimeAssertions<TAssertions> { InvalidShouldCall(); } /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should<TAssertions>(this DateTimeOffsetAssertions<TAssertions> _) where TAssertions : DateTimeOffsetAssertions<TAssertions> { InvalidShouldCall(); } /// <summary> /// You are asserting the <see cref="AndConstraint{T}"/> itself. Remove the <c>Should()</c> method directly following <c>And</c>. /// </summary> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should(this ExecutionTimeAssertions _) { InvalidShouldCall(); } /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should<TAssertions>(this GuidAssertions<TAssertions> _) where TAssertions : GuidAssertions<TAssertions> { InvalidShouldCall(); } /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should(this MethodInfoSelectorAssertions _) { InvalidShouldCall(); } /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should<TSubject, TAssertions>(this NumericAssertions<TSubject, TAssertions> _) where TSubject : struct, IComparable<TSubject> where TAssertions : NumericAssertions<TSubject, TAssertions> { InvalidShouldCall(); } /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should(this PropertyInfoSelectorAssertions _) { InvalidShouldCall(); } /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should<TAssertions>(this SimpleTimeSpanAssertions<TAssertions> _) where TAssertions : SimpleTimeSpanAssertions<TAssertions> { InvalidShouldCall(); } /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should<TSubject>(this TaskCompletionSourceAssertions<TSubject> _) { InvalidShouldCall(); } /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should(this TypeSelectorAssertions _) { InvalidShouldCall(); } /// <inheritdoc cref="Should(ExecutionTimeAssertions)" /> [Obsolete("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'", error: true)] public static void Should<TEnum, TAssertions>(this EnumAssertions<TEnum, TAssertions> _) where TEnum : struct, Enum where TAssertions : EnumAssertions<TEnum, TAssertions> { InvalidShouldCall(); } private static void InvalidShouldCall() { throw new InvalidOperationException("You are asserting the 'AndConstraint' itself. Remove the 'Should()' method directly following 'And'."); } #endregion } }
40.849076
183
0.611582
[ "Apache-2.0" ]
MullerWasHere/fluentassertions
Src/FluentAssertions/AssertionExtensions.cs
39,789
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class SkeletonMage : EnemyBase { private double healInterval; private double healTimer; protected override void Update() { base.Update(); if (!isDead) UpdateHealTimer(); } public override void InitInfo() { base.InitInfo(); maxHP = 60; curHP = 60; atk = 1; moveSpeed = 3.5f; coinValue = 350; agent.speed = moveSpeed; agent.angularSpeed = 120f; agent.acceleration = 8f; healInterval = 10; healTimer = 0; } private void UpdateHealTimer() { healTimer += Time.deltaTime; if (healTimer >= healInterval) { healTimer = 0; HealAbility(); } } private void HealAbility() { List<IHeal> heals = new List<IHeal>(); var healables = FindObjectsOfType<EnemyBase>().OfType<IHeal>(); foreach (var enemy in healables) { enemy.heal(); } } }
19.033333
71
0.532399
[ "MIT" ]
996Studio/GoblinMustDie
Assets/Scripts/Game Assets/Enemy/SkeletonMage.cs
1,142
C#
namespace AbstractFactory { class Program { static void Main(string[] args) { IMachineFactory factory = new HighBudgetMachine();// Or new LowBudgetMachine(); ComputerShop shop = new ComputerShop(factory); shop.AssembleMachine(); } } }
20.666667
91
0.580645
[ "MIT" ]
didimitrov/Algo
SortingAlgorithmsDemo/OOP/DesignPatterns/Creational/AbstractFactory/Program.cs
312
C#
namespace BlazorState.Pipeline.ReduxDevTools; using MediatR; internal class CommitRequest : DispatchRequest<CommitRequest.PayloadClass>, IRequest, IReduxRequest { internal class PayloadClass { public string Type { get; set; } } }
20.166667
99
0.772727
[ "Unlicense" ]
ScriptBox99/blazor-state
Source/BlazorState/Pipeline/ReduxDevTools/Features/Commit/CommitRequest.cs
242
C#
//--------------------------------------------------------------------- // <copyright file="CsdlConstantExpression.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- using ODataToolkit.Vocabularies; namespace ODataToolkit.Csdl.Parsing.Ast { /// <summary> /// Represents a CSDL constant expression. /// </summary> internal class CsdlConstantExpression : CsdlExpressionBase { private readonly EdmValueKind kind; private readonly string value; public CsdlConstantExpression(EdmValueKind kind, string value, CsdlLocation location) : base(location) { this.kind = kind; this.value = value; } public override EdmExpressionKind ExpressionKind { get { switch (this.kind) { case EdmValueKind.Binary: return EdmExpressionKind.BinaryConstant; case EdmValueKind.Boolean: return EdmExpressionKind.BooleanConstant; case EdmValueKind.DateTimeOffset: return EdmExpressionKind.DateTimeOffsetConstant; case EdmValueKind.Decimal: return EdmExpressionKind.DecimalConstant; case EdmValueKind.Floating: return EdmExpressionKind.FloatingConstant; case EdmValueKind.Guid: return EdmExpressionKind.GuidConstant; case EdmValueKind.Integer: return EdmExpressionKind.IntegerConstant; case EdmValueKind.String: return EdmExpressionKind.StringConstant; case EdmValueKind.Duration: return EdmExpressionKind.DurationConstant; case EdmValueKind.Date: return EdmExpressionKind.DateConstant; case EdmValueKind.TimeOfDay: return EdmExpressionKind.TimeOfDayConstant; case EdmValueKind.Null: return EdmExpressionKind.Null; default: return EdmExpressionKind.None; } } } public EdmValueKind ValueKind { get { return this.kind; } } public string Value { get { return this.value; } } } }
35.947368
126
0.509517
[ "MIT" ]
GCAE/ODataToolkit
ODataToolkit/Edm/Csdl/Parsing/Ast/CsdlConstantExpression.cs
2,732
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebApi.Template.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } } }
18.473684
45
0.592593
[ "MIT" ]
cobusbernard/CSharp.WebApi.Template
src/WebApi.Template/Controllers/HomeController.cs
353
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the networkmanager-2019-07-05.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.NetworkManager.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.NetworkManager.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CreateDevice operation /// </summary> public class CreateDeviceResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateDeviceResponse response = new CreateDeviceResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Device", targetDepth)) { var unmarshaller = DeviceUnmarshaller.Instance; response.Device = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException")) { return ConflictExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException")) { return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceQuotaExceededException")) { return ServiceQuotaExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException")) { return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException")) { return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonNetworkManagerException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static CreateDeviceResponseUnmarshaller _instance = new CreateDeviceResponseUnmarshaller(); internal static CreateDeviceResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateDeviceResponseUnmarshaller Instance { get { return _instance; } } } }
41.126866
197
0.636001
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/NetworkManager/Generated/Model/Internal/MarshallTransformations/CreateDeviceResponseUnmarshaller.cs
5,511
C#
using System.Collections.Generic; using System; using System.Collections; public class InstanceUtility { public static object InstanceOfType(Type type) { if (type.IsEnum) { return InstanceOfEnum(type); } else if (type == typeof(DateTime)) { return DateTime.Now; } else if (type.IsPrimitive || type.IsValueType) { return Activator.CreateInstance(type); } else if (type == typeof(string)) { return "Text"; } else { if (type.IsGenericType) { var typeDef = type.GetGenericTypeDefinition(); if (typeDef == typeof(Dictionary<,>)) { return InstanceOfDict(type); } else if (typeDef == typeof(List<>)) { return InstanceOfList(type); } else { Console.Error.WriteLine("Not Supported Type {0}", type); return null; } } else if (type.IsArray) { return InstanceOfArray(type); } else { return InstanceOfClass(type); } } } private static object InstanceOfEnum(Type type) { Array values = Enum.GetValues(type); if (values.Length > 0) { return values.GetValue(0); } else { return Activator.CreateInstance(type); } } private static object InstanceOfDict(Type type) { var args = type.GetGenericArguments(); var keyType = args[0]; var valueType = args[1]; var obj = Activator.CreateInstance(type); if (obj != null && obj is IDictionary) { var dict = obj as IDictionary; addKeyValuePair(dict, keyType, valueType); } else { Console.Error.WriteLine("InstanceOfDict fail {0}", type); } return obj; } public static void addKeyValuePair(IDictionary dict, Type keyType, Type valueType) { if (dict == null) return; if (keyType == typeof(int)) { int max = int.MinValue; foreach (var key in dict.Keys) { if ((int)key > max) max = (int)key; } int k = dict.Keys.Count == 0 ? 0 : max + 1; dict.Add(k, InstanceOfType(valueType)); } if (keyType == typeof(string)) { TimeSpan diff = DateTime.UtcNow.Subtract(new DateTime(1970,1,1,0,0,0)); dict.Add(((long)diff.TotalMilliseconds).ToString(), InstanceOfType(valueType)); } else if (keyType.IsEnum) { Array enumValues = Enum.GetValues(keyType); List<int> indexes = new List<int>(enumValues.Length); for (int i = 0; i < enumValues.Length; ++i) indexes.Add(i); foreach (var key in dict.Keys) { for (int j = 0; j < enumValues.Length; ++j) { if (enumValues.GetValue(j).Equals(key)) { indexes.Remove(j); break; } } } if (indexes.Count == 0) return; else dict.Add(enumValues.GetValue(indexes[0]), InstanceOfType(valueType)); } } private static object InstanceOfList(Type type) { var valueType = type.GetGenericArguments()[0]; var list = Activator.CreateInstance(type); if(list != null && list is IList) { var lst = list as IList; lst.Add(InstanceOfType(valueType)); } else { Console.Error.WriteLine("InstanceOfList fail {0}", type); } return list; } private static object InstanceOfArray(Type type) { var valueType = type.GetElementType(); var list = (Array)Activator.CreateInstance(type, 1); if(list != null) { list.SetValue(InstanceOfType(valueType), 0); } else { Console.Error.WriteLine("InstanceOfArray fail {0}", type); } return list; } private static object InstanceOfClass(Type type) { var obj = Activator.CreateInstance(type); if (obj != null) { foreach (var field in type.GetFields()) { if (field.IsLiteral) continue; field.SetValue(obj, InstanceOfType(field.FieldType)); } } else { Console.Error.WriteLine("IntanceOfClass fail {0}", type); } return obj; } }
20.726257
83
0.637736
[ "MIT" ]
sric0880/unity-framework
tools/build_codegen_configgen/ConfigGen/ConfigGen/Utility/InstanceUtility.cs
3,712
C#
#region using LoESoft.Core; #endregion namespace LoESoft.GameServer.networking.outgoing { public class PETYARDUPDATE : OutgoingMessage { public int Type { get; set; } public override MessageID ID => MessageID.PETYARDUPDATE; public override Message CreateInstance() => new PETYARDUPDATE(); protected override void Read(NReader rdr) { Type = rdr.ReadInt32(); } protected override void Write(NWriter wtr) { wtr.Write(Type); } } }
19.392857
72
0.607735
[ "MIT" ]
Devwarlt/LOE-V6-SERVER
gameserver/networking/messages/outgoing/PETYARDUPDATE.cs
545
C#
// lucene version compatibility level: 4.8.1 using System.Collections.Generic; using System.Text; namespace Lucene.Net.Analysis.Cn.Smart.Hhmm { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Finds the optimal segmentation of a sentence into Chinese words /// <para/> /// @lucene.experimental /// </summary> public class HHMMSegmenter { private static WordDictionary wordDict = WordDictionary.GetInstance(); /// <summary> /// Create the <see cref="SegGraph"/> for a sentence. /// </summary> /// <param name="sentence">input sentence, without start and end markers</param> /// <returns><see cref="SegGraph"/> corresponding to the input sentence.</returns> private SegGraph CreateSegGraph(string sentence) { int i = 0, j; int length = sentence.Length; int foundIndex; CharType[] charTypeArray = GetCharTypes(sentence); StringBuilder wordBuf = new StringBuilder(); SegToken token; int frequency = 0; // the number of times word appears. bool hasFullWidth; WordType wordType; char[] charArray; SegGraph segGraph = new SegGraph(); while (i < length) { hasFullWidth = false; switch (charTypeArray[i]) { case CharType.SPACE_LIKE: i++; break; case CharType.HANZI: j = i + 1; //wordBuf.delete(0, wordBuf.length()); wordBuf.Remove(0, wordBuf.Length); // It doesn't matter if a single Chinese character (Hanzi) can form a phrase or not, // it will store that single Chinese character (Hanzi) in the SegGraph. Otherwise, it will // cause word division. wordBuf.Append(sentence[i]); charArray = new char[] { sentence[i] }; frequency = wordDict.GetFrequency(charArray); token = new SegToken(charArray, i, j, WordType.CHINESE_WORD, frequency); segGraph.AddToken(token); foundIndex = wordDict.GetPrefixMatch(charArray); while (j <= length && foundIndex != -1) { if (wordDict.IsEqual(charArray, foundIndex) && charArray.Length > 1) { // It is the phrase we are looking for; In other words, we have found a phrase SegToken // from i to j. It is not a monosyllabic word (single word). frequency = wordDict.GetFrequency(charArray); token = new SegToken(charArray, i, j, WordType.CHINESE_WORD, frequency); segGraph.AddToken(token); } while (j < length && charTypeArray[j] == CharType.SPACE_LIKE) j++; if (j < length && charTypeArray[j] == CharType.HANZI) { wordBuf.Append(sentence[j]); charArray = new char[wordBuf.Length]; //wordBuf.GetChars(0, charArray.Length, charArray, 0); wordBuf.CopyTo(0, charArray, 0, charArray.Length); // idArray has been found (foundWordIndex!=-1) as a prefix before. // Therefore, idArray after it has been lengthened can only appear after foundWordIndex. // So start searching after foundWordIndex. foundIndex = wordDict.GetPrefixMatch(charArray, foundIndex); j++; } else { break; } } i++; break; case CharType.FULLWIDTH_LETTER: hasFullWidth = true; /* intentional fallthrough */ j = i + 1; while (j < length && (charTypeArray[j] == CharType.LETTER || charTypeArray[j] == CharType.FULLWIDTH_LETTER)) { if (charTypeArray[j] == CharType.FULLWIDTH_LETTER) hasFullWidth = true; j++; } // Found a Token from i to j. Type is LETTER char string. charArray = Utility.STRING_CHAR_ARRAY; frequency = wordDict.GetFrequency(charArray); wordType = hasFullWidth ? WordType.FULLWIDTH_STRING : WordType.STRING; token = new SegToken(charArray, i, j, wordType, frequency); segGraph.AddToken(token); i = j; break; case CharType.LETTER: j = i + 1; while (j < length && (charTypeArray[j] == CharType.LETTER || charTypeArray[j] == CharType.FULLWIDTH_LETTER)) { if (charTypeArray[j] == CharType.FULLWIDTH_LETTER) hasFullWidth = true; j++; } // Found a Token from i to j. Type is LETTER char string. charArray = Utility.STRING_CHAR_ARRAY; frequency = wordDict.GetFrequency(charArray); wordType = hasFullWidth ? WordType.FULLWIDTH_STRING : WordType.STRING; token = new SegToken(charArray, i, j, wordType, frequency); segGraph.AddToken(token); i = j; break; case CharType.FULLWIDTH_DIGIT: hasFullWidth = true; /* intentional fallthrough */ j = i + 1; while (j < length && (charTypeArray[j] == CharType.DIGIT || charTypeArray[j] == CharType.FULLWIDTH_DIGIT)) { if (charTypeArray[j] == CharType.FULLWIDTH_DIGIT) hasFullWidth = true; j++; } // Found a Token from i to j. Type is NUMBER char string. charArray = Utility.NUMBER_CHAR_ARRAY; frequency = wordDict.GetFrequency(charArray); wordType = hasFullWidth ? WordType.FULLWIDTH_NUMBER : WordType.NUMBER; token = new SegToken(charArray, i, j, wordType, frequency); segGraph.AddToken(token); i = j; break; case CharType.DIGIT: j = i + 1; while (j < length && (charTypeArray[j] == CharType.DIGIT || charTypeArray[j] == CharType.FULLWIDTH_DIGIT)) { if (charTypeArray[j] == CharType.FULLWIDTH_DIGIT) hasFullWidth = true; j++; } // Found a Token from i to j. Type is NUMBER char string. charArray = Utility.NUMBER_CHAR_ARRAY; frequency = wordDict.GetFrequency(charArray); wordType = hasFullWidth ? WordType.FULLWIDTH_NUMBER : WordType.NUMBER; token = new SegToken(charArray, i, j, wordType, frequency); segGraph.AddToken(token); i = j; break; case CharType.DELIMITER: j = i + 1; // No need to search the weight for the punctuation. Picking the highest frequency will work. frequency = Utility.MAX_FREQUENCE; charArray = new char[] { sentence[i] }; token = new SegToken(charArray, i, j, WordType.DELIMITER, frequency); segGraph.AddToken(token); i = j; break; default: j = i + 1; // Treat the unrecognized char symbol as unknown string. // For example, any symbol not in GB2312 is treated as one of these. charArray = Utility.STRING_CHAR_ARRAY; frequency = wordDict.GetFrequency(charArray); token = new SegToken(charArray, i, j, WordType.STRING, frequency); segGraph.AddToken(token); i = j; break; } } // Add two more Tokens: "beginning xx beginning" charArray = Utility.START_CHAR_ARRAY; frequency = wordDict.GetFrequency(charArray); token = new SegToken(charArray, -1, 0, WordType.SENTENCE_BEGIN, frequency); segGraph.AddToken(token); // "end xx end" charArray = Utility.END_CHAR_ARRAY; frequency = wordDict.GetFrequency(charArray); token = new SegToken(charArray, length, length + 1, WordType.SENTENCE_END, frequency); segGraph.AddToken(token); return segGraph; } /// <summary> /// Get the character types for every character in a sentence. /// </summary> /// <param name="sentence">input sentence</param> /// <returns>array of character types corresponding to character positions in the sentence</returns> /// <seealso cref="Utility.GetCharType(char)"/> private static CharType[] GetCharTypes(string sentence) { int length = sentence.Length; CharType[] charTypeArray = new CharType[length]; // the type of each character by position for (int i = 0; i < length; i++) { charTypeArray[i] = Utility.GetCharType(sentence[i]); } return charTypeArray; } /// <summary> /// Return a list of <see cref="SegToken"/> representing the best segmentation of a sentence /// </summary> /// <param name="sentence">input sentence</param> /// <returns>best segmentation as a <see cref="T:IList{SegToken}"/></returns> public virtual IList<SegToken> Process(string sentence) { SegGraph segGraph = CreateSegGraph(sentence); BiSegGraph biSegGraph = new BiSegGraph(segGraph); IList<SegToken> shortPath = biSegGraph.GetShortPath(); return shortPath; } } }
48.555118
122
0.478878
[ "Apache-2.0" ]
DiogenesPolanco/lucenenet
src/Lucene.Net.Analysis.SmartCn/Hhmm/HHMMSegmenter.cs
12,335
C#
using NUnit.Framework; using ScottPlot; using System; using System.Collections.Generic; using System.Text; namespace ScottPlotTests.Ticks { class TickGeneration { [Test] public void Test_DefinedSpacing_NumericAxis() { int pointCount = 20; // create a series of day numbers double[] days = ScottPlot.DataGen.Consecutive(pointCount); // simulate data for each date double[] values = new double[pointCount]; Random rand = new Random(0); for (int i = 1; i < pointCount; i++) values[i] = values[i - 1] + rand.NextDouble(); var mplt = new ScottPlot.MultiPlot(1000, 400, 1, 2); var pltDefault = mplt.GetSubplot(0, 0); pltDefault.Title("Default xSpacing"); pltDefault.AddScatter(days, values); var pltTest = mplt.GetSubplot(0, 1); pltTest.Title("xSpacing = 1 unit"); pltTest.AddScatter(days, values); // force inter-tick distance on a numerical axis pltTest.XAxis.ManualTickSpacing(1); TestTools.SaveFig(mplt); } [Test] public void Test_DefinedSpacing_DateTimeAxis() { int pointCount = 20; // create a series of dates double[] dates = new double[pointCount]; var firstDay = new DateTime(2020, 1, 22); for (int i = 0; i < pointCount; i++) dates[i] = firstDay.AddDays(i).ToOADate(); // simulate data for each date double[] values = new double[pointCount]; Random rand = new Random(0); for (int i = 1; i < pointCount; i++) values[i] = values[i - 1] + rand.NextDouble(); var mplt = new ScottPlot.MultiPlot(1000, 400, 1, 2); var pltDefault = mplt.GetSubplot(0, 0); pltDefault.Title("Default xSpacing"); pltDefault.AddScatter(dates, values); pltDefault.XAxis.DateTimeFormat(true); var pltTest = mplt.GetSubplot(0, 1); pltTest.Title("xSpacing = 1 day"); pltTest.AddScatter(dates, values); pltTest.XAxis.DateTimeFormat(true); pltTest.XAxis.TickLabelStyle(rotation: 45); pltTest.Layout(bottom: 60); // need extra height to accomodate rotated labels // force 1 tick per day on a DateTime axis pltTest.XAxis.ManualTickSpacing(1, ScottPlot.Ticks.DateTimeUnit.Day); TestTools.SaveFig(mplt); } [Test] public void Test_LargePlot_DateTimeAxis() { Random rand = new Random(0); double[] data = DataGen.RandomWalk(rand, 100_000); DateTime firstDay = new DateTime(2020, 1, 1); var plt = new ScottPlot.Plot(4000, 400); var sig = plt.AddSignal(data, sampleRate: 60 * 24); sig.OffsetX = firstDay.ToOADate(); plt.XAxis.DateTimeFormat(true); TestTools.SaveFig(plt); } } }
32.547368
89
0.562096
[ "MIT" ]
Jmerk523/ScottPlot
src/tests/Ticks/TickGeneration.cs
3,094
C#
using System; using System.IO; using System.Windows.Forms; using NLog; using NSW.StarCitizen.Tools.Lib.Global; using NSW.StarCitizen.Tools.Properties; namespace NSW.StarCitizen.Tools.Controllers { public sealed class GameModesController { private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly string _gameFolder; private readonly GameInfo? _currentGameInfo; public GameModesController(string gameFolder, GameInfo? currentGameInfo) { _gameFolder = gameFolder; _currentGameInfo = currentGameInfo; } public bool MoveGameMode(Control window, GameMode srcMode, GameMode destMode) { var destPath = GameConstants.GetGameModePath(_gameFolder, destMode); if (Directory.Exists(destPath)) { MessageBox.Show(window, Resources.Localization_File_ErrorText, Resources.Localization_File_ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } var srcPath = GameConstants.GetGameModePath(_gameFolder, srcMode); if (!Directory.Exists(srcPath)) { MessageBox.Show(window, Resources.Localization_File_ErrorText, Resources.Localization_File_ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (_currentGameInfo != null && _currentGameInfo.Mode == srcMode) { var controller = new LocalizationController(_currentGameInfo); if (!controller.Uninstall(window)) { return false; } } using var gameMutex = new GameMutex(); if (!GameMutexController.AcquireWithRetryDialog(window, gameMutex)) { return false; } try { Directory.Move(srcPath, destPath); } catch (Exception e) { gameMutex.Release(); _logger.Error(e, "Failed rename game folder: " + srcPath); MessageBox.Show(window, Resources.Localization_File_ErrorText, Resources.Localization_File_ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } } }
36.820896
104
0.591001
[ "MIT" ]
Terrencetodd/StarCitizen
SCTools/SCTools/Controllers/GameModesController.cs
2,467
C#
using Common.Logging; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Serilog; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace Basket.API { public class Program { public static void Main(string[] args) { Activity.DefaultIdFormat = ActivityIdFormat.W3C; Activity.ForceDefaultIdFormat = true; CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseSerilog(SeriLogger.Configure) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26.852941
70
0.657174
[ "MIT" ]
lateef10/CleanArchitectureMicroservice
MicroserviceArchitecture/Services/Basket/Basket.API/Program.cs
913
C#
using System; using System.Collections.Generic; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Client.UserInterface.CustomControls; using Robust.Shared.Localization; using Robust.Shared.Maths; namespace Content.Client.GameObjects.Components.Body.Surgery { public class SurgeryWindow : SS14Window { public delegate void OptionSelectedCallback(int selectedOptionData); private readonly VBoxContainer _optionsBox; private OptionSelectedCallback? _optionSelectedCallback; public SurgeryWindow() { MinSize = SetSize = (300, 400); Title = Loc.GetString("Surgery"); RectClipContent = true; var vSplitContainer = new VBoxContainer { Children = { new ScrollContainer { VerticalExpand = true, HorizontalExpand = true, HScrollEnabled = true, VScrollEnabled = true, Children = { (_optionsBox = new VBoxContainer { HorizontalExpand = true }) } } } }; Contents.AddChild(vSplitContainer); } public void BuildDisplay(Dictionary<string, int> data, OptionSelectedCallback callback) { _optionsBox.DisposeAllChildren(); _optionSelectedCallback = callback; foreach (var (displayText, callbackData) in data) { var button = new SurgeryButton(callbackData); button.SetOnToggleBehavior(OnButtonPressed); button.SetDisplayText(Loc.GetString(displayText)); _optionsBox.AddChild(button); } } private void OnButtonPressed(BaseButton.ButtonEventArgs args) { if (args.Button.Parent is SurgeryButton surgery) { _optionSelectedCallback?.Invoke(surgery.CallbackData); } } } class SurgeryButton : PanelContainer { public Button Button { get; } private SpriteView SpriteView { get; } private Label DisplayText { get; } public int CallbackData { get; } public SurgeryButton(int callbackData) { CallbackData = callbackData; Button = new Button { HorizontalExpand = true, VerticalExpand = true, ToggleMode = true, MouseFilter = MouseFilterMode.Stop }; AddChild(Button); AddChild(new HBoxContainer { Children = { (SpriteView = new SpriteView { MinSize = new Vector2(32.0f, 32.0f) }), (DisplayText = new Label { VerticalAlignment = VAlignment.Center, Text = "N/A", }), (new Control { HorizontalExpand = true }) } }); } public void SetDisplayText(string text) { DisplayText.Text = text; } public void SetOnToggleBehavior(Action<BaseButton.ButtonToggledEventArgs> behavior) { Button.OnToggled += behavior; } public void SetSprite() { //button.SpriteView.Sprite = sprite; } } }
28.514925
95
0.490709
[ "MIT" ]
BingoJohnson/space-station-14
Content.Client/GameObjects/Components/Body/Surgery/SurgeryWindow.cs
3,823
C#
/** * Copyright 2015 Canada Health Infoway, 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. * * Author: $LastChangedBy: jmis $ * Last modified: $LastChangedDate: 2015-09-15 10:24:28 -0400 (Tue, 15 Sep 2015) $ * Revision: $LastChangedRevision: 9776 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Interaction { using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Model; using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Mcci_mt000300ca; using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Quqi_mt120000ca; using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt060020ca; using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt060030ca; /** * <summary>Business Name: PORX_IN060080CA: Device prescription * dispense summary query resp.</summary> * * <p>Returns basic information about all device dispenses * provided to a particular patient.</p> Message: * MCCI_MT000300CA.Message Control Act: * QUQI_MT120000CA.ControlActEvent --> Payload: * PORX_MT060020CA.DeviceDispense --> Payload: * PORX_MT060030CA.ParameterList */ [Hl7PartTypeMappingAttribute(new string[] {"PORX_IN060080CA"})] public class DevicePrescriptionDispenseSummaryQueryResp : HL7Message<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Quqi_mt120000ca.TriggerEvent<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt060020ca.Dispense,Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt060030ca.GenericQueryParameters>>, IInteraction { public DevicePrescriptionDispenseSummaryQueryResp() { } } }
48.612245
362
0.742653
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-v01_r04_3/Main/Ca/Infoway/Messagebuilder/Model/Pcs_cerx_v01_r04_3/Interaction/DevicePrescriptionDispenseSummaryQueryResp.cs
2,382
C#
namespace BO.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitDb : DbMigration { public override void Up() { CreateTable( "dbo.CategoryPOIs", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(maxLength: 50), DateMAJ = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.DisplayConfigurations", c => new { Id = c.Int(nullable: false, identity: true), TypeUnite = c.Int(nullable: false), DateMAJ = c.DateTime(nullable: false), Person_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.People", t => t.Person_Id) .Index(t => t.Person_Id); CreateTable( "dbo.People", c => new { Id = c.Int(nullable: false, identity: true), FirstName = c.String(maxLength: 50), LastName = c.String(maxLength: 50), PhoneNumber = c.String(), BirthDate = c.DateTime(nullable: false), DateMAJ = c.DateTime(nullable: false), User_Id = c.String(maxLength: 128), Race_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.User_Id) .ForeignKey("dbo.Races", t => t.Race_Id) .Index(t => t.User_Id) .Index(t => t.Race_Id); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.POIs", c => new { Id = c.Int(nullable: false, identity: true), Latitude = c.Single(nullable: false), Longitude = c.Single(nullable: false), DateMAJ = c.DateTime(nullable: false), CategoryPOI_Id = c.Int(), Race_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.CategoryPOIs", t => t.CategoryPOI_Id) .ForeignKey("dbo.Races", t => t.Race_Id) .Index(t => t.CategoryPOI_Id) .Index(t => t.Race_Id); CreateTable( "dbo.Races", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(maxLength: 50), PlacesNumber = c.Int(nullable: false), City = c.String(maxLength: 50), ZipCode = c.String(), Price = c.Single(nullable: false), Description = c.String(maxLength: 200), DateMAJ = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.RaceTypes", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 50), DateMAJ = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.POIs", "Race_Id", "dbo.Races"); DropForeignKey("dbo.People", "Race_Id", "dbo.Races"); DropForeignKey("dbo.POIs", "CategoryPOI_Id", "dbo.CategoryPOIs"); DropForeignKey("dbo.DisplayConfigurations", "Person_Id", "dbo.People"); DropForeignKey("dbo.People", "User_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.POIs", new[] { "Race_Id" }); DropIndex("dbo.POIs", new[] { "CategoryPOI_Id" }); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.People", new[] { "Race_Id" }); DropIndex("dbo.People", new[] { "User_Id" }); DropIndex("dbo.DisplayConfigurations", new[] { "Person_Id" }); DropTable("dbo.AspNetRoles"); DropTable("dbo.RaceTypes"); DropTable("dbo.Races"); DropTable("dbo.POIs"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.People"); DropTable("dbo.DisplayConfigurations"); DropTable("dbo.CategoryPOIs"); } } }
44.12
83
0.437443
[ "MIT" ]
Alexandre-Delaunay/ENI_Projet_Sport
ENI_Projet_Sport/BO/Migrations/201903041503367_InitDb.cs
8,824
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace Linehaul_Helper.Converters { class TrackingNumberValidConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return (value == null) ? false : ((string)value).Length >= 7; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
29.909091
124
0.697568
[ "MIT" ]
RodgerLeblanc/Linehaul-Helper
Linehaul Helper/Linehaul_Helper/Converters/TrackingNumberValidConverter.cs
660
C#
using System; using System.Collections.Generic; namespace SICore.Connections { /// <summary> /// Базовый класс для всех внешних серверов /// </summary> public abstract class ConnectionBase : IConnection { protected bool IsClosed { get; private set; } = false; public string ConnectionId { get; protected set; } /// <summary> /// Уникальный идентификатор внешнего сервера /// </summary> public string Id { get; } = Guid.NewGuid().ToString(); /// <summary> /// Доступные клиенты на внешнем сервере /// </summary> public List<string> Clients { get; } = new List<string>(); public object ClientsSync { get; } = new object(); /// <summary> /// Адрес удалённого подключения /// </summary> public abstract string RemoteAddress { get; } /// <summary> /// Авторизован ли удалённый клиент /// </summary> public bool IsAuthenticated { get; set; } /// <summary> /// Получено сообщение /// </summary> public event Action<IConnection, Message> MessageReceived; /// <summary> /// Соединение закрылось /// </summary> public event Action<IConnection, bool> ConnectionClose; /// <summary> /// Ошибка /// </summary> public event Action<Exception, bool> Error; public event Action<Message, Exception> SerializationError; public string UserName { get; set; } = Guid.NewGuid().ToString(); public int GameId { get; set; } public abstract void SendMessage(Message m); public virtual void Close() { } protected virtual void CloseCore(bool informServer, bool withError = false) { if (IsClosed) { return; } Close(); IsClosed = true; if (informServer) { OnConnectionClose(withError); } } protected void OnMessageReceived(Message message) => MessageReceived?.Invoke(this, message); protected void OnConnectionClose(bool withError) { System.Threading.Tasks.Task.Run(() => { ConnectionClose?.Invoke(this, withError); }).ContinueWith(task => { if (task.IsFaulted) { OnError(task.Exception.InnerException, true); } }); } public void OnError(Exception exc, bool isWarning) => Error?.Invoke(exc, isWarning); protected void OnSerializationError(Message message, Exception exc) => SerializationError?.Invoke(message, exc); protected abstract void Dispose(bool disposing); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
26.684685
120
0.54659
[ "MIT" ]
wurunduk/SI
src/SICore/SICore.Connections/ConnectionBase.cs
3,164
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Repository.Pattern.Abstractions; using Repository.Pattern.Abstractions.Batches; using Repository.Pattern.Abstractions.Exceptions; using Repository.Pattern.Abstractions.Exceptions.Models; namespace Repository.Pattern.InMemory { /// <summary> /// In memory implementation of the repository pattern using a ConcurrentDictionary /// </summary> /// <typeparam name="T">A Mode object not related with Table storage at all</typeparam> public abstract class InMemoryRepository<TDomainModel> : IRepository<TDomainModel> where TDomainModel : class, IDomainModel, new() { protected readonly ConcurrentDictionary<string, ConcurrentDictionary<string, TDomainModel>> _repository = new ConcurrentDictionary<string, ConcurrentDictionary<string, TDomainModel>>(); public Task<IEnumerable<TDomainModel>> GetAllAsync() { var result = _repository.SelectMany(r => r.Value.Values).ToList(); return Task.FromResult(result as IEnumerable<TDomainModel>); } public Task<IEnumerable<TDomainModel>> GetAllAsync(string partitionKey) { var partitionKeyValues = GetValue(partitionKey, _repository, throwException: false); var result = partitionKeyValues == null ? new List<TDomainModel>() : partitionKeyValues.Values as IEnumerable<TDomainModel>; return Task.FromResult(result); } public Task<TDomainModel> GetAsync(string partitionKey, string rowKey) { var partitionKeyValues = GetValue(partitionKey, _repository); var rowKeyValue = GetValue(rowKey, partitionKeyValues); return Task.FromResult(rowKeyValue); } public Task<TDomainModel> AddAsync(TDomainModel domainModel) { var partitionKeyValues = GetValue(domainModel.PartitionKey, _repository, throwException: false); if (partitionKeyValues == null) { _repository.TryAdd(domainModel.PartitionKey, new ConcurrentDictionary<string, TDomainModel>()); partitionKeyValues = GetValue(domainModel.PartitionKey, _repository, nameof(AddAsync)); } var success = partitionKeyValues.TryAdd(domainModel.RowKey, domainModel); if (!success) { throw new AlreadyExistsException(nameof(AddAsync)) { DomainModelUids = BuildDomainModelUids(domainModel) }; } return Task.FromResult(domainModel); } public async Task AddBatchAsync(IEnumerable<TDomainModel> domainModelEnumerable, BatchOperationOptions options = null) { var domainModels = domainModelEnumerable.ToList(); Func<TDomainModel, Task<TDomainModel>> operation = (dm) => AddOrUpdateAsync(dm); if (options != null) { switch (options.BatchInsertMethod) { case BatchInsertMethod.Insert: var existingDomainModels = domainModels.Where(dm => Exists(dm)).ToArray(); if (existingDomainModels.Any()) { throw new AlreadyExistsException(nameof(AddBatchAsync)) { DomainModelUids = BuildDomainModelUids(existingDomainModels) }; } operation = (dm) => AddAsync(dm); break; // We will implement both the same way, like an upsert //case BatchInsertMethod.InsertOrMerge: //case BatchInsertMethod.InsertOrReplace: } } foreach (var domainModel in domainModelEnumerable) { await operation(domainModel); } return; } public Task<TDomainModel> AddOrUpdateAsync(TDomainModel domainModel) { var partitionKeyValues = GetValue(domainModel.PartitionKey, _repository, throwException: false); if (partitionKeyValues == null) { _repository.TryAdd(domainModel.PartitionKey, new ConcurrentDictionary<string, TDomainModel>()); partitionKeyValues = GetValue(domainModel.PartitionKey, _repository, nameof(AddOrUpdateAsync)); } var result = partitionKeyValues.AddOrUpdate(domainModel.RowKey, domainModel, (s, d) => d); return Task.FromResult(result); } public Task<TDomainModel> UpdateAsync(TDomainModel domainModel) { var partitionKeyValues = GetValue(domainModel.PartitionKey, _repository, nameof(UpdateAsync)); var success = partitionKeyValues.TryUpdate(domainModel.RowKey, domainModel, domainModel); if (!success) { throw new DoesNotExistsException(nameof(UpdateAsync)) { DomainModelUids = BuildDomainModelUids(domainModel) }; } return Task.FromResult(domainModel); } public Task DeleteAllAsync(string partitionKey) { _ = _repository.TryRemove(partitionKey, out _); return Task.CompletedTask; } public Task<TDomainModel> DeleteAsync(TDomainModel domainModel) { return DeleteAsync(domainModel.PartitionKey, domainModel.RowKey); } public Task<TDomainModel> DeleteAsync(string partitionKey, string rowKey) { var partitionKeyValues = GetValue(partitionKey, _repository, nameof(DeleteAsync)); var success = partitionKeyValues.TryRemove(rowKey, out TDomainModel deleted); if (!success) { throw new DoesNotExistsException(nameof(DeleteAsync)) { DomainModelUids = new[] { new DomainModelUid() { PartitionKey = partitionKey, RowKey = rowKey }} }; } return Task.FromResult(deleted); } private bool Exists(TDomainModel domainModel) { var partitionKeyValues = GetValue(domainModel.PartitionKey, _repository, throwException: false); if (partitionKeyValues == null) { return false; } var rowKeyValue = GetValue(domainModel.RowKey, partitionKeyValues, throwException: false); return rowKeyValue != null; } private T GetValue<T>(string key, ConcurrentDictionary<string, T> dictionary, string callerName = nameof(GetValue), bool throwException = true) { var exists = dictionary.TryGetValue(key, out T entries); if (throwException && !exists) { throw new DoesNotExistsException($"{callerName}: {key}"); } return entries; } private DomainModelUid[] BuildDomainModelUids(params IDomainModel[] domainModels) { return domainModels.Select(dm => new DomainModelUid() { PartitionKey = dm.PartitionKey, RowKey = dm.RowKey }).ToArray(); } } }
37.411765
134
0.588574
[ "MIT" ]
alvaromongon/Repository.Pattern.InMemory
src/Repository.Pattern.InMemory/InMemoryRepository.cs
7,634
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MvcMovie.Models; namespace MvcMovie.Migrations { [DbContext(typeof(MvcMovieContext))] partial class MvcMovieContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.1-rtm-30846") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("MvcMovie.Models.Movie", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Genre"); b.Property<decimal>("Price") .HasColumnType("decimal(18, 2)"); b.Property<string>("Rating"); b.Property<DateTime>("ReleaseDate"); b.Property<string>("Title"); b.HasKey("ID"); b.ToTable("Movie"); }); #pragma warning restore 612, 618 } } }
33.085106
125
0.603859
[ "MIT" ]
reelleer/dotNetCoreTutorials
MvcMovie/Migrations/MvcMovieContextModelSnapshot.cs
1,557
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Dingtalkattendance_1_0.Models { public class GetUserHolidaysResponseBody : TeaModel { /// <summary> /// 员工假期列表 /// </summary> [NameInMap("result")] [Validation(Required=false)] public List<GetUserHolidaysResponseBodyResult> Result { get; set; } public class GetUserHolidaysResponseBodyResult : TeaModel { /// <summary> /// 员工id /// </summary> [NameInMap("userId")] [Validation(Required=false)] public string UserId { get; set; } /// <summary> /// 假期列表 /// </summary> [NameInMap("holidays")] [Validation(Required=false)] public List<GetUserHolidaysResponseBodyResultHolidays> Holidays { get; set; } public class GetUserHolidaysResponseBodyResultHolidays : TeaModel { /// <summary> /// 日期 /// </summary> [NameInMap("workDate")] [Validation(Required=false)] public long? WorkDate { get; set; } /// <summary> /// 假期名称 /// </summary> [NameInMap("holidayName")] [Validation(Required=false)] public string HolidayName { get; set; } /// <summary> /// 假期类型,festival:法定节假日;rest:调休日;overtime:加班日; /// </summary> [NameInMap("holidayType")] [Validation(Required=false)] public string HolidayType { get; set; } /// <summary> /// 补休日,只有假期类型为加班日时才有值 /// </summary> [NameInMap("realWorkDate")] [Validation(Required=false)] public long? RealWorkDate { get; set; } } } } }
30.102941
89
0.49829
[ "Apache-2.0" ]
aliyun/dingtalk-sdk
dingtalk/csharp/core/attendance_1_0/Models/GetUserHolidaysResponseBody.cs
2,163
C#
using NBitcoin; using Stratis.Bitcoin.Utilities; namespace Stratis.Bitcoin.Base.Deployments { public class NodeDeployments { /// <summary>Specification of the network the node runs on - regtest/testnet/mainnet.</summary> private readonly Network network; public ThresholdConditionCache BIP9 { get; } /// <summary>Thread safe access to the best chain of block headers (that the node is aware of) from genesis.</summary> private readonly ConcurrentChain chain; public NodeDeployments(Network network, ConcurrentChain chain) { Guard.NotNull(network, nameof(network)); Guard.NotNull(chain, nameof(chain)); this.network = network; this.chain = chain; this.BIP9 = new ThresholdConditionCache(network.Consensus); } public virtual DeploymentFlags GetFlags(ChainedBlock block) { Guard.NotNull(block, nameof(block)); lock (this.BIP9) { ThresholdState[] states = this.BIP9.GetStates(block.Previous); var flags = new DeploymentFlags(block, states, this.network.Consensus, this.chain); return flags; } } } }
32.282051
126
0.622716
[ "MIT" ]
MIPPL/StratisBitcoinFullNode
src/Stratis.Bitcoin/Base/Deployments/NodeDeployments.cs
1,261
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Zeron.ZCore.Utils.Tests { [TestClass()] public class Md5ProviderTests { [TestMethod()] public void GenerateBase64Test() { string encodeMd5 = Md5Provider.GenerateBase64("zeron"); Assert.AreEqual(encodeMd5, "b3z777naGB7+WBz7tMRQ/Q=="); } } }
23.5
67
0.630319
[ "MIT" ]
inwazy/Zeron
ZeronTests/ZCore/Utils/Md5ProviderTests.cs
378
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DataTable { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.592593
70
0.643994
[ "MIT" ]
reshamkafle/jQuery-DataTable-ASP.NET-5
DataTable/Program.cs
691
C#
namespace PierresSavoryAndSweet.ViewModels { public class LoginViewModel { public string Email { get; set; } public string Password { get; set; } } }
20.375
42
0.699387
[ "Unlicense" ]
mikah-mathews/PierresSavoryAndSweets
PierresSavoryAndSweet/ViewModels/LoginViewModel.cs
163
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Data.Common; using Microsoft.EntityFrameworkCore.Specification.Tests; using Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests.Utilities; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.EntityFrameworkCore.SqlServer.FunctionalTests { public class TransactionSqlServerFixture : TransactionFixtureBase<SqlServerTestStore> { private readonly IServiceProvider _serviceProvider; public TransactionSqlServerFixture() { _serviceProvider = new ServiceCollection() .AddEntityFrameworkSqlServer() .AddSingleton(TestModelSource.GetFactory(OnModelCreating)) .BuildServiceProvider(); } public override SqlServerTestStore CreateTestStore() => SqlServerTestStore.GetOrCreateShared(DatabaseName, () => { var optionsBuilder = new DbContextOptionsBuilder() .UseSqlServer(SqlServerTestStore.CreateConnectionString(DatabaseName), b => b.ApplyConfiguration()) .UseInternalServiceProvider(_serviceProvider); using (var context = new DbContext(optionsBuilder.Options)) { context.Database.EnsureCreated(); var connection = context.Database.GetDbConnection(); connection.Open(); using (var command = connection.CreateCommand()) { command.CommandTimeout = 600; command.CommandText = "ALTER DATABASE [" + connection.Database + "] SET ALLOW_SNAPSHOT_ISOLATION ON"; command.ExecuteNonQuery(); } using (var command = connection.CreateCommand()) { command.CommandTimeout = 600; command.CommandText = "ALTER DATABASE [" + connection.Database + "] SET READ_COMMITTED_SNAPSHOT ON"; command.ExecuteNonQuery(); } connection.Close(); } }); public override DbContext CreateContext(SqlServerTestStore testStore) => new DbContext(new DbContextOptionsBuilder() .UseSqlServer(testStore.ConnectionString, b => { b.ApplyConfiguration(); b.MaxBatchSize(1); }) .UseInternalServiceProvider(_serviceProvider).Options); public override DbContext CreateContext(DbConnection connection) => new DbContext(new DbContextOptionsBuilder() .UseSqlServer(connection, b => { b.ApplyConfiguration(); b.MaxBatchSize(1); }) .UseInternalServiceProvider(_serviceProvider).Options); } }
42.434211
129
0.567442
[ "Apache-2.0" ]
pmiddleton/EntityFramework
test/EFCore.SqlServer.FunctionalTests/TransactionSqlServerFixture.cs
3,225
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System.Net; using System.Net.Http.Headers; using System.Threading; using EnsureThat; using FellowOakDicom; using Hl7.Fhir.Model; using Hl7.Fhir.Utility; using Microsoft.Health.DicomCast.Core.Extensions; using Microsoft.Health.DicomCast.Core.Features.Fhir; using Task = System.Threading.Tasks.Task; namespace Microsoft.Health.DicomCast.Core.Features.Worker.FhirTransaction; /// <summary> /// Pipeline step for handling <see cref="ImagingStudy"/>. /// </summary> public class PatientPipelineStep : IFhirTransactionPipelineStep { private readonly IFhirService _fhirService; private readonly IPatientSynchronizer _patientSynchronizer; public PatientPipelineStep( IFhirService fhirService, IPatientSynchronizer patientSynchronizer) { EnsureArg.IsNotNull(fhirService, nameof(fhirService)); EnsureArg.IsNotNull(patientSynchronizer, nameof(patientSynchronizer)); _fhirService = fhirService; _patientSynchronizer = patientSynchronizer; } /// <inheritdoc/> public async Task PrepareRequestAsync(FhirTransactionContext context, CancellationToken cancellationToken) { EnsureArg.IsNotNull(context, nameof(context)); DicomDataset dataset = context.ChangeFeedEntry.Metadata; if (dataset == null) { return; } if (!dataset.TryGetSingleValue(DicomTag.PatientID, out string patientId)) { throw new MissingRequiredDicomTagException(nameof(DicomTag.PatientID)); } var patientIdentifier = new Identifier(string.Empty, patientId); FhirTransactionRequestMode requestMode = FhirTransactionRequestMode.None; Patient existingPatient = await _fhirService.RetrievePatientAsync(patientIdentifier, cancellationToken); var patient = (Patient)existingPatient?.DeepCopy(); if (existingPatient == null) { patient = new Patient(); patient.Identifier.Add(patientIdentifier); requestMode = FhirTransactionRequestMode.Create; } await _patientSynchronizer.SynchronizeAsync(context, patient, requestMode.Equals(FhirTransactionRequestMode.Create), cancellationToken); if (requestMode == FhirTransactionRequestMode.None && !existingPatient.IsExactly(patient)) { requestMode = FhirTransactionRequestMode.Update; } Bundle.RequestComponent request = requestMode switch { FhirTransactionRequestMode.Create => GenerateCreateRequest(patientIdentifier), FhirTransactionRequestMode.Update => GenerateUpdateRequest(patient), _ => null }; IResourceId resourceId = requestMode switch { FhirTransactionRequestMode.Create => new ClientResourceId(), _ => existingPatient.ToServerResourceId(), }; context.Request.Patient = new FhirTransactionRequestEntry( requestMode, request, resourceId, patient); } /// <inheritdoc/> public void ProcessResponse(FhirTransactionContext context) { EnsureArg.IsNotNull(context, nameof(context)); // If the Patient does not exist, we will use conditional create to create the resource // to avoid duplicated resource being created. However, if the resource with the identifier // was created externally between the retrieve and create, conditional create will return 200 // and might not contain the changes so we will need to try again. if (context.Request.Patient?.RequestMode == FhirTransactionRequestMode.Create) { FhirTransactionResponseEntry patient = context.Response.Patient; HttpStatusCode statusCode = patient.Response.Annotation<HttpStatusCode>(); if (statusCode == HttpStatusCode.OK) { throw new ResourceConflictException(); } } } private static Bundle.RequestComponent GenerateCreateRequest(Identifier patientIdentifier) { return new Bundle.RequestComponent() { Method = Bundle.HTTPVerb.POST, IfNoneExist = patientIdentifier.ToSearchQueryParameter(), Url = ResourceType.Patient.GetLiteral(), }; } private static Bundle.RequestComponent GenerateUpdateRequest(Patient patient) { return new Bundle.RequestComponent() { Method = Bundle.HTTPVerb.PUT, IfMatch = new EntityTagHeaderValue($"\"{patient.Meta.VersionId}\"", true).ToString(), Url = $"{ResourceType.Patient.GetLiteral()}/{patient.Id}", }; } }
35.886525
144
0.652767
[ "MIT" ]
IoTFier/dicom-server
converter/dicom-cast/src/Microsoft.Health.DicomCast.Core/Features/Worker/FhirTransaction/Patient/PatientPipelineStep.cs
5,062
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; using FeatureBits.Data.EF; namespace FeatureBitsData.Migrations { [DbContext(typeof(FeatureBitsEfDbContext))] [Migration("20180424182241_Initial-Create")] partial class InitialCreate { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.2-rtm-10011") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("FeatureBitsData.IFeatureBitDefinition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AllowedUsers") .HasMaxLength(2048); b.Property<string>("CreatedByUser") .IsRequired() .HasMaxLength(100); b.Property<DateTime>("CreatedDateTime"); b.Property<string>("ExcludedEnvironments") .HasMaxLength(300); b.Property<string>("LastModifiedByUser") .IsRequired() .HasMaxLength(100); b.Property<DateTime>("LastModifiedDateTime"); b.Property<int>("MinimumAllowedPermissionLevel"); b.Property<string>("Name") .IsRequired() .HasMaxLength(100); b.Property<bool>("OnOff"); b.HasKey("Id"); b.ToTable("IFeatureBitDefinitions"); }); #pragma warning restore 612, 618 } } }
32.377049
117
0.556962
[ "MIT" ]
Bhaskers-Blu-Org2/featurebits
src/FeatureBits.Data/Migrations/20180424182241_Initial-Create.Designer.cs
1,977
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.ComponentModel; using Pulumi; namespace Pulumi.AzureNextGen.HybridData { /// <summary> /// This is the preferred geo location for the job to run. /// </summary> [EnumType] public readonly struct RunLocation : IEquatable<RunLocation> { private readonly string _value; private RunLocation(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static RunLocation None { get; } = new RunLocation("none"); public static RunLocation Australiaeast { get; } = new RunLocation("australiaeast"); public static RunLocation Australiasoutheast { get; } = new RunLocation("australiasoutheast"); public static RunLocation Brazilsouth { get; } = new RunLocation("brazilsouth"); public static RunLocation Canadacentral { get; } = new RunLocation("canadacentral"); public static RunLocation Canadaeast { get; } = new RunLocation("canadaeast"); public static RunLocation Centralindia { get; } = new RunLocation("centralindia"); public static RunLocation Centralus { get; } = new RunLocation("centralus"); public static RunLocation Eastasia { get; } = new RunLocation("eastasia"); public static RunLocation Eastus { get; } = new RunLocation("eastus"); public static RunLocation Eastus2 { get; } = new RunLocation("eastus2"); public static RunLocation Japaneast { get; } = new RunLocation("japaneast"); public static RunLocation Japanwest { get; } = new RunLocation("japanwest"); public static RunLocation Koreacentral { get; } = new RunLocation("koreacentral"); public static RunLocation Koreasouth { get; } = new RunLocation("koreasouth"); public static RunLocation Southeastasia { get; } = new RunLocation("southeastasia"); public static RunLocation Southcentralus { get; } = new RunLocation("southcentralus"); public static RunLocation Southindia { get; } = new RunLocation("southindia"); public static RunLocation Northcentralus { get; } = new RunLocation("northcentralus"); public static RunLocation Northeurope { get; } = new RunLocation("northeurope"); public static RunLocation Uksouth { get; } = new RunLocation("uksouth"); public static RunLocation Ukwest { get; } = new RunLocation("ukwest"); public static RunLocation Westcentralus { get; } = new RunLocation("westcentralus"); public static RunLocation Westeurope { get; } = new RunLocation("westeurope"); public static RunLocation Westindia { get; } = new RunLocation("westindia"); public static RunLocation Westus { get; } = new RunLocation("westus"); public static RunLocation Westus2 { get; } = new RunLocation("westus2"); public static bool operator ==(RunLocation left, RunLocation right) => left.Equals(right); public static bool operator !=(RunLocation left, RunLocation right) => !left.Equals(right); public static explicit operator string(RunLocation value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is RunLocation other && Equals(other); public bool Equals(RunLocation other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// State of the job definition. /// </summary> [EnumType] public readonly struct State : IEquatable<State> { private readonly string _value; private State(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static State Disabled { get; } = new State("Disabled"); public static State Enabled { get; } = new State("Enabled"); public static State Supported { get; } = new State("Supported"); public static bool operator ==(State left, State right) => left.Equals(right); public static bool operator !=(State left, State right) => !left.Equals(right); public static explicit operator string(State value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is State other && Equals(other); public bool Equals(State other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The encryption algorithm used to encrypt data. /// </summary> [EnumType] public readonly struct SupportedAlgorithm : IEquatable<SupportedAlgorithm> { private readonly string _value; private SupportedAlgorithm(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static SupportedAlgorithm None { get; } = new SupportedAlgorithm("None"); public static SupportedAlgorithm RSA1_5 { get; } = new SupportedAlgorithm("RSA1_5"); public static SupportedAlgorithm RSA_OAEP { get; } = new SupportedAlgorithm("RSA_OAEP"); public static SupportedAlgorithm PlainText { get; } = new SupportedAlgorithm("PlainText"); public static bool operator ==(SupportedAlgorithm left, SupportedAlgorithm right) => left.Equals(right); public static bool operator !=(SupportedAlgorithm left, SupportedAlgorithm right) => !left.Equals(right); public static explicit operator string(SupportedAlgorithm value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is SupportedAlgorithm other && Equals(other); public bool Equals(SupportedAlgorithm other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// Enum to detect if user confirmation is required. If not passed will default to NotRequired. /// </summary> [EnumType] public readonly struct UserConfirmation : IEquatable<UserConfirmation> { private readonly string _value; private UserConfirmation(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static UserConfirmation NotRequired { get; } = new UserConfirmation("NotRequired"); public static UserConfirmation Required { get; } = new UserConfirmation("Required"); public static bool operator ==(UserConfirmation left, UserConfirmation right) => left.Equals(right); public static bool operator !=(UserConfirmation left, UserConfirmation right) => !left.Equals(right); public static explicit operator string(UserConfirmation value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is UserConfirmation other && Equals(other); public bool Equals(UserConfirmation other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } }
48.561728
118
0.680691
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/HybridData/Enums.cs
7,867
C#
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OGFrp.UI { public partial class Config { ConfigModel[] ConfigArray = new ConfigModel[5]; /// <summary> /// 构造函数 /// </summary> public Config() { ConfigArray[0] = this.Lang; ConfigArray[1] = this.Username; ConfigArray[2] = this.Password; ConfigArray[3] = this.FrpcLaunchMode; ConfigArray[4] = this.Theme; try { ReadConfig(); } catch { WriteConfig(); ReadConfig(); } } /// <summary> /// ASCII码转字符 /// </summary> /// <param name="asciiCode">ASCII码值</param> /// <returns>ASCII码对应的字符</returns> public static string Chr(int asciiCode) { if (asciiCode >= 0 && asciiCode <= 255) { ASCIIEncoding asciiEncoding = new ASCIIEncoding(); byte[] byteArray = new byte[] { (byte)asciiCode }; string strCharacter = asciiEncoding.GetString(byteArray); return (strCharacter); } else { throw new Exception("ASCII Code is not valid."); } } /// <summary> /// Appdata/OGFrp的位置 /// </summary> public static readonly string FolderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\OGFrp"; /// <summary> /// 创建Appdata文件夹 /// </summary> public void CreateFolder() { if (Directory.Exists(FolderPath) == false) { Directory.CreateDirectory(FolderPath); } return; } /// <summary> /// config.ini的位置 /// </summary> public readonly string configpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\OGFrp\\config.ini"; /// <summary> /// 加载配置文件 /// </summary> public void ReadConfig() { StreamReader reader = new StreamReader(configpath); string Left = ""; //配置名(等号左边的内容) string Right; //配置值(等号右边的内容) while (Left != "::end") { Left = ""; Right = ""; //read left: int temp = 0; while (true) { temp = reader.Read(); if (Chr(temp) == "=") { break; } else { Left += Chr(temp); } } Right = reader.ReadLine(); if (Left == "::end") { reader.Close(); return; } switch (Left) { case "Lang": this.Lang.Val = Right; break; case "Username": this.Username.Val = Right; break; case "Password": this.Password.Val = Right; break; case "FrpcLaunchMode": this.FrpcLaunchMode.Val = Right; break; case "Theme": this.Theme.Val = Right; break; default: break; } } reader.Close(); } /// <summary> /// 写入配置文件 /// </summary> public void WriteConfig() { CreateFolder(); StreamWriter writer = new StreamWriter(configpath); string content = null; for (int i = 0; i < ConfigArray.Length; i++) { content += ConfigArray[i].Name; content += "="; content += ConfigArray[i].Val; content += "\n"; } content += "::end=1"; writer.Write(content); writer.Close(); } } }
28.254777
137
0.403517
[ "Apache-2.0" ]
MarchStudio/OGFrp
src/OGFrp.SharedCS/Config/Config.cs
4,556
C#
using Xunit; using System.Linq; using Newtonsoft.Json; using Elements; using Hypar.Functions.Execution.Local; using Elements.Serialization.glTF; using Elements.Serialization.JSON; using System.Collections.Generic; using Elements.Geometry; namespace SiteBySketch.Tests { public class SiteBySketchTests { [Fact] public void SiteBySketchTest() { var model = new Model(); var polygon = new Polygon( new[] { new Vector3(-46.0, -29.0, 0.0), new Vector3(-10.0, -43.0, -0.0), new Vector3(33.0, -40.0, -0.0), new Vector3(36.0, 71.0, 0.0) }); var inputs = new SiteBySketchInputs (polygon, "", "", new Dictionary<string, string>(), "", "", ""); var outputs = SiteBySketch.Execute(new Dictionary<string, Model> { { "Test", model } }, inputs); System.IO.File.WriteAllText("../../../../../../TestOutput/SiteBySketch.json", outputs.Model.ToJson()); outputs.Model.ToGlTF("../../../../../../TestOutput/SiteBySketch.glb"); } } }
32.945946
114
0.521739
[ "MIT" ]
M-JULIANI/BuildingBlocks
Site/SiteBySketch/test/SiteBySketchTests.cs
1,221
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Spice.Data; using Spice.Models; using Spice.Models.ViewModels; using Spice.Utility; namespace Spice.Controllers { [Area("Customer")] public class HomeController : Controller { private readonly ApplicationDbContext _dbContext; public HomeController(ApplicationDbContext dbContext) { _dbContext = dbContext; } public async Task<IActionResult> Index() { IndexViewModel IndexVM = new IndexViewModel() { MenuItem = await _dbContext.MenuItem.Include(m => m.Category).Include(m => m.SubCategory).ToListAsync(), Category = await _dbContext.Category.ToListAsync(), Coupon = await _dbContext.Coupon.Where(c => c.IsActive == true).ToListAsync() }; var claimsIdentity = (ClaimsIdentity)User.Identity; var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier); if (claim != null) { var cnt = _dbContext.ShoppingCart.Where(u => u.ApplicationUserId == claim.Value).ToList().Count; HttpContext.Session.SetInt32(SD.ssShoppingCartCount, cnt); } return View(IndexVM); } [Authorize] public async Task<IActionResult> Details(int id) { var menuItemFromDb = await _dbContext.MenuItem.Include(m => m.Category).Include(m => m.SubCategory).Where(m => m.Id == id).FirstOrDefaultAsync(); ShoppingCart cartObj = new ShoppingCart() { MenuItem = menuItemFromDb, MenuItemId = menuItemFromDb.Id }; return View(cartObj); } [Authorize] [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Details(ShoppingCart CartObject) { CartObject.Id = 0; if (ModelState.IsValid) { var claimsIdentity = (ClaimsIdentity)this.User.Identity; var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier); CartObject.ApplicationUserId = claim.Value; ShoppingCart cartFromDb = await _dbContext.ShoppingCart.Where(c => c.ApplicationUserId == CartObject.ApplicationUserId && c.MenuItemId == CartObject.MenuItemId).FirstOrDefaultAsync(); if (cartFromDb == null) { await _dbContext.ShoppingCart.AddAsync(CartObject); } else { cartFromDb.Count = cartFromDb.Count + CartObject.Count; } await _dbContext.SaveChangesAsync(); var count = _dbContext.ShoppingCart.Where(c => c.ApplicationUserId == CartObject.ApplicationUserId).ToList().Count(); HttpContext.Session.SetInt32(SD.ssShoppingCartCount, count); return RedirectToAction("Index"); } else { var menuItemFromDb = await _dbContext.MenuItem.Include(m => m.Category).Include(m => m.SubCategory).Where(m => m.Id == CartObject.MenuItemId).FirstOrDefaultAsync(); ShoppingCart cartObj = new ShoppingCart() { MenuItem = menuItemFromDb, MenuItemId = menuItemFromDb.Id }; return View(cartObj); } } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
34.418033
180
0.585377
[ "MIT" ]
Iamkemical/ECommerceApp
src/Spice/Areas/Customer/Controllers/HomeController.cs
4,201
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [System.Serializable] public class Confirm_button_options { public GameObject Collector; } public class Confirm_button : MonoBehaviour { public struct Seed_info { public int plant_type; public Seed_info(int plant_type) { this.plant_type = plant_type; } } GameObjectCollector Collector; public string Mode = ""; public Confirm_button_options options; private GameObject grid; private GameObject veget; private GameObject shovel_button; public Seed_info seed_info; private Saver_script saver; // Start is called before the first frame update void Start() { Collector = options.Collector.GetComponent<GameObjectCollector>(); saver = Collector.GameObjects.Saver.GetComponent<Saver_script>(); grid = Collector.GameObjects.Grid; veget = Collector.GameObjects.Veget; shovel_button = Collector.GameObjects.ShovelButton; } public void OnMouseDown() { if (grid.GetComponent<Grid_script>().current == null) return; switch(Mode) { case "Plant": if (grid.GetComponent<Grid_script>().current.info.plant != 0) break; veget.GetComponent<Veget_script>().New_veget(seed_info.plant_type); grid.GetComponent<Grid_script>().Clear_grid(); grid.GetComponent<Grid_script>().Switch("Plant"); Mode = ""; veget.SetActive(true); this.gameObject.SetActive(false); break; case "Bed": if (grid.GetComponent<Grid_script>().current.info.is_dug_up) break; if (Collector.Online) if (saver.Save(new ShovelUpdate(grid.GetComponent<Grid_script>().current.info.id))) grid.GetComponent<Grid_script>().current.info.is_dug_up = true; else grid.GetComponent<Grid_script>().current.info.is_dug_up = true; grid.GetComponent<Grid_script>().Clear_grid(); grid.GetComponent<Grid_script>().Switch("Bed"); Mode = ""; veget.SetActive(true); shovel_button.GetComponentInParent<Image>().color = new Color(1f, 1f, 1f); this.gameObject.SetActive(false); break; } } }
32.628205
103
0.59332
[ "MIT" ]
ValenDtv/Gargen_AR
Assets/Scripts/Buttons/Confirm_button.cs
2,547
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("FileProcessor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FileProcessor")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6c21bfa0-f2a9-445d-bd51-0eb8eb16787a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.675676
84
0.748207
[ "MIT" ]
SamIge7/SideWork
06NullOperators/FileProcessor/Properties/AssemblyInfo.cs
1,397
C#
using System; using System.Runtime.InteropServices; namespace UMP.Wrappers { internal class WrapperStandalone : IWrapperNative, IWrapperPlayer, IWrapperSpu, IWrapperAudio { private IntPtr _libVLCHandler = IntPtr.Zero; private IntPtr _libUMPHandler = IntPtr.Zero; private int _nativeIndex; private delegate void ManageLogCallback(string msg); private ManageLogCallback _manageLogCallback; #region Native Imports [DllImport(UMPSettings.ASSET_NAME)] private static extern int UMPNativeInit(); [DllImport(UMPSettings.ASSET_NAME)] private static extern void UMPNativeUpdateIndex(int index); [DllImport(UMPSettings.ASSET_NAME)] private static extern void UMPNativeSetTexture(int index, IntPtr texture); [DllImport(UMPSettings.ASSET_NAME)] private static extern void UMPNativeSetPixelsBuffer(int index, IntPtr buffer, int width, int height); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeGetPixelsBuffer(int index); [DllImport(UMPSettings.ASSET_NAME)] private static extern int UMPNativeGetPixelsBufferWidth(int index); [DllImport(UMPSettings.ASSET_NAME)] private static extern int UMPNativeGetPixelsBufferHeight(int index); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeGetLogMessage(int index); [DllImport(UMPSettings.ASSET_NAME)] private static extern int UMPNativeGetLogLevel(int index); [DllImport(UMPSettings.ASSET_NAME)] private static extern int UMPNativeGetState(int index); [DllImport(UMPSettings.ASSET_NAME)] private static extern float UMPNativeGetStateFloatValue(int index); [DllImport(UMPSettings.ASSET_NAME)] private static extern long UMPNativeGetStateLongValue(int index); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeGetStateStringValue(int index); [DllImport(UMPSettings.ASSET_NAME)] private static extern int UMPNativeSetPixelsVerticalFlip(int index, bool flip); [DllImport(UMPSettings.ASSET_NAME)] internal static extern void UMPNativeSetAudioParams(int index, int numChannels, int sampleRate); [DllImport(UMPSettings.ASSET_NAME)] internal static extern IntPtr UMPNativeGetAudioParams(int index, char separator); [DllImport(UMPSettings.ASSET_NAME)] internal static extern int UMPNativeGetAudioSamples(int index, IntPtr decodedSamples, int samplesLength, AudioOutput.AudioChannels audioChannel); [DllImport(UMPSettings.ASSET_NAME)] internal static extern bool UMPNativeClearAudioSamples(int index, int samplesLength); [DllImport(UMPSettings.ASSET_NAME)] internal static extern void UMPNativeDirectRender(int index); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeGetUnityRenderCallback(); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeGetVideoLockCallback(); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeGetVideoDisplayCallback(); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeGetVideoFormatCallback(); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeGetVideoCleanupCallback(); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeGetAudioSetupCallback(); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeGetAudioPlayCallback(); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeMediaPlayerEventCallback(); [DllImport(UMPSettings.ASSET_NAME)] private static extern IntPtr UMPNativeGetLogMessageCallback(); [DllImport(UMPSettings.ASSET_NAME)] private static extern void UMPNativeSetUnityLogMessageCallback(IntPtr callback); [DllImport(UMPSettings.ASSET_NAME)] private static extern void UMPNativeUpdateFramesCounter(int index, int counter); [DllImport(UMPSettings.ASSET_NAME)] private static extern int UMPNativeGetFramesCounter(int index); [InteropFunction("UMPNativeInit")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int UMPNativeInitDel(); [InteropFunction("UMPNativeUpdateIndex")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void UMPNativeUpdateIndexDel(int index); [InteropFunction("UMPNativeSetTexture")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void UMPNativeSetTextureDel(int index, IntPtr texture); [InteropFunction("UMPNativeSetPixelsBuffer")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void UMPNativeSetPixelsBufferDel(int index, IntPtr buffer, int width, int height); [InteropFunction("UMPNativeGetPixeslBuffer")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetPixelsBufferDel(int index); [InteropFunction("UMPNativeGetPixelsBufferWidth")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int UMPNativeGetPixelsBufferWidthDel(int index); [InteropFunction("UMPNativeGetPixelsBufferHeight")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int UMPNativeGetPixelsBufferHeightDel(int index); [InteropFunction("UMPNativeGetLogMessage")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetLogMessageDel(int index); [InteropFunction("UMPNativeGetLogLevel")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int UMPNativeGetLogLevelDel(int index); [InteropFunction("UMPNativeGetState")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int UMPNativeGetStateDel(int index); [InteropFunction("UMPNativeGetStateFloatValue")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate float UMPNativeGetStateFloatValueDel(int index); [InteropFunction("UMPNativeGetStateLongValue")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate long UMPNativeGetStateLongValueDel(int index); [InteropFunction("UMPNativeGetStateStringValue")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetStateStringValueDel(int index); [InteropFunction("UMPNativeSetPixelsVerticalFlip")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void UMPNativeSetPixelsVerticalFlipDel(int index, bool flip); [InteropFunction("UMPNativeSetAudioParams")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void UMPNativeSetAudioParamsDel(int index, int numChannels, int sampleRate); [InteropFunction("UMPNativeGetAudioParams")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetAudioParamsDel(int index, char separator); [InteropFunction("UMPNativeGetAudioChannels")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int UMPNativeGetAudioChannelsDel(int index); [InteropFunction("UMPNativeGetAudioSamples")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int UMPNativeGetAudioSamplesDel(int index, IntPtr decodedSamples, int samplesLength, AudioOutput.AudioChannels audioChannel); [InteropFunction("UMPNativeClearAudioSamples")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool UMPNativeClearAudioSamplesDel(int index, int samplesLength); [InteropFunction("UMPNativeDirectRender")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void UMPNativeDirectRenderDel(int index); [InteropFunction("UMPNativeGetUnityRenderCallback")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetUnityRenderCallbackDel(); [InteropFunction("UMPNativeGetVideoLockCallback")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetVideoLockCallbackDel(); [InteropFunction("UMPNativeGetVideoDisplayCallback")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetVideoDisplayCallbackDel(); [InteropFunction("UMPNativeGetVideoFormatCallback")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetVideoFormatCallbackDel(); [InteropFunction("UMPNativeGetVideoCleanupCallback")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetVideoCleanupCallbackDel(); [InteropFunction("UMPNativeGetAudioSetupCallback")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetAudioSetupCallbackDel(); [InteropFunction("UMPNativeGetAudioPlayCallback")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetAudioPlayCallbackDel(); [InteropFunction("UMPNativeMediaPlayerEventCallback")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeMediaPlayerEventCallbackDel(); [InteropFunction("UMPNativeGetLogMessageCallback")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr UMPNativeGetLogMessageCallbackDel(); [InteropFunction("UMPNativeSetUnityLogMessageCallback")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void UMPNativeSetUnityLogMessageCallbackDel(IntPtr callback); [InteropFunction("UMPNativeUpdateFramesCounter")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void UMPNativeUpdateFramesCounterCallbackDel(int index, int counter); [InteropFunction("UMPNativeGetFramesCounter")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int UMPNativeGetFramesCounterCallbackDel(int index); #endregion #region LibVLC Imports /// <summary> /// Set current crop filter geometry. /// </summary> [InteropFunction("libvlc_video_set_aspect_ratio")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetVideoAspectRatio(IntPtr playerObject, string cropGeometry); /// <summary> /// Unset libvlc log instance. /// </summary> [InteropFunction("libvlc_log_unset")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void LogUnset(IntPtr instance); /// <summary> /// Unset libvlc log instance. /// </summary> [InteropFunction("libvlc_log_set")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void LogSet(IntPtr instance, IntPtr callback, IntPtr data); /// <summary> /// Create and initialize a libvlc instance. /// </summary> /// <returns>Return the libvlc instance or NULL in case of error.</returns> [InteropFunction("libvlc_new")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr CreateNewInstance(int argc, string[] argv); /// <summary> /// Destroy libvlc instance. /// </summary> [InteropFunction("libvlc_release")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void ReleaseInstance(IntPtr instance); /// <summary> /// Frees an heap allocation returned by a LibVLC function. /// </summary> /// <returns>Return the libvlc instance or NULL in case of error.</returns> [InteropFunction("libvlc_free")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void Free(IntPtr ptr); /// <summary> /// CCallback function notification. /// </summary> [InteropFunction("libvlc_callback_t")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void EventCallback(IntPtr args); /// <summary> /// Register for an event notification. /// </summary> /// <param name="eventManagerInstance">Event manager to which you want to attach to.</param> /// <param name="eventType">The desired event to which we want to listen.</param> /// <param name="callback">The function to call when i_event_type occurs.</param> /// <param name="userData">User provided data to carry with the event.</param> /// <returns>Return 0 on success, ENOMEM on error.</returns> [InteropFunction("libvlc_event_attach")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int AttachEvent(IntPtr eventManagerInstance, EventTypes eventType, IntPtr callback, IntPtr userData); /// <summary> /// Unregister an event notification. /// </summary> /// <param name="eventManagerInstance">Event manager to which you want to attach to.</param> /// <param name="eventType">The desired event to which we want to listen.</param> /// <param name="callback">The function to call when i_event_type occurs.</param> /// <param name="userData">User provided data to carry with the event.</param> /// <returns>Return 0 on success, ENOMEM on error.</returns> [InteropFunction("libvlc_event_detach")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int DetachEvent(IntPtr eventManagerInstance, EventTypes eventType, IntPtr callback, IntPtr userData); /// <summary> /// Create a media with a certain given media resource location, for instance a valid URL. /// </summary> /// <returns>Return the newly created media or NULL on error.</returns> [InteropFunction("libvlc_media_new_location")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr CreateNewMediaFromLocation(IntPtr instance, [MarshalAs(UnmanagedType.LPStr)] string path); /// <summary> /// Create a media for a certain file path. /// </summary> /// <returns>Return the newly created media or NULL on error.</returns> [InteropFunction("libvlc_media_new_path")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr CreateNewMediaFromPath(IntPtr instance, [MarshalAs(UnmanagedType.LPStr)] string path); /// <summary> /// Add an option to the media. /// </summary> [InteropFunction("libvlc_media_add_option")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void AddOptionToMedia(IntPtr mediaInstance, [MarshalAs(UnmanagedType.LPStr)] string option); /// <summary> /// It will release the media descriptor object. It will send out an libvlc_MediaFreed event to all listeners. If the media descriptor object has been released it should not be used again. /// </summary> [InteropFunction("libvlc_media_release")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void ReleaseMedia(IntPtr mediaInstance); /// <summary> /// Get the media resource locator (mrl) from a media descriptor object. /// </summary> [InteropFunction("libvlc_media_get_mrl")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetMediaMrl(IntPtr mediaInstance); /// <summary> /// Get Parsed status for media descriptor object. /// </summary> [InteropFunction("libvlc_media_get_parsed_status")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate ParsedStatus GetMediaParsedStatus(IntPtr mediaInstance); /// <summary> /// Read a meta of the media. /// </summary> [InteropFunction("libvlc_media_get_meta")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetMediaMetadata(IntPtr mediaInstance, MediaMetadatas meta); /// <summary> /// Get the current statistics about the media /// </summary> /// <param name="mediaInstance">Media descriptor object</param> /// <param name="statsInformationsPointer">Structure that contain /// the statistics about the media /// (this structure must be allocated by the caller)</param> /// <returns></returns> [InteropFunction("libvlc_media_get_stats")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int GetMediaStats(IntPtr mediaInstance, out MediaStats statsInformationsPointer); /// <summary> /// Parse a media meta data and tracks information. /// </summary> [InteropFunction("libvlc_media_parse")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void ParseMedia(IntPtr mediaInstance); /// <summary> /// Parse a media meta data and tracks information async. /// </summary> [InteropFunction("libvlc_media_parse_async")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void ParseMediaAsync(IntPtr mediaInstance); /// <summary> /// Get Parsed status for media descriptor object. /// </summary> [InteropFunction("libvlc_media_is_parsed")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int IsParsedMedia(IntPtr mediaInstance); /// <summary> /// Get media descriptor's elementary streams description. /// </summary> [InteropFunction("libvlc_media_get_tracks_info")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int GetMediaTracksInformations(IntPtr mediaInstance, out IntPtr tracksInformationsPointer); /// <summary> /// Create an empty Media Player object. /// </summary> /// <returns>Return a new media player object, or NULL on error.</returns> [InteropFunction("libvlc_media_player_new")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr CreateMediaPlayer(IntPtr instance); /// <summary> /// It will release the media player object. If the media player object has been released, then it should not be used again. /// </summary> [InteropFunction("libvlc_media_player_release")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void ReleaseMediaPlayer(IntPtr playerObject); /// <summary> /// Set the media that will be used by the media_player. If any, previous media will be released. /// </summary> /// <returns>Return a new media player object, or NULL on error.</returns> [InteropFunction("libvlc_media_player_set_media")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetMediaToMediaPlayer(IntPtr playerObject, IntPtr mediaInstance); /// <summary> /// Get the Event Manager from which the media player send event. /// </summary> /// <returns>Return the event manager associated with media player.</returns> [InteropFunction("libvlc_media_player_event_manager")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetMediaPlayerEventManager(IntPtr playerObject); /// <summary> /// Check if media player is playing. /// </summary> [InteropFunction("libvlc_media_player_is_playing")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int IsPlaying(IntPtr playerObject); /// <summary> /// Play. /// </summary> /// <returns>Return 0 if playback started (and was already started), or -1 on error.</returns> [InteropFunction("libvlc_media_player_play")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int Play(IntPtr playerObject); /// <summary> /// Toggle pause (no effect if there is no media). /// </summary> [InteropFunction("libvlc_media_player_pause")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void Pause(IntPtr playerObject); /// <summary> /// Stop. /// </summary> [InteropFunction("libvlc_media_player_stop")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void Stop(IntPtr playerObject); /// <summary> /// Set video callbacks. /// </summary> [InteropFunction("libvlc_video_set_callbacks")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetVideoCallbacks(IntPtr playerObject, IntPtr @lock, IntPtr unlock, IntPtr display, IntPtr opaque); /// <summary> /// Set video format. /// </summary> [InteropFunction("libvlc_video_set_format")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetVideoFormat(IntPtr playerObject, [MarshalAs(UnmanagedType.LPStr)] string chroma, uint width, uint height, uint pitch); /// <summary> /// Set video format callbacks. /// </summary> [InteropFunction("libvlc_video_set_format_callbacks")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetVideoFormatCallbacks(IntPtr playerObject, IntPtr setup, IntPtr cleanup); /// <summary> /// Get length of movie playing /// </summary> /// <returns>Get the requested movie play rate.</returns> [InteropFunction("libvlc_media_player_get_length")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate long GetLength(IntPtr playerObject); /// <summary> /// Get Rate at which movie is playing. /// </summary> /// <returns>Get the requested movie play rate.</returns> [InteropFunction("libvlc_media_player_get_time")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate long GetTime(IntPtr playerObject); /// <summary> /// Get time at which movie is playing. /// </summary> /// <returns>Get the requested movie play time.</returns> [InteropFunction("libvlc_media_player_set_time")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetTime(IntPtr playerObject, long time); /// <summary> /// Get media position. /// </summary> [InteropFunction("libvlc_media_player_get_position")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate float GetMediaPosition(IntPtr playerObject); /// <summary> /// Get media position. /// </summary> [InteropFunction("libvlc_media_player_set_position")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetMediaPosition(IntPtr playerObject, float position); /// <summary> /// Is the player able to play. /// </summary> [InteropFunction("libvlc_media_player_will_play")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int CouldPlay(IntPtr playerObject); /// <summary> /// Get the requested media play rate. /// </summary> [InteropFunction("libvlc_media_player_get_rate")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate float GetRate(IntPtr playerObject); /// <summary> /// Set the requested media play rate. /// </summary> [InteropFunction("libvlc_media_player_set_rate")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int SetRate(IntPtr playerObject, float rate); /// <summary> /// Get the media state. /// </summary> [InteropFunction("libvlc_media_player_get_state")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate MediaStates GetMediaPlayerState(IntPtr playerObject); /// <summary> /// Get media fps rate. /// </summary> [InteropFunction("libvlc_media_player_get_fps")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate float GetFramesPerSecond(IntPtr playerObject); /// <summary> /// Get video size in pixels. /// </summary> [InteropFunction("libvlc_video_get_size")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int GetVideoSize(IntPtr playerObject, uint num, out uint px, out uint py); /// <summary> /// Get video scale. /// </summary> [InteropFunction("libvlc_video_get_scale")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate float GetVideoScale(IntPtr playerObject); /// <summary> /// Set video scale. /// </summary> [InteropFunction("libvlc_video_set_scale")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate float SetVideoScale(IntPtr playerObject, float f_factor); /// <summary> /// Take a snapshot of the current video window. /// </summary> /// <returns>Return 0 on success, -1 if the video was not found.</returns> [InteropFunction("libvlc_video_take_snapshot")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int TakeSnapshot(IntPtr playerObject, uint num, string fileName, uint width, uint height); #region Spu setup /// <summary> /// Get the number of available video subtitles. /// </summary> [InteropFunction("libvlc_video_get_spu_count")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int GetVideoSpuCount(IntPtr playerObject); /// <summary> /// Get the description of available video subtitles. /// </summary> [InteropFunction("libvlc_video_get_spu_description")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetVideoSpuDescription(IntPtr playerObject); /// <summary> /// Get current video subtitle. /// </summary> [InteropFunction("libvlc_video_get_spu")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int GetVideoSpu(IntPtr playerObject); /// <summary> /// Set new video subtitle. /// </summary> [InteropFunction("libvlc_video_set_spu")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int SetVideoSpu(IntPtr playerObject, int spu); /// <summary> /// Set new video subtitle file. /// </summary> [InteropFunction("libvlc_video_set_subtitle_file")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int SetVideoSubtitleFile(IntPtr playerObject, [MarshalAs(UnmanagedType.LPStr)] string path); #endregion #region Audio setup /// <summary> /// Set audio format. /// </summary> [InteropFunction("libvlc_audio_set_format")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetAudioFormat(IntPtr playerObject, [MarshalAs(UnmanagedType.LPStr)] string format, int rate, int channels); /// <summary> /// Set audio callbacks. /// </summary> [InteropFunction("libvlc_audio_set_callbacks")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetAudioCallbacks(IntPtr playerObject, IntPtr play, IntPtr pause, IntPtr resume, IntPtr flush, IntPtr drain, IntPtr opaque); /// <summary> /// Set audio format callbacks. /// </summary> [InteropFunction("libvlc_audio_set_format_callbacks")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetAudioFormatCallbacks(IntPtr playerObject, IntPtr setup, IntPtr cleanup); /// <summary> /// Get number of available audio tracks. /// </summary> [InteropFunction("libvlc_audio_get_track_count")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int GetAudioTracksCount(IntPtr playerObject); /// <summary> /// Get the description of available audio tracks. /// </summary> [InteropFunction("libvlc_audio_get_track_description")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetAudioTracksDescriptions(IntPtr playerObject); /// <summary> /// Relase the description of available track. /// </summary> [InteropFunction("libvlc_track_description_release")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr ReleaseTracksDescriptions(IntPtr trackDescription); /// <summary> /// Get current audio track. /// </summary> [InteropFunction("libvlc_audio_get_track")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int GetAudioTrack(IntPtr playerObject); /// <summary> /// Set audio track. /// </summary> [InteropFunction("libvlc_audio_set_track")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int SetAudioTrack(IntPtr playerObject, int trackId); /// <summary> /// Get current audio delay. /// </summary> [InteropFunction("libvlc_audio_get_delay")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate long GetAudioDelay(IntPtr playerObject); /// <summary> /// Set current audio delay. The audio delay will be reset to zero each time the media changes. /// </summary> [InteropFunction("libvlc_audio_set_delay")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetAudioDelay(IntPtr playerObject, long channel); /// <summary> /// Get current software audio volume. /// </summary> [InteropFunction("libvlc_audio_get_volume")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int GetVolume(IntPtr playerObject); /// <summary> /// Set current software audio volume. /// </summary> [InteropFunction("libvlc_audio_set_volume")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int SetVolume(IntPtr playerObject, int volume); /// <summary> /// Set current mute status. /// </summary> [InteropFunction("libvlc_audio_set_mute")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetMute(IntPtr playerObject, int status); /// <summary> /// Get current mute status. /// </summary> [InteropFunction("libvlc_audio_get_mute")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int IsMute(IntPtr playerObject); /// <summary> /// Get the list of available audio outputs. /// </summary> [InteropFunction("libvlc_audio_output_list_get")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetAudioOutputsDescriptions(IntPtr instance); /// <summary> /// It will release the list of available audio outputs. /// </summary> [InteropFunction("libvlc_audio_output_list_release")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void ReleaseAudioOutputDescription(IntPtr audioOutput); /// <summary> /// Set the audio output. Change will be applied after stop and play. /// </summary> [InteropFunction("libvlc_audio_output_set")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int SetAudioOutput(IntPtr playerObject, IntPtr audioOutputName); /// <summary> /// Set audio output device. Changes are only effective after stop and play. /// </summary> [InteropFunction("libvlc_audio_output_device_set")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void SetAudioOutputDevice(IntPtr playerObject, [MarshalAs(UnmanagedType.LPStr)] string audioOutputName, [MarshalAs(UnmanagedType.LPStr)] string deviceName); /// <summary> /// Get audio output devices list. /// </summary> [InteropFunction("libvlc_audio_output_device_list_get")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetAudioOutputDeviceList(IntPtr playerObject, [MarshalAs(UnmanagedType.LPStr)] string aout); /// <summary> /// Release audio output devices list. /// </summary> [InteropFunction("libvlc_audio_output_device_list_release")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr ReleaseAudioOutputDeviceList(IntPtr p_list); #endregion #endregion public WrapperStandalone(PlayerOptionsStandalone options) { var libraryExtension = string.Empty; var settings = UMPSettings.GetSettings(); if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux && settings.UseExternalLibs) libraryExtension = ".8"; // Additional loading of 'libVLCCore' library for correct work of main library InteropLibraryLoader.Load(UMPSettings.LIB_VLC_CORE_NAME, settings.UseExternalLibs, settings.AdditionalLibsPath, libraryExtension); if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux && settings.UseExternalLibs) libraryExtension = ".5"; _libVLCHandler = InteropLibraryLoader.Load(UMPSettings.LIB_VLC_NAME, settings.UseExternalLibs, settings.AdditionalLibsPath, libraryExtension); if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) _libUMPHandler = InteropLibraryLoader.Load(UMPSettings.ASSET_NAME, false, string.Empty, string.Empty); _manageLogCallback = DebugLogHandler; NativeSetUnityLogMessageCallback(Marshal.GetFunctionPointerForDelegate(_manageLogCallback)); if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) _nativeIndex = InteropLibraryLoader.GetInteropDelegate<UMPNativeInitDel>(_libUMPHandler).Invoke(); else _nativeIndex = UMPNativeInit(); } private void DebugLogHandler(string msg) { UnityEngine.Debug.LogError(msg); } #region Native public int NativeIndex { get { return _nativeIndex; } } public void NativeUpdateIndex() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) InteropLibraryLoader.GetInteropDelegate<UMPNativeUpdateIndexDel>(_libUMPHandler).Invoke(_nativeIndex); else UMPNativeUpdateIndex(_nativeIndex); } public void NativeSetTexture(IntPtr texture) { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) InteropLibraryLoader.GetInteropDelegate<UMPNativeSetTextureDel>(_libUMPHandler).Invoke(_nativeIndex, texture); else UMPNativeSetTexture(_nativeIndex, texture); } public void NativeSetPixelsBuffer(IntPtr buffer, int width, int height) { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) InteropLibraryLoader.GetInteropDelegate<UMPNativeSetPixelsBufferDel>(_libUMPHandler).Invoke(_nativeIndex, buffer, width, height); else UMPNativeSetPixelsBuffer(_nativeIndex, buffer, width, height); } public IntPtr NativeGetPixelsBuffer() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetPixelsBufferDel>(_libUMPHandler).Invoke(_nativeIndex); return UMPNativeGetPixelsBuffer(_nativeIndex); } public int NativeGetPixelsBufferWidth() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetPixelsBufferWidthDel>(_libUMPHandler).Invoke(_nativeIndex); return UMPNativeGetPixelsBufferWidth(_nativeIndex); } public int NativeGetPixelsBufferHeight() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetPixelsBufferHeightDel>(_libUMPHandler).Invoke(_nativeIndex); return UMPNativeGetPixelsBufferHeight(_nativeIndex); } public string NativeGetLogMessage() { IntPtr value = IntPtr.Zero; if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) value = InteropLibraryLoader.GetInteropDelegate<UMPNativeGetLogMessageDel>(_libUMPHandler).Invoke(_nativeIndex); else value = UMPNativeGetLogMessage(_nativeIndex); return value != IntPtr.Zero ? Marshal.PtrToStringAnsi(value) : null; } public int NativeGetLogLevel() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetLogLevelDel>(_libUMPHandler).Invoke(_nativeIndex); return UMPNativeGetLogLevel(_nativeIndex); } public int NativeGetState() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetStateDel>(_libUMPHandler).Invoke(_nativeIndex); return UMPNativeGetState(_nativeIndex); } private float NativeGetStateFloatValue() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetStateFloatValueDel>(_libUMPHandler).Invoke(_nativeIndex); return UMPNativeGetStateFloatValue(_nativeIndex); } private long NativeGetStateLongValue() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetStateLongValueDel>(_libUMPHandler).Invoke(_nativeIndex); return UMPNativeGetStateLongValue(_nativeIndex); } private string NativeGetStateStringValue() { IntPtr value = IntPtr.Zero; if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) value = InteropLibraryLoader.GetInteropDelegate<UMPNativeGetStateStringValueDel>(_libUMPHandler).Invoke(_nativeIndex); else value = UMPNativeGetStateStringValue(_nativeIndex); return value != IntPtr.Zero ? Marshal.PtrToStringAnsi(value) : null; } public void NativeSetPixelsVerticalFlip(bool flip) { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) InteropLibraryLoader.GetInteropDelegate<UMPNativeSetPixelsVerticalFlipDel>(_libUMPHandler).Invoke(_nativeIndex, flip); else UMPNativeSetPixelsVerticalFlip(_nativeIndex, flip); } public void NativeSetAudioParams(int numChannels, int sampleRate) { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) InteropLibraryLoader.GetInteropDelegate<UMPNativeSetAudioParamsDel>(_libUMPHandler).Invoke(_nativeIndex, numChannels, sampleRate); else UMPNativeSetAudioParams(_nativeIndex, numChannels, sampleRate); } public string NativeGetAudioParams(char separator) { IntPtr value = IntPtr.Zero; if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) value = InteropLibraryLoader.GetInteropDelegate<UMPNativeGetAudioParamsDel>(_libUMPHandler).Invoke(_nativeIndex, separator); else value = UMPNativeGetAudioParams(_nativeIndex, separator); return value != IntPtr.Zero ? Marshal.PtrToStringAnsi(value) : null; } public int NativeGetAudioSamples(IntPtr decodedSamples, int samplesLength, AudioOutput.AudioChannels audioChannel) { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetAudioSamplesDel>(_libUMPHandler).Invoke(_nativeIndex, decodedSamples, samplesLength, audioChannel); return UMPNativeGetAudioSamples(_nativeIndex, decodedSamples, samplesLength, audioChannel); } public bool NativeClearAudioSamples(int samplesLength) { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeClearAudioSamplesDel>(_libUMPHandler).Invoke(_nativeIndex, samplesLength); return UMPNativeClearAudioSamples(_nativeIndex, samplesLength); } public IntPtr NativeGetUnityRenderCallback() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetUnityRenderCallbackDel>(_libUMPHandler).Invoke(); return UMPNativeGetUnityRenderCallback(); } public IntPtr NativeGetVideoLockCallback() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetVideoLockCallbackDel>(_libUMPHandler).Invoke(); return UMPNativeGetVideoLockCallback(); } public IntPtr NativeGetVideoDisplayCallback() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetVideoDisplayCallbackDel>(_libUMPHandler).Invoke(); return UMPNativeGetVideoDisplayCallback(); } public IntPtr NativeGetVideoFormatCallback() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetVideoFormatCallbackDel>(_libUMPHandler).Invoke(); return UMPNativeGetVideoFormatCallback(); } public IntPtr NativeGetVideoCleanupCallback() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetVideoCleanupCallbackDel>(_libUMPHandler).Invoke(); return UMPNativeGetVideoCleanupCallback(); } public IntPtr NativeGetAudioSetupCallback() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetAudioSetupCallbackDel>(_libUMPHandler).Invoke(); return UMPNativeGetAudioSetupCallback(); } public IntPtr NativeGetAudioPlayCallback() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetAudioPlayCallbackDel>(_libUMPHandler).Invoke(); return UMPNativeGetAudioPlayCallback(); } public IntPtr NativeMediaPlayerEventCallback() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeMediaPlayerEventCallbackDel>(_libUMPHandler).Invoke(); return UMPNativeMediaPlayerEventCallback(); } public IntPtr NativeGetLogMessageCallback() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetLogMessageCallbackDel>(_libUMPHandler).Invoke(); return UMPNativeGetLogMessageCallback(); } public void NativeSetUnityLogMessageCallback(IntPtr callback) { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) InteropLibraryLoader.GetInteropDelegate<UMPNativeSetUnityLogMessageCallbackDel>(_libUMPHandler).Invoke(callback); else UMPNativeSetUnityLogMessageCallback(callback); } public void NativeUpdateFramesCounter(int counter) { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) InteropLibraryLoader.GetInteropDelegate<UMPNativeUpdateFramesCounterCallbackDel>(_libUMPHandler).Invoke(_nativeIndex, counter); else UMPNativeUpdateFramesCounter(_nativeIndex, counter); } public int NativeGetFramesCounter() { if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Linux) return InteropLibraryLoader.GetInteropDelegate<UMPNativeGetFramesCounterCallbackDel>(_libUMPHandler).Invoke(_nativeIndex); return UMPNativeGetFramesCounter(_nativeIndex); } #endregion #region Player public void PlayerSetDataSource(string path, object playerObject = null) { } public bool PlayerPlay(object playerObject) { return InteropLibraryLoader.GetInteropDelegate<Play>(_libVLCHandler).Invoke((IntPtr)playerObject) == 0; } public void PlayerPause(object playerObject) { InteropLibraryLoader.GetInteropDelegate<Pause>(_libVLCHandler).Invoke((IntPtr)playerObject); } public void PlayerStop(object playerObject) { InteropLibraryLoader.GetInteropDelegate<Stop>(_libVLCHandler).Invoke((IntPtr)playerObject); } public void PlayerRelease(object playerObject) { InteropLibraryLoader.GetInteropDelegate<ReleaseMediaPlayer>(_libVLCHandler).Invoke((IntPtr)playerObject); } public bool PlayerIsPlaying(object playerObject) { return InteropLibraryLoader.GetInteropDelegate<IsPlaying>(_libVLCHandler).Invoke((IntPtr)playerObject) == 1; } public bool PlayerWillPlay(object playerObject) { return InteropLibraryLoader.GetInteropDelegate<CouldPlay>(_libVLCHandler).Invoke((IntPtr)playerObject) == 1; } public long PlayerGetLength(object playerObject) { return InteropLibraryLoader.GetInteropDelegate<GetLength>(_libVLCHandler).Invoke((IntPtr)playerObject); } public float PlayerGetBufferingPercentage(object playerObject) { return 0; } public long PlayerGetTime(object playerObject) { return InteropLibraryLoader.GetInteropDelegate<GetTime>(_libVLCHandler).Invoke((IntPtr)playerObject); } public void PlayerSetTime(long time, object playerObject) { InteropLibraryLoader.GetInteropDelegate<SetTime>(_libVLCHandler).Invoke((IntPtr)playerObject, time); } public float PlayerGetPosition(object playerObject) { return InteropLibraryLoader.GetInteropDelegate<GetMediaPosition>(_libVLCHandler).Invoke((IntPtr)playerObject); } public void PlayerSetPosition(float pos, object playerObject) { InteropLibraryLoader.GetInteropDelegate<SetMediaPosition>(_libVLCHandler).Invoke((IntPtr)playerObject, pos); } public float PlayerGetRate(object playerObject) { return InteropLibraryLoader.GetInteropDelegate<GetRate>(_libVLCHandler).Invoke((IntPtr)playerObject); } public bool PlayerSetRate(float rate, object playerObject) { return InteropLibraryLoader.GetInteropDelegate<SetRate>(_libVLCHandler).Invoke((IntPtr)playerObject, rate) == 0; } public int PlayerGetVolume(object playerObject) { return InteropLibraryLoader.GetInteropDelegate<GetVolume>(_libVLCHandler).Invoke((IntPtr)playerObject); } public int PlayerSetVolume(int volume, object playerObject) { return InteropLibraryLoader.GetInteropDelegate<SetVolume>(_libVLCHandler).Invoke((IntPtr)playerObject, volume); } public bool PlayerGetMute(object playerObject) { return InteropLibraryLoader.GetInteropDelegate<IsMute>(_libVLCHandler).Invoke((IntPtr)playerObject) == 1; } public void PlayerSetMute(bool mute, object playerObject) { InteropLibraryLoader.GetInteropDelegate<SetMute>(_libVLCHandler).Invoke((IntPtr)playerObject, mute ? 1 : 0); } public int PlayerVideoWidth(object playerObject) { uint width = 0, height = 0; InteropLibraryLoader.GetInteropDelegate<GetVideoSize>(_libVLCHandler).Invoke((IntPtr)playerObject, 0, out width, out height); return (int)width; } public int PlayerVideoHeight(object playerObject) { uint width = 0, height = 0; InteropLibraryLoader.GetInteropDelegate<GetVideoSize>(_libVLCHandler).Invoke((IntPtr)playerObject, 0, out width, out height); return (int)height; } public int PlayerVideoFramesCounter(object playerObject) { return 0; } public PlayerState PlayerGetState() { return (PlayerState)NativeGetState(); } public object PlayerGetStateValue() { object value = NativeGetStateFloatValue(); if ((float)value < 0) { value = NativeGetStateLongValue(); if ((long)value < 0) { value = NativeGetStateStringValue(); } } return value; } #endregion #region Player Spu public MediaTrackInfo[] PlayerSpuGetTracks(object playerObject) { var tracks = new System.Collections.Generic.List<MediaTrackInfo>(); var tracksCount = InteropLibraryLoader.GetInteropDelegate<GetVideoSpuCount>(_libVLCHandler).Invoke((IntPtr)playerObject); var tracksHandler = InteropLibraryLoader.GetInteropDelegate<GetVideoSpuDescription>(_libVLCHandler).Invoke((IntPtr)playerObject); for (int i = 0; i < tracksCount; i++) { if (tracksHandler != IntPtr.Zero) { var track = (TrackDescription)Marshal.PtrToStructure(tracksHandler, typeof(TrackDescription)); tracks.Add(new MediaTrackInfo(track.Id, track.Name)); tracksHandler = track.NextDescription; } } return tracks.ToArray(); } public int PlayerSpuGetTrack(object playerObject) { return InteropLibraryLoader.GetInteropDelegate<GetVideoSpu>(_libVLCHandler).Invoke((IntPtr)playerObject); } public int PlayerSpuSetTrack(int spuIndex, object playerObject) { return InteropLibraryLoader.GetInteropDelegate<SetVideoSpu>(_libVLCHandler).Invoke((IntPtr)playerObject, spuIndex); } #endregion #region Player Audio public MediaTrackInfo[] PlayerAudioGetTracks(object playerObject) { var tracks = new System.Collections.Generic.List<MediaTrackInfo>(); var tracksCount = InteropLibraryLoader.GetInteropDelegate<GetAudioTracksCount>(_libVLCHandler).Invoke((IntPtr)playerObject); var tracksHandler = InteropLibraryLoader.GetInteropDelegate<GetAudioTracksDescriptions>(_libVLCHandler).Invoke((IntPtr)playerObject); for (int i = 0; i < tracksCount; i++) { if (tracksHandler != IntPtr.Zero) { var track = (TrackDescription)Marshal.PtrToStructure(tracksHandler, typeof(TrackDescription)); tracks.Add(new MediaTrackInfo(track.Id, track.Name)); tracksHandler = track.NextDescription; } } //InteropLibraryLoader.GetInteropDelegate<ReleaseTracksDescriptions>(_libVLCHandler).Invoke(tracksHandler); return tracks.ToArray(); } public int PlayerAudioGetTrack(object playerObject) { return InteropLibraryLoader.GetInteropDelegate<GetAudioTrack>(_libVLCHandler).Invoke((IntPtr)playerObject); } public int PlayerAudioSetTrack(int audioIndex, object playerObject) { return InteropLibraryLoader.GetInteropDelegate<SetAudioTrack>(_libVLCHandler).Invoke((IntPtr)playerObject, audioIndex); } #endregion #region Platform dependent functionality public IntPtr ExpandedLibVLCNew(string[] args) { if (args == null) args = new string[0]; return InteropLibraryLoader.GetInteropDelegate<CreateNewInstance>(_libVLCHandler).Invoke(args.Length, args); } public void ExpandedLibVLCRelease(IntPtr libVLCInst) { InteropLibraryLoader.GetInteropDelegate<ReleaseInstance>(_libVLCHandler).Invoke(libVLCInst); } public IntPtr ExpandedMediaNewLocation(IntPtr libVLCInst, string path) { return InteropLibraryLoader.GetInteropDelegate<CreateNewMediaFromLocation>(_libVLCHandler).Invoke(libVLCInst, path); } public void ExpandedSetMedia(IntPtr mpInstance, IntPtr libVLCMediaInst) { InteropLibraryLoader.GetInteropDelegate<SetMediaToMediaPlayer>(_libVLCHandler).Invoke(mpInstance, libVLCMediaInst); } public void ExpandedAddOption(IntPtr libVLCMediaInst, string option) { InteropLibraryLoader.GetInteropDelegate<AddOptionToMedia>(_libVLCHandler).Invoke(libVLCMediaInst, option); } // TODO Move to IPlayerWrapper public void ExpandedMediaGetStats(IntPtr mpInstance, out MediaStats mediaStats) { InteropLibraryLoader.GetInteropDelegate<GetMediaStats>(_libVLCHandler).Invoke(mpInstance, out mediaStats); } // TODO Move to IPlayerWrapper public TrackInfo[] ExpandedMediaGetTracksInfo(IntPtr mpInstance) { IntPtr result_buffer = new IntPtr(); int trackCount = InteropLibraryLoader.GetInteropDelegate<GetMediaTracksInformations>(_libVLCHandler).Invoke(mpInstance, out result_buffer); if (trackCount < 0) return null; IntPtr buffer = result_buffer; var tracks = new TrackInfo[trackCount]; for (int i = 0; i < tracks.Length; i++) { tracks[i] = (TrackInfo)Marshal.PtrToStructure(buffer, typeof(TrackInfo)); buffer = new IntPtr(buffer.ToInt64() + Marshal.SizeOf(typeof(TrackInfo))); } ExpandedFree(result_buffer); return tracks; } public void ExpandedMediaRelease(IntPtr libVLCMediaInst) { InteropLibraryLoader.GetInteropDelegate<ReleaseMedia>(_libVLCHandler).Invoke(libVLCMediaInst); } public IntPtr ExpandedMediaPlayerNew(IntPtr libVLCInst) { return InteropLibraryLoader.GetInteropDelegate<CreateMediaPlayer>(_libVLCHandler).Invoke(libVLCInst); } public void ExpandedFree(IntPtr instance) { InteropLibraryLoader.GetInteropDelegate<Free>(_libVLCHandler).Invoke(instance); } public IntPtr ExpandedEventManager(IntPtr mpInstance) { return InteropLibraryLoader.GetInteropDelegate<GetMediaPlayerEventManager>(_libVLCHandler).Invoke(mpInstance); } public int ExpandedEventAttach(IntPtr eventManagerInst, EventTypes eventType, IntPtr callback, IntPtr userData) { return InteropLibraryLoader.GetInteropDelegate<AttachEvent>(_libVLCHandler).Invoke(eventManagerInst, eventType, callback, userData); } public void ExpandedEventDetach(IntPtr eventManagerInst, EventTypes eventType, IntPtr callback, IntPtr userData) { InteropLibraryLoader.GetInteropDelegate<DetachEvent>(_libVLCHandler).Invoke(eventManagerInst, eventType, callback, userData); } public void ExpandedLogSet(IntPtr libVLC, IntPtr callback, IntPtr data) { InteropLibraryLoader.GetInteropDelegate<LogSet>(_libVLCHandler).Invoke(libVLC, callback, data); } public void ExpandedLogUnset(IntPtr libVLC) { InteropLibraryLoader.GetInteropDelegate<LogUnset>(_libVLCHandler).Invoke(libVLC); } public void ExpandedVideoSetCallbacks(IntPtr mpInstance, IntPtr @lock, IntPtr unlock, IntPtr display, IntPtr opaque) { InteropLibraryLoader.GetInteropDelegate<SetVideoCallbacks>(_libVLCHandler).Invoke(mpInstance, @lock, unlock, display, opaque); } public void ExpandedVideoSetFormatCallbacks(IntPtr mpInstance, IntPtr setup, IntPtr cleanup) { InteropLibraryLoader.GetInteropDelegate<SetVideoFormatCallbacks>(_libVLCHandler).Invoke(mpInstance, setup, cleanup); } public void ExpandedVideoSetFormat(IntPtr mpInstance, string chroma, uint width, uint height, uint pitch) { InteropLibraryLoader.GetInteropDelegate<SetVideoFormat>(_libVLCHandler).Invoke(mpInstance, chroma, width, height, pitch); } public void ExpandedAudioSetCallbacks(IntPtr mpInstance, IntPtr play, IntPtr pause, IntPtr resume, IntPtr flush, IntPtr drain, IntPtr opaque) { InteropLibraryLoader.GetInteropDelegate<SetAudioCallbacks>(_libVLCHandler).Invoke(mpInstance, play, pause, resume, flush, drain, opaque); } public void ExpandedAudioSetFormatCallbacks(IntPtr mpInstance, IntPtr setup, IntPtr cleanup) { InteropLibraryLoader.GetInteropDelegate<SetAudioFormatCallbacks>(_libVLCHandler).Invoke(mpInstance, setup, cleanup); } public void ExpandedAudioSetFormat(IntPtr mpInstance, string format, int rate, int channels) { InteropLibraryLoader.GetInteropDelegate<SetAudioFormat>(_libVLCHandler).Invoke(mpInstance, format, rate, channels); } public long ExpandedGetAudioDelay(IntPtr mpInstance) { return InteropLibraryLoader.GetInteropDelegate<GetAudioDelay>(_libVLCHandler).Invoke(mpInstance); } public void ExpandedSetAudioDelay(IntPtr mpInstance, long channel) { InteropLibraryLoader.GetInteropDelegate<SetAudioDelay>(_libVLCHandler).Invoke(mpInstance, channel); } public int ExpandedAudioOutputSet(IntPtr mpInstance, string psz_name) { return InteropLibraryLoader.GetInteropDelegate<SetAudioOutput>(_libVLCHandler).Invoke(mpInstance, Marshal.StringToHGlobalAnsi(psz_name)); } public IntPtr ExpandedAudioOutputListGet(IntPtr mpInstance) { return InteropLibraryLoader.GetInteropDelegate<GetAudioOutputsDescriptions>(_libVLCHandler).Invoke(mpInstance); } public void ExpandedAudioOutputListRelease(IntPtr outputListInst) { InteropLibraryLoader.GetInteropDelegate<ReleaseAudioOutputDescription>(_libVLCHandler).Invoke(outputListInst); } public void ExpandedAudioOutputDeviceSet(IntPtr mpInstance, string psz_audio_output, string psz_device_id) { InteropLibraryLoader.GetInteropDelegate<SetAudioOutputDevice>(_libVLCHandler).Invoke(mpInstance, psz_audio_output, psz_device_id); } public IntPtr ExpandedAudioOutputDeviceListGet(IntPtr mpInstance, string aout) { return InteropLibraryLoader.GetInteropDelegate<GetAudioOutputDeviceList>(_libVLCHandler).Invoke(mpInstance, aout); } public void ExpandedAudioOutputDeviceListRelease(IntPtr deviceListInst) { InteropLibraryLoader.GetInteropDelegate<ReleaseAudioOutputDeviceList>(_libVLCHandler).Invoke(deviceListInst); } public int ExpandedSpuSetFile(IntPtr mpInstance, string path) { return InteropLibraryLoader.GetInteropDelegate<SetVideoSubtitleFile>(_libVLCHandler).Invoke(mpInstance, path); } public float ExpandedVideoGetScale(IntPtr mpInstance) { return InteropLibraryLoader.GetInteropDelegate<GetVideoScale>(_libVLCHandler).Invoke(mpInstance); } public void ExpandedVideoSetScale(IntPtr mpInstance, float factor) { InteropLibraryLoader.GetInteropDelegate<SetVideoScale>(_libVLCHandler).Invoke(mpInstance, factor); } public void ExpandedVideoTakeSnapshot(IntPtr mpInstance, uint stream, string filePath, uint width, uint height) { InteropLibraryLoader.GetInteropDelegate<TakeSnapshot>(_libVLCHandler).Invoke(mpInstance, stream, filePath, width, height); } public float ExpandedVideoFrameRate(IntPtr mpInstance) { return InteropLibraryLoader.GetInteropDelegate<GetFramesPerSecond>(_libVLCHandler).Invoke(mpInstance); } #endregion } }
43.198347
196
0.68371
[ "Apache-2.0" ]
auroraland-vr/auroraland-client
Assets/UniversalMediaPlayer/Scripts/Sources/Wrappers/WrapperStandalone.cs
62,726
C#
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.1 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ namespace Vixen { using System; using System.Runtime.InteropServices; public class CoreTree : SharedObj { private HandleRef swigCPtr; internal CoreTree(IntPtr cPtr, bool cMemoryOwn) : base(VixenLibPINVOKE.CoreTree_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new HandleRef(this, cPtr); } internal static HandleRef getCPtr(CoreTree obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } ~CoreTree() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; VixenLibPINVOKE.delete_CoreTree(swigCPtr); } swigCPtr = new HandleRef(null, IntPtr.Zero); } GC.SuppressFinalize(this); base.Dispose(); } } public CoreTree() : this(VixenLibPINVOKE.new_CoreTree(), true) { } public CoreTree Parent() { IntPtr cPtr = VixenLibPINVOKE.CoreTree_Parent(swigCPtr); CoreTree ret = (cPtr == IntPtr.Zero) ? null : new CoreTree(cPtr, false); return ret; } public CoreTree First() { IntPtr cPtr = VixenLibPINVOKE.CoreTree_First(swigCPtr); CoreTree ret = (cPtr == IntPtr.Zero) ? null : new CoreTree(cPtr, false); return ret; } public CoreTree Last() { IntPtr cPtr = VixenLibPINVOKE.CoreTree_Last(swigCPtr); CoreTree ret = (cPtr == IntPtr.Zero) ? null : new CoreTree(cPtr, false); return ret; } public bool IsParent() { bool ret = VixenLibPINVOKE.CoreTree_IsParent(swigCPtr); return ret; } public bool IsChild() { bool ret = VixenLibPINVOKE.CoreTree_IsChild(swigCPtr); return ret; } public bool IsLast() { bool ret = VixenLibPINVOKE.CoreTree_IsLast(swigCPtr); return ret; } public int GetSize() { int ret = VixenLibPINVOKE.CoreTree_GetSize(swigCPtr); return ret; } public CoreTree GetAt(int n) { IntPtr cPtr = VixenLibPINVOKE.CoreTree_GetAt(swigCPtr, n); CoreTree ret = (cPtr == IntPtr.Zero) ? null : new CoreTree(cPtr, false); return ret; } public virtual bool PutFirst(CoreTree child) { bool ret = VixenLibPINVOKE.CoreTree_PutFirst(swigCPtr, CoreTree.getCPtr(child)); return ret; } public virtual bool Append(CoreTree child) { bool ret = VixenLibPINVOKE.CoreTree_Append(swigCPtr, CoreTree.getCPtr(child)); return ret; } public virtual bool PutAfter(CoreTree follow) { bool ret = VixenLibPINVOKE.CoreTree_PutAfter(swigCPtr, CoreTree.getCPtr(follow)); return ret; } public virtual bool PutBefore(CoreTree before) { bool ret = VixenLibPINVOKE.CoreTree_PutBefore(swigCPtr, CoreTree.getCPtr(before)); return ret; } public virtual bool Remove(bool free) { bool ret = VixenLibPINVOKE.CoreTree_Remove__SWIG_0(swigCPtr, free); return ret; } public virtual bool Remove() { bool ret = VixenLibPINVOKE.CoreTree_Remove__SWIG_1(swigCPtr); return ret; } public virtual void Empty() { VixenLibPINVOKE.CoreTree_Empty(swigCPtr); } public virtual bool Replace(CoreTree src) { bool ret = VixenLibPINVOKE.CoreTree_Replace(swigCPtr, CoreTree.getCPtr(src)); return ret; } public static readonly int DEPTH_FIRST = VixenLibPINVOKE.CoreTree_DEPTH_FIRST_get(); public static readonly int PARENTS_REVERSE = VixenLibPINVOKE.CoreTree_PARENTS_REVERSE_get(); public static readonly int CHILDREN = VixenLibPINVOKE.CoreTree_CHILDREN_get(); public static readonly int CHILDREN_REVERSE = VixenLibPINVOKE.CoreTree_CHILDREN_REVERSE_get(); public static readonly int SEARCH_MASK = VixenLibPINVOKE.CoreTree_SEARCH_MASK_get(); } }
28.934783
113
0.675933
[ "BSD-2-Clause" ]
Caprica666/vixen
build/swig/VixenCS/Sources/CoreTree.cs
3,993
C#
using FluentAssertions; using Sirh3e.Rust.Option; using Xunit; namespace Sirh3e.Rust.Test.Option { public partial class OptionUnitTest { [Fact] public void Option_Map() { { var option = Option<string>.Some("Hello, World!"); option.IsSome.Should().BeTrue(); option.IsNone.Should().BeFalse(); var lenght = option.Map(s => s.Length).Unwrap(); lenght.Should().Be(13); } { var option = Option<string>.Some("Hello, World!"); option.IsSome.Should().BeTrue(); option.IsNone.Should().BeFalse(); var length = option.Map(s => s.Length).Unwrap(); //ToDo must be equal to rust doc length.Should().Be(13); } { var option = Option<string>.None; option.IsSome.Should().BeFalse(); option.IsNone.Should().BeTrue(); var none = option.Map(s => s.Length); //ToDo must be equal to rust doc none.IsSome.Should().BeFalse(); none.IsNone.Should().BeTrue(); } } } }
27.111111
97
0.485246
[ "BSD-3-Clause" ]
sirh3e/Rust
test/Sirh3e.Rust.Test/Option/Methods/Option.Map.UnitTest.cs
1,220
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.Management.RecoveryServices.SiteRecovery.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery; using Newtonsoft.Json; using System.Linq; /// <summary> /// Create network mappings input properties/behaviour specific to Vmm to /// Azure Network mapping. /// </summary> [Newtonsoft.Json.JsonObject("VmmToAzure")] public partial class VmmToAzureCreateNetworkMappingInput : FabricSpecificCreateNetworkMappingInput { /// <summary> /// Initializes a new instance of the /// VmmToAzureCreateNetworkMappingInput class. /// </summary> public VmmToAzureCreateNetworkMappingInput() { CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); } }
32.238095
102
0.696455
[ "MIT" ]
AzureAutomationTeam/azure-sdk-for-net
src/SDKs/RecoveryServices.SiteRecovery/Management.RecoveryServices.SiteRecovery/Generated/Models/VmmToAzureCreateNetworkMappingInput.cs
1,354
C#
using System; using Skybrud.Social.Http; using Skybrud.Social.Twitter.Models.Search; namespace Skybrud.Social.Twitter.Responses.Search { /// <summary> /// Class representing the response of a request to the Twitter API for searching through Twitter status messages (tweets). /// </summary> public class TwitterSearchTweetsResponse : TwitterResponse<TwitterSearchTweetsResults> { #region Constructors private TwitterSearchTweetsResponse(SocialHttpResponse response) : base(response) { // Validate the response ValidateResponse(response); // Parse the response body Body = ParseJsonObject(response.Body, TwitterSearchTweetsResults.Parse); } #endregion #region Static methods /// <summary> /// Parses the specified <paramref name="response"/> into an instance of <see cref="TwitterSearchTweetsResponse"/>. /// </summary> /// <param name="response">The response to be parsed.</param> /// <returns>An instance of <see cref="TwitterSearchTweetsResponse"/> representing the response.</returns> public static TwitterSearchTweetsResponse ParseResponse(SocialHttpResponse response) { if (response == null) throw new ArgumentNullException(nameof(response)); return new TwitterSearchTweetsResponse(response); } #endregion } }
33.857143
127
0.678622
[ "MIT" ]
ohunecker/Skybrud.Social.Twitter
src/Skybrud.Social.Twitter/Responses/Search/TwitterSearchTweetsResponse.cs
1,422
C#
using System.Reflection; 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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ControleVendas.Core")] [assembly: AssemblyTrademark("")] // 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("0fa75a5b-ab83-4fd0-b545-279774c01e87")]
41.578947
84
0.778481
[ "MIT" ]
leandro-SI/Controle-vendas-dotnetcore
aspnet-core/src/ControleVendas.Core/Properties/AssemblyInfo.cs
792
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSLibrary { public partial class HighLevelInterface { byte[] _recvBuffer = new byte[8 + 255 + 20]; // receive packet buffer int _currentRecvBufferSize = 0; byte[] _recvBufferBackup = new byte[8 + 255 + 20]; // backup receive packet buffer int _currentRecvBufferSizeBackup = 0; private void CharacteristicOnValueUpdated(byte[] recvData) { CSLibrary.Debug.WriteBytes("BT data received", recvData); if (CheckSingalPacket(recvData)) return; // First Method if (FirstAssemblePacketMohod(recvData) || BackupAssemblePacketMohod(recvData)) { _currentRecvBufferSize = 0; _currentRecvBufferSizeBackup = 0; } } byte _blePacketRunningNumber = 0x82; bool CheckAPIHeader(byte[] data) { return (data[0] == 0xa7 && data[1] == 0xb3 && data[2] <= 120 && // data[4] == 0x82 && data[5] == 0x9e && (data[3] == 0xc2 || data[3] == 0x6a || data[3] == 0xd9 || data[3] == 0xe8 || data[3] == 0x5f) ); } bool CheckSingalPacket(byte[] data) { if (!CheckAPIHeader(data) || data[2] != (data.Length - 8)) return false; UInt16 recvCRC = (UInt16)(data[6] << 8 | data[7]); if (recvCRC != Tools.Crc.ComputeChecksum(data)) return false; ProcessAPIPacket(data); return true; } bool FirstAssemblePacketMohod(byte[] recvData) { if (CheckAPIHeader(recvData)) { if (_currentRecvBufferSize > 0) { Debug.WriteLine("BT1 : Packet Too small, can not process"); //Trace.Message("BT1 : Packet Too small, can not process"); } Array.Copy(recvData, 0, _recvBuffer, 0, recvData.Length); _currentRecvBufferSize = recvData.Length; return false; } if ((_currentRecvBufferSize + recvData.Length) > _recvBuffer[2] + 8) { Debug.WriteLine("BT1 : Current packet size too large"); //Trace.Message("BT1 : Current packet size too large"); _currentRecvBufferSize = 0; return false; } Array.Copy(recvData, 0, _recvBuffer, _currentRecvBufferSize, recvData.Length); _currentRecvBufferSize += recvData.Length; if (_currentRecvBufferSize == (_recvBuffer[2] + 8)) { UInt16 recvCRC = (UInt16)(_recvBuffer[6] << 8 | _recvBuffer[7]); UInt16 calCRC = Tools.Crc.ComputeChecksum(_recvBuffer); if (recvCRC != calCRC) { Debug.WriteLine("BT1 : Checksum error " + recvCRC.ToString("X4") + " " + calCRC.ToString("X4")); //Trace.Message("BT1 : Checksum error " + recvCRC.ToString("X4") + " " + calCRC.ToString("X4")); _currentRecvBufferSize = 0; return false; } ProcessAPIPacket(_recvBuffer); return true; } return false; } bool BackupAssemblePacketMohod(byte[] recvData) { if (_currentRecvBufferSizeBackup == 0) { if (!CheckAPIHeader(recvData)) return false; Array.Copy(recvData, 0, _recvBufferBackup, 0, recvData.Length); _currentRecvBufferSizeBackup = recvData.Length; return false; } if ((_currentRecvBufferSizeBackup + recvData.Length) > _recvBuffer[2] + 8) { Debug.WriteLine("BT2 : Current packet size too large"); //Trace.Message("BT2 : Current packet size too large"); _currentRecvBufferSizeBackup = 0; return false; } Array.Copy(recvData, 0, _recvBufferBackup, _currentRecvBufferSizeBackup, recvData.Length); _currentRecvBufferSizeBackup += recvData.Length; if (_currentRecvBufferSizeBackup == (_recvBuffer[2] + 8)) { UInt16 recvCRC = (UInt16)(_recvBufferBackup[6] << 8 | _recvBufferBackup[7]); UInt16 calCRC = Tools.Crc.ComputeChecksum(_recvBuffer); if (recvCRC != calCRC) { Debug.WriteLine("BT2 : Checksum error " + recvCRC.ToString("X4") + " " + calCRC.ToString("X4")); //Trace.Message("BT2 : Checksum error " + recvCRC.ToString("X4") + " " + calCRC.ToString("X4")); _currentRecvBufferSizeBackup = 0; return false; } ProcessAPIPacket(_recvBufferBackup); return true; } return false; } } }
35.489933
116
0.506051
[ "MIT" ]
cslrfid/CS108-Windows-UWP-App
CSLibrary/CS108READER/CodeFileReceive.cs
5,290
C#
using System; using Pds.Core.Enums; namespace Pds.Api.Contracts.Content { public class GetContentResponse { public string Id { get; set; } public string Title { get; set; } public Guid BillId { get; set; } public decimal BillValue { get; set; } public string BillComment { get; set; } public BillStatus BillStatus { get; set; } public PaymentType? BillPaymentType { get; set; } public DateTime? BillPaidAt { get; set; } } }
21.166667
57
0.610236
[ "Apache-2.0" ]
catdog50rus/bloggers-cms
Pds/Pds.Api.Contracts/Content/GetContentResponse.cs
510
C#
// // Copyright (C) 2010 Novell Inc. http://novell.com // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Windows.Markup; using System.Xaml.Schema; namespace System.Xaml { public class XamlXmlWriterSettings : XamlWriterSettings { public XamlXmlWriterSettings () { } XamlXmlWriterSettings (XamlXmlWriterSettings other) : base (other) { AssumeValidInput = other.AssumeValidInput; CloseOutput = other.CloseOutput; } public bool AssumeValidInput { get; set; } public bool CloseOutput { get; set; } public XamlXmlWriterSettings Copy () { return new XamlXmlWriterSettings (this); } } }
32.740741
73
0.753959
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Xaml/System.Xaml/XamlXmlWriterSettings.cs
1,768
C#
namespace Primeira_Aula { partial class frmPrincipal { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.lblPrimeiroNumero = new System.Windows.Forms.Label(); this.txbPrimeiroNumero = new System.Windows.Forms.TextBox(); this.txbSegundoNumero = new System.Windows.Forms.TextBox(); this.lblSegundoNumero = new System.Windows.Forms.Label(); this.btnSomar = new System.Windows.Forms.Button(); this.lblResultado = new System.Windows.Forms.Label(); this.lblTitulo = new System.Windows.Forms.Label(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.SuspendLayout(); // // lblPrimeiroNumero // this.lblPrimeiroNumero.AutoSize = true; this.lblPrimeiroNumero.BackColor = System.Drawing.SystemColors.Window; this.lblPrimeiroNumero.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblPrimeiroNumero.Location = new System.Drawing.Point(17, 56); this.lblPrimeiroNumero.Name = "lblPrimeiroNumero"; this.lblPrimeiroNumero.Size = new System.Drawing.Size(151, 15); this.lblPrimeiroNumero.TabIndex = 0; this.lblPrimeiroNumero.Text = "Digite o primeiro nuúmero"; // // txbPrimeiroNumero // this.txbPrimeiroNumero.Location = new System.Drawing.Point(15, 74); this.txbPrimeiroNumero.Name = "txbPrimeiroNumero"; this.txbPrimeiroNumero.Size = new System.Drawing.Size(173, 20); this.txbPrimeiroNumero.TabIndex = 1; this.toolTip1.SetToolTip(this.txbPrimeiroNumero, "Digite um número"); // // txbSegundoNumero // this.txbSegundoNumero.Location = new System.Drawing.Point(15, 137); this.txbSegundoNumero.Name = "txbSegundoNumero"; this.txbSegundoNumero.Size = new System.Drawing.Size(173, 20); this.txbSegundoNumero.TabIndex = 3; this.toolTip1.SetToolTip(this.txbSegundoNumero, "Digite um número"); // // lblSegundoNumero // this.lblSegundoNumero.AutoSize = true; this.lblSegundoNumero.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblSegundoNumero.Location = new System.Drawing.Point(17, 119); this.lblSegundoNumero.Name = "lblSegundoNumero"; this.lblSegundoNumero.Size = new System.Drawing.Size(146, 15); this.lblSegundoNumero.TabIndex = 2; this.lblSegundoNumero.Text = "Digite o segundo número"; // // btnSomar // this.btnSomar.BackColor = System.Drawing.SystemColors.ControlLightLight; this.btnSomar.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnSomar.ForeColor = System.Drawing.SystemColors.ControlText; this.btnSomar.Location = new System.Drawing.Point(65, 180); this.btnSomar.Name = "btnSomar"; this.btnSomar.Size = new System.Drawing.Size(75, 26); this.btnSomar.TabIndex = 4; this.btnSomar.Text = "Somar"; this.toolTip1.SetToolTip(this.btnSomar, "Click para somar"); this.btnSomar.UseVisualStyleBackColor = false; this.btnSomar.Click += new System.EventHandler(this.btnSomar_Click); // // lblResultado // this.lblResultado.AutoSize = true; this.lblResultado.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblResultado.Location = new System.Drawing.Point(17, 220); this.lblResultado.Name = "lblResultado"; this.lblResultado.Size = new System.Drawing.Size(0, 17); this.lblResultado.TabIndex = 5; this.toolTip1.SetToolTip(this.lblResultado, "Resultado da soma"); this.lblResultado.Click += new System.EventHandler(this.label3_Click); // // lblTitulo // this.lblTitulo.AutoSize = true; this.lblTitulo.BackColor = System.Drawing.Color.White; this.lblTitulo.Font = new System.Drawing.Font("Segoe UI Emoji", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblTitulo.Location = new System.Drawing.Point(18, 12); this.lblTitulo.Name = "lblTitulo"; this.lblTitulo.Size = new System.Drawing.Size(170, 24); this.lblTitulo.TabIndex = 6; this.lblTitulo.Text = "Some dois números"; // // frmPrincipal // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(204, 261); this.Controls.Add(this.lblTitulo); this.Controls.Add(this.lblResultado); this.Controls.Add(this.btnSomar); this.Controls.Add(this.txbSegundoNumero); this.Controls.Add(this.lblSegundoNumero); this.Controls.Add(this.txbPrimeiroNumero); this.Controls.Add(this.lblPrimeiroNumero); this.Name = "frmPrincipal"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Somar"; this.Load += new System.EventHandler(this.frmPrincipal_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lblPrimeiroNumero; private System.Windows.Forms.TextBox txbPrimeiroNumero; private System.Windows.Forms.TextBox txbSegundoNumero; private System.Windows.Forms.Label lblSegundoNumero; private System.Windows.Forms.Button btnSomar; private System.Windows.Forms.Label lblResultado; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.Label lblTitulo; } }
50.48
177
0.606313
[ "MIT" ]
LucasValentimK/ADS-OO
Primeira Aula/Primeira Aula/Form1.Designer.cs
7,579
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using System.Diagnostics; namespace BlazorExample.Api.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
26.75
89
0.639519
[ "MIT" ]
Forestbrook/BlazorAuthorizationExample
Api/Pages/Error.cshtml.cs
751
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using Xunit; namespace System.ComponentModel.Tests { public class TypeListConverterTests : ConverterTestBase { // TypeListConverter is an abstract type private static TypeListConverter s_converter = new MyTypeListConverter(new Type[] { typeof(bool), typeof(int) }); [Fact] public static void CanConvertFrom_WithContext() { CanConvertFrom_WithContext(new object[2, 2] { { typeof(string), true }, { typeof(int), false } }, TypeListConverterTests.s_converter); } [Fact] public static void ConvertFrom_WithContext() { ConvertFrom_WithContext(new object[1, 3] { { "System.Int32", typeof(int), null } }, TypeListConverterTests.s_converter); } [Fact] public static void ConvertTo_WithContext() { RemoteInvoke(() => { CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; ConvertTo_WithContext(new object[2, 3] { { typeof(char), "System.Char", null }, // the base class is not verifying if this type is not in the list { null, "(none)", CultureInfo.InvariantCulture } }, TypeListConverterTests.s_converter); }).Dispose(); } [Fact] public static void ConvertTo_WithContext_Negative() { Assert.Throws<InvalidCastException>( () => TypeListConverterTests.s_converter.ConvertTo(TypeConverterTests.s_context, null, 3, typeof(string))); } } }
33.583333
131
0.561787
[ "MIT" ]
2E0PGS/corefx
src/System.ComponentModel.TypeConverter/tests/TypeListConverterTests.cs
2,015
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview { using static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Extensions; /// <summary>Defines reference to an Azure resource.</summary> public partial class AzureResourceReference : Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IAzureResourceReference, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IAzureResourceReferenceInternal { /// <summary>Backing field for <see cref="SourceArmResourceId" /> property.</summary> private string _sourceArmResourceId; /// <summary>Gets the ARM resource ID of the tracked resource being referenced.</summary> [Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Origin(Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.PropertyOrigin.Owned)] public string SourceArmResourceId { get => this._sourceArmResourceId; set => this._sourceArmResourceId = value; } /// <summary>Creates an new <see cref="AzureResourceReference" /> instance.</summary> public AzureResourceReference() { } } /// Defines reference to an Azure resource. public partial interface IAzureResourceReference : Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.IJsonSerializable { /// <summary>Gets the ARM resource ID of the tracked resource being referenced.</summary> [Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Info( Required = true, ReadOnly = false, Description = @"Gets the ARM resource ID of the tracked resource being referenced.", SerializedName = @"sourceArmResourceId", PossibleTypes = new [] { typeof(string) })] string SourceArmResourceId { get; set; } } /// Defines reference to an Azure resource. internal partial interface IAzureResourceReferenceInternal { /// <summary>Gets the ARM resource ID of the tracked resource being referenced.</summary> string SourceArmResourceId { get; set; } } }
46.978261
137
0.706155
[ "MIT" ]
3quanfeng/azure-powershell
src/ResourceMover/generated/api/Models/Api20191001Preview/AzureResourceReference.cs
2,116
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// AlipayCommerceKidsAccountBindModel Data Structure. /// </summary> [Serializable] public class AlipayCommerceKidsAccountBindModel : AopObject { /// <summary> /// 与child_cert_type对应,如果child_cert_type为IDENTITY_CARD,对应的取值为身份证号 /// </summary> [XmlElement("child_cert_no")] public string ChildCertNo { get; set; } /// <summary> /// 证件类型,暂时只支持身份证 /// </summary> [XmlElement("child_cert_type")] public string ChildCertType { get; set; } /// <summary> /// 儿童唯一id /// </summary> [XmlElement("child_id")] public string ChildId { get; set; } /// <summary> /// 儿童名字 /// </summary> [XmlElement("child_name")] public string ChildName { get; set; } /// <summary> /// 所在班级 /// </summary> [XmlElement("class_name")] public string ClassName { get; set; } /// <summary> /// 联系人手机 /// </summary> [XmlElement("contact_mobile")] public string ContactMobile { get; set; } /// <summary> /// 家长支付宝userId,创建的账户将会同时与家长绑定关系 /// </summary> [XmlElement("parent_uid")] public string ParentUid { get; set; } /// <summary> /// 场景码,接入前需要进行申请 /// </summary> [XmlElement("scene_code")] public string SceneCode { get; set; } /// <summary> /// 学校id,建议采用支付宝分配的学校编号 /// </summary> [XmlElement("school_id")] public string SchoolId { get; set; } /// <summary> /// 学号 /// </summary> [XmlElement("student_no")] public string StudentNo { get; set; } } }
25.164384
73
0.523136
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Domain/AlipayCommerceKidsAccountBindModel.cs
2,041
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; using SpatialLite.Core; using SpatialLite.Core.API; using SpatialLite.Core.Geometries; namespace Tests.SpatialLite.Core.Geometries { public class GeometryCollectionTests { #region Test Data Point[] _geometries; Coordinate[] _coordinatesXYZM = new Coordinate[] { new Coordinate(12,10,100, 1000), new Coordinate(22,20,200, 2000), new Coordinate(32,30,300, 3000) }; #endregion public GeometryCollectionTests() { _geometries = new Point[3]; _geometries[0] = new Point(1, 2, 3); _geometries[1] = new Point(1.1, 2.1, 3.1); _geometries[2] = new Point(1.2, 2.2, 3.2); } private void CheckGeometries(GeometryCollection<Geometry> target, Geometry[] geometries) { Assert.Equal(geometries.Length, target.Geometries.Count); for (int i = 0; i < geometries.Length; i++) { Assert.Same(geometries[i], target.Geometries[i]); } } #region Constructors tests #region Default constructors tests [Fact] public void Constructor__CreatesNewEmptyCollectionInWSG84() { GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(); Assert.Equal(SRIDList.WSG84, target.Srid); Assert.NotNull(target.Geometries); Assert.Empty(target.Geometries); } #endregion #region Constructor(SRID) tests [Fact] public void Constructor_SRID_CreatesEmptyCollectionInSpecifiedSRID() { int srid = 1; GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(srid); Assert.Equal(srid, target.Srid); Assert.NotNull(target.Geometries); Assert.Empty(target.Geometries); } #endregion #region Constructor(IEnumerable<IGeometry>) [Fact] public void Constructor_IEnumerable_CreateNewCollectionWithDataInWSG84() { GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(_geometries); Assert.Equal(SRIDList.WSG84, target.Srid); CheckGeometries(target, _geometries); } #endregion #region Constructor(SRID, IEnumerable) [Fact] public void Constructor_SRIDIEnumerable_CreateNewCollectionWithDataInWSpecifiedSRID() { int srid = 1; GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(srid, _geometries); Assert.Equal(srid, target.Srid); CheckGeometries(target, _geometries); } #endregion #endregion #region Is3D tests [Fact] public void Is3D_ReturnsFalseForEmptyCollection() { GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(); Assert.False(target.Is3D); } [Fact] public void Is3D_ReturnsFalseForCollectionOf2DObjects() { var members2d = new Geometry[] { new Point(1, 2), new Point(2, 3) }; GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(members2d); Assert.False(target.Is3D); } [Fact] public void Is3D_ReturnsTrueForCollectionWithAtLeastOne3DObject() { GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(_geometries); Assert.True(target.Is3D); } #endregion #region IsMeasured tests [Fact] public void IsMeasured_ReturnsFalseForEmptyCollection() { GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(); Assert.False(target.IsMeasured); } [Fact] public void IsMeasured_ReturnsFalseForCollectionOfNonMeasuredObjects() { GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(_geometries); Assert.False(target.IsMeasured); } [Fact] public void IsMeasured_ReturnsTrueForCollectionWithAtLeastOneMeasuredObject() { var members = new Geometry[] { new Point(1, 2), new Point(2, 3, 4, 5) }; GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(members); Assert.True(target.IsMeasured); } #endregion #region GetEnvelope tests [Fact] public void GetEnvelopeReturnsEmptyEnvelopeForEmptyCollection() { GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(); Assert.Equal(Envelope.Empty, target.GetEnvelope()); } [Fact] public void GetEnvelopeReturnsUnionOfMembersEnvelopes() { GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(_geometries); Envelope expected = new Envelope(new Coordinate[] {_geometries[0].Position, _geometries[1].Position, _geometries[2].Position}); Assert.Equal(expected, target.GetEnvelope()); } #endregion #region GetBoundary tests [Fact] public void GetBoundary_ReturnsGeometryCollectionWithBoundariesOfObjectsInCollection() { int srid = 1; GeometryCollection<Geometry> target = new GeometryCollection<Geometry>(srid); target.Geometries.Add(new LineString(srid, _coordinatesXYZM)); IGeometryCollection<IGeometry> boundary = target.GetBoundary() as IGeometryCollection<IGeometry>; Assert.NotNull(boundary); Assert.Equal(srid, boundary.Srid); Assert.Equal(target.Geometries.Count, boundary.Geometries.Count()); IMultiPoint expectedChildBoundary = target.Geometries[0].GetBoundary() as IMultiPoint; IMultiPoint childBoundary = boundary.Geometries.First() as IMultiPoint;; Assert.Equal(expectedChildBoundary.Geometries.First().Position, childBoundary.Geometries.First().Position); Assert.Equal(expectedChildBoundary.Geometries.Last().Position, childBoundary.Geometries.Last().Position); } #endregion } }
28.61658
131
0.72533
[ "BSD-3-Clause" ]
AntonBursch/spatiallite-net
src/Tests.SpatialLite.Core/Geometries/GeometryCollectionTests.cs
5,525
C#
using System.Data.Entity; using UniversityManagementSystem.Data.Contexts; using UniversityManagementSystem.Data.Entities; namespace UniversityManagementSystem.Services { /// <summary> /// Defines implementations for the inherited members which perform year dimension related business logic. /// </summary> public class YearDimService : DimServiceBase<YearDim>, IYearDimService { /// <inheritdoc /> protected override DbSet<YearDim> GetDbSet(ApplicationDbContext context) { return context.YearDims; } } }
32
114
0.710069
[ "MIT" ]
tnc1997/wpf-university-management-system
UniversityManagementSystem.Services/YearDimService.cs
576
C#
using System.Collections.Generic; using System.Linq; using NUnit.Framework; using static Linqor.Tests.Helpers; namespace Linqor.Tests { [TestFixture] public class ExceptTests { [TestCaseSource(nameof(GetTestCases))] public string[] Except(string[] left, string[] right) { return Extensions .Except( left.AsOrderedBy(NumberInString), right) .ToArray(); } public static IEnumerable<TestCaseData> GetTestCases() { var testCases = new[] { (new string[] { }, new string[] { }, new string[] { }), (new[] { "L0", "L1", "L2" }, new string[] { }, new[] { "L0", "L1", "L2" }), (new string[] { }, new[] { "R0", "R1", "R2" }, new string[] { }), (new[] { "L0" }, new[] { "R0" }, new string[] { }), (new[] { "L0", "L1", "L2" }, new[] { "R0", "R1", "R2" }, new string[] { }), (new[] { "L0", "L1", "L2" }, new[] { "R2", "R3", "R4" }, new string[] { "L0", "L1" }), (new[] { "L2", "L3", "L4" }, new[] { "R0", "R1", "R2" }, new string[] { "L3", "L4" }), (new[] { "L0", "L0", "L1", "L2", "L2" }, new[] { "R0", "R1", "R1", "R2" }, new string[] { }), (new[] { "L0", "L0", "L1", "L3", "L3" }, new[] { "R1", "R1", "R2", "R2", "R3" }, new[] { "L0" }), (new[] { "L0", "L1", "L2", "L3", "L4", "L5" }, new string[] { "R3", "R4", "R5", "R6", "R7", "R8" }, new string[] { "L0", "L1", "L2" }), }; var linqTestCases = testCases .Select(c => (c.Item1, c.Item2, Enumerable .Except(c.Item1, c.Item2, new NumberInStringComparer()) .ToArray())); return testCases.Concat(linqTestCases) .Select((c, index) => new TestCaseData(c.Item1, c.Item2).Returns(c.Item3).SetName($"Except {Helpers.Get2DID(index, testCases.Length)}")); } [TestCaseSource(nameof(GetErrorCases))] public void ExceptError(string[] left, string[] right) { var result = Extensions .Except( left.AsOrderedBy(NumberInString), right); Assert.That(() => result.ToArray(), Throws.TypeOf<UnorderedElementDetectedException>()); } private static IEnumerable<TestCaseData> GetErrorCases() { var exceptionTestCases = new[] { (new[] { "L0", "L1" }, new[] { "R1", "R0" }), (new[] { "L1", "L0" }, new[] { "R0", "R1" }), }; return exceptionTestCases .Select(c => new TestCaseData(c.Item1, c.Item2)); } } }
38.013514
153
0.441877
[ "MIT" ]
b-maslennikov/linqor
Linqor.Tests/ExceptTests.cs
2,815
C#
using System.Text.Json; using FluentAssertions; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; using Microsoft.Extensions.Options; using RSql4Net.Configurations; using RSql4Net.Models.Queries; using Xunit; namespace RSql4Net.Tests.Models.Queries { public class QueryModelBinderProviderTest { [Fact] public void ShouldBeNotQueryModelBinder() { var modelBinderProviderContextMock = new MockModelBinderProviderContext(typeof(string)); var expected = new RSqlQueryModelBinderProvider(); expected.GetBinder(modelBinderProviderContextMock) .Should().BeNull(); modelBinderProviderContextMock = new MockModelBinderProviderContext(typeof(int?)); expected = new RSqlQueryModelBinderProvider(); expected.GetBinder(modelBinderProviderContextMock) .Should().BeNull(); } [Fact] public void ShouldBeQueryModelBinder() { var modelBinderProviderContextMock = new MockModelBinderProviderContext(typeof(RSqlQuery<Customer>)); var expected = new RSqlQueryModelBinderProvider(); expected.GetBinder(modelBinderProviderContextMock) .Should().BeOfType<BinderTypeModelBinder>(); } } }
34.075
100
0.676449
[ "MIT" ]
gwendallg/RSql4Net
src/RSql4Net.Tests/Models/Queries/QueryModelBinderProviderTest.cs
1,365
C#
using UnityEngine; using System.Collections; public class MathUtil { public static Vector3 AngleToVector(float degrees) { return new Vector3(Mathf.Cos(Mathf.Deg2Rad * degrees), Mathf.Sin(Mathf.Deg2Rad * degrees)).normalized; } public static float VectorToAngle(Vector3 vector) { return Mathf.Rad2Deg * Mathf.Atan2(vector.y, vector.x); } public static float AngleBetween(float angle1, float angle2) { // This is pretty hilariously bad return Vector3.Angle(AngleToVector(angle1), AngleToVector(angle2)); } public static float RotateAngle(float startAngle, float targetAngle, float delta) { Vector3 startVec = AngleToVector(startAngle); Vector3 targetVec = AngleToVector(targetAngle); float diff = Vector3.Angle(startVec, targetVec); if (diff < delta) { return targetAngle; } Vector3 rightStart = new Vector3(startVec.y, -startVec.x); // If the right-facing vector is in the direction of the target, rotate that way if (Vector3.Dot(rightStart, targetVec) > 0) { startAngle -= delta; } else { startAngle += delta; } return startAngle; } public static Vector3 RotateVector(Vector3 start, Vector3 end, float angleDelta) { float startMagnitude = start.magnitude; // Super inefficient float targetAngle = RotateAngle(VectorToAngle(start), VectorToAngle(end), angleDelta); return AngleToVector(targetAngle) * startMagnitude; } public static bool SignsMatch(float val1, float val2) { return (val1 > 0 && val2 > 0) || (val1 == 0 && val2 == 0) || (val1 < 0 && val2 < 0); } public static Vector3 RotateVector(Vector3 input, float rotateZDegrees) { // NOTE(alex): This just ignores the z coord entirely! float cosine = Mathf.Cos(toRadians(rotateZDegrees)); float sine = Mathf.Sin(toRadians(rotateZDegrees)); return new Vector3( cosine * input.x - sine * input.y, sine * input.x + cosine * input.y, input.z); } public static float toRadians(float degrees) { return degrees * Mathf.PI / 180; } public static float toDegrees(float radians) { return radians * 180 / Mathf.PI; } }
24.623529
88
0.709508
[ "MIT" ]
zillix/LD46
Assets/Scripts/Util/MathUtil.cs
2,095
C#