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 Boformer.Redirection; using ColossalFramework; using System; using UnityEngine; namespace WG_CitizenEdit { [TargetType(typeof(OutsideConnectionAI))] public class NewOutsideConnectionAI : OutsideConnectionAI { [RedirectMethod] // Copied from game code. Ugh.... // OutsideConnectionAI private static bool StartConnectionTransferImpl(ushort buildingID, ref Building data, TransferManager.TransferReason material, TransferManager.TransferOffer offer, int touristFactor0, int touristFactor1, int touristFactor2) { BuildingManager instance = Singleton<BuildingManager>.instance; VehicleInfo vehicleInfo = null; Citizen.Education education = Citizen.Education.Uneducated; int num = 0; bool flag = false; bool flag2 = false; bool flag3 = false; if (material == TransferManager.TransferReason.DummyCar) { ushort building = offer.Building; if (building != 0) { Vector3 position = instance.m_buildings.m_buffer[(int)building].m_position; if (Vector3.SqrMagnitude(position - data.m_position) > 40000f) { flag2 = true; switch (Singleton<SimulationManager>.instance.m_randomizer.Int32(38u)) { case 0: material = TransferManager.TransferReason.Ore; break; case 1: material = TransferManager.TransferReason.Coal; break; case 2: material = TransferManager.TransferReason.Oil; break; case 3: material = TransferManager.TransferReason.Petrol; break; case 4: material = TransferManager.TransferReason.Grain; break; case 5: material = TransferManager.TransferReason.Food; break; case 6: material = TransferManager.TransferReason.Logs; break; case 7: material = TransferManager.TransferReason.Lumber; break; case 8: material = TransferManager.TransferReason.Goods; break; case 9: material = TransferManager.TransferReason.Goods; break; case 10: material = TransferManager.TransferReason.Single0; break; case 11: material = TransferManager.TransferReason.Single1; break; case 12: material = TransferManager.TransferReason.Single2; break; case 13: material = TransferManager.TransferReason.Single3; break; case 14: material = TransferManager.TransferReason.Single0B; break; case 15: material = TransferManager.TransferReason.Single1B; break; case 16: material = TransferManager.TransferReason.Single2B; break; case 17: material = TransferManager.TransferReason.Single3B; break; case 18: material = TransferManager.TransferReason.Family0; break; case 19: material = TransferManager.TransferReason.Family1; break; case 20: material = TransferManager.TransferReason.Family2; break; case 21: material = TransferManager.TransferReason.Family3; break; case 22: material = TransferManager.TransferReason.Shopping; break; case 23: material = TransferManager.TransferReason.ShoppingB; break; case 24: material = TransferManager.TransferReason.ShoppingC; break; case 25: material = TransferManager.TransferReason.ShoppingD; break; case 26: material = TransferManager.TransferReason.ShoppingE; break; case 27: material = TransferManager.TransferReason.ShoppingF; break; case 28: material = TransferManager.TransferReason.ShoppingG; break; case 29: material = TransferManager.TransferReason.ShoppingH; break; case 30: material = TransferManager.TransferReason.Entertainment; break; case 31: material = TransferManager.TransferReason.EntertainmentB; break; case 32: material = TransferManager.TransferReason.EntertainmentC; break; case 33: material = TransferManager.TransferReason.EntertainmentD; break; case 34: material = TransferManager.TransferReason.TouristA; break; case 35: material = TransferManager.TransferReason.TouristB; break; case 36: material = TransferManager.TransferReason.TouristC; break; case 37: material = TransferManager.TransferReason.TouristD; break; } } } } switch (material) { case TransferManager.TransferReason.Oil: vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.Industrial, ItemClass.SubService.IndustrialOil, ItemClass.Level.Level2); goto IL_63C; case TransferManager.TransferReason.Ore: vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.Industrial, ItemClass.SubService.IndustrialOre, ItemClass.Level.Level2); goto IL_63C; case TransferManager.TransferReason.Logs: vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.Industrial, ItemClass.SubService.IndustrialForestry, ItemClass.Level.Level2); goto IL_63C; case TransferManager.TransferReason.Grain: vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.Industrial, ItemClass.SubService.IndustrialFarming, ItemClass.Level.Level2); goto IL_63C; case TransferManager.TransferReason.Goods: vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.Industrial, ItemClass.SubService.IndustrialGeneric, ItemClass.Level.Level1); goto IL_63C; case TransferManager.TransferReason.PassengerTrain: case TransferManager.TransferReason.PartnerYoung: case TransferManager.TransferReason.PartnerAdult: case TransferManager.TransferReason.LeaveCity0: case TransferManager.TransferReason.LeaveCity1: case TransferManager.TransferReason.LeaveCity2: case TransferManager.TransferReason.GarbageMove: case TransferManager.TransferReason.MetroTrain: case TransferManager.TransferReason.PassengerPlane: case TransferManager.TransferReason.PassengerShip: case TransferManager.TransferReason.DeadMove: case TransferManager.TransferReason.DummyCar: IL_33B: switch (material) { case TransferManager.TransferReason.TouristA: case TransferManager.TransferReason.TouristB: case TransferManager.TransferReason.TouristC: case TransferManager.TransferReason.TouristD: goto IL_53D; case TransferManager.TransferReason.UnsortedMail: case TransferManager.TransferReason.OutgoingMail: flag3 = true; vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.PublicTransport, ItemClass.SubService.PublicTransportPost, ItemClass.Level.Level5); goto IL_63C; case TransferManager.TransferReason.SortedMail: case TransferManager.TransferReason.IncomingMail: vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.PublicTransport, ItemClass.SubService.PublicTransportPost, ItemClass.Level.Level5); goto IL_63C; } return false; case TransferManager.TransferReason.Coal: vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.Industrial, ItemClass.SubService.IndustrialOre, ItemClass.Level.Level1); goto IL_63C; case TransferManager.TransferReason.Family0: education = Citizen.Education.Uneducated; num = Singleton<SimulationManager>.instance.m_randomizer.Int32(2, 5); goto IL_63C; case TransferManager.TransferReason.Family1: education = Citizen.Education.OneSchool; num = Singleton<SimulationManager>.instance.m_randomizer.Int32(2, 5); goto IL_63C; case TransferManager.TransferReason.Family2: education = Citizen.Education.TwoSchools; num = Singleton<SimulationManager>.instance.m_randomizer.Int32(2, 5); goto IL_63C; case TransferManager.TransferReason.Family3: education = Citizen.Education.ThreeSchools; num = Singleton<SimulationManager>.instance.m_randomizer.Int32(2, 5); goto IL_63C; case TransferManager.TransferReason.Single0: case TransferManager.TransferReason.Single0B: education = Citizen.Education.Uneducated; num = 1; goto IL_63C; case TransferManager.TransferReason.Single1: case TransferManager.TransferReason.Single1B: education = Citizen.Education.OneSchool; num = 1; goto IL_63C; case TransferManager.TransferReason.Single2: case TransferManager.TransferReason.Single2B: education = Citizen.Education.TwoSchools; num = 1; goto IL_63C; case TransferManager.TransferReason.Single3: case TransferManager.TransferReason.Single3B: education = Citizen.Education.ThreeSchools; num = 1; goto IL_63C; case TransferManager.TransferReason.Shopping: case TransferManager.TransferReason.Entertainment: case TransferManager.TransferReason.ShoppingB: case TransferManager.TransferReason.ShoppingC: case TransferManager.TransferReason.ShoppingD: case TransferManager.TransferReason.ShoppingE: case TransferManager.TransferReason.ShoppingF: case TransferManager.TransferReason.ShoppingG: case TransferManager.TransferReason.ShoppingH: case TransferManager.TransferReason.EntertainmentB: case TransferManager.TransferReason.EntertainmentC: case TransferManager.TransferReason.EntertainmentD: goto IL_53D; case TransferManager.TransferReason.Petrol: vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.Industrial, ItemClass.SubService.IndustrialOil, ItemClass.Level.Level1); goto IL_63C; case TransferManager.TransferReason.Food: vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.Industrial, ItemClass.SubService.IndustrialFarming, ItemClass.Level.Level1); goto IL_63C; case TransferManager.TransferReason.Lumber: vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.Industrial, ItemClass.SubService.IndustrialForestry, ItemClass.Level.Level1); goto IL_63C; case TransferManager.TransferReason.DummyTrain: if (offer.Building != buildingID) { flag2 = true; if (Singleton<SimulationManager>.instance.m_randomizer.Int32(2u) == 0) { vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.PublicTransport, ItemClass.SubService.PublicTransportTrain, ItemClass.Level.Level4); } else { vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.PublicTransport, ItemClass.SubService.PublicTransportTrain, ItemClass.Level.Level1); } } goto IL_63C; case TransferManager.TransferReason.DummyShip: if (offer.Building != buildingID) { flag2 = true; if (Singleton<SimulationManager>.instance.m_randomizer.Int32(2u) == 0) { vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.PublicTransport, ItemClass.SubService.PublicTransportShip, ItemClass.Level.Level4); } else { vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.PublicTransport, ItemClass.SubService.PublicTransportShip, ItemClass.Level.Level1); } } goto IL_63C; case TransferManager.TransferReason.DummyPlane: if (offer.Building != buildingID) { flag2 = true; vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.PublicTransport, ItemClass.SubService.PublicTransportPlane, ItemClass.Level.Level1); } goto IL_63C; } // Copy paste to get it to work switch (material) { case TransferManager.TransferReason.TouristA: case TransferManager.TransferReason.TouristB: case TransferManager.TransferReason.TouristC: case TransferManager.TransferReason.TouristD: goto IL_53D; case TransferManager.TransferReason.UnsortedMail: case TransferManager.TransferReason.OutgoingMail: flag3 = true; vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.PublicTransport, ItemClass.SubService.PublicTransportPost, ItemClass.Level.Level5); goto IL_63C; case TransferManager.TransferReason.SortedMail: case TransferManager.TransferReason.IncomingMail: vehicleInfo = Singleton<VehicleManager>.instance.GetRandomVehicleInfo(ref Singleton<SimulationManager>.instance.m_randomizer, ItemClass.Service.PublicTransport, ItemClass.SubService.PublicTransportPost, ItemClass.Level.Level5); goto IL_63C; } return false; IL_53D: flag = true; IL_63C: if (num != 0) { CitizenManager instance2 = Singleton<CitizenManager>.instance; ushort building2 = offer.Building; if (building2 != 0) { uint num2 = 0u; if (!flag2) { num2 = instance.m_buildings.m_buffer[(int)building2].GetEmptyCitizenUnit(CitizenUnit.Flags.Home); } if (num2 != 0u || flag2) { int family = Singleton<SimulationManager>.instance.m_randomizer.Int32(256u); ushort num3 = 0; Citizen.Gender gender = Citizen.Gender.Male; int[] ageArray = num == 1 ? DataStore.incomingSingleAge : DataStore.incomingAdultAge; // Start of changes! ------------------------------------------------------- ------------------------------------------------------- int childrenAgeMax = 0; // 80 less than the youngest adult int childrenAgeMin = 0; // 180 less than the youngest adult int minAdultAge = 0; for (int i = 0; i < num; i++) { uint num4 = 0u; //int min = (i >= 2) ? 0 : 90; //int max = (i >= 2) ? 15 : 105; int min = ageArray[0]; int max = ageArray[1]; if (i == 1) { // min max shouldn't be too far from the first. Just because. min = Math.Max(minAdultAge - 20, DataStore.incomingAdultAge[0]); max = Math.Min(minAdultAge + 20, DataStore.incomingAdultAge[1]); } else if (i >= 2) { min = childrenAgeMin; max = childrenAgeMax; } int age = Singleton<SimulationManager>.instance.m_randomizer.Int32(min, max); if (i == 0) { minAdultAge = age; } else if (i == 1) { // Restrict to adult age. Young adult is 18 according to National Institutes of Health... even if the young adult section in a library isn't that range. minAdultAge = Math.Min(age, minAdultAge); childrenAgeMax = Math.Max(minAdultAge - 80, 0); // Allow people 10 ticks from 'adulthood' to have kids childrenAgeMin = Math.Max(minAdultAge - 178, 0); // Accounting gestation, which isn't simulated yet (2 ticks) } Citizen.Education education2 = education; if (i < 2) { // 24% different education levels int eduModifier = Singleton<SimulationManager>.instance.m_randomizer.Int32(-12, 12) / 10; education2 += eduModifier; if (education2 < Citizen.Education.Uneducated) { education2 = Citizen.Education.Uneducated; } else if (education2 > Citizen.Education.ThreeSchools) { education2 = Citizen.Education.ThreeSchools; } } else // children { switch (Citizen.GetAgeGroup(age)) { case Citizen.AgeGroup.Child: education2 = Citizen.Education.Uneducated; break; case Citizen.AgeGroup.Teen: education2 = Citizen.Education.OneSchool; break; default: // Make it that 80% graduate from high school education2 = (Singleton<SimulationManager>.instance.m_randomizer.Int32(0, 100) < 80) ? Citizen.Education.TwoSchools : education2 = Citizen.Education.OneSchool; break; } } // End of changes? -------------------------------------------------------------------------------------------------------------- bool flag5; if (i == 1) { bool flag4 = Singleton<SimulationManager>.instance.m_randomizer.Int32(100u) < 5; Citizen.Gender gender2; if (flag4) { gender2 = gender; } else { gender2 = ((gender != Citizen.Gender.Male) ? Citizen.Gender.Male : Citizen.Gender.Female); } flag5 = instance2.CreateCitizen(out num4, age, family, ref Singleton<SimulationManager>.instance.m_randomizer, gender2); } else { flag5 = instance2.CreateCitizen(out num4, age, family, ref Singleton<SimulationManager>.instance.m_randomizer); } if (!flag5) { break; } if (i == 0) { gender = Citizen.GetGender(num4); } if (education2 >= Citizen.Education.OneSchool) { instance2.m_citizens.m_buffer[(int)((UIntPtr)num4)].Education1 = true; } if (education2 >= Citizen.Education.TwoSchools) { instance2.m_citizens.m_buffer[(int)((UIntPtr)num4)].Education1 = true; instance2.m_citizens.m_buffer[(int)((UIntPtr)num4)].Education2 = true; } if (education2 >= Citizen.Education.ThreeSchools) { instance2.m_citizens.m_buffer[(int)((UIntPtr)num4)].Education1 = true; instance2.m_citizens.m_buffer[(int)((UIntPtr)num4)].Education2 = true; instance2.m_citizens.m_buffer[(int)((UIntPtr)num4)].Education3 = true; } if (flag2) { Citizen[] expr_85E_cp_0 = instance2.m_citizens.m_buffer; UIntPtr expr_85E_cp_1 = (UIntPtr)num4; expr_85E_cp_0[(int)expr_85E_cp_1].m_flags = (expr_85E_cp_0[(int)expr_85E_cp_1].m_flags | Citizen.Flags.DummyTraffic); } else { instance2.m_citizens.m_buffer[(int)((UIntPtr)num4)].SetHome(num4, 0, num2); } Citizen[] expr_8A3_cp_0 = instance2.m_citizens.m_buffer; UIntPtr expr_8A3_cp_1 = (UIntPtr)num4; expr_8A3_cp_0[(int)expr_8A3_cp_1].m_flags = (expr_8A3_cp_0[(int)expr_8A3_cp_1].m_flags | Citizen.Flags.MovingIn); CitizenInfo citizenInfo = instance2.m_citizens.m_buffer[(int)((UIntPtr)num4)].GetCitizenInfo(num4); ushort num5; if (citizenInfo != null && instance2.CreateCitizenInstance(out num5, ref Singleton<SimulationManager>.instance.m_randomizer, citizenInfo, num4)) { if (num3 == 0) { citizenInfo.m_citizenAI.SetSource(num5, ref instance2.m_instances.m_buffer[(int)num5], buildingID); citizenInfo.m_citizenAI.SetTarget(num5, ref instance2.m_instances.m_buffer[(int)num5], building2); num3 = num5; } else { citizenInfo.m_citizenAI.SetSource(num5, ref instance2.m_instances.m_buffer[(int)num5], buildingID); citizenInfo.m_citizenAI.JoinTarget(num5, ref instance2.m_instances.m_buffer[(int)num5], num3); } instance2.m_citizens.m_buffer[(int)((UIntPtr)num4)].CurrentLocation = Citizen.Location.Moving; } } } } } if (flag) { CitizenManager instance3 = Singleton<CitizenManager>.instance; ushort building3 = offer.Building; ushort transportLine = offer.TransportLine; if (building3 != 0) { int family2 = Singleton<SimulationManager>.instance.m_randomizer.Int32(256u); uint num6 = 0u; if (!flag2) { num6 = instance.m_buildings.m_buffer[(int)building3].GetEmptyCitizenUnit(CitizenUnit.Flags.Visit); } if (num6 != 0u || flag2) { int age2 = Singleton<SimulationManager>.instance.m_randomizer.Int32(0, 240); Citizen.Wealth wealth = Citizen.Wealth.High; int num7 = touristFactor0 + touristFactor1 + touristFactor2; if (num7 != 0) { int num8 = Singleton<SimulationManager>.instance.m_randomizer.Int32((uint)num7); if (num8 < touristFactor0) { wealth = Citizen.Wealth.Low; } else if (num8 < touristFactor0 + touristFactor1) { wealth = Citizen.Wealth.Medium; } } uint num9; if (instance3.CreateCitizen(out num9, age2, family2, ref Singleton<SimulationManager>.instance.m_randomizer)) { Citizen[] expr_ABB_cp_0 = instance3.m_citizens.m_buffer; UIntPtr expr_ABB_cp_1 = (UIntPtr)num9; expr_ABB_cp_0[(int)expr_ABB_cp_1].m_flags = (expr_ABB_cp_0[(int)expr_ABB_cp_1].m_flags | Citizen.Flags.Tourist); Citizen[] expr_ADC_cp_0 = instance3.m_citizens.m_buffer; UIntPtr expr_ADC_cp_1 = (UIntPtr)num9; expr_ADC_cp_0[(int)expr_ADC_cp_1].m_flags = (expr_ADC_cp_0[(int)expr_ADC_cp_1].m_flags | Citizen.Flags.MovingIn); instance3.m_citizens.m_buffer[(int)((UIntPtr)num9)].WealthLevel = wealth; if (flag2) { Citizen[] expr_B20_cp_0 = instance3.m_citizens.m_buffer; UIntPtr expr_B20_cp_1 = (UIntPtr)num9; expr_B20_cp_0[(int)expr_B20_cp_1].m_flags = (expr_B20_cp_0[(int)expr_B20_cp_1].m_flags | Citizen.Flags.DummyTraffic); } else { instance3.m_citizens.m_buffer[(int)((UIntPtr)num9)].SetVisitplace(num9, 0, num6); } CitizenInfo citizenInfo2 = instance3.m_citizens.m_buffer[(int)((UIntPtr)num9)].GetCitizenInfo(num9); ushort num10; if (citizenInfo2 != null && instance3.CreateCitizenInstance(out num10, ref Singleton<SimulationManager>.instance.m_randomizer, citizenInfo2, num9)) { citizenInfo2.m_citizenAI.SetSource(num10, ref instance3.m_instances.m_buffer[(int)num10], buildingID); citizenInfo2.m_citizenAI.SetTarget(num10, ref instance3.m_instances.m_buffer[(int)num10], building3); instance3.m_citizens.m_buffer[(int)((UIntPtr)num9)].CurrentLocation = Citizen.Location.Moving; } if (!flag2) { StatisticBase statisticBase = Singleton<StatisticsManager>.instance.Acquire<StatisticArray>(StatisticType.IncomingTourists); statisticBase = statisticBase.Acquire<StatisticInt32>((int)wealth, 3); statisticBase.Add(1); } } } } else if (transportLine != 0) { TransportManager instance4 = Singleton<TransportManager>.instance; int num11 = instance4.m_lines.m_buffer[(int)transportLine].CountStops(transportLine); if (num11 > 0) { int index = Singleton<SimulationManager>.instance.m_randomizer.Int32((uint)num11); ushort stop = instance4.m_lines.m_buffer[(int)transportLine].GetStop(index); if (stop != 0) { int family3 = Singleton<SimulationManager>.instance.m_randomizer.Int32(256u); int age3 = Singleton<SimulationManager>.instance.m_randomizer.Int32(0, 240); Citizen.Wealth wealth2 = Citizen.Wealth.High; int num12 = touristFactor0 + touristFactor1 + touristFactor2; if (num12 != 0) { int num13 = Singleton<SimulationManager>.instance.m_randomizer.Int32((uint)num12); if (num13 < touristFactor0) { wealth2 = Citizen.Wealth.Low; } else if (num13 < touristFactor0 + touristFactor1) { wealth2 = Citizen.Wealth.Medium; } } uint num14; if (instance3.CreateCitizen(out num14, age3, family3, ref Singleton<SimulationManager>.instance.m_randomizer)) { Citizen[] expr_D29_cp_0 = instance3.m_citizens.m_buffer; UIntPtr expr_D29_cp_1 = (UIntPtr)num14; expr_D29_cp_0[(int)expr_D29_cp_1].m_flags = (expr_D29_cp_0[(int)expr_D29_cp_1].m_flags | Citizen.Flags.Tourist); Citizen[] expr_D4A_cp_0 = instance3.m_citizens.m_buffer; UIntPtr expr_D4A_cp_1 = (UIntPtr)num14; expr_D4A_cp_0[(int)expr_D4A_cp_1].m_flags = (expr_D4A_cp_0[(int)expr_D4A_cp_1].m_flags | Citizen.Flags.MovingIn); instance3.m_citizens.m_buffer[(int)((UIntPtr)num14)].WealthLevel = wealth2; CitizenInfo citizenInfo3 = instance3.m_citizens.m_buffer[(int)((UIntPtr)num14)].GetCitizenInfo(num14); ushort num15; if (citizenInfo3 != null && instance3.CreateCitizenInstance(out num15, ref Singleton<SimulationManager>.instance.m_randomizer, citizenInfo3, num14)) { citizenInfo3.m_citizenAI.SetSource(num15, ref instance3.m_instances.m_buffer[(int)num15], buildingID); citizenInfo3.m_citizenAI.SetTarget(num15, ref instance3.m_instances.m_buffer[(int)num15], stop, true); instance3.m_citizens.m_buffer[(int)((UIntPtr)num14)].CurrentLocation = Citizen.Location.Moving; StatisticBase statisticBase2 = Singleton<StatisticsManager>.instance.Acquire<StatisticArray>(StatisticType.IncomingTourists); statisticBase2 = statisticBase2.Acquire<StatisticInt32>((int)wealth2, 3); statisticBase2.Add(1); } else { instance3.ReleaseCitizen(num14); } } } } } } if (vehicleInfo != null) { Array16<Vehicle> vehicles = Singleton<VehicleManager>.instance.m_vehicles; ushort num16; if (Singleton<VehicleManager>.instance.CreateVehicle(out num16, ref Singleton<SimulationManager>.instance.m_randomizer, vehicleInfo, data.m_position, material, flag3, !flag3)) { if (flag2) { Vehicle[] expr_E93_cp_0 = vehicles.m_buffer; ushort expr_E93_cp_1 = num16; expr_E93_cp_0[(int)expr_E93_cp_1].m_flags = (expr_E93_cp_0[(int)expr_E93_cp_1].m_flags | Vehicle.Flags.DummyTraffic); Vehicle[] expr_EB2_cp_0 = vehicles.m_buffer; ushort expr_EB2_cp_1 = num16; expr_EB2_cp_0[(int)expr_EB2_cp_1].m_flags = (expr_EB2_cp_0[(int)expr_EB2_cp_1].m_flags & ~Vehicle.Flags.WaitingCargo); } vehicleInfo.m_vehicleAI.SetSource(num16, ref vehicles.m_buffer[(int)num16], buildingID); vehicleInfo.m_vehicleAI.StartTransfer(num16, ref vehicles.m_buffer[(int)num16], material, offer); if (!flag2) { ushort building4 = offer.Building; if (building4 != 0) { int amount; int num17; vehicleInfo.m_vehicleAI.GetSize(num16, ref vehicles.m_buffer[(int)num16], out amount, out num17); if (!flag3) { OutsideConnectionAI.ImportResource(building4, ref Singleton<BuildingManager>.instance.m_buildings.m_buffer[(int)building4], material, amount); } } } } } return true; } // end } }
61.345257
256
0.481607
[ "Apache-2.0" ]
WhitefangGreytail/WG_CitizenEdit
WG_CitizenEdit/Code/AI/NewOutsideConnectionAI.cs
39,447
C#
using Newtonsoft.Json; namespace BaiduBce.CFC.Demo { public class InvokeEvent { [JsonProperty(PropertyName = "event")] public string Event { get; set; } } }
23.625
49
0.619048
[ "Apache-2.0" ]
bcelabs/bce-sam-cli
bsamcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/InvokeEvent.cs
189
C#
using GraphQLParser.AST; using Shouldly; using Xunit; namespace GraphQLParser.Tests { public class Issue82 { private readonly string _query = @"query($username: String) { Person(uname: $username, firstName: ""Pete"") { id, email } } "; [Theory] [InlineData(IgnoreOptions.None)] [InlineData(IgnoreOptions.Comments)] [InlineData(IgnoreOptions.Locations)] [InlineData(IgnoreOptions.All)] public void Parse_Named_And_Literal_Variables(IgnoreOptions options) { using var document = _query.Parse(new ParserOptions { Ignore = options }); var def = document.Definitions[0] as GraphQLOperationDefinition; def.VariableDefinitions.Count.ShouldBe(1); def.VariableDefinitions[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("String"); def.VariableDefinitions[0].Variable.Name.Value.ShouldBe("username"); var selection = def.SelectionSet.Selections[0].ShouldBeAssignableTo<GraphQLField>(); selection.Arguments.Count.ShouldBe(2); selection.Arguments[0].Value.ShouldBeAssignableTo<GraphQLVariable>().Name.Value.ShouldBe("username"); selection.Arguments[1].Value.ShouldBeAssignableTo<GraphQLScalarValue>().Value.ShouldBe("Pete"); } } }
36.378378
115
0.677563
[ "MIT" ]
graphql-dotnet/parser
src/GraphQLParser.Tests/Issue82.cs
1,346
C#
using System; using System.Windows; using System.Windows.Input; using System.Windows.Interactivity; using Plainion.Flames.Presentation; using Plainion.Flames.Controls; namespace Plainion.Flames.Behaviors { public class ZoomOnMouseWheelBehavior : Behavior<FlameView> { public TimelineViewport TimelineViewport { get { return ( TimelineViewport )GetValue( TimelineViewportProperty ); } set { SetValue( TimelineViewportProperty, value ); } } public static readonly DependencyProperty TimelineViewportProperty = DependencyProperty.Register( "TimelineViewport", typeof( TimelineViewport ), typeof( ZoomOnMouseWheelBehavior ), new FrameworkPropertyMetadata( null ) ); protected override void OnAttached() { base.OnAttached(); AssociatedObject.PreviewMouseWheel += OnMouseWheel; } private void OnMouseWheel( object sender, MouseWheelEventArgs e ) { var timePos = TimelineViewport.CalculateTime(AssociatedObject.ActualWidth, ( int )e.GetPosition( AssociatedObject ).X ); var scale = Math.Sign( e.Delta ) * 0.1; var deltaLeft = ( timePos - TimelineViewport.Start ) * scale; var deltaRight = ( TimelineViewport.End - timePos ) * scale; var min = ( long )Math.Max( TimelineViewport.Min, TimelineViewport.Start + deltaLeft ); var max = ( long )Math.Min( TimelineViewport.Max, TimelineViewport.End - deltaRight ); TimelineViewport.Set( min, max ); e.Handled = true; } protected override void OnDetaching() { AssociatedObject.PreviewMouseWheel -= OnMouseWheel; base.OnDetaching(); } } }
36.039216
154
0.633297
[ "BSD-3-Clause" ]
plainionist/Plainion.Flames
src/Plainion.Flames/Behaviors/ZoomOnMouseWheelBehavior.cs
1,840
C#
using System.Security.Claims; using Microsoft.Extensions.Logging; using TNO.Entities; namespace TNO.DAL.Services; public class SourceActionService : BaseService<SourceAction, int>, ISourceActionService { #region Properties #endregion #region Constructors public SourceActionService(TNOContext dbContext, ClaimsPrincipal principal, IServiceProvider serviceProvider, ILogger<SourceActionService> logger) : base(dbContext, principal, serviceProvider, logger) { } #endregion #region Methods public IEnumerable<SourceAction> FindAll() { return this.Context.SourceActions.OrderBy(a => a.SortOrder).ThenBy(a => a.Name).ToArray(); } #endregion }
27.92
204
0.747851
[ "Apache-2.0" ]
Fosol/TNO
libs/net/dal/Services/SourceActionService.cs
698
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.IO; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.Common.Core; using Microsoft.Common.Core.IO; namespace Microsoft.R.Platform.Host { public sealed class BrokerExecutableLocator { public const string BrokerName = "Microsoft.R.Host.Broker.dll"; public const string HostName = "Microsoft.R.Host"; private readonly IFileSystem _fs; private readonly OSPlatform _platform; public static BrokerExecutableLocator Create(IFileSystem fs) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return new BrokerExecutableLocator(fs, OSPlatform.Windows); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return new BrokerExecutableLocator(fs, OSPlatform.OSX); } return new BrokerExecutableLocator(fs, OSPlatform.Linux); } public BrokerExecutableLocator(IFileSystem fs, OSPlatform platform) { _fs = fs; _platform = platform; BaseDirectory = Path.GetDirectoryName(typeof(BrokerExecutableLocator).GetTypeInfo().Assembly.GetAssemblyPath()); } public string BaseDirectory { get; } public string GetBrokerExecutablePath() { var path = Path.Combine(BaseDirectory, BrokerName); return _fs.FileExists(path) ? path : null; } public string GetHostExecutablePath() { var path = Path.Combine(BaseDirectory, GetHostMultiplatformSubPath()); return _fs.FileExists(path) ? path : null; } private string GetHostMultiplatformSubPath() { string folder; var ext = string.Empty; if(_platform == OSPlatform.Windows) { folder = "Windows"; ext = ".exe"; } else if(_platform == OSPlatform.OSX) { folder = "Mac"; } else { folder = "Linux"; } return Path.Combine("Host", folder, HostName + ext); } } }
36.704918
124
0.623493
[ "MIT" ]
M3Supreme45/vscode-r
src/R/Platform/Impl/Host/BrokerExecutableLocator.cs
2,241
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Oracle.DataAccess.Client; namespace OrionEscritorio { class TTest { public int ingresarTest(Test test) { int resp = 0; OracleConnection conexion = Conexion.abrirConexion(); OracleCommand orden = new OracleCommand(string.Format("INSERT INTO TEST(DATO_QLO) VALUES('{0}')", test.datoqlo), conexion); resp = orden.ExecuteNonQuery(); conexion.Close(); return resp; } public static List<Test> listarTest() { List<Test> lista = new List<Test>(); OracleConnection conexion = Conexion.abrirConexion();//Singleton OracleCommand orden = new OracleCommand(string.Format("SELECT * FROM TEST"), conexion); OracleDataReader lector = orden.ExecuteReader(); while (lector.Read()) { Test test = new Test(); test.datoqlo = lector.GetString(0); lista.Add(test); } return lista; } public int modificarTest(Test test) { int resp = 0; OracleConnection conexion = Conexion.abrirConexion();//Singleton OracleCommand orden = new OracleCommand(string.Format("UPDATE TEST SET DATO_QLO='{0}' WHERE DATO_QLO='{0}'", test.datoqlo), conexion); resp = orden.ExecuteNonQuery(); conexion.Close(); return resp; } public int eliminarTest(string dato) { int resp = 0; OracleConnection conexion = Conexion.abrirConexion();//Singleton OracleCommand orden = new OracleCommand(string.Format("DELETE FROM TEST WHERE DATO_QLO='{0}'", dato), conexion); resp = orden.ExecuteNonQuery(); conexion.Close(); return resp; } //Queries public Test buscarTest(string dato) { Test test = new Test(); OracleConnection conexion = Conexion.abrirConexion(); OracleCommand orden = new OracleCommand(String.Format("SELECT * FROM TEST WHERE DATO_QLO='{0}'", test.datoqlo), conexion); OracleDataReader lector = orden.ExecuteReader(); if (lector.Read()) { test.datoqlo = lector.GetString(0); } conexion.Close(); return test; } }//Class }
33.302632
146
0.568155
[ "MIT" ]
Portafolio-titulo2017-Grupo3/Sistema_escritorio_NET
OrionEscritorio/OrionEscritorio/TTest.cs
2,533
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: AssemblyTitle("Clarity.Native.Linux")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Clarity.Native.Linux")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8c5acdc5-bd0b-4c15-b730-38f88e95f2d2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.166667
84
0.74163
[ "MIT" ]
Zulkir/ClarityWorlds
Source/Clarity.Native.Linux/Properties/AssemblyInfo.cs
1,377
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("FryQuotes")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("FryQuotes")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2f9446bb-d99a-4ed1-98bf-a0801181d806")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.081081
84
0.747339
[ "Apache-2.0" ]
kibmcz/SharpIRC
SharpIRC/plugins/FryQuotes/Properties/AssemblyInfo.cs
1,412
C#
namespace ShoppingCartStore.Services.DataServices { using ShoppingCartStore.Models; using System.Threading.Tasks; public interface ICustomerService { Task SubtractBalance(decimal amount, Customer customer); } }
21.909091
64
0.738589
[ "MIT" ]
raulerivassanz/ShoppingCartStore
src/Services/ShoppingCartStore.Services.DataServices/ICustomerService.cs
243
C#
using System; using System.Threading.Tasks; namespace Razensoft.Functional { public static partial class AsyncResultExtensionsBothOperands { /// <summary> /// Executes the given action if the calling result is a success and condition is true. Returns the calling result. /// </summary> public static Task<Result> TapIf(this Task<Result> resultTask, bool condition, Func<Task> func) { if (condition) return resultTask.Tap(func); else return resultTask; } /// <summary> /// Executes the given action if the calling result is a success and condition is true. Returns the calling result. /// </summary> public static Task<Result<T>> TapIf<T>(this Task<Result<T>> resultTask, bool condition, Func<Task> func) { if (condition) return resultTask.Tap(func); else return resultTask; } /// <summary> /// Executes the given action if the calling result is a success and condition is true. Returns the calling result. /// </summary> public static Task<Result<T>> TapIf<T>(this Task<Result<T>> resultTask, bool condition, Func<T, Task> func) { if (condition) return resultTask.Tap(func); else return resultTask; } /// <summary> /// Executes the given action if the calling result is a success and condition is true. Returns the calling result. /// </summary> public static Task<Result<T, E>> TapIf<T, E>(this Task<Result<T, E>> resultTask, bool condition, Func<Task> func) { if (condition) return resultTask.Tap(func); else return resultTask; } /// <summary> /// Executes the given action if the calling result is a success and condition is true. Returns the calling result. /// </summary> public static Task<Result<T, E>> TapIf<T, E>(this Task<Result<T, E>> resultTask, bool condition, Func<T, Task> func) { if (condition) return resultTask.Tap(func); else return resultTask; } /// <summary> /// Executes the given action if the calling result is a success and condition is true. Returns the calling result. /// </summary> public static async Task<Result<T>> TapIf<T>(this Task<Result<T>> resultTask, Func<T, bool> predicate, Func<Task> func) { Result<T> result = await resultTask.DefaultAwait(); if (result.IsSuccess && predicate(result.Value)) return await result.Tap(func).DefaultAwait(); else return result; } /// <summary> /// Executes the given action if the calling result is a success and condition is true. Returns the calling result. /// </summary> public static async Task<Result<T>> TapIf<T>(this Task<Result<T>> resultTask, Func<T, bool> predicate, Func<T, Task> func) { Result<T> result = await resultTask.DefaultAwait(); if (result.IsSuccess && predicate(result.Value)) return await result.Tap(func).DefaultAwait(); else return result; } /// <summary> /// Executes the given action if the calling result is a success and condition is true. Returns the calling result. /// </summary> public static async Task<Result<T, E>> TapIf<T, E>(this Task<Result<T, E>> resultTask, Func<T, bool> predicate, Func<Task> func) { Result<T, E> result = await resultTask.DefaultAwait(); if (result.IsSuccess && predicate(result.Value)) return await result.Tap(func).DefaultAwait(); else return result; } /// <summary> /// Executes the given action if the calling result is a success and condition is true. Returns the calling result. /// </summary> public static async Task<Result<T, E>> TapIf<T, E>(this Task<Result<T, E>> resultTask, Func<T, bool> predicate, Func<T, Task> func) { Result<T, E> result = await resultTask.DefaultAwait(); if (result.IsSuccess && predicate(result.Value)) return await result.Tap(func).DefaultAwait(); else return result; } } }
39.560345
139
0.570495
[ "MIT" ]
Razenpok/Razensoft.Functional
src/Razensoft.Functional/Runtime/Result/Extensions/TapIfAsyncBoth.cs
4,589
C#
namespace SharpHook.Internal; using System; using System.Runtime.CompilerServices; internal static class HashCodeUtil { #if !NETCOREAPP3_0_OR_GREATER private const int HashStart = unchecked((int)2166136261); private const int HashMultiplier = 16777619; #endif [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetHashCode<T1, T2, T3>(T1 value1, T2 value2, T3 value3) { #if NETCOREAPP3_0_OR_GREATER return HashCode.Combine(value1, value2, value3); #else unchecked { int hash = HashStart; hash = (hash * HashMultiplier) ^ value1?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value2?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value3?.GetHashCode() ?? 0; return hash; } #endif } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetHashCode<T1, T2, T3, T4>(T1 value1, T2 value2, T3 value3, T4 value4) { #if NETCOREAPP3_0_OR_GREATER return HashCode.Combine(value1, value2, value3, value4); #else unchecked { int hash = HashStart; hash = (hash * HashMultiplier) ^ value1?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value2?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value3?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value4?.GetHashCode() ?? 0; return hash; } #endif } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetHashCode<T1, T2, T3, T4, T5>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) { #if NETCOREAPP3_0_OR_GREATER return HashCode.Combine(value1, value2, value3, value4, value5); #else unchecked { int hash = HashStart; hash = (hash * HashMultiplier) ^ value1?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value2?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value3?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value4?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value5?.GetHashCode() ?? 0; return hash; } #endif } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetHashCode<T1, T2, T3, T4, T5, T6, T7>( T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) { #if NETCOREAPP3_0_OR_GREATER return HashCode.Combine(value1, value2, value3, value4, value5, value6, value7); #else unchecked { int hash = HashStart; hash = (hash * HashMultiplier) ^ value1?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value2?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value3?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value4?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value5?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value6?.GetHashCode() ?? 0; hash = (hash * HashMultiplier) ^ value7?.GetHashCode() ?? 0; return hash; } #endif } }
34.284211
110
0.594412
[ "MIT" ]
Luxusio/SharpHook
SharpHook/Internal/HashCodeUtil.cs
3,257
C#
using System; using System.Reflection; using Terraria; namespace TerrariaOverhaul.Common.Seasons { // Replaces rain with snow public sealed class SnowSeasonComponent : SeasonComponent { private static Action<SceneMetrics, int> snowTileCountSetter; public override void Load() { base.Load(); snowTileCountSetter = (Action<SceneMetrics, int>)typeof(SceneMetrics) .GetProperty(nameof(SceneMetrics.SnowTileCount), BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) .SetMethod .CreateDelegate(typeof(Action<SceneMetrics, int>)); On.Terraria.Main.snowing += orig => WrapCall(() => orig()); On.Terraria.Rain.NewRain += (orig, position, velocity) => { int result = 0; WrapCall(() => { result = orig(position, velocity); }); return result; }; } public override void Unload() { snowTileCountSetter = null; } private static void WrapCall(Action action) { if (!SeasonSystem.CurrentSeason.Components.Has<SnowSeasonComponent>() || snowTileCountSetter == null) { action(); return; } var sceneMetrics = Main.SceneMetrics; int originalSnowCount = sceneMetrics.SnowTileCount; try { snowTileCountSetter(sceneMetrics, SceneMetrics.SnowTileMax); action(); } finally { snowTileCountSetter(sceneMetrics, originalSnowCount); } } } }
23.033898
122
0.700515
[ "MIT" ]
JaksonD/TerrariaOverhaul
Common/Seasons/_Components/SnowSeasonComponent.cs
1,361
C#
//Copyright (C) 2005 Richard J. Northedge // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //This file is based on the Pair.java source file found in the //original java implementation of OpenNLP. That source file contains the following header: // Copyright (C) 2002 Jason Baldridge and Gann Bierner // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. using System; namespace OpenNLP.Tools.Util { /// <summary> /// Dinky class to package pairs of things /// </summary> public sealed class Pair<A, B> { private A mFirst; private B mSecond; /// <summary> /// Value of the first object in the Pair. /// </summary> public A FirstValue { get { return mFirst; } } /// <summary> /// Value of the second object in the Pair. /// </summary> public B SecondValue { get { return mSecond; } } /// <summary> /// Constructor for the Pair object. /// </summary> /// <param name="first"> /// First object to add to the Pair. /// </param> /// <param name="second"> /// Second object to add to the Pair. /// </param> public Pair(A first, B second) { mFirst = first; mSecond = second; } /// <summary> /// Lists the values of the Pair object. /// </summary> /// <returns> /// String value. /// </returns> public override string ToString() { return "[" + mFirst.ToString() + "/" + mSecond.ToString() + "]"; } } }
29.824742
92
0.659523
[ "MIT" ]
arghyabiswas/bnlp
DBNLP/OpenNLP/Tools/Util/Pair.cs
2,893
C#
/* * Copyright © 2017-2018 Cloudveil Technology Inc. * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; namespace CloudVeil.IPC.Messages { /// <summary> /// The ServerUpdateQueryMessage class represents an IPC communication between server (Service) /// and client (GUI) about application updates. This message is sent exclusively by the server /// with information about an available update. The update in question will only be installed if /// a response is received from the client accepting the update in question. /// </summary> [Serializable] public class ServerUpdateQueryMessage : ServerOnlyMessage { /// <summary> /// The update title. /// </summary> public string Title { get; private set; } /// <summary> /// The update HTML body. This will usually be release notes in HTML format. /// </summary> public string HtmlBody { get; private set; } /// <summary> /// The current application version string. /// </summary> public string CurrentVersionString { get; private set; } /// <summary> /// The application version post-update, if accepted. /// </summary> public string NewVersionString { get; private set; } public bool IsRestartRequired { get; private set; } /// <summary> /// Constructs a new ServerUpdateQueryMessage instance. /// </summary> /// <param name="title"> /// The update title. /// </param> /// <param name="htmlBody"> /// The update HTML body. This will usually be release notes in HTML format. /// </param> /// <param name="currentVersionString"> /// The current application version string. /// </param> /// <param name="newVersionString"> /// The application version post-update, if accepted. /// </param> public ServerUpdateQueryMessage(string title, string htmlBody, string currentVersionString, string newVersionString, bool isRestartRequired) { Title = title; HtmlBody = htmlBody; CurrentVersionString = currentVersionString; NewVersionString = newVersionString; IsRestartRequired = isRestartRequired; } } }
31.034483
148
0.575185
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
cloudveiltech/Filter-Windows
Filter.Platform.Common/IPC/Messages/ServerUpdateQueryMessage.cs
2,703
C#
namespace Learning.Portfolio { public class Fund { public string Id { get; private set; } public string Name { get; private set; } public string Code { get; private set; } public Fund(string id, string name, string code) { Id = id; Name = name; Code = code; } } }
24.928571
58
0.527221
[ "Unlicense" ]
alex-piccione/learning.AWS
src/Functions/Portfolio/Entities/Fund.cs
349
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.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers { internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider { private class State { public TextSpan TextSpan { get; private set; } public IMethodSymbol MatchingConstructor { get; private set; } public IMethodSymbol DelegatedConstructor { get; private set; } public INamedTypeSymbol ContainingType { get; private set; } public ImmutableArray<ISymbol> SelectedMembers { get; private set; } public ImmutableArray<IParameterSymbol> Parameters { get; private set; } public bool IsContainedInUnsafeType { get; private set; } public static async Task<State> TryGenerateAsync( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, textSpan, containingType, selectedMembers, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { if (!selectedMembers.All(IsWritableInstanceFieldOrProperty)) { return false; } SelectedMembers = selectedMembers; ContainingType = containingType; TextSpan = textSpan; if (ContainingType == null || ContainingType.TypeKind == TypeKind.Interface) { return false; } IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(containingType); var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); Parameters = DetermineParameters(selectedMembers, rules); MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(ContainingType, Parameters); // We are going to create a new contructor and pass part of the parameters into DelegatedConstructor, // so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated. DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(ContainingType, Parameters); return true; } private static IMethodSymbol GetDelegatedConstructorBasedOnParameterTypes( INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters) { var q = from c in containingType.InstanceConstructors orderby c.Parameters.Length descending where c.Parameters.Length > 0 && c.Parameters.Length < parameters.Length where c.Parameters.All(p => p.RefKind == RefKind.None) && !c.Parameters.Any(p => p.IsParams) let constructorTypes = c.Parameters.Select(p => p.Type) let symbolTypes = parameters.Take(c.Parameters.Length).Select(p => p.Type) where constructorTypes.SequenceEqual(symbolTypes, SymbolEqualityComparer.Default) select c; return q.FirstOrDefault(); } private static IMethodSymbol GetMatchingConstructorBasedOnParameterTypes(INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters) => containingType.InstanceConstructors.FirstOrDefault(c => MatchesConstructorBasedOnParameterTypes(c, parameters)); private static bool MatchesConstructorBasedOnParameterTypes(IMethodSymbol constructor, ImmutableArray<IParameterSymbol> parameters) => parameters.Select(p => p.Type).SequenceEqual(constructor.Parameters.Select(p => p.Type)); } } }
49.653465
162
0.647458
[ "MIT" ]
IanKemp/roslyn
src/Features/Core/Portable/GenerateConstructorFromMembers/AbstractGenerateConstructorFromMembersCodeRefactoringProvider.State.cs
5,017
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Cofoundry.Domain.Data; namespace Cofoundry.Domain { /// <summary> /// Simple mapper for mapping to RoleDetails objects. /// </summary> public interface IRoleDetailsMapper { /// <summary> /// Maps an EF Role record from the db into an RoleDetails /// object. If the db record is null then null is returned. /// </summary> /// <param name="dbRole">Role record from the database.</param> RoleDetails Map(Role dbRole); } }
26.782609
71
0.652597
[ "MIT" ]
BOBO41/cofoundry
src/Cofoundry.Domain/Domain/Roles/Mapping/IRoleDetailsMapper.cs
618
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iotevents-data-2018-10-23.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.IoTEventsData.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.IoTEventsData.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for BatchPutMessage operation /// </summary> public class BatchPutMessageResponseUnmarshaller : 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) { BatchPutMessageResponse response = new BatchPutMessageResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("BatchPutMessageErrorEntries", targetDepth)) { var unmarshaller = new ListUnmarshaller<BatchPutMessageErrorEntry, BatchPutMessageErrorEntryUnmarshaller>(BatchPutMessageErrorEntryUnmarshaller.Instance); response.BatchPutMessageErrorEntries = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("InternalFailureException")) { return new InternalFailureException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException")) { return new InvalidRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException")) { return new ServiceUnavailableException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException")) { return new ThrottlingException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonIoTEventsDataException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static BatchPutMessageResponseUnmarshaller _instance = new BatchPutMessageResponseUnmarshaller(); internal static BatchPutMessageResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static BatchPutMessageResponseUnmarshaller Instance { get { return _instance; } } } }
41.938053
174
0.67145
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/IoTEventsData/Generated/Model/Internal/MarshallTransformations/BatchPutMessageResponseUnmarshaller.cs
4,739
C#
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Sensus.Adaptation { public enum SensingAgentState { /// <summary> /// The <see cref="SensingAgent"/> is neither observing data nor controlling sensing. /// </summary> Idle, /// <summary> /// The <see cref="SensingAgent"/> is observing data opportunistically through normal /// operation of the <see cref="IProtocol"/> when the <see cref="SensingAgent"/> is /// in the <see cref="Idle"/> state. /// </summary> OpportunisticObservation, /// <summary> /// The <see cref="SensingAgent"/> is controlling sensing in response to data observed /// during <see cref="OpportunisticObservation"/>. /// </summary> OpportunisticControl, /// <summary> /// The <see cref="SensingAgent"/> is actively observing to determine whether <see cref="ActiveControl"/> is desired. /// </summary> ActiveObservation, /// <summary> /// The <see cref="SensingAgent"/> is controlling sensing in response to <see cref="ActiveObservation"/>. /// </summary> ActiveControl, /// <summary> /// The <see cref="SensingAgent"/> is ending sensing control (either <see cref="OpportunisticControl"/> or <see cref="ActiveControl"/>). /// </summary> EndingControl } }
38.403846
144
0.639459
[ "Apache-2.0" ]
MatthewGerber/sensus
Sensus.Shared.NuGet/Adaptation/SensingAgentState.cs
1,999
C#
using System.Web; using System.Web.Mvc; namespace api_loja0001 { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
18.928571
80
0.656604
[ "MIT" ]
wesley2018/api_loja0001
api_loja0001/api_loja0001/App_Start/FilterConfig.cs
267
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.ResourceGroups")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Resource Groups. AWS Resource Groups lets you search and group AWS resources from multiple services based on their tags.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Resource Groups. AWS Resource Groups lets you search and group AWS resources from multiple services based on their tags.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWS Resource Groups. AWS Resource Groups lets you search and group AWS resources from multiple services based on their tags.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWS Resource Groups. AWS Resource Groups lets you search and group AWS resources from multiple services based on their tags.")] #elif CORECLR [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (CoreCLR)- AWS Resource Groups. AWS Resource Groups lets you search and group AWS resources from multiple services based on their tags.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.1.3")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
47.385965
207
0.768974
[ "Apache-2.0" ]
GitGaby/aws-sdk-net
sdk/src/Services/ResourceGroups/Properties/AssemblyInfo.cs
2,701
C#
// Copyright 2010-2011 Green Code LLC // All rights reserved. // // The copyright holders license this file under the New (3-clause) BSD // License (the "License"). You may not use this file except in // compliance with the License. A copy of the License is available at // // http://www.opensource.org/licenses/BSD-3-Clause // // and is included in the NOTICE.txt file distributed with this work. // // Contributors: // James Domingo, Green Code LLC using Landis.SpatialModeling; using OSGeo.GDAL; using System; using System.Collections.Generic; namespace Landis.RasterIO.Gdal { public class RasterFactory : IConfigurableRasterFactory { private IDictionary<string, Driver> extToDriver; //--------------------------------------------------------------------- static RasterFactory() { GdalSystem.Initialize(); } //--------------------------------------------------------------------- public RasterFactory () { extToDriver = new Dictionary<string, Driver>(StringComparer.InvariantCultureIgnoreCase); } //--------------------------------------------------------------------- public RasterFormat GetFormat(string code) { if (code == null) throw new ArgumentNullException(); Driver driver = OSGeo.GDAL.Gdal.GetDriverByName(code); if (driver == null) return null; bool canWrite = driver.GetMetadataItem("DCAP_CREATE", "") == "YES"; return new RasterFormat(driver.ShortName, driver.LongName, canWrite); } //--------------------------------------------------------------------- public void BindExtensionToFormat(string fileExtension, RasterFormat format) { if (fileExtension == null) throw new ArgumentNullException("fileExtension"); if (fileExtension.Length == 0 || fileExtension[0] != '.') throw new ArgumentException("fileExtension does not start with a period"); if (format == null) { extToDriver.Remove(fileExtension); } else { Driver driver = OSGeo.GDAL.Gdal.GetDriverByName(format.Code); if (driver == null) throw new ArgumentException(string.Format("Unknown format code: \"{0}\"", format.Code)); extToDriver[fileExtension] = driver; } } //--------------------------------------------------------------------- public IInputRaster<TPixel> OpenRaster<TPixel>(string path) where TPixel : Pixel, new() { return new GdalInputRaster<TPixel>(path); } //--------------------------------------------------------------------- public IOutputRaster<TPixel> CreateRaster<TPixel>(string path, Dimensions dimensions) where TPixel : Pixel, new() { // Fetch extension from path. // Get the GDAL driver associated with that extension. string extension = System.IO.Path.GetExtension(path); if (extension == null) throw new ArgumentNullException("path"); if (extension == string.Empty) throw new ArgumentException("path has no extension"); Driver driver; if (! extToDriver.TryGetValue(extension, out driver)) throw new ApplicationException(string.Format("Unknown file extension: \"{0}\"", extension)); return new GdalOutputRaster<TPixel>(path, dimensions, driver); } } }
37.6
109
0.488095
[ "Apache-2.0" ]
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
src/RasterIO.Gdal/RasterFactory.cs
3,948
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using NuKeeper.Abstractions.CollaborationModels; using NuKeeper.Abstractions.CollaborationPlatform; using NuKeeper.Abstractions.Configuration; using NuKeeper.Abstractions.Logging; using NuKeeper.BitBucket.Models; using Repository = NuKeeper.Abstractions.CollaborationModels.Repository; using User = NuKeeper.Abstractions.CollaborationModels.User; namespace NuKeeper.BitBucket { public class BitbucketPlatform : ICollaborationPlatform { private readonly INuKeeperLogger _logger; private BitbucketRestClient _client; private AuthSettings _settings; public BitbucketPlatform(INuKeeperLogger logger) { _logger = logger; } public void Initialise(AuthSettings settings) { _settings = settings; var httpClient = new HttpClient { BaseAddress = settings.ApiBase }; _client = new BitbucketRestClient(httpClient, _logger, settings.Username, settings.Token); } public Task<User> GetCurrentUser() { return Task.FromResult(new User(_settings.Username, "", "")); } public async Task OpenPullRequest(ForkData target, PullRequestRequest request, IEnumerable<string> labels) { var repo = await _client.GetGitRepository(target.Owner, target.Name); var req = new PullRequest { title = request.Title, source = new Source { branch = new Branch { name = request.Head } }, destination = new Source { branch = new Branch { name = request.BaseRef } }, description = request.Body }; await _client.CreatePullRequest(req, target.Owner, repo.name); } public async Task<IReadOnlyList<Organization>> GetOrganizations() { var projects = await _client.GetProjects(_settings.Username); return projects .Select(project => new Organization(project.name)) .ToList(); } public async Task<IReadOnlyList<Repository>> GetRepositoriesForOrganisation(string projectName) { var repos = await _client.GetGitRepositories(projectName); return repos.Select(MapRepository) .ToList(); } public async Task<Repository> GetUserRepository(string projectName, string repositoryName) { var repo = await _client.GetGitRepository(projectName, repositoryName); if (repo == null) return default; return MapRepository(repo); } public Task<Repository> MakeUserFork(string owner, string repositoryName) { throw new NotImplementedException(); } public async Task<bool> RepositoryBranchExists(string projectName, string repositoryName, string branchName) { var repo = await _client.GetGitRepository(projectName, repositoryName); var refs = await _client.GetRepositoryRefs(projectName, repo.name); var count = refs.Count(x => x.Name.Equals(branchName, StringComparison.OrdinalIgnoreCase)); if (count > 0) { _logger.Detailed($"Branch found for {projectName} / {repositoryName} / {branchName}"); return true; } _logger.Detailed($"No branch found for {projectName} / {repositoryName} / {branchName}"); return false; } public Task<SearchCodeResult> Search(SearchCodeRequest search) { throw new NotImplementedException(); } private static Repository MapRepository(BitBucket.Models.Repository repo) { return new Repository(repo.name, false, new UserPermissions(true, true, true), new Uri(repo.links.clone.First(x => x.name == "https").href), new Uri(repo.links.html.href), null, false, null); } } }
35.136
116
0.589481
[ "Apache-2.0" ]
markkemper1/NuKeeper
NuKeeper.BitBucket/BitbucketPlatform.cs
4,392
C#
using System; using System.ComponentModel.Composition; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; using Paket.VisualStudio.IntelliSense.Classifier; namespace Paket.VisualStudio.IntelliSense { [Export(typeof(IVsTextViewCreationListener))] [ContentType(PaketDependenciesFileContentType.ContentType)] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal sealed class PaketDependenciesCompletionController : IVsTextViewCreationListener { [Import] internal IVsEditorAdaptersFactoryService AdaptersFactory; [Import] internal ICompletionBroker CompletionBroker; [Import] internal ITextDocumentFactoryService TextDocumentFactoryService; public void VsTextViewCreated(IVsTextView textViewAdapter) { IWpfTextView view = AdaptersFactory.GetWpfTextView(textViewAdapter); Debug.Assert(view != null); ITextDocument document; if (!TextDocumentFactoryService.TryGetTextDocument(view.TextDataModel.DocumentBuffer, out document)) return; if (!PaketDependenciesClassifierProvider.IsPaketDependenciesFile(document.FilePath)) return; CommandFilter filter = new CommandFilter(view, CompletionBroker); IOleCommandTarget next; ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(filter, out next)); filter.Next = next; } } [Export(typeof(IVsTextViewCreationListener))] [ContentType(PaketReferencesFileContentType.ContentType)] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal sealed class PaketReferencesCompletionController : IVsTextViewCreationListener { [Import] internal IVsEditorAdaptersFactoryService AdaptersFactory; [Import] internal ICompletionBroker CompletionBroker; [Import] internal ITextDocumentFactoryService TextDocumentFactoryService; public void VsTextViewCreated(IVsTextView textViewAdapter) { IWpfTextView view = AdaptersFactory.GetWpfTextView(textViewAdapter); Debug.Assert(view != null); ITextDocument document; if (!TextDocumentFactoryService.TryGetTextDocument(view.TextDataModel.DocumentBuffer, out document)) return; if (!PaketDependenciesClassifierProvider.IsPaketReferencesFile(document.FilePath)) return; CommandFilter filter = new CommandFilter(view, CompletionBroker); IOleCommandTarget next; ErrorHandler.ThrowOnFailure(textViewAdapter.AddCommandFilter(filter, out next)); filter.Next = next; } } internal sealed class CommandFilter : IOleCommandTarget { private ICompletionSession currentSession; public CommandFilter(IWpfTextView textView, ICompletionBroker broker) { currentSession = null; TextView = textView; Broker = broker; } public IWpfTextView TextView { get; private set; } public ICompletionBroker Broker { get; private set; } public IOleCommandTarget Next { get; set; } private static char GetTypeChar(IntPtr pvaIn) { return (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn); } public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { bool handled = false; int hresult = VSConstants.S_OK; // 1. Pre-process if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)nCmdID) { case VSConstants.VSStd2KCmdID.AUTOCOMPLETE: case VSConstants.VSStd2KCmdID.COMPLETEWORD: handled = StartSession(); break; case VSConstants.VSStd2KCmdID.RETURN: handled = Complete(false); break; case VSConstants.VSStd2KCmdID.TAB: handled = Complete(true); break; case VSConstants.VSStd2KCmdID.CANCEL: handled = Cancel(); break; } } if (!handled) hresult = Next.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); if (ErrorHandler.Succeeded(hresult)) { if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)nCmdID) { case VSConstants.VSStd2KCmdID.TYPECHAR: char ch = GetTypeChar(pvaIn); if (ch == ':') Cancel(); else if (!char.IsPunctuation(ch) && !char.IsControl(ch)) StartSession(); else if (currentSession != null) Filter(); break; case VSConstants.VSStd2KCmdID.BACKSPACE: if (currentSession == null) StartSession(); Filter(); break; } } } return hresult; } private void Filter() { if (currentSession == null) return; currentSession.SelectedCompletionSet.SelectBestMatch(); currentSession.SelectedCompletionSet.Recalculate(); } private bool Cancel() { if (currentSession == null) return false; currentSession.Dismiss(); return true; } private bool Complete(bool force) { if (currentSession == null) return false; if (!currentSession.SelectedCompletionSet.SelectionStatus.IsSelected && !force) { currentSession.Dismiss(); return false; } else { currentSession.Commit(); return true; } } private bool StartSession() { if (currentSession != null) return false; SnapshotPoint caret = TextView.Caret.Position.BufferPosition; ITextSnapshot snapshot = caret.Snapshot; if (!Broker.IsCompletionActive(TextView)) { currentSession = Broker.CreateCompletionSession(TextView, snapshot.CreateTrackingPoint(caret, PointTrackingMode.Positive), true); } else { currentSession = Broker.GetSessions(TextView)[0]; } currentSession.Dismissed += (sender, args) => currentSession = null; if (!currentSession.IsStarted) currentSession.Start(); return true; } public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)prgCmds[0].cmdID) { case VSConstants.VSStd2KCmdID.AUTOCOMPLETE: case VSConstants.VSStd2KCmdID.COMPLETEWORD: prgCmds[0].cmdf = (uint)OLECMDF.OLECMDF_ENABLED | (uint)OLECMDF.OLECMDF_SUPPORTED; return VSConstants.S_OK; } } return Next.QueryStatus(pguidCmdGroup, cCmds, prgCmds, pCmdText); } } }
34.219917
112
0.573057
[ "MIT" ]
KinNeko-De/Paket.VisualStudio
src/Paket.VisualStudio/IntelliSense/PaketCompletionController.cs
8,249
C#
namespace Mapsui.Providers.ArcGIS.Dynamic { public class ArcGISLayer { public int id { get; set; } public string name { get; set; } public int parentLayerId { get; set; } public bool defaultVisibility { get; set; } public double minScale { get; set; } public double maxScale { get; set; } public int[] subLayerIds { get; set; } } }
28.571429
51
0.5925
[ "MIT" ]
rgn/stellar-playground
Vendor/Mapsui/Providers/ArcGIS/Dynamic/ArcGISLayer.cs
400
C#
//author: P. Oscar Boykin <boykin@pobox.com> //There is no license on this file because it is so trivial //it can be considered public domain, MIT-X11, or GPLv2 or later if //that is convienient for licensing. using System.Collections.Generic; namespace Brunet.Collections { /** A simple readonly pair class similar to std::pair in C++ */ public class Pair<T0,T1> { public readonly T0 First; public readonly T1 Second; protected int _hc; public Pair(T0 f, T1 s) { First = f; Second = s; _hc = 0; } public override bool Equals(object o) { if( System.Object.ReferenceEquals(o, this) ) { return true; } Pair<T0, T1> op = o as Pair<T0,T1>; if( op == null ) { return false; } bool first = First == null ? op.First == null : First.Equals(op.First); if (false == first) { return false; } //else first is equal, now check second: return Second == null ? op.Second == null : Second.Equals(op.Second); } public override int GetHashCode() { if( _hc == 0 ) { //Make sure null doesn't map 0, else we'd recompute in that common //case _hc = (First != null ? First.GetHashCode() : -1) ^ (Second != null ? Second.GetHashCode() : 0 ); } return _hc; } public object[] ToArray() { return new object[]{ First, Second }; } public override string ToString() { return System.String.Format("Pair({0}, {1})", First, Second); } } /** A simple readonly pair class similar to std::pair in C++ */ public class Triple<T0,T1,T2> { public readonly T0 First; public readonly T1 Second; public readonly T2 Third; protected int _hc; public Triple(T0 f, T1 s, T2 t) { First = f; Second = s; Third = t; _hc = 0; } public override bool Equals(object o) { if( System.Object.ReferenceEquals(o, this) ) { return true; } Triple<T0, T1, T2> op = o as Triple<T0,T1,T2>; if( op == null ) { return false; } bool first = First == null ? op.First == null : First.Equals(op.First); if (false == first) { return false; } //else first is equal, now check second: bool second = Second == null ? op.Second == null : Second.Equals(op.Second); if (false == second) { return false; } //else second is equal, now check third: return Third == null ? op.Third == null : Third.Equals(op.Third); } public override int GetHashCode() { if( _hc == 0 ) { _hc = (First != null ? First.GetHashCode() : -1) ^ (Second != null ? Second.GetHashCode() : 0) ^ (Third != null ? Third.GetHashCode() : 0); } return _hc; } public object[] ToArray() { return new object[]{ First, Second, Third }; } public override string ToString() { return System.String.Format("Triple({0}, {1}, {2})", First, Second, Third); } } }
33.727273
82
0.576819
[ "MIT" ]
hseom/brunet-1
src/Brunet/Collections/Tuple.cs
2,968
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Mechanoid.Parser.CSV")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Mechanoid.Parser.CSV")] [assembly: System.Reflection.AssemblyTitleAttribute("Mechanoid.Parser.CSV")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
42.083333
80
0.651485
[ "MIT" ]
Zandervds/codeGem
Parser/Mechanoid.Parser.CSV/obj/Debug/netcoreapp3.1/Mechanoid.Parser.CSV.AssemblyInfo.cs
1,010
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/urlmon.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System; namespace TerraFX.Interop { public unsafe partial struct CONFIRMSAFETY { [NativeTypeName("CLSID")] public Guid clsid; public IUnknown* pUnk; [NativeTypeName("DWORD")] public uint dwFlags; } }
26
145
0.694139
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/um/urlmon/CONFIRMSAFETY.cs
548
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 iotwireless-2020-11-22.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IoTWireless.Model { /// <summary> /// The LoRaWAN information that is to be returned from getting multicast group information. /// </summary> public partial class LoRaWANMulticastGet { private DlClass _dlClass; private int? _numberOfDevicesInGroup; private int? _numberOfDevicesRequested; private SupportedRfRegion _rfRegion; /// <summary> /// Gets and sets the property DlClass. /// </summary> [AWSProperty(Max=256)] public DlClass DlClass { get { return this._dlClass; } set { this._dlClass = value; } } // Check to see if DlClass property is set internal bool IsSetDlClass() { return this._dlClass != null; } /// <summary> /// Gets and sets the property NumberOfDevicesInGroup. /// </summary> public int NumberOfDevicesInGroup { get { return this._numberOfDevicesInGroup.GetValueOrDefault(); } set { this._numberOfDevicesInGroup = value; } } // Check to see if NumberOfDevicesInGroup property is set internal bool IsSetNumberOfDevicesInGroup() { return this._numberOfDevicesInGroup.HasValue; } /// <summary> /// Gets and sets the property NumberOfDevicesRequested. /// </summary> public int NumberOfDevicesRequested { get { return this._numberOfDevicesRequested.GetValueOrDefault(); } set { this._numberOfDevicesRequested = value; } } // Check to see if NumberOfDevicesRequested property is set internal bool IsSetNumberOfDevicesRequested() { return this._numberOfDevicesRequested.HasValue; } /// <summary> /// Gets and sets the property RfRegion. /// </summary> public SupportedRfRegion RfRegion { get { return this._rfRegion; } set { this._rfRegion = value; } } // Check to see if RfRegion property is set internal bool IsSetRfRegion() { return this._rfRegion != null; } } }
30.291262
109
0.628205
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/IoTWireless/Generated/Model/LoRaWANMulticastGet.cs
3,120
C#
using System; using NUnit.Framework; namespace UnityEditor.ProjectAuditor.EditorTests { class ProjectAuditorTests { [Test] public void ProjectAuditor_IsInstantiated() { Activator.CreateInstance(typeof(Unity.ProjectAuditor.Editor.ProjectAuditor)); } } }
20.666667
89
0.677419
[ "MIT" ]
MikkoHimanka/farmasia-vr
UnityPackages/ProjectAuditor-master/Tests/Editor/ProjectAuditorTests.cs
310
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.RocketMQ.V2.Model { /// <summary> /// Request Object /// </summary> public class ListInstancesRequest { /// <summary> /// 实例状态。 /// </summary> /// <value>实例状态。</value> [JsonConverter(typeof(EnumClassConverter<StatusEnum>))] public class StatusEnum { /// <summary> /// Enum CREATING for value: CREATING /// </summary> public static readonly StatusEnum CREATING = new StatusEnum("CREATING"); /// <summary> /// Enum RUNNING for value: RUNNING /// </summary> public static readonly StatusEnum RUNNING = new StatusEnum("RUNNING"); /// <summary> /// Enum FAULTY for value: FAULTY /// </summary> public static readonly StatusEnum FAULTY = new StatusEnum("FAULTY"); /// <summary> /// Enum RESTARTING for value: RESTARTING /// </summary> public static readonly StatusEnum RESTARTING = new StatusEnum("RESTARTING"); /// <summary> /// Enum RESIZING for value: RESIZING /// </summary> public static readonly StatusEnum RESIZING = new StatusEnum("RESIZING"); /// <summary> /// Enum RESIZING_FAILED for value: RESIZING FAILED /// </summary> public static readonly StatusEnum RESIZING_FAILED = new StatusEnum("RESIZING FAILED"); /// <summary> /// Enum FROZEN for value: FROZEN /// </summary> public static readonly StatusEnum FROZEN = new StatusEnum("FROZEN"); private static readonly Dictionary<string, StatusEnum> StaticFields = new Dictionary<string, StatusEnum>() { { "CREATING", CREATING }, { "RUNNING", RUNNING }, { "FAULTY", FAULTY }, { "RESTARTING", RESTARTING }, { "RESIZING", RESIZING }, { "RESIZING FAILED", RESIZING_FAILED }, { "FROZEN", FROZEN }, }; private string Value; public StatusEnum(string value) { Value = value; } public static StatusEnum FromValue(string value) { if(value == null){ return null; } if (StaticFields.ContainsKey(value)) { return StaticFields[value]; } return null; } public string GetValue() { return Value; } public override string ToString() { return $"{Value}"; } public override int GetHashCode() { return this.Value.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (this.Equals(obj as StatusEnum)) { return true; } return false; } public bool Equals(StatusEnum obj) { if ((object)obj == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value); } public static bool operator ==(StatusEnum a, StatusEnum b) { if (System.Object.ReferenceEquals(a, b)) { return true; } if ((object)a == null) { return false; } return a.Equals(b); } public static bool operator !=(StatusEnum a, StatusEnum b) { return !(a == b); } } /// <summary> /// 是否返回创建失败的实例数。 当参数值为“true”时,返回创建失败的实例数。参数值为“false”或者其他值,不返回创建失败的实例数。 /// </summary> /// <value>是否返回创建失败的实例数。 当参数值为“true”时,返回创建失败的实例数。参数值为“false”或者其他值,不返回创建失败的实例数。</value> [JsonConverter(typeof(EnumClassConverter<IncludeFailureEnum>))] public class IncludeFailureEnum { /// <summary> /// Enum TRUE for value: true /// </summary> public static readonly IncludeFailureEnum TRUE = new IncludeFailureEnum("true"); /// <summary> /// Enum FALSE for value: false /// </summary> public static readonly IncludeFailureEnum FALSE = new IncludeFailureEnum("false"); private static readonly Dictionary<string, IncludeFailureEnum> StaticFields = new Dictionary<string, IncludeFailureEnum>() { { "true", TRUE }, { "false", FALSE }, }; private string Value; public IncludeFailureEnum(string value) { Value = value; } public static IncludeFailureEnum FromValue(string value) { if(value == null){ return null; } if (StaticFields.ContainsKey(value)) { return StaticFields[value]; } return null; } public string GetValue() { return Value; } public override string ToString() { return $"{Value}"; } public override int GetHashCode() { return this.Value.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (this.Equals(obj as IncludeFailureEnum)) { return true; } return false; } public bool Equals(IncludeFailureEnum obj) { if ((object)obj == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value); } public static bool operator ==(IncludeFailureEnum a, IncludeFailureEnum b) { if (System.Object.ReferenceEquals(a, b)) { return true; } if ((object)a == null) { return false; } return a.Equals(b); } public static bool operator !=(IncludeFailureEnum a, IncludeFailureEnum b) { return !(a == b); } } /// <summary> /// 是否按照实例名称进行精确匹配查询。 默认为“false”,表示模糊匹配实例名称查询。若参数值为“true”表示按照实例名称进行精确匹配查询。 /// </summary> /// <value>是否按照实例名称进行精确匹配查询。 默认为“false”,表示模糊匹配实例名称查询。若参数值为“true”表示按照实例名称进行精确匹配查询。</value> [JsonConverter(typeof(EnumClassConverter<ExactMatchNameEnum>))] public class ExactMatchNameEnum { /// <summary> /// Enum TRUE for value: true /// </summary> public static readonly ExactMatchNameEnum TRUE = new ExactMatchNameEnum("true"); /// <summary> /// Enum FALSE for value: false /// </summary> public static readonly ExactMatchNameEnum FALSE = new ExactMatchNameEnum("false"); private static readonly Dictionary<string, ExactMatchNameEnum> StaticFields = new Dictionary<string, ExactMatchNameEnum>() { { "true", TRUE }, { "false", FALSE }, }; private string Value; public ExactMatchNameEnum(string value) { Value = value; } public static ExactMatchNameEnum FromValue(string value) { if(value == null){ return null; } if (StaticFields.ContainsKey(value)) { return StaticFields[value]; } return null; } public string GetValue() { return Value; } public override string ToString() { return $"{Value}"; } public override int GetHashCode() { return this.Value.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (this.Equals(obj as ExactMatchNameEnum)) { return true; } return false; } public bool Equals(ExactMatchNameEnum obj) { if ((object)obj == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value); } public static bool operator ==(ExactMatchNameEnum a, ExactMatchNameEnum b) { if (System.Object.ReferenceEquals(a, b)) { return true; } if ((object)a == null) { return false; } return a.Equals(b); } public static bool operator !=(ExactMatchNameEnum a, ExactMatchNameEnum b) { return !(a == b); } } /// <summary> /// 消息引擎:reliability。 /// </summary> [SDKProperty("engine", IsQuery = true)] [JsonProperty("engine", NullValueHandling = NullValueHandling.Ignore)] public string Engine { get; set; } /// <summary> /// 实例名称。 /// </summary> [SDKProperty("name", IsQuery = true)] [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] public string Name { get; set; } /// <summary> /// 实例ID。 /// </summary> [SDKProperty("instance_id", IsQuery = true)] [JsonProperty("instance_id", NullValueHandling = NullValueHandling.Ignore)] public string InstanceId { get; set; } /// <summary> /// 实例状态。 /// </summary> [SDKProperty("status", IsQuery = true)] [JsonProperty("status", NullValueHandling = NullValueHandling.Ignore)] public StatusEnum Status { get; set; } /// <summary> /// 是否返回创建失败的实例数。 当参数值为“true”时,返回创建失败的实例数。参数值为“false”或者其他值,不返回创建失败的实例数。 /// </summary> [SDKProperty("include_failure", IsQuery = true)] [JsonProperty("include_failure", NullValueHandling = NullValueHandling.Ignore)] public IncludeFailureEnum IncludeFailure { get; set; } /// <summary> /// 是否按照实例名称进行精确匹配查询。 默认为“false”,表示模糊匹配实例名称查询。若参数值为“true”表示按照实例名称进行精确匹配查询。 /// </summary> [SDKProperty("exact_match_name", IsQuery = true)] [JsonProperty("exact_match_name", NullValueHandling = NullValueHandling.Ignore)] public ExactMatchNameEnum ExactMatchName { get; set; } /// <summary> /// 企业项目ID。 /// </summary> [SDKProperty("enterprise_project_id", IsQuery = true)] [JsonProperty("enterprise_project_id", NullValueHandling = NullValueHandling.Ignore)] public string EnterpriseProjectId { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ListInstancesRequest {\n"); sb.Append(" engine: ").Append(Engine).Append("\n"); sb.Append(" name: ").Append(Name).Append("\n"); sb.Append(" instanceId: ").Append(InstanceId).Append("\n"); sb.Append(" status: ").Append(Status).Append("\n"); sb.Append(" includeFailure: ").Append(IncludeFailure).Append("\n"); sb.Append(" exactMatchName: ").Append(ExactMatchName).Append("\n"); sb.Append(" enterpriseProjectId: ").Append(EnterpriseProjectId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as ListInstancesRequest); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(ListInstancesRequest input) { if (input == null) return false; return ( this.Engine == input.Engine || (this.Engine != null && this.Engine.Equals(input.Engine)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.InstanceId == input.InstanceId || (this.InstanceId != null && this.InstanceId.Equals(input.InstanceId)) ) && ( this.Status == input.Status || (this.Status != null && this.Status.Equals(input.Status)) ) && ( this.IncludeFailure == input.IncludeFailure || (this.IncludeFailure != null && this.IncludeFailure.Equals(input.IncludeFailure)) ) && ( this.ExactMatchName == input.ExactMatchName || (this.ExactMatchName != null && this.ExactMatchName.Equals(input.ExactMatchName)) ) && ( this.EnterpriseProjectId == input.EnterpriseProjectId || (this.EnterpriseProjectId != null && this.EnterpriseProjectId.Equals(input.EnterpriseProjectId)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Engine != null) hashCode = hashCode * 59 + this.Engine.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.InstanceId != null) hashCode = hashCode * 59 + this.InstanceId.GetHashCode(); if (this.Status != null) hashCode = hashCode * 59 + this.Status.GetHashCode(); if (this.IncludeFailure != null) hashCode = hashCode * 59 + this.IncludeFailure.GetHashCode(); if (this.ExactMatchName != null) hashCode = hashCode * 59 + this.ExactMatchName.GetHashCode(); if (this.EnterpriseProjectId != null) hashCode = hashCode * 59 + this.EnterpriseProjectId.GetHashCode(); return hashCode; } } } }
31.400763
98
0.467424
[ "Apache-2.0" ]
huaweicloud/huaweicloud-sdk-net
Services/RocketMQ/V2/Model/ListInstancesRequest.cs
17,224
C#
using System.Reflection; using Microsoft.Extensions.DependencyInjection; using Orleans; using Orleans.Runtime; using Tester.StorageFacet.Abstractions; namespace Tester.StorageFacet.Infrastructure { public class ExampleStorageAttributeMapper : IAttributeToFactoryMapper<ExampleStorageAttribute> { private static readonly MethodInfo create = typeof(INamedExampleStorageFactory).GetMethod("Create"); public Factory<IGrainContext, object> GetFactory(ParameterInfo parameter, ExampleStorageAttribute attribute) { IExampleStorageConfig config = attribute; // set state name to parameter name, if not already specified if (string.IsNullOrEmpty(config.StateName)) { config = new ExampleStorageConfig(parameter.Name); } // use generic type args to define collection type. MethodInfo genericCreate = create.MakeGenericMethod(parameter.ParameterType.GetGenericArguments()); object[] args = new object[] {attribute.StorageProviderName, config}; return context => Create(context, genericCreate, args); } private object Create(IGrainContext context, MethodInfo genericCreate, object[] args) { INamedExampleStorageFactory factory = context.ActivationServices.GetRequiredService<INamedExampleStorageFactory>(); return genericCreate.Invoke(factory, args); } } }
43.088235
127
0.70785
[ "MIT" ]
Allen-Xiao/orleans
test/Tester/StorageFacet/Feature.Infrastructure/ExampleStorageAttributeMapper.cs
1,467
C#
namespace MetroDev.Boilerplate.Authorization.Roles { public static class StaticRoleNames { public static class Host { public const string Admin = "Admin"; } public static class Tenants { public const string Admin = "Admin"; } } }
19.6875
50
0.561905
[ "MIT" ]
juanwfer/MetroDev-AbpTest
src/MetroDev.Boilerplate.Core/Authorization/Roles/StaticRoleNames.cs
315
C#
namespace LabCSharp.Resources.Forms { partial class CreateStudent { /// <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.NameBox = new System.Windows.Forms.TextBox(); this.SchoolSelect = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.AddButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // NameBox // this.NameBox.Location = new System.Drawing.Point(13, 125); this.NameBox.Name = "NameBox"; this.NameBox.Size = new System.Drawing.Size(100, 22); this.NameBox.TabIndex = 0; this.NameBox.Enter += new System.EventHandler(this.NameBox_Enter); this.NameBox.Leave += new System.EventHandler(this.NameBox_Leave); // // SchoolSelect // this.SchoolSelect.FormattingEnabled = true; this.SchoolSelect.Location = new System.Drawing.Point(168, 123); this.SchoolSelect.Name = "SchoolSelect"; this.SchoolSelect.Size = new System.Drawing.Size(165, 24); this.SchoolSelect.TabIndex = 1; this.SchoolSelect.Text = "Select school..."; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 22.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.label1.Location = new System.Drawing.Point(50, 36); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(239, 44); this.label1.TabIndex = 2; this.label1.Text = "Add Student"; // // AddButton // this.AddButton.Location = new System.Drawing.Point(12, 174); this.AddButton.Name = "AddButton"; this.AddButton.Size = new System.Drawing.Size(75, 23); this.AddButton.TabIndex = 3; this.AddButton.Text = "Add"; this.AddButton.UseVisualStyleBackColor = true; this.AddButton.Click += new System.EventHandler(this.AddButton_Click); // // CreateStudent // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(345, 209); this.Controls.Add(this.AddButton); this.Controls.Add(this.label1); this.Controls.Add(this.SchoolSelect); this.Controls.Add(this.NameBox); this.Name = "CreateStudent"; this.Text = "CreateStudent"; this.Load += new System.EventHandler(this.CreateStudent_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox NameBox; private System.Windows.Forms.ComboBox SchoolSelect; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button AddButton; } }
33.292929
158
0.698726
[ "MIT" ]
renteadan/map
LabCSharp/Resources/Forms/CreateStudent.Designer.cs
3,298
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (http://www.specflow.org/). // SpecFlow Version:1.9.0.77 // SpecFlow Generator Version:1.9.0.0 // Runtime Version:4.0.30319.17929 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace PicklesDoc.Pickles.Example.Features._01TestRunner { using TechTalk.SpecFlow; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.9.0.77")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [NUnit.Framework.TestFixtureAttribute()] [NUnit.Framework.DescriptionAttribute("The test runner is not (very) important")] public partial class TheTestRunnerIsNotVeryImportantFeature { private static TechTalk.SpecFlow.ITestRunner testRunner; #line 1 "TestRunnerIsNotImportant.feature" #line hidden [NUnit.Framework.TestFixtureSetUpAttribute()] public virtual void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "The test runner is not (very) important", "In order to show that the test runner is just for the autogenerated stuff in Spec" + "Flow\r\nAs a SpecFlow evanglist\r\nI want to be able to call my steps in the same ma" + "nner inspite of the testrunner configured", ProgrammingLanguage.CSharp, ((string[])(null))); testRunner.OnFeatureStart(featureInfo); } [NUnit.Framework.TestFixtureTearDownAttribute()] public virtual void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [NUnit.Framework.SetUpAttribute()] public virtual void TestInitialize() { } [NUnit.Framework.TearDownAttribute()] public virtual void ScenarioTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioStart(scenarioInfo); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("A couple of simple steps")] public virtual void ACoupleOfSimpleSteps() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("A couple of simple steps", ((string[])(null))); #line 6 this.ScenarioSetup(scenarioInfo); #line 7 testRunner.Given("I have step defintions in place", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line 8 testRunner.When("I call a step", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 9 testRunner.Then("the step should have been called", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } } } #pragma warning restore #endregion
39.41573
265
0.624287
[ "Apache-2.0" ]
marcusoftnet/pickles
src/Pickles/Pickles.Example/Features/01TestRunner/TestRunnerIsNotImportant1.feature.cs
3,510
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using TGIS.Web.Entities; using IMIS.Web.DAL; using Atlassian.Connect; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace IMIS.Web.ControllersAPI { [Route("api/PmProjects"), Produces("application/json"), EnableCors("AppPolicy")] public class PmProjectController : Controller { private IMISTestContext _ctx = null; public PmProjectController(IMISTestContext context) { _ctx = context; } // GET: api/PmProjects/GetProjects [HttpGet, Route("GetProjects")] public List<PmProjects> Get() { //var qry = from t in _ctx.PmProjects.Include(a => a.PmIssues) select t; var qry = from t in _ctx.PmProjects .Include(prj => prj.PmProjectEpicLink) .ThenInclude(prjEpic => prjEpic.PmEpic) .Include(ftr => ftr.PmProjectFeaturesLink) .ThenInclude(prjFtr => prjFtr.PmFeature) .Include(iss => iss.PmIssues) select t; return qry.ToList(); } // GET api/PmProjects/GetProjects/5 [HttpGet, Route("GetProjects/{id}")] public List<PmProjects> Get(int id) { var qry = from t in _ctx.PmProjects .Include(prj => prj.PmProjectEpicLink) .ThenInclude(prjEpic => prjEpic.PmEpic) .Include(ftr => ftr.PmProjectFeaturesLink) .ThenInclude(prjFtr => prjFtr.PmFeature) .Include(iss=>iss.PmIssues) select t; return qry.ToList(); } // POST api/PmProjects/PostProjects [HttpPost, Route("PostProjects")] public async Task<object> PostProjects([FromBody]PmProjects model) { return null; } // PUT api/PmProjects/PutProjects/5 [HttpPut, Route("PutProjects/{id}")] public async Task<object> PutProjects(int id, [FromBody]PmProjects model) { return null; } // DELETE api/PmProjects/DeleteProjectsByID/5 [HttpDelete, Route("DeleteProjectsByID/{id}")] public async Task<object> DeleteProjectsByID(int id) { return null; } } }
33.960526
116
0.582332
[ "MIT" ]
jpwits/HorseBetting
Agile/API/PmProjectController.cs
2,583
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Gama.Cooperacion.Wpf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Gama.Cooperacion.Wpf")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42.785714
98
0.707429
[ "MIT" ]
PFC-acl-amg/GamaPFC
GamaPFC/Gama.Cooperacion.Wpf/Properties/AssemblyInfo.cs
2,399
C#
using System.Collections.Generic; namespace SuperRocket.AspNetCoreVue.Authentication.External { public interface IExternalAuthConfiguration { List<ExternalLoginProviderInfo> Providers { get; } } }
21.9
59
0.757991
[ "MIT" ]
dystudio/SuperRocket.AspNetCoreVue
aspnet-core/src/SuperRocket.AspNetCoreVue.Web.Core/Authentication/External/IExternalAuthConfiguration.cs
221
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2018-11-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.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ListInvalidations operation /// </summary> public class ListInvalidationsResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { ListInvalidationsResponse response = new ListInvalidationsResponse(); UnmarshallResult(context,response); return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, ListInvalidationsResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("InvalidationList", targetDepth)) { var unmarshaller = InvalidationListUnmarshaller.Instance; response.InvalidationList = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return; } } return; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDenied")) { return new AccessDeniedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidArgument")) { return new InvalidArgumentException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NoSuchDistribution")) { return new NoSuchDistributionException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonCloudFrontException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static ListInvalidationsResponseUnmarshaller _instance = new ListInvalidationsResponseUnmarshaller(); internal static ListInvalidationsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListInvalidationsResponseUnmarshaller Instance { get { return _instance; } } } }
38.902439
171
0.638245
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/Internal/MarshallTransformations/ListInvalidationsResponseUnmarshaller.cs
4,785
C#
using UnityEngine; using System.Collections; public class CollectibleController : MonoBehaviour { public float speed = 1.0f; private GameObject pickUpFX; void Start() { pickUpFX = transform.FindChild("MagicEffect1").gameObject; } void Update() { transform.FindChild("Diamond").transform.Rotate (new Vector3(0, 30, 0) * speed * Time.deltaTime); // TODO make slowly bounce } public void PickUp() { GetComponent<AudioSource>().Play(); GetComponent<SphereCollider>().enabled = false; transform.FindChild("Diamond").gameObject.SetActive(false); transform.FindChild("GodRays").gameObject.SetActive(false); transform.FindChild("MagicEffect1").GetComponent<ParticleSystem>().Play(); Invoke("DisablePickUpFx", 1); } private void DisablePickUpFx() { pickUpFX.SetActive(false); } }
22.583333
99
0.731857
[ "MIT" ]
aornelas/Tiny-Planets
Assets/Scripts/CollectibleController.cs
815
C#
using RiotCaller.Api.Cache; using RiotCaller.StatusEndPoints.Shards; using System.Collections.Generic; namespace RiotCaller.Api { public interface IStatusApi { ApiCache Cache { get; } List<Shards> GetShards(); } }
18.769231
40
0.696721
[ "MIT" ]
MSAlih1/RiotApiCaller
RiotCaller/Api/IStatusApi.cs
246
C#
// Copyright (c) Microsoft Corporation.// Licensed under the MIT license. namespace Microsoft.SCIM.WebHostSample.Provider { using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.SCIM; using Microsoft.SCIM.WebHostSample.Resources; public class InMemoryProvider : ProviderBase { private readonly ProviderBase groupProvider; private readonly ProviderBase userProvider; private static readonly Lazy<IReadOnlyCollection<TypeScheme>> TypeSchema = new Lazy<IReadOnlyCollection<TypeScheme>>( () => new TypeScheme[] { SampleTypeScheme.UserTypeSceme, SampleTypeScheme.GroupTypeSceme, SampleTypeScheme.EnterpriseUserTypeScheme }); private static readonly Lazy<IReadOnlyCollection<Core2ResourceType>> Types = new Lazy<IReadOnlyCollection<Core2ResourceType>>( () => new Core2ResourceType[] { SampleResourceTypes.userResourceType, SampleResourceTypes.groupResourceType } ); public InMemoryProvider() { this.groupProvider = new InMemoryGroupProvider(); this.userProvider = new InMemoryUserProvider(); } public override IReadOnlyCollection<Core2ResourceType> ResourceTypes { get { return InMemoryProvider.Types.Value; } } public override IReadOnlyCollection<TypeScheme> Schema { get { return InMemoryProvider.TypeSchema.Value; } } public override Task<Resource> CreateAsync(Resource resource, string correlationIdentifier) { if (resource is Core2EnterpriseUser) { return this.userProvider.CreateAsync(resource, correlationIdentifier); } if (resource is Core2Group) { return this.groupProvider.CreateAsync(resource, correlationIdentifier); } throw new NotImplementedException(); } public override Task DeleteAsync(IResourceIdentifier resourceIdentifier, string correlationIdentifier) { if (resourceIdentifier.SchemaIdentifier.Equals(SchemaIdentifiers.Core2EnterpriseUser)) { return this.userProvider.DeleteAsync(resourceIdentifier, correlationIdentifier); } if (resourceIdentifier.SchemaIdentifier.Equals(SchemaIdentifiers.Core2Group)) { return this.groupProvider.DeleteAsync(resourceIdentifier, correlationIdentifier); } throw new NotImplementedException(); } public override Task<Resource[]> QueryAsync(IQueryParameters parameters, string correlationIdentifier) { if (parameters.SchemaIdentifier.Equals(SchemaIdentifiers.Core2EnterpriseUser)) { return this.userProvider.QueryAsync(parameters, correlationIdentifier); } if (parameters.SchemaIdentifier.Equals(SchemaIdentifiers.Core2Group)) { return this.groupProvider.QueryAsync(parameters, correlationIdentifier); } throw new NotImplementedException(); } public override Task<Resource> ReplaceAsync(Resource resource, string correlationIdentifier) { if (resource is Core2EnterpriseUser) { return this.userProvider.ReplaceAsync(resource, correlationIdentifier); } if (resource is Core2Group) { return this.groupProvider.ReplaceAsync(resource, correlationIdentifier); } throw new NotImplementedException(); } public override Task<Resource> RetrieveAsync(IResourceRetrievalParameters parameters, string correlationIdentifier) { if (parameters.SchemaIdentifier.Equals(SchemaIdentifiers.Core2EnterpriseUser)) { return this.userProvider.RetrieveAsync(parameters, correlationIdentifier); } if (parameters.SchemaIdentifier.Equals(SchemaIdentifiers.Core2Group)) { return this.groupProvider.RetrieveAsync(parameters, correlationIdentifier); } throw new NotImplementedException(); } public override Task UpdateAsync(IPatch patch, string correlationIdentifier) { if (patch == null) { throw new ArgumentNullException(nameof(patch)); } if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.Identifier)) { throw new ArgumentException(nameof(patch)); } if (string.IsNullOrWhiteSpace(patch.ResourceIdentifier.SchemaIdentifier)) { throw new ArgumentException(nameof(patch)); } if (patch.ResourceIdentifier.SchemaIdentifier.Equals(SchemaIdentifiers.Core2EnterpriseUser)) { return this.userProvider.UpdateAsync(patch, correlationIdentifier); } if (patch.ResourceIdentifier.SchemaIdentifier.Equals(SchemaIdentifiers.Core2Group)) { return this.groupProvider.UpdateAsync(patch, correlationIdentifier); } throw new NotImplementedException(); } } }
35.393548
149
0.626322
[ "MIT" ]
MiguelCaldasMS/SCIM
Microsoft.SCIM.WebHostSample/Provider/InMemoryProvider.cs
5,486
C#
// -------------------------------------------------------------------------------------------- // <copyright file="DataLoaderConfigurationKey.cs" company="Effort Team"> // Copyright (C) Effort Team // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // </copyright> // -------------------------------------------------------------------------------------------- namespace Effort.Internal.Caching { using System; using Effort.DataLoaders; /// <summary> /// Represents a key that identifies a data loader configuration. /// </summary> internal class DataLoaderConfigurationKey : IEquatable<DataLoaderConfigurationKey> { /// <summary> /// The type of the data loader. /// </summary> private Type type; /// <summary> /// The argument of the data loader that describes its complete state. /// </summary> private string argument; /// <summary> /// Initializes a new instance of the <see cref="DataLoaderConfigurationKey" /> /// class. /// </summary> /// <param name="loader"> The data loader. </param> public DataLoaderConfigurationKey(IDataLoader loader) { if (loader == null) { throw new ArgumentNullException("loader"); } this.type = loader.GetType(); this.argument = loader.Argument ?? string.Empty; } /// <summary> /// Determines whether the specified <see cref="DataLoaderConfigurationKey" /> is /// equal to this instance. /// </summary> /// <param name="other"> /// The <see cref="DataLoaderConfigurationKey" /> to compare with this instance. /// </param> /// <returns> /// <c>true</c> if the specified <see cref="DataLoaderConfigurationKey" /> is equal /// to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(DataLoaderConfigurationKey other) { if (other == null) { return false; } return this.type.Equals(other.type) && this.argument.Equals(other.argument, StringComparison.InvariantCulture); } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this /// instance. /// </summary> /// <param name="obj"> /// The <see cref="System.Object" /> to compare with this instance. /// </param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this /// instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return base.Equals(obj as DataLoaderConfigurationKey); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data /// structures like a hash table. /// </returns> public override int GetHashCode() { return this.type.GetHashCode() % this.argument.GetHashCode(); } } }
39.451327
96
0.56236
[ "MIT" ]
JonathanMagnan/effort
Main/Source/Effort.Shared/Internal/Caching/DataLoaderConfigurationKey.cs
4,460
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using Elastic.Elasticsearch.Ephemeral; using Elastic.Elasticsearch.Xunit.XunitPlumbing; using Elasticsearch.Net; using FluentAssertions; using Nest; using Tests.Core.ManagedElasticsearch.Clusters; using Tests.Framework.EndpointTests; using Tests.Framework.EndpointTests.TestState; using static Elastic.Elasticsearch.Ephemeral.ClusterAuthentication; namespace Tests.XPack.Security.Authenticate { [SkipVersion("<2.3.0", "")] public class AuthenticateApiTests : ApiIntegrationTestBase<XPackCluster, AuthenticateResponse, IAuthenticateRequest, AuthenticateDescriptor, AuthenticateRequest> { public AuthenticateApiTests(XPackCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override bool ExpectIsValid => true; protected override int ExpectStatusCode => 200; protected override HttpMethod HttpMethod => HttpMethod.GET; protected override string UrlPath => $"/_security/_authenticate"; protected override LazyResponses ClientUsage() => Calls( (client, f) => client.Security.Authenticate(f), (client, f) => client.Security.AuthenticateAsync(f), (client, r) => client.Security.Authenticate(r), (client, r) => client.Security.AuthenticateAsync(r) ); protected override void ExpectResponse(AuthenticateResponse response) { response.Username.Should().Be(Admin.Username); response.Roles.Should().Contain(Admin.Role); } } [SkipVersion("<2.3.0", "")] public class AuthenticateRequestConfigurationApiTests : AuthenticateApiTests { public AuthenticateRequestConfigurationApiTests(XPackCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override Func<AuthenticateDescriptor, IAuthenticateRequest> Fluent => f => f .RequestConfiguration(c => c .BasicAuthentication(ClusterAuthentication.User.Username, ClusterAuthentication.User.Password) ); protected override AuthenticateRequest Initializer => new AuthenticateRequest { RequestConfiguration = new RequestConfiguration { BasicAuthenticationCredentials = new BasicAuthenticationCredentials( ClusterAuthentication.User.Username, ClusterAuthentication.User.Password) } }; protected override void ExpectResponse(AuthenticateResponse response) { response.Username.Should().Be(ClusterAuthentication.User.Username); response.Roles.Should().Contain(ClusterAuthentication.User.Role); } } }
36.605634
129
0.783378
[ "Apache-2.0" ]
Brightspace/elasticsearch-net
tests/Tests/XPack/Security/Authenticate/AuthenticateApiTests.cs
2,601
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Synapse { public static class GetIntegrationRuntimeConnectionInfo { /// <summary> /// Connection information for encrypting the on-premises data source credentials. /// API Version: 2020-12-01. /// </summary> public static Task<GetIntegrationRuntimeConnectionInfoResult> InvokeAsync(GetIntegrationRuntimeConnectionInfoArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetIntegrationRuntimeConnectionInfoResult>("azure-native:synapse:getIntegrationRuntimeConnectionInfo", args ?? new GetIntegrationRuntimeConnectionInfoArgs(), options.WithVersion()); } public sealed class GetIntegrationRuntimeConnectionInfoArgs : Pulumi.InvokeArgs { /// <summary> /// Integration runtime name /// </summary> [Input("integrationRuntimeName", required: true)] public string IntegrationRuntimeName { get; set; } = null!; /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the workspace. /// </summary> [Input("workspaceName", required: true)] public string WorkspaceName { get; set; } = null!; public GetIntegrationRuntimeConnectionInfoArgs() { } } [OutputType] public sealed class GetIntegrationRuntimeConnectionInfoResult { /// <summary> /// The on-premises integration runtime host URL. /// </summary> public readonly string HostServiceUri; /// <summary> /// The integration runtime SSL certificate thumbprint. Click-Once application uses it to do server validation. /// </summary> public readonly string IdentityCertThumbprint; /// <summary> /// Whether the identity certificate is expired. /// </summary> public readonly bool IsIdentityCertExprired; /// <summary> /// The public key for encrypting a credential when transferring the credential to the integration runtime. /// </summary> public readonly string PublicKey; /// <summary> /// The token generated in service. Callers use this token to authenticate to integration runtime. /// </summary> public readonly string ServiceToken; /// <summary> /// The integration runtime version. /// </summary> public readonly string Version; [OutputConstructor] private GetIntegrationRuntimeConnectionInfoResult( string hostServiceUri, string identityCertThumbprint, bool isIdentityCertExprired, string publicKey, string serviceToken, string version) { HostServiceUri = hostServiceUri; IdentityCertThumbprint = identityCertThumbprint; IsIdentityCertExprired = isIdentityCertExprired; PublicKey = publicKey; ServiceToken = serviceToken; Version = version; } } }
35.42
235
0.645116
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Synapse/GetIntegrationRuntimeConnectionInfo.cs
3,542
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace R5T.Frisia.Standard.Testing { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { } } }
17
52
0.584034
[ "MIT" ]
MinexAutomation/R5T.Frisia.Standard
source/R5T.Frisia.Standard.Testing/UnitTest1.cs
238
C#
using System.Runtime.InteropServices; namespace EarTrumpet.Interop.MMDeviceAPI { [ComImport] [Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumerator { } }
23.875
51
0.722513
[ "MIT" ]
Remixninja/EarTrumpet
EarTrumpet/Interop/MMDeviceAPI/MMDeviceEnumerator.cs
186
C#
using System; using GroorineCore.DataModel; using GroorineCore.Helpers; namespace GroorineCore.Synth { public class Mssf : IAudioSource { /// <summary> /// 波形データを取得します. /// </summary> public short[] Wave { get; } /// <summary> /// エンベロープデータを取得します. /// </summary> public Envelope Envelope { get; } /// <summary> /// -256 ~ 255 の範囲をとるパンポットを取得します。 /// </summary> public int Pan { get; } internal Mssf(short[] wave, Envelope envelope, int pan) { if (wave == null) throw new ArgumentNullException(nameof(wave)); if (wave.Length != 32) throw new ArgumentException("波形の大きさは32でなければなりません。"); Wave = wave; Envelope = envelope; Pan = pan; } public (short l, short r) GetSample(int index, double sampleRate) { var time = MidiTimingConverter.GetTime(index, (int)sampleRate); //var cycle = sampleRate / freq; //if (cycle == 0) // return (0, 0); var i = (int)((index % (100)) * (32 / 100d)); //var i = index; if (i > 31) i -= 32; var o = Wave[i]; float vol; EnvelopeFlag flag = EnvelopeFlag.Attack; if (time > Envelope.A) flag = EnvelopeFlag.Decay; if (time > Envelope.A + Envelope.D) flag = EnvelopeFlag.Sustain; switch (flag) { case EnvelopeFlag.Attack: vol = (float)MathHelper.Linear(time, 0, Envelope.A, 0, 1); break; case EnvelopeFlag.Decay: vol = (float)MathHelper.Linear(time, Envelope.A + 1, Envelope.D, 1, Envelope.S / 255d); break; case EnvelopeFlag.Sustain: vol = Envelope.S / 255f; break; case EnvelopeFlag.Release: case EnvelopeFlag.None: default: vol = 0; break; } return ((short)(o * vol), (short)(o * vol)); } } }
23.246753
93
0.584358
[ "MIT" ]
Citringo/Groorine_1
GroorineCore/Synth/Mssf.cs
1,922
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace AppMongoDB.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
47.207207
229
0.58645
[ "MIT" ]
brzozasr/AppMongoDB
AppMongoDB/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs
20,960
C#
using Content.Server.Access.Components; using Content.Server.Light.Components; using Content.Server.Light.EntitySystems; using Content.Server.Light.Events; using Content.Server.Traitor.Uplink; using Content.Server.Traitor.Uplink.Components; using Content.Server.Traitor.Uplink.Systems; using Content.Server.UserInterface; using Content.Shared.Containers.ItemSlots; using Content.Shared.Interaction; using Content.Shared.PDA; using Robust.Server.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.IoC; namespace Content.Server.PDA { public class PDASystem : EntitySystem { [Dependency] private readonly SharedItemSlotsSystem _slotsSystem = default!; [Dependency] private readonly UplinkSystem _uplinkSystem = default!; [Dependency] private readonly UnpoweredFlashlightSystem _unpoweredFlashlight = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<PDAComponent, ComponentInit>(OnComponentInit); SubscribeLocalEvent<PDAComponent, MapInitEvent>(OnMapInit); SubscribeLocalEvent<PDAComponent, ActivateInWorldEvent>(OnActivateInWorld); SubscribeLocalEvent<PDAComponent, UseInHandEvent>(OnUse); SubscribeLocalEvent<PDAComponent, ItemSlotChangedEvent>(OnItemSlotChanged); SubscribeLocalEvent<PDAComponent, LightToggleEvent>(OnLightToggle); SubscribeLocalEvent<PDAComponent, UplinkInitEvent>(OnUplinkInit); SubscribeLocalEvent<PDAComponent, UplinkRemovedEvent>(OnUplinkRemoved); } private void OnComponentInit(EntityUid uid, PDAComponent pda, ComponentInit args) { var ui = pda.Owner.GetUIOrNull(PDAUiKey.Key); if (ui != null) ui.OnReceiveMessage += (msg) => OnUIMessage(pda, msg); UpdatePDAAppearance(pda); } private void OnMapInit(EntityUid uid, PDAComponent pda, MapInitEvent args) { // try to place ID inside item slot if (!string.IsNullOrEmpty(pda.StartingIdCard)) { // if pda prototype doesn't have slots, ID will drop down on ground var idCard = EntityManager.SpawnEntity(pda.StartingIdCard, pda.Owner.Transform.Coordinates); if (EntityManager.TryGetComponent(uid, out SharedItemSlotsComponent? itemSlots)) _slotsSystem.TryInsertContent(itemSlots, idCard, pda.IdSlot); } } private void OnUse(EntityUid uid, PDAComponent pda, UseInHandEvent args) { if (args.Handled) return; args.Handled = OpenUI(pda, args.User); } private void OnActivateInWorld(EntityUid uid, PDAComponent pda, ActivateInWorldEvent args) { if (args.Handled) return; args.Handled = OpenUI(pda, args.User); } private void OnItemSlotChanged(EntityUid uid, PDAComponent pda, ItemSlotChangedEvent args) { // check if ID slot changed if (args.SlotName == pda.IdSlot) { var item = args.ContainedItem; if (item == null || !EntityManager.TryGetComponent(item.Value, out IdCardComponent ? idCard)) pda.ContainedID = null; else pda.ContainedID = idCard; } else if (args.SlotName == pda.PenSlot) { var item = args.ContainedItem; pda.PenInserted = item != null; } UpdatePDAAppearance(pda); UpdatePDAUserInterface(pda); } private void OnLightToggle(EntityUid uid, PDAComponent pda, LightToggleEvent args) { pda.FlashlightOn = args.IsOn; UpdatePDAUserInterface(pda); } public void SetOwner(PDAComponent pda, string ownerName) { pda.OwnerName = ownerName; UpdatePDAUserInterface(pda); } private void OnUplinkInit(EntityUid uid, PDAComponent pda, UplinkInitEvent args) { UpdatePDAUserInterface(pda); } private void OnUplinkRemoved(EntityUid uid, PDAComponent pda, UplinkRemovedEvent args) { UpdatePDAUserInterface(pda); } private bool OpenUI(PDAComponent pda, IEntity user) { if (!user.TryGetComponent(out ActorComponent? actor)) return false; var ui = pda.Owner.GetUIOrNull(PDAUiKey.Key); ui?.Toggle(actor.PlayerSession); return true; } private void UpdatePDAAppearance(PDAComponent pda) { if (pda.Owner.TryGetComponent(out AppearanceComponent? appearance)) appearance.SetData(PDAVisuals.IDCardInserted, pda.ContainedID != null); } private void UpdatePDAUserInterface(PDAComponent pda) { var ownerInfo = new PDAIdInfoText { ActualOwnerName = pda.OwnerName, IdOwner = pda.ContainedID?.FullName, JobTitle = pda.ContainedID?.JobTitle }; var hasUplink = pda.Owner.HasComponent<UplinkComponent>(); var ui = pda.Owner.GetUIOrNull(PDAUiKey.Key); ui?.SetState(new PDAUpdateState(pda.FlashlightOn, pda.PenInserted, ownerInfo, hasUplink)); } private void OnUIMessage(PDAComponent pda, ServerBoundUserInterfaceMessage msg) { switch (msg.Message) { case PDARequestUpdateInterfaceMessage _: UpdatePDAUserInterface(pda); break; case PDAToggleFlashlightMessage _: { if (pda.Owner.TryGetComponent(out UnpoweredFlashlightComponent? flashlight)) _unpoweredFlashlight.ToggleLight(flashlight); break; } case PDAEjectIDMessage _: { _slotsSystem.TryEjectContent(pda.Owner.Uid, pda.IdSlot, msg.Session.AttachedEntity); break; } case PDAEjectPenMessage _: { _slotsSystem.TryEjectContent(pda.Owner.Uid, pda.PenSlot, msg.Session.AttachedEntity); break; } case PDAShowUplinkMessage _: { if (pda.Owner.TryGetComponent(out UplinkComponent? uplink)) _uplinkSystem.ToggleUplinkUI(uplink, msg.Session); break; } } } } }
37.251366
109
0.59381
[ "MIT" ]
Day-OS/space-station-14
Content.Server/PDA/PDASystem.cs
6,817
C#
using System; using System.IO; namespace Microsoft.Build.MSBuildLocator { /// <summary> /// Represents an installed .NET SDK instance (on any OS platform) /// </summary> public class DotNetSdkInstance : MSBuildInstance { public DotNetSdkInstance(Version version, string path, DiscoveryType discoveryType) { Name = ".NET Core SDK"; Version = version; DiscoveryType = discoveryType; MSBuildPath = path; // the DLLs, etc, are right in the root of the .NET SDK path } } }
28.35
93
0.620811
[ "MIT" ]
dlitty/MSBuildLocator
src/MSBuildLocator/DotNetSdkInstance.cs
569
C#
#pragma checksum "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/Shared/MainLayout.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8837edcfa5b03aa0567fc3c7aad751f1a30b065a" // <auto-generated/> #pragma warning disable 1591 namespace blazor_DB.Shared { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/_Imports.razor" using Microsoft.AspNetCore.Authorization; #line default #line hidden #nullable disable #nullable restore #line 3 "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/_Imports.razor" using Microsoft.AspNetCore.Components.Authorization; #line default #line hidden #nullable disable #nullable restore #line 4 "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 5 "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 6 "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 7 "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/_Imports.razor" using Microsoft.AspNetCore.Components.Web.Virtualization; #line default #line hidden #nullable disable #nullable restore #line 8 "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 9 "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/_Imports.razor" using blazor_DB; #line default #line hidden #nullable disable #nullable restore #line 10 "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/_Imports.razor" using blazor_DB.Shared; #line default #line hidden #nullable disable public partial class MainLayout : LayoutComponentBase { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { __builder.OpenElement(0, "div"); __builder.AddAttribute(1, "class", "page"); __builder.AddAttribute(2, "b-7mjokoozi7"); __builder.OpenElement(3, "div"); __builder.AddAttribute(4, "class", "sidebar"); __builder.AddAttribute(5, "b-7mjokoozi7"); __builder.OpenComponent<blazor_DB.Shared.NavMenu>(6); __builder.CloseComponent(); __builder.CloseElement(); __builder.AddMarkupContent(7, "\r\n\r\n "); __builder.OpenElement(8, "div"); __builder.AddAttribute(9, "class", "main"); __builder.AddAttribute(10, "b-7mjokoozi7"); __builder.AddMarkupContent(11, "<div class=\"top-row px-4\" b-7mjokoozi7><a href=\"https://docs.microsoft.com/aspnet/\" target=\"_blank\" b-7mjokoozi7><button type=\"button\" class=\"btn btn-light\" b-7mjokoozi7>Sobre</button></a></div>\r\n\r\n "); __builder.OpenElement(12, "div"); __builder.AddAttribute(13, "class", "content px-4"); __builder.AddAttribute(14, "b-7mjokoozi7"); __builder.AddContent(15, #nullable restore #line 15 "/Volumes/HDD/macOs/Faculdade/Programação Web/blazor_DB/Shared/MainLayout.razor" Body #line default #line hidden #nullable disable ); __builder.CloseElement(); __builder.CloseElement(); __builder.CloseElement(); } #pragma warning restore 1998 } } #pragma warning restore 1591
33.396694
267
0.721356
[ "MIT" ]
yuriqpaiva/CRUD-Blazor
obj/Debug/net5.0/Razor/Shared/MainLayout.razor.g.cs
4,065
C#
namespace JKang.IpcServiceFramework.Core.Tests.Fixtures { public interface IComplexType { int Int32Value { get; } string StringValue { get; } } }
19.444444
56
0.645714
[ "MIT" ]
BryanMThomas/FactoryOrchestrator
oss/IpcFramework/JKang.IpcServiceFramework.Core.Tests/Fixtures/IComplexType.cs
177
C#
using System; using System.Security.Cryptography; namespace CryptoBase.SymmetricCryptos.BlockCryptos.AES; public sealed class AESECBCrypto : DefaultAESCrypto { protected override ICryptoTransform Encryptor { get; } protected override ICryptoTransform Decryptor { get; } public AESECBCrypto(ReadOnlySpan<byte> key) : base(key) { Encryptor = AESUtils.AesEcb.CreateEncryptor(key.ToArray(), null); Decryptor = AESUtils.AesEcb.CreateDecryptor(key.ToArray(), null); } }
28
67
0.787815
[ "MIT" ]
HMBSbige/CryptoBase
CryptoBase/SymmetricCryptos/BlockCryptos/AES/AESECBCrypto.cs
476
C#
using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace DiBK.RuleValidator.Config { public sealed class ValidationOptions { internal List<Type> SkippedRules { get; } = new(); internal List<string> SkippedGroups { get; } = new(); internal List<ValidationGroupOptions> GroupOptions { get; set; } = new(); internal List<ValidationRuleOptions> RuleOptions { get; set; } = new(); internal Dictionary<string, object> GlobalSettings { get; } = new(); internal List<Assembly> ResourceAssemblies { get; } = new(); public void SkipRule<T>() where T : Rule { var type = typeof(T); if (!SkippedRules.Contains(type)) SkippedRules.Add(type); } public void SkipGroup(string groupId) { if (!SkippedGroups.Contains(groupId)) SkippedGroups.Add(groupId); } public void AddGlobalSettings(string key, object value) => GlobalSettings[key] = value; public void AddResources(Assembly assembly, string namespacePrefix) => ResourceAssemblies.Add(assembly); public void ForGroup(string id, Action<ValidationGroupOptions> options) { var groupOptions = new ValidationGroupOptions(id); options.Invoke(groupOptions); if (groupOptions.Skipped) SkipGroup(id); GroupOptions.Add(groupOptions); } public void ForRule<T>(Action<ValidationRuleOptions> options) where T : Rule { var ruleOptions = new ValidationRuleOptions(typeof(T)); options.Invoke(ruleOptions); if (ruleOptions.Skipped) SkipRule<T>(); RuleOptions.Add(ruleOptions); } } }
31.482759
112
0.610624
[ "MIT" ]
Arkitektum/DiBK.RuleValidator
DiBK.RuleValidator/Models/Config/ValidationOptions.cs
1,828
C#
using System; using System.Runtime.InteropServices; namespace KeraLua { /// <summary> /// Structure for lua debug information /// </summary> /// <remarks> /// Do not change this struct because it must match the lua structure lua_Debug /// </remarks> /// <author>Reinhard Ostermeier</author> [StructLayout(LayoutKind.Sequential)] public struct LuaDebug { /// <summary> /// Get a LuaDebug from IntPtr /// </summary> /// <param name="ar"></param> /// <returns></returns> public static LuaDebug FromIntPtr(IntPtr ar) { #if NETFRAMEWORK return (LuaDebug)Marshal.PtrToStructure(ar, typeof(LuaDebug)); #else return Marshal.PtrToStructure<LuaDebug>(ar); #endif } /// <summary> /// Debug event code /// </summary> [MarshalAs(UnmanagedType.I4)] public LuaHookEvent Event; /// <summary> /// a reasonable name for the given function. Because functions in Lua are first-class values, they do not have a fixed name: some functions can be the value of multiple global variables, while others can be stored only in a table field /// </summary> public string Name => Marshal.PtrToStringAnsi(name); IntPtr name; /// <summary> /// explains the name field. The value of namewhat can be "global", "local", "method", "field", "upvalue", or "" (the empty string) /// </summary> public string NameWhat => Marshal.PtrToStringAnsi(what); IntPtr nameWhat; /// <summary> /// the string "Lua" if the function is a Lua function, "C" if it is a C function, "main" if it is the main part of a chunk /// </summary> public string What => Marshal.PtrToStringAnsi(what); IntPtr what; /// <summary> /// the name of the chunk that created the function. If source starts with a '@', it means that the function was defined in a file where the file name follows the '@'. /// </summary> /// public string Source => Marshal.PtrToStringAnsi(source); IntPtr source; /// <summary> /// the current line where the given function is executing. When no line information is available, currentline is set to -1 /// </summary> public int CurrentLine; /// <summary> /// /// </summary> public int LineDefined; /// <summary> /// the line number where the definition of the function ends. /// </summary> public int LastLineDefined; /// <summary> /// number of upvalues /// </summary> public byte NumberUpValues; /// <summary> /// number of parameters /// </summary> public byte NumberParameters; /// <summary> /// true if the function is a vararg function (always true for C functions). /// </summary> [MarshalAs(UnmanagedType.I1)] public bool IsVarArg; /* (u) */ /// <summary> /// true if this function invocation was called by a tail call. In this case, the caller of this level is not in the stack. /// </summary> [MarshalAs(UnmanagedType.I1)] public bool IsTailCall; /* (t) */ /// <summary> /// a "printable" version of source, to be used in error messages /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 60)] public string ShortSource; IntPtr i_ci; } }
38.397849
245
0.58275
[ "MIT" ]
Missingreference/KeraLua
src/LuaDebug.cs
3,573
C#
namespace NTMY.Web.ViewModels.Users { public class RemoveUserIncomingWeddingViewModel { public int No { get; set; } } }
20
51
0.664286
[ "MIT" ]
SebastianTyr/wsei-projektowanie-profesjonalnej-aplikacji
be/NiceToMeetYou/NTMY.Web/ViewModels/Users/RemoveUserIncomingWeddingViewModel.cs
142
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GoToLevel : MonoBehaviour { public void Continue() { //SceneFader sceneFader = GameObject.Find("SceneFader").GetComponent<SceneFader>(); //GameStatus gameStatus = GameObject.Find("GameManager").GetComponent<GameStatus>(); SceneManager.LoadScene("Level" + GlobalSceneManager.sceneIndex); } public void Back() { SceneManager.LoadScene("StartMenu"); } }
26.85
92
0.707635
[ "MIT" ]
gameholics-usc/DefendTommyTrojan
Assets/Scripts/UI/GoToLevel.cs
539
C#
using UnityEngine; [CreateAssetMenuAttribute(fileName="Character", menuName="Character/Info")] public class CharacterInfo : ScriptableObject { public string Name; public float Speed; public float Accuracy; public int HP; public GameObject Weapon; //prefab public ActiveSkill ActiveSkill; public PassiveSkill PassiveSkill; }
21.058824
75
0.743017
[ "MIT" ]
Zammy/Project42
Assets/Game/Crew/_ScriptableObjs/CharacterInfo.cs
360
C#
using System; namespace AspectCore.APM.AspNetCore.Sample.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
20.909091
70
0.686957
[ "MIT" ]
AspectCore/AspectCore-APM
sample/AspectCore.APM.AspNetCore.Sample/Models/ErrorViewModel.cs
230
C#
using System; using System.Windows.Forms; using System.Drawing; namespace Zbx1425.BveCSRegistry { public static class DebugInputBox { public static string ShowInputBox(string title, string promptText, string currentValue) { var form = InputBox(title, promptText, currentValue); DialogResult dialogResult = form.ShowDialog(); return dialogResult == DialogResult.OK ? form.Controls["textBox"].Text : ""; } public static Form InputBox(string title, string promptText, string currentValue) { Form form = new Form(); Label label = new Label(); TextBox textBox = new TextBox(); Button buttonOk = new Button(); Button buttonCancel = new Button(); form.Text = title; label.Text = promptText; textBox.Text = currentValue; textBox.Name = "textBox"; buttonOk.Text = "OK"; buttonCancel.Text = "Cancel"; buttonOk.DialogResult = DialogResult.OK; buttonCancel.DialogResult = DialogResult.Cancel; label.SetBounds(9, 20, 372, 13); textBox.SetBounds(12, 36, 372, 20); buttonOk.SetBounds(228, 72, 75, 23); buttonCancel.SetBounds(309, 72, 75, 23); label.AutoSize = true; textBox.Anchor = textBox.Anchor | AnchorStyles.Right; buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; form.ClientSize = new Size(396, 107); form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel }); form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.StartPosition = FormStartPosition.CenterScreen; form.MinimizeBox = false; form.MaximizeBox = false; form.AcceptButton = buttonOk; form.CancelButton = buttonCancel; return form; } } }
30.403226
92
0.685411
[ "MIT" ]
BVEContentService/BVEPackMan
source/Plugins/BveCSRegistry/Winform/DebugInputBox.cs
1,887
C#
// *********************************************************************** // Copyright (c) 2017 Dominik Lachance // // 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.Collections.Generic; using System.Xml.Serialization; namespace YellowJacket.Core.NUnitWrapper.Models { /// <summary> /// Represents an NUnit test suite. /// </summary> [XmlRoot(ElementName = "test-suite")] public class TestSuite { /// <summary> /// Gets or sets the properties. /// </summary> /// <value> /// The properties. /// </value> [XmlElement(ElementName = "properties")] public Properties Properties { get; set; } /// <summary> /// Gets or sets the test case. /// </summary> /// <value> /// The test case. /// </value> [XmlElement(ElementName = "test-case")] public List<TestCase> TestCases { get; set; } /// <summary> /// Gets or sets the type. /// </summary> /// <value> /// The type. /// </value> [XmlAttribute(AttributeName = "type")] public string Type { get; set; } /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> [XmlAttribute(AttributeName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets the name. /// </summary> /// <value> /// The name. /// </value> [XmlAttribute(AttributeName = "name")] public string Name { get; set; } /// <summary> /// Gets or sets the full name. /// </summary> /// <value> /// The full name. /// </value> [XmlAttribute(AttributeName = "fullname")] public string FullName { get; set; } /// <summary> /// Gets or sets the name of the class. /// </summary> /// <value> /// The name of the class. /// </value> [XmlAttribute(AttributeName = "classname")] public string ClassName { get; set; } /// <summary> /// Gets or sets the state of the run. /// </summary> /// <value> /// The state of the run. /// </value> [XmlAttribute(AttributeName = "runstate")] public string RunState { get; set; } /// <summary> /// Gets or sets the test case count. /// </summary> /// <value> /// The test case count. /// </value> [XmlAttribute(AttributeName = "testcasecount")] public int TestCaseCount { get; set; } /// <summary> /// Gets or sets the result. /// </summary> /// <value> /// The result. /// </value> [XmlAttribute(AttributeName = "result")] public string Result { get; set; } /// <summary> /// Gets or sets the start time. /// </summary> /// <value> /// The start time. /// </value> [XmlAttribute(AttributeName = "start-time")] public string StartTime { get; set; } /// <summary> /// Gets or sets the end time. /// </summary> /// <value> /// The end time. /// </value> [XmlAttribute(AttributeName = "end-time")] public string EndTime { get; set; } /// <summary> /// Gets or sets the duration. /// </summary> /// <value> /// The duration. /// </value> [XmlAttribute(AttributeName = "duration")] public double Duration { get; set; } /// <summary> /// Gets or sets the total. /// </summary> /// <value> /// The total. /// </value> [XmlAttribute(AttributeName = "total")] public int Total { get; set; } /// <summary> /// Gets or sets the passed. /// </summary> /// <value> /// The passed. /// </value> [XmlAttribute(AttributeName = "passed")] public int Passed { get; set; } /// <summary> /// Gets or sets the failed. /// </summary> /// <value> /// The failed. /// </value> [XmlAttribute(AttributeName = "failed")] public int Failed { get; set; } /// <summary> /// Gets or sets the warnings. /// </summary> /// <value> /// The warnings. /// </value> [XmlAttribute(AttributeName = "warnings")] public int Warnings { get; set; } /// <summary> /// Gets or sets the inconclusive. /// </summary> /// <value> /// The inconclusive. /// </value> [XmlAttribute(AttributeName = "inconclusive")] public int Inconclusive { get; set; } /// <summary> /// Gets or sets the skipped. /// </summary> /// <value> /// The skipped. /// </value> [XmlAttribute(AttributeName = "skipped")] public int Skipped { get; set; } /// <summary> /// Gets or sets the asserts. /// </summary> /// <value> /// The asserts. /// </value> [XmlAttribute(AttributeName = "asserts")] public int Asserts { get; set; } } }
30.078704
75
0.508542
[ "MIT" ]
domtheluck/yellowjacket
YellowJacket/src/YellowJacket.Core/NUnitWrapper/Models/TestSuite.cs
6,499
C#
using UnityEngine; using System.Collections; public class NewItemText : MonoBehaviour { private bool fading = false; private TextMesh textMesh; private static float scaleFactor = 0.002f; #pragma warning disable 0414 private Vector3 scaleVector = new Vector3(scaleFactor, scaleFactor, scaleFactor); void Start() { textMesh = gameObject.GetComponent<TextMesh>(); Invoke("StartFading", 2f); } void StartFading() { fading = true; } void Update() { if (fading) { Color color = textMesh.color; color.a = color.a - 0.01f; textMesh.color = color; if (color.a < 0.1) Destroy(this.gameObject, 0.1f); } } }
20.756757
85
0.578125
[ "MIT" ]
sd-f/orbi
Orbi-App/Assets/Resources/Prefabs/NewItemText/NewItemText.cs
770
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2018 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // namespace DaggerfallConnect.Utility { /// <summary> /// Stores size data. /// </summary> public class DFSize { #region Fields public int Width; public int Height; #endregion #region Constructors /// <summary> /// Default constructor. /// </summary> public DFSize() { Width = 0; Height = 0; } /// <summary> /// Value constructor. /// </summary> public DFSize(int width, int height) { Width = width; Height = height; } #endregion } }
21.32
84
0.532833
[ "MIT" ]
ChristianBasiga/daggerfall-unity
Assets/Scripts/API/DFSize.cs
1,068
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class AnaMenuKontrol : MonoBehaviour { //GameObject level1, level2, level3; (!!! for döngülerini yazınca gerek kalmadı) GameObject levellar, kilitler; void Start () { //level1 = GameObject.Find("level 1"); // level objemizi buluyoruz.(!!!gameobject.find çok obje olduğunda yavaş çalışır) //level2 = GameObject.Find("level 2"); //level3 = GameObject.Find("level 3"); levellar = GameObject.Find("levellar"); // levellar objesine ulaşıyoruz kilitler = GameObject.Find("kilitler"); // kilitler objesine ulaşıyoruz for (int i = 0; i < levellar.transform.childCount; i++) { levellar.transform.GetChild(i).gameObject.SetActive(false); //başlangıçta levellar görünmesin. } for (int i = 0; i < kilitler.transform.childCount; i++) { kilitler.transform.GetChild(i).gameObject.SetActive(false); //başlangıçta kilitler görünmesin. } for (int i = 0; i < PlayerPrefs.GetInt("kacinciLevel"); i++) //bulunduğu level bilgisine göre koşul { levellar.transform.GetChild(i).GetComponent<Button>().interactable =true; //bulunulan level ve öncekilerin butonunu tıklanabilir yapıyoruz. } } public void butonSec(int gelenButon) //tıklanan butona göre çalışacak metot { if (gelenButon == 1) //oyuna basla butonu { SceneManager.LoadScene(PlayerPrefs.GetInt("kacinciLevel")); //kacinci levelda kalındıysa oradan basla } else if (gelenButon == 2) // bolumler butonu { for (int i = 0; i < levellar.transform.childCount; i++) { levellar.transform.GetChild(i).gameObject.SetActive(true); //level butonlarını görünür yap } for (int i = 0; i < kilitler.transform.childCount; i++) { kilitler.transform.GetChild(i).gameObject.SetActive(true); //kilitleri görünür yap } for (int i = 0; i < PlayerPrefs.GetInt("kacinciLevel"); i++) { kilitler.transform.GetChild(i).gameObject.SetActive(false); //bulunulan level ve öncekilerin kilidini aç(sil) } } else if (gelenButon == 3) //oyundan cik butonu { Application.Quit(); } } public void levellarButon(int gelenLevel) // level butonlarına tıklandığında çalışacak metot { SceneManager.LoadScene(gelenLevel); //tıklanan butona göre levela git } }
37.408451
151
0.625753
[ "MIT" ]
Avodhel/Unity_Learn_Projects
Red Java/Assets/Kodlar/AnaMenuKontrol.cs
2,716
C#
//------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Runtime Version:2.0.50727.42 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> //------------------------------------------------------------------------------ namespace InsertingSeparators.Properties { using System; using System.IO; using System.Resources; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the Strongly Typed Resource Builder // class via a tool like ResGen or Visual Studio.NET. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. class Resources { private static System.Resources.ResourceManager _resMgr; private static System.Globalization.CultureInfo _resCulture; /*FamANDAssem*/ internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static System.Resources.ResourceManager ResourceManager { get { if ((_resMgr == null)) { System.Resources.ResourceManager temp = new System.Resources.ResourceManager("Resources", typeof(Resources).Assembly); _resMgr = temp; } return _resMgr; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static System.Globalization.CultureInfo Culture { get { return _resCulture; } set { _resCulture = value; } } } }
28.028169
123
0.651256
[ "MIT" ]
bstollnitz/old-wpf-blog
20-InsertingSeparators/InsertingSeparators/Properties/Resources.cs
1,992
C#
using System.IO; using System.Text; namespace Mages.Script.Tokens { public class TextToken : Token { public string Value; public TextToken(Reader reader) : base(TokenType.TextMask) { var sb = new StringBuilder(); while (true) { byte next = reader.ReadByte(); if (next == (byte)TokenType.LineBreak) { sb.Append("\n"); continue; } else if (next == (byte)TokenType.Terminator || (next & (byte)TokenType.TextMask) == 0) { reader.BaseStream.Position--; break; } sb.Append(reader.ReadChar(next)); } Value = sb.ToString(); } public override void Encode(SCXWriter target) { foreach (var c in Value) { if (c == '\n') { target.Write(TokenType.LineBreak); continue; } target.WriteChar(c); } } public override string ToString() => "\"" + Value.Replace("\\", "\\\\").Replace("\n", "\\n").Replace("\"", "\\\"") + "\""; } }
28.595745
131
0.401786
[ "MIT" ]
wetor/MagesTools
MagesLib/Script/Tokens/TextToken.cs
1,346
C#
using EFCore.Sharding; namespace Demo.DI { public interface IMyRepository : IRepository { } }
10.9
48
0.669725
[ "Apache-2.0" ]
chengxulvtu/EFCore.Sharding
examples/Demo.DI/IMyRepository.cs
111
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EDEngineer.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.6.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string LogDirectory { get { return ((string)(this["LogDirectory"])); } set { this["LogDirectory"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::System.Collections.Specialized.StringCollection Favorites { get { return ((global::System.Collections.Specialized.StringCollection)(this["Favorites"])); } set { this["Favorites"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::System.Collections.Specialized.StringCollection Ignored { get { return ((global::System.Collections.Specialized.StringCollection)(this["Ignored"])); } set { this["Ignored"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::System.Collections.Specialized.StringCollection FiltersChecked { get { return ((global::System.Collections.Specialized.StringCollection)(this["FiltersChecked"])); } set { this["FiltersChecked"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string Shortcut { get { return ((string)(this["Shortcut"])); } set { this["Shortcut"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("True")] public bool UpgradeRequired { get { return ((bool)(this["UpgradeRequired"])); } set { this["UpgradeRequired"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("1.1.4.0")] public string Version { get { return ((string)(this["Version"])); } set { this["Version"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public double WindowWidth { get { return ((double)(this["WindowWidth"])); } set { this["WindowWidth"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public double WindowHeight { get { return ((double)(this["WindowHeight"])); } set { this["WindowHeight"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public double WindowTop { get { return ((double)(this["WindowTop"])); } set { this["WindowTop"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public double WindowLeft { get { return ((double)(this["WindowLeft"])); } set { this["WindowLeft"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string CurrentVersion { get { return ((string)(this["CurrentVersion"])); } set { this["CurrentVersion"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public double LeftSideWidth { get { return ((double)(this["LeftSideWidth"])); } set { this["LeftSideWidth"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public double RightSideWidth { get { return ((double)(this["RightSideWidth"])); } set { this["RightSideWidth"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool ResetUI { get { return ((bool)(this["ResetUI"])); } set { this["ResetUI"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool WindowUnlocked { get { return ((bool)(this["WindowUnlocked"])); } set { this["WindowUnlocked"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string Language { get { return ((string)(this["Language"])); } set { this["Language"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool AutoRunServer { get { return ((bool)(this["AutoRunServer"])); } set { this["AutoRunServer"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public ushort ServerPort { get { return ((ushort)(this["ServerPort"])); } set { this["ServerPort"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0")] public int CargoTabIndex { get { return ((int)(this["CargoTabIndex"])); } set { this["CargoTabIndex"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::System.Collections.Specialized.StringCollection ShoppingList { get { return ((global::System.Collections.Specialized.StringCollection)(this["ShoppingList"])); } set { this["ShoppingList"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string SelectedCommander { get { return ((string)(this["SelectedCommander"])); } set { this["SelectedCommander"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string Comparer { get { return ((string)(this["Comparer"])); } set { this["Comparer"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool SilentLaunch { get { return ((bool)(this["SilentLaunch"])); } set { this["SilentLaunch"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string NotificationKindBlueprintReady { get { return ((string)(this["NotificationKindBlueprintReady"])); } set { this["NotificationKindBlueprintReady"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string NotificationVoice { get { return ((string)(this["NotificationVoice"])); } set { this["NotificationVoice"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("100")] public double LeftFontRatio { get { return ((double)(this["LeftFontRatio"])); } set { this["LeftFontRatio"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("100")] public double RightRatio { get { return ((double)(this["RightRatio"])); } set { this["RightRatio"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("100")] public double BottomFontRatio { get { return ((double)(this["BottomFontRatio"])); } set { this["BottomFontRatio"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("0.9")] public double Opacity { get { return ((double)(this["Opacity"])); } set { this["Opacity"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("True")] public bool IngredientsGrouped { get { return ((bool)(this["IngredientsGrouped"])); } set { this["IngredientsGrouped"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("True")] public bool SyncShoppingList { get { return ((bool)(this["SyncShoppingList"])); } set { this["SyncShoppingList"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::System.Collections.Specialized.StringCollection ShowAllGrades { get { return ((global::System.Collections.Specialized.StringCollection)(this["ShowAllGrades"])); } set { this["ShowAllGrades"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("False")] public bool ClearAggregation { get { return ((bool)(this["ClearAggregation"])); } set { this["ClearAggregation"] = value; } } } }
38.027907
152
0.539384
[ "MIT" ]
enachos71/EDEngineer
EDEngineer/Properties/Settings.Designer.cs
16,354
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace UAOOI.Configuration.Networking.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("UAOOI.Configuration.Networking.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to File: {0} has benn opened.. /// </summary> internal static string InformationFileOpened2 { get { return ResourceManager.GetString("InformationFileOpened2", resourceCulture); } } /// <summary> /// Looks up a localized string similar to File: {0} is saved.. /// </summary> internal static string InformationFileSaved2 { get { return ResourceManager.GetString("InformationFileSaved2", resourceCulture); } } } }
42.280488
196
0.601961
[ "MIT" ]
BiancoRoyal/OPC-UA-OOI
Configuration/Networking/Properties/Resources.Designer.cs
3,469
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Text.Encodings.Web; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Identity.UI.V4.Pages.Account.Internal; /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [AllowAnonymous] [IdentityDefaultUI(typeof(RegisterModel<>))] public abstract class RegisterModel : PageModel { /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [BindProperty] public InputModel Input { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public string ReturnUrl { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public IList<AuthenticationScheme> ExternalLogins { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class InputModel { /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual Task OnGetAsync(string returnUrl = null) => throw new NotImplementedException(); /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual Task<IActionResult> OnPostAsync(string returnUrl = null) => throw new NotImplementedException(); } internal class RegisterModel<TUser> : RegisterModel where TUser : class { private readonly SignInManager<TUser> _signInManager; private readonly UserManager<TUser> _userManager; private readonly IUserStore<TUser> _userStore; private readonly IUserEmailStore<TUser> _emailStore; private readonly ILogger<RegisterModel> _logger; private readonly IEmailSender _emailSender; public RegisterModel( UserManager<TUser> userManager, IUserStore<TUser> userStore, SignInManager<TUser> signInManager, ILogger<RegisterModel> logger, IEmailSender emailSender) { _userManager = userManager; _userStore = userStore; _emailStore = GetEmailStore(); _signInManager = signInManager; _logger = logger; _emailSender = emailSender; } public override async Task OnGetAsync(string returnUrl = null) { ReturnUrl = returnUrl; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); } public override async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = CreateUser(); await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None); await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None); var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation(LoggerEventIds.UserCreated, "User created a new account with password."); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }); } else { await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(returnUrl); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return Page(); } private TUser CreateUser() { try { return Activator.CreateInstance<TUser>(); } catch { throw new InvalidOperationException($"Can't create an instance of '{nameof(TUser)}'. " + $"Ensure that '{nameof(TUser)}' is not an abstract class and has a parameterless constructor, or alternatively " + $"override the register page in /Areas/Identity/Pages/Account/Register.cshtml"); } } private IUserEmailStore<TUser> GetEmailStore() { if (!_userManager.SupportsUserEmail) { throw new NotSupportedException("The default UI requires a user store with email support."); } return (IUserEmailStore<TUser>)_userStore; } }
42.28866
130
0.650049
[ "MIT" ]
Aezura/aspnetcore
src/Identity/UI/src/Areas/Identity/Pages/V4/Account/Register.cshtml.cs
8,204
C#
using SignalR.Hubs; namespace DescribeMe.Web.Hubs { public class StatisticsHub : Hub { } }
11.666667
36
0.657143
[ "MIT" ]
museumsvictoria/describe-me
src/DescribeMe.Web/Hubs/StatisticsHub.cs
107
C#
using Robust.Shared.Input; namespace Content.Shared.Input { [KeyFunctions] public static class ContentKeyFunctions { public static readonly BoundKeyFunction UseItemInHand = "ActivateItemInHand"; public static readonly BoundKeyFunction AltUseItemInHand = "AltActivateItemInHand"; public static readonly BoundKeyFunction ActivateItemInWorld = "ActivateItemInWorld"; public static readonly BoundKeyFunction AltActivateItemInWorld = "AltActivateItemInWorld"; public static readonly BoundKeyFunction Drop = "Drop"; public static readonly BoundKeyFunction ExamineEntity = "ExamineEntity"; public static readonly BoundKeyFunction FocusChat = "FocusChatInputWindow"; public static readonly BoundKeyFunction FocusLocalChat = "FocusLocalChatWindow"; public static readonly BoundKeyFunction FocusWhisperChat = "FocusWhisperChatWindow"; public static readonly BoundKeyFunction FocusRadio = "FocusRadioWindow"; public static readonly BoundKeyFunction FocusOOC = "FocusOOCWindow"; public static readonly BoundKeyFunction FocusAdminChat = "FocusAdminChatWindow"; public static readonly BoundKeyFunction FocusDeadChat = "FocusDeadChatWindow"; public static readonly BoundKeyFunction FocusConsoleChat = "FocusConsoleChatWindow"; public static readonly BoundKeyFunction CycleChatChannelForward = "CycleChatChannelForward"; public static readonly BoundKeyFunction CycleChatChannelBackward = "CycleChatChannelBackward"; public static readonly BoundKeyFunction OpenCharacterMenu = "OpenCharacterMenu"; public static readonly BoundKeyFunction OpenContextMenu = "OpenContextMenu"; public static readonly BoundKeyFunction OpenCraftingMenu = "OpenCraftingMenu"; public static readonly BoundKeyFunction OpenInventoryMenu = "OpenInventoryMenu"; public static readonly BoundKeyFunction SmartEquipBackpack = "SmartEquipBackpack"; public static readonly BoundKeyFunction SmartEquipBelt = "SmartEquipBelt"; public static readonly BoundKeyFunction OpenInfo = "OpenInfo"; public static readonly BoundKeyFunction SwapHands = "SwapHands"; public static readonly BoundKeyFunction ThrowItemInHand = "ThrowItemInHand"; public static readonly BoundKeyFunction TryPullObject = "TryPullObject"; public static readonly BoundKeyFunction MovePulledObject = "MovePulledObject"; public static readonly BoundKeyFunction ReleasePulledObject = "ReleasePulledObject"; public static readonly BoundKeyFunction MouseMiddle = "MouseMiddle"; public static readonly BoundKeyFunction OpenEntitySpawnWindow = "OpenEntitySpawnWindow"; public static readonly BoundKeyFunction OpenSandboxWindow = "OpenSandboxWindow"; public static readonly BoundKeyFunction OpenTileSpawnWindow = "OpenTileSpawnWindow"; public static readonly BoundKeyFunction OpenDecalSpawnWindow = "OpenDecalSpawnWindow"; public static readonly BoundKeyFunction OpenAdminMenu = "OpenAdminMenu"; public static readonly BoundKeyFunction TakeScreenshot = "TakeScreenshot"; public static readonly BoundKeyFunction TakeScreenshotNoUI = "TakeScreenshotNoUI"; public static readonly BoundKeyFunction Point = "Point"; public static readonly BoundKeyFunction ArcadeUp = "ArcadeUp"; public static readonly BoundKeyFunction ArcadeDown = "ArcadeDown"; public static readonly BoundKeyFunction ArcadeLeft = "ArcadeLeft"; public static readonly BoundKeyFunction ArcadeRight = "ArcadeRight"; public static readonly BoundKeyFunction Arcade1 = "Arcade1"; public static readonly BoundKeyFunction Arcade2 = "Arcade2"; public static readonly BoundKeyFunction Arcade3 = "Arcade3"; public static readonly BoundKeyFunction OpenActionsMenu = "OpenAbilitiesMenu"; public static readonly BoundKeyFunction Fart = "Fart"; public static readonly BoundKeyFunction Hotbar0 = "Hotbar0"; public static readonly BoundKeyFunction Hotbar1 = "Hotbar1"; public static readonly BoundKeyFunction Hotbar2 = "Hotbar2"; public static readonly BoundKeyFunction Hotbar3 = "Hotbar3"; public static readonly BoundKeyFunction Hotbar4 = "Hotbar4"; public static readonly BoundKeyFunction Hotbar5 = "Hotbar5"; public static readonly BoundKeyFunction Hotbar6 = "Hotbar6"; public static readonly BoundKeyFunction Hotbar7 = "Hotbar7"; public static readonly BoundKeyFunction Hotbar8 = "Hotbar8"; public static readonly BoundKeyFunction Hotbar9 = "Hotbar9"; public static readonly BoundKeyFunction Loadout1 = "Loadout1"; public static readonly BoundKeyFunction Loadout2 = "Loadout2"; public static readonly BoundKeyFunction Loadout3 = "Loadout3"; public static readonly BoundKeyFunction Loadout4 = "Loadout4"; public static readonly BoundKeyFunction Loadout5 = "Loadout5"; public static readonly BoundKeyFunction Loadout6 = "Loadout6"; public static readonly BoundKeyFunction Loadout7 = "Loadout7"; public static readonly BoundKeyFunction Loadout8 = "Loadout8"; public static readonly BoundKeyFunction Loadout9 = "Loadout9"; public static readonly BoundKeyFunction Vote0 = "Vote0"; public static readonly BoundKeyFunction Vote1 = "Vote1"; public static readonly BoundKeyFunction Vote2 = "Vote2"; public static readonly BoundKeyFunction Vote3 = "Vote3"; public static readonly BoundKeyFunction Vote4 = "Vote4"; public static readonly BoundKeyFunction Vote5 = "Vote5"; public static readonly BoundKeyFunction Vote6 = "Vote6"; public static readonly BoundKeyFunction Vote7 = "Vote7"; public static readonly BoundKeyFunction Vote8 = "Vote8"; public static readonly BoundKeyFunction Vote9 = "Vote9"; public static readonly BoundKeyFunction EditorCopyObject = "EditorCopyObject"; } }
70.406977
102
0.754748
[ "MIT" ]
arcadia-station/space-station-14
Content.Shared/Input/ContentKeyFunctions.cs
6,055
C#
using AbhsChinese.Admin.Models.Question; using AbhsChinese.Bll; using AbhsChinese.Domain.Entity.Subject; using AbhsChinese.Domain.JsonEntity.Subject; using AbhsChinese.Domain.JsonTranslator; using System; namespace AbhsChinese.Admin.Models.Common { public class FillInBlankContentFetcher : ContentFetcher { protected override Yw_SubjectContent GetContent( QuestionInputModel sub, SubjectBll bll, int currentUser, Yw_SubjectContent content) { FillInBlank subject = sub as FillInBlank; Yw_FillInBlankContent derivedContent = null; if (content == null) { derivedContent = new Yw_FillInBlankContent(); derivedContent.Ysc_CreateTime = DateTime.Now; derivedContent.Ysc_Creator = currentUser; derivedContent.Ysc_SubjectType = subject.SubjectType; } else { derivedContent = content as Yw_FillInBlankContent; } derivedContent.Ysc_Editor = currentUser; derivedContent.Ysc_Explain = subject.Explain; derivedContent.Ysc_Content_Obj = new FillInBlankContentObj { Stem = UeditorContentFactory.Blank(subject.Name) }; derivedContent.Ysc_Answer_Obj = new FillInBlankAnswerObj { Correct = subject.Correct.Blanks, Other = subject.Other.Blanks, Perfect = subject.Perfect.Blanks }; derivedContent.Ysc_UpdateTime = DateTime.Now; return derivedContent; } } }
35.765957
70
0.610946
[ "Apache-2.0" ]
GuoQqizz/SmartChinese
AbhsChinese.Admin/Models/Common/FillInBlankContentFetcher.cs
1,683
C#
/* THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF REVIVAL PRODUCTIONS, LLC ("REVIVAL"). REVIVAL, IN DISTRIBUTING THE CODE TO END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE. COPYRIGHT 2015-2020 REVIVAL PRODUCTIONS, LLC. ALL RIGHTS RESERVED. */ using UnityEngine; using System; public class Mathfx { public static float Hermite(float start, float end, float value) { return Mathf.Lerp(start, end, value * value * (3.0f - 2.0f * value)); } public static float Sinerp(float start, float end, float value) { return Mathf.Lerp(start, end, Mathf.Sin(value * Mathf.PI * 0.5f)); } public static float Coserp(float start, float end, float value) { return Mathf.Lerp(start, end, 1.0f - Mathf.Cos(value * Mathf.PI * 0.5f)); } public static float Berp(float start, float end, float value) { value = Mathf.Clamp01(value); value = (Mathf.Sin(value * Mathf.PI * (0.2f + 2.5f * value * value * value)) * Mathf.Pow(1f - value, 2.2f) + value) * (1f + (1.2f * (1f - value))); return start + (end - start) * value; } public static float SmoothStep(float x, float min, float max) { x = Mathf.Clamp(x, min, max); float v1 = (x - min) / (max - min); float v2 = (x - min) / (max - min); return -2 * v1 * v1 * v1 + 3 * v2 * v2; } public static float Lerp(float start, float end, float value) { return ((1.0f - value) * start) + (value * end); } public static Vector3 NearestPoint(Vector3 line_start, Vector3 line_end, Vector3 point) { Vector3 lineDirection = Vector3.Normalize(line_end - line_start); float closestPoint = Vector3.Dot((point - line_start), lineDirection) / Vector3.Dot(lineDirection, lineDirection); return line_start + (closestPoint * lineDirection); } public static Vector3 NearestPointStrict(Vector3 lineStart, Vector3 lineEnd, Vector3 point) { Vector3 fullDirection = lineEnd - lineStart; Vector3 lineDirection = Vector3.Normalize(fullDirection); float closestPoint = Vector3.Dot((point - lineStart), lineDirection) / Vector3.Dot(lineDirection, lineDirection); return lineStart + (Mathf.Clamp(closestPoint, 0.0f, Vector3.Magnitude(fullDirection)) * lineDirection); } public static float Bounce(float x) { return Mathf.Abs(Mathf.Sin(6.28f * (x + 1f) * (x + 1f)) * (1f - x)); } // test for value that is near specified float (due to floating point inprecision) // all thanks to Opless for this! public static bool Approx(float val, float about, float range) { return ((Mathf.Abs(val - about) < range)); } // test if a Vector3 is close to another Vector3 (due to floating point inprecision) // compares the square of the distance to the square of the range as this // avoids calculating a square root which is much slower than squaring the range public static bool Approx(Vector3 val, Vector3 about, float range) { return ((val - about).sqrMagnitude < range * range); } /* * CLerp - Circular Lerp - is like lerp but handles the wraparound from 0 to 360. * This is useful when interpolating eulerAngles and the object * crosses the 0/360 boundary. The standard Lerp function causes the object * to rotate in the wrong direction and looks stupid. Clerp fixes that. */ public static float Clerp(float start, float end, float value) { float min = 0.0f; float max = 360.0f; float half = Mathf.Abs((max - min) / 2.0f);//half the distance between min and max float retval = 0.0f; float diff = 0.0f; if ((end - start) < -half) { diff = ((max - start) + end) * value; retval = start + diff; } else if ((end - start) > half) { diff = -((max - end) + start) * value; retval = start + diff; } else retval = start + (end - start) * value; // if (Debug.isDebugBuild) Debug.Log("Start: " + start + " End: " + end + " Value: " + value + " Half: " + half + " Diff: " + diff + " Retval: " + retval); return retval; } }
38.265487
164
0.691489
[ "MIT" ]
SiriusTR/OverloadLevelEditor
Editor/Common/Mathfx.cs
4,326
C#
using System.Windows.Controls; namespace moddingSuite.View.Ndfbin.ValueEditing { /// <summary> /// Interaction logic for TransTableReferenceEditingTemplate.xaml /// </summary> public partial class TransTableReferenceEditingTemplate : UserControl { public TransTableReferenceEditingTemplate() { InitializeComponent(); } } }
24.0625
73
0.680519
[ "MIT" ]
RemiGC/moddingSuite
moddingSuite/View/Ndfbin/ValueEditing/TransTableReferenceEditingTemplate.xaml.cs
387
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Modules.RootComposition.PokemonGoScriptableObjs { public class M1Behaviour : MonoBehaviour { public void Log() { Debug.Log("I'm M1Behaviour 1"); } } }
19.333333
57
0.658621
[ "MIT" ]
Dechichi01/DependencyInjection
Assets/Modules/RootComposition/PokemonGo_ScriptableObjs/Behaviours/M1Behaviour.cs
292
C#
using System; using System.Collections.ObjectModel; using System.Linq; using Xalendar.Api.Interfaces; using Xamarin.Forms; namespace Xalendar.Sample { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); BindingContext = new MainPageViewModel(); } private void OnRandomButtonClick(object sender, EventArgs e) { if (BindingContext is MainPageViewModel viewModel) viewModel.AddRandomEvent(); } private void OnRemoveButtonClick(object sender, EventArgs e) { if (BindingContext is MainPageViewModel viewModel) viewModel.RemoveEvent(); } } public class MainPageViewModel { public ObservableCollection<ICalendarViewEvent> Events { get; } public Command RemoveAllEventsCommand { get; } public Command ReplaceEventCommand { get; } public MainPageViewModel() { Events = new ObservableCollection<ICalendarViewEvent>(); RemoveAllEventsCommand = new Command(RemoveAllEvents); ReplaceEventCommand = new Command(ReplaceEvent); for (var index = 1; index <= 10; index++) { var eventDate = new DateTime(2020, 9, index); Events.Add(new CustomEvent(index, "Nome evento", eventDate, eventDate, false)); } } private void RemoveAllEvents() => Events.Clear(); private void ReplaceEvent() { var firstEvent = Events.FirstOrDefault(); if (firstEvent is null) return; var eventDate = new DateTime(2020, 9, 24); var newEvent = new CustomEvent(firstEvent.Id, firstEvent.Name, eventDate, eventDate, firstEvent.IsAllDay); Events[0] = newEvent; } private int _dayEventToStart = 11; public void AddRandomEvent() { try { var eventDate = new DateTime(2020, 9, _dayEventToStart); var customEvent = new CustomEvent(_dayEventToStart, "Nome evento", eventDate, eventDate, false); Events.Add(customEvent); _dayEventToStart++; } catch (Exception) { } } public void RemoveEvent() { var firstEvent = Events.FirstOrDefault(); if (firstEvent != null) Events.Remove(firstEvent); } } public class CustomEvent : ICalendarViewEvent { public object Id { get; } public string Name { get; } public DateTime StartDateTime { get; } public DateTime EndDateTime { get; } public bool IsAllDay { get; } public CustomEvent(object id, string name, DateTime startDateTime, DateTime endDateTime, bool isAllDay) { Id = id; Name = name; StartDateTime = startDateTime; EndDateTime = endDateTime; IsAllDay = isAllDay; } } }
29.783019
118
0.56351
[ "MIT" ]
brendonbarreto/Xalendar
src/Xalendar.Sample/Xalendar.Sample/MainPage.xaml.cs
3,159
C#
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections.Generic; using System.ComponentModel; using Microsoft.DotNet.XUnitExtensions; using Xunit; namespace System.Drawing.Drawing2D.Tests { public class GraphicsPathTests { private const float Pi4 = (float)(Math.PI / 4); private const float Delta = 0.0003f; [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_Default_Success() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Equal(FillMode.Alternate, gp.FillMode); AssertEmptyGrahicsPath(gp); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_FillMode_Success() { using (GraphicsPath gpa = new GraphicsPath(FillMode.Alternate)) using (GraphicsPath gpw = new GraphicsPath(FillMode.Winding)) { Assert.Equal(FillMode.Alternate, gpa.FillMode); AssertEmptyGrahicsPath(gpa); Assert.Equal(FillMode.Winding, gpw.FillMode); AssertEmptyGrahicsPath(gpw); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_SamePoints_Success() { byte[] types = new byte[6] { 0, 1, 1, 1, 1, 1 }; Point[] points = new Point[] { new Point (1, 1), new Point (1, 1), new Point (1, 1), new Point (1, 1), new Point (1, 1), new Point (1, 1), }; PointF[] fPoints = new PointF[] { new PointF (1f, 1f), new PointF (1f, 1f), new PointF (1f, 1f), new PointF (1f, 1f), new PointF (1f, 1f), new PointF (1f, 1f), }; using (GraphicsPath gp = new GraphicsPath(points, types)) using (GraphicsPath gpf = new GraphicsPath(fPoints, types)) { Assert.Equal(FillMode.Alternate, gp.FillMode); Assert.Equal(6, gp.PointCount); Assert.Equal(FillMode.Alternate, gpf.FillMode); Assert.Equal(6, gpf.PointCount); types[0] = 1; Assert.Equal(FillMode.Alternate, gp.FillMode); Assert.Equal(6, gp.PointCount); Assert.Equal(FillMode.Alternate, gpf.FillMode); Assert.Equal(6, gpf.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_PointsNull_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("pts", () => new GraphicsPath((Point[])null, new byte[1])); } public static IEnumerable<object[]> AddCurve_PointsTypesLengthMismatch_TestData() { yield return new object[] { 1, 2 }; yield return new object[] { 2, 1 }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddCurve_PointsTypesLengthMismatch_TestData))] public void Ctor_PointsTypesLengthMismatch_ThrowsArgumentException(int pointsLength, int typesLength) { AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath(new Point[pointsLength], new byte[typesLength])); AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath(new PointF[pointsLength], new byte[typesLength])); } [ConditionalFact(Helpers.IsDrawingSupported)] public void Clone_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { Assert.Equal(FillMode.Alternate, clone.FillMode); AssertEmptyGrahicsPath(clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reset_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.Reset(); Assert.Equal(FillMode.Alternate, gp.FillMode); AssertEmptyGrahicsPath(gp); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GraphicsPath_FillModeChange() { using (GraphicsPath gp = new GraphicsPath()) { gp.FillMode = FillMode.Winding; Assert.Equal(FillMode.Winding, gp.FillMode); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(FillMode.Alternate - 1)] [InlineData(FillMode.Winding + 1)] public void GraphicsPath_InvalidFillMode_ThrowsInvalidEnumArgumentException(FillMode fillMode) { using (GraphicsPath gp = new GraphicsPath()) { Assert.ThrowsAny<ArgumentException>(() => gp.FillMode = fillMode); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathData_ReturnsExpected() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Equal(0, gp.PathData.Points.Length); Assert.Equal(0, gp.PathData.Types.Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathData_CannotChange() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(1, 1, 2, 2)); Assert.Equal(1f, gp.PathData.Points[0].X); Assert.Equal(1f, gp.PathData.Points[0].Y); gp.PathData.Points[0] = new Point(0, 0); Assert.Equal(1f, gp.PathData.Points[0].X); Assert.Equal(1f, gp.PathData.Points[0].Y); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathPoints_CannotChange() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(1, 1, 2, 2)); Assert.Equal(1f, gp.PathPoints[0].X); Assert.Equal(1f, gp.PathPoints[0].Y); gp.PathPoints[0] = new Point(0, 0); Assert.Equal(1f, gp.PathPoints[0].X); Assert.Equal(1f, gp.PathPoints[0].Y); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathPoints_EmptyPath_ThrowsArgumentException() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Throws<ArgumentException>(() => gp.PathPoints); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathTypes_CannotChange() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(1, 1, 2, 2)); Assert.Equal(0, gp.PathTypes[0]); gp.PathTypes[0] = 1; Assert.Equal(0, gp.PathTypes[0]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathTypes_EmptyPath_ThrowsArgumentException() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Throws<ArgumentException>(() => gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetLastPoint_ReturnsExpected() { byte[] types = new byte[3] { 0, 1, 1 }; PointF[] points = new PointF[] { new PointF (1f, 1f), new PointF (2f, 2f), new PointF (3f, 3f), }; using (GraphicsPath gp = new GraphicsPath(points, types)) { Assert.Equal(gp.GetLastPoint(), points[2]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLine_Success() { using (GraphicsPath gpInt = new GraphicsPath()) using (GraphicsPath gpFloat = new GraphicsPath()) using (GraphicsPath gpPointsInt = new GraphicsPath()) using (GraphicsPath gpfPointsloat = new GraphicsPath()) { gpInt.AddLine(1, 1, 2, 2); // AssertLine() method expects line drawn between points with coordinates 1, 1 and 2, 2, here and below. AssertLine(gpInt); gpFloat.AddLine(1, 1, 2, 2); AssertLine(gpFloat); gpPointsInt.AddLine(new Point(1, 1), new Point(2, 2)); AssertLine(gpPointsInt); gpfPointsloat.AddLine(new PointF(1, 1), new PointF(2, 2)); AssertLine(gpfPointsloat); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLine_SamePoints_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddLine(new Point(49, 157), new Point(75, 196)); gpi.AddLine(new Point(75, 196), new Point(102, 209)); Assert.Equal(3, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1 }, gpi.PathTypes); gpi.AddLine(new Point(102, 209), new Point(75, 196)); Assert.Equal(4, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpi.PathTypes); gpf.AddLine(new PointF(49, 157), new PointF(75, 196)); gpf.AddLine(new PointF(75, 196), new PointF(102, 209)); Assert.Equal(3, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1 }, gpf.PathTypes); gpf.AddLine(new PointF(102, 209), new PointF(75, 196)); Assert.Equal(4, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpf.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLines_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddLines(new Point[] { new Point(1, 1), new Point(2, 2) }); AssertLine(gpi); gpf.AddLines(new PointF[] { new PointF(1, 1), new PointF(2, 2) }); AssertLine(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLines_SinglePoint_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddLines(new PointF[] { new PointF(1, 1) }); Assert.Equal(1, gpi.PointCount); Assert.Equal(0, gpi.PathTypes[0]); gpf.AddLines(new PointF[] { new PointF(1, 1) }); Assert.Equal(1, gpf.PointCount); Assert.Equal(0, gpf.PathTypes[0]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLines_SamePoint_Success() { Point[] intPoints = new Point[] { new Point(49, 157), new Point(49, 157) }; PointF[] floatPoints = new PointF[] { new PointF(49, 57), new PointF(49, 57), new PointF(49, 57), new PointF(49, 57) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddLines(intPoints); Assert.Equal(2, gpi.PointCount); Assert.Equal(new byte[] { 0, 1 }, gpi.PathTypes); gpi.AddLines(intPoints); Assert.Equal(3, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1 }, gpi.PathTypes); gpi.AddLines(intPoints); Assert.Equal(4, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpi.PathTypes); gpf.AddLines(floatPoints); Assert.Equal(4, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpf.PathTypes); gpf.AddLines(floatPoints); Assert.Equal(7, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 1, 1, 1, 1 }, gpf.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLines_PointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddLines((Point[])null)); AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddLines((PointF[])null)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLines_ZeroPoints_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath().AddLines(new Point[0])); AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath().AddLines(new PointF[0])); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddArc_Values_Success() { if (PlatformDetection.IsArmOrArm64Process) { //ActiveIssue: 35744 throw new SkipTestException("Precision on float numbers"); } using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddArc(1, 1, 2, 2, Pi4, Pi4); // AssertArc() method expects added Arc with parameters // x=1, y=1, width=2, height=2, startAngle=Pi4, seewpAngle=Pi4 here and below. AssertArc(gpi); gpf.AddArc(1f, 1f, 2f, 2f, Pi4, Pi4); AssertArc(gpf); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddArc_Rectangle_Success() { if (PlatformDetection.IsArmOrArm64Process) { //ActiveIssue: 35744 throw new SkipTestException("Precision on float numbers"); } using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddArc(new Rectangle(1, 1, 2, 2), Pi4, Pi4); AssertArc(gpi); gpf.AddArc(new RectangleF(1, 1, 2, 2), Pi4, Pi4); AssertArc(gpf); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(0, 1)] public void AddArc_ZeroWidthHeight_ThrowsArgumentException(int width, int height) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddArc(1, 1, width, height, Pi4, Pi4)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddArc(1.0f, 1.0f, (float)width, (float)height, Pi4, Pi4)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddBezier_Points_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddBezier(new Point(1, 1), new Point(2, 2), new Point(3, 3), new Point(4, 4)); // AssertBezier() method expects added Bezier with points (1, 1), (2, 2), (3, 3), (4, 4), here and below. AssertBezier(gpi); gpf.AddBezier(new PointF(1, 1), new PointF(2, 2), new PointF(3, 3), new PointF(4, 4)); AssertBezier(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddBezier_SamePoints_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gp.AddBezier(new Point(0, 0), new Point(0, 0), new Point(0, 0), new Point(0, 0)); Assert.Equal(4, gp.PointCount); Assert.Equal(new byte[] { 0, 3, 3, 3 }, gp.PathTypes); gp.AddBezier(new Point(0, 0), new Point(0, 0), new Point(0, 0), new Point(0, 0)); Assert.Equal(7, gp.PointCount); Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3 }, gp.PathTypes); gpf.AddBezier(new PointF(0, 0), new PointF(0, 0), new PointF(0, 0), new PointF(0, 0)); Assert.Equal(4, gpf.PointCount); Assert.Equal(new byte[] { 0, 3, 3, 3 }, gpf.PathTypes); gpf.AddBezier(new PointF(0, 0), new PointF(0, 0), new PointF(0, 0), new PointF(0, 0)); Assert.Equal(7, gpf.PointCount); Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3 }, gpf.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddBezier_Values_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddBezier(1, 1, 2, 2, 3, 3, 4, 4); AssertBezier(gpi); gpf.AddBezier(1f, 1f, 2f, 2f, 3f, 3f, 4f, 4f); AssertBezier(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddBeziers_Points_Success() { PointF[] points = new PointF[] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3), new PointF(4, 4) }; using (GraphicsPath gpf = new GraphicsPath()) { gpf.AddBeziers(points); AssertBezier(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddBeziers_PointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddBeziers((PointF[])null)); AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddBeziers((Point[])null)); } } public static IEnumerable<object[]> AddBeziers_InvalidFloatPointsLength_TestData() { yield return new object[] { new PointF[0] }; yield return new object[] { new PointF[1] { new PointF(1f, 1f) } }; yield return new object[] { new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) } }; yield return new object[] { new PointF[3] { new PointF(1f, 1f), new PointF(2f, 2f), new PointF(3f, 3f) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddBeziers_InvalidFloatPointsLength_TestData))] public void AddBeziers_InvalidFloatPointsLength_ThrowsArgumentException(PointF[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddBeziers(points)); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_TwoPoints_Success() { Point[] intPoints = new Point[] { new Point(1, 1), new Point(2, 2) }; PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(2, 2) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpf.AddCurve(floatPoints); // AssertCurve() method expects added Curve with points (1, 1), (2, 2), here and below. AssertCurve(gpf); gpi.AddCurve(intPoints); AssertCurve(gpi); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_TwoPointsWithTension_Success() { Point[] intPoints = new Point[] { new Point(1, 1), new Point(2, 2) }; PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(2, 2) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddCurve(intPoints, 0.5f); AssertCurve(gpi); gpf.AddCurve(floatPoints, 0.5f); AssertCurve(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_SamePoints_Success() { Point[] intPoints = new Point[] { new Point(1, 1), new Point(1, 1) }; PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(1, 1) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddCurve(intPoints); Assert.Equal(4, gpi.PointCount); gpi.AddCurve(intPoints); Assert.Equal(7, gpi.PointCount); gpf.AddCurve(floatPoints); Assert.Equal(4, gpf.PointCount); gpf.AddCurve(floatPoints); Assert.Equal(7, gpf.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_LargeTension_Success() { Point[] intPoints = new Point[] { new Point(1, 1), new Point(2, 2) }; PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(2, 2) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddCurve(intPoints, float.MaxValue); Assert.Equal(4, gpi.PointCount); gpf.AddCurve(floatPoints, float.MaxValue); Assert.Equal(4, gpf.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_Success() { PointF[] points = new PointF[] { new PointF (37f, 185f), new PointF (99f, 185f), new PointF (161f, 159f), new PointF (223f, 185f), new PointF (285f, 54f), }; PointF[] expectedPoints = new PointF[] { new PointF (37f, 185f), new PointF (47.33333f, 185f), new PointF (78.3333f, 189.3333f), new PointF (99f, 185f), new PointF (119.6667f, 180.6667f), new PointF (140.3333f, 159f), new PointF (161f, 159f), new PointF (181.6667f, 159f), new PointF (202.3333f, 202.5f), new PointF (223f, 185f), new PointF (243.6667f, 167.5f), new PointF (274.6667f, 75.8333f), new PointF (285f, 54f), }; byte[] expectedTypes = new byte[] { 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }; int[] pointsCount = { 4, 7, 10, 13 }; using (GraphicsPath gp = new GraphicsPath()) { for (int i = 0; i < points.Length - 1; i++) { gp.AddCurve(points, i, 1, 0.5f); Assert.Equal(pointsCount[i], gp.PointCount); } AssertPointsSequenceEqual(expectedPoints, gp.PathPoints, Delta); Assert.Equal(expectedTypes, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_PointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddCurve((PointF[])null)); AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddCurve((Point[])null)); } } public static IEnumerable<object[]> AddCurve_InvalidFloatPointsLength_TestData() { yield return new object[] { new PointF[0] }; yield return new object[] { new PointF[1] { new PointF(1f, 1f) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddCurve_InvalidFloatPointsLength_TestData))] public void AddCurve_InvalidFloatPointsLength_ThrowsArgumentException(PointF[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points, 0, 2, 0.5f)); } } public static IEnumerable<object[]> AddCurve_InvalidPointsLength_TestData() { yield return new object[] { new Point[0] }; yield return new object[] { new Point[1] { new Point(1, 1) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddCurve_InvalidPointsLength_TestData))] public void AddCurve_InvalidPointsLength_ThrowsArgumentException(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points, 0, 2, 0.5f)); } } public static IEnumerable<object[]> AddCurve_InvalidSegment_TestData() { yield return new object[] { 0 }; yield return new object[] { -1 }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddCurve_InvalidSegment_TestData))] public void AddCurve_InvalidSegment_ThrowsArgumentException(int segment) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve( new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) }, 0, segment, 0.5f)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve( new Point[2] { new Point(1, 1), new Point(2, 2) }, 0, segment, 0.5f)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_OffsetTooLarge_ThrowsArgumentException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve( new PointF[3] { new PointF(1f, 1f), new PointF(0f, 20f), new PointF(20f, 0f) }, 1, 2, 0.5f)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve( new Point[3] { new Point(1, 1), new Point(0, 20), new Point(20, 0) }, 1, 2, 0.5f)); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddClosedCurve_Points_Success() { if (PlatformDetection.IsArmOrArm64Process) { //ActiveIssue: 35744 throw new SkipTestException("Precision on float numbers"); } using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); // AssertClosedCurve() method expects added ClosedCurve with points (1, 1), (2, 2), (3, 3), here and below. AssertClosedCurve(gpi); gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); AssertClosedCurve(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddClosedCurve_SamePoints_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(1, 1), new Point(1, 1) }); Assert.Equal(10, gpi.PointCount); gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(1, 1), new Point(1, 1) }); Assert.Equal(20, gpi.PointCount); gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(1, 1), new PointF(1, 1) }); Assert.Equal(10, gpf.PointCount); gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(1, 1), new PointF(1, 1) }); Assert.Equal(20, gpf.PointCount); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddClosedCurve_Tension_Success() { if (PlatformDetection.IsArmOrArm64Process) { //ActiveIssue: 35744 throw new SkipTestException("Precision on float numbers"); } using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }, 0.5f); AssertClosedCurve(gpi); gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }, 0.5f); AssertClosedCurve(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddClosedCurve_PointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddClosedCurve((PointF[])null)); AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddClosedCurve((Point[])null)); } } public static IEnumerable<object[]> AddClosedCurve_InvalidPointsLength_TestData() { yield return new object[] { new Point[0] }; yield return new object[] { new Point[1] { new Point(1, 1) } }; yield return new object[] { new Point[2] { new Point(1, 1), new Point(2, 2) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddCurve_InvalidPointsLength_TestData))] public void AddClosedCurve_InvalidPointsLength_ThrowsArgumentException(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddClosedCurve(points)); } } public static IEnumerable<object[]> AddClosedCurve_InvalidFloatPointsLength_TestData() { yield return new object[] { new PointF[0] }; yield return new object[] { new PointF[1] { new PointF(1f, 1f) } }; yield return new object[] { new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddClosedCurve_InvalidFloatPointsLength_TestData))] public void AddClosedCurve_InvalidFloatPointsLength_ThrowsArgumentException(PointF[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddClosedCurve(points)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddRectangle_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddRectangle(new Rectangle(1, 1, 2, 2)); // AssertRectangle() method expects added Rectangle with parameters x=1, y=1, width=2, height=2, here and below. AssertRectangle(gpi); gpf.AddRectangle(new RectangleF(1, 1, 2, 2)); AssertRectangle(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddRectangle_SameRectangles_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddRectangle(new Rectangle(1, 1, 1, 1)); Assert.Equal(4, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 129 }, gpi.PathTypes); PointF endI = gpi.PathPoints[3]; gpi.AddRectangle(new Rectangle((int)endI.X, (int)endI.Y, 1, 1)); Assert.Equal(8, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 129, 0, 1, 1, 129 }, gpi.PathTypes); gpf.AddRectangle(new RectangleF(1, 1, 1, 1)); Assert.Equal(4, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 129 }, gpf.PathTypes); Assert.Equal(129, gpf.PathTypes[3]); PointF endF = gpf.PathPoints[3]; gpf.AddRectangle(new RectangleF(endF.X, endF.Y, 1, 1)); Assert.Equal(8, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 129, 0, 1, 1, 129 }, gpf.PathTypes); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(0, 0)] [InlineData(3, 0)] [InlineData(0, 4)] public void AddRectangle_ZeroWidthHeight_Success(int width, int height) { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddRectangle(new Rectangle(1, 2, width, height)); Assert.Equal(0, gpi.PathData.Points.Length); gpf.AddRectangle(new RectangleF(1f, 2f, (float)width, (float)height)); Assert.Equal(0, gpf.PathData.Points.Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddRectangles_Success() { Rectangle[] rectInt = new Rectangle[] { new Rectangle(1, 1, 2, 2), new Rectangle(3, 3, 4, 4) }; RectangleF[] rectFloat = new RectangleF[] { new RectangleF(1, 1, 2, 2), new RectangleF(3, 3, 4, 4) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddRectangles(rectInt); Assert.Equal(8, gpi.PathPoints.Length); Assert.Equal(8, gpi.PathTypes.Length); Assert.Equal(8, gpi.PathData.Points.Length); gpf.AddRectangles(rectFloat); Assert.Equal(8, gpf.PathPoints.Length); Assert.Equal(8, gpf.PathTypes.Length); Assert.Equal(8, gpf.PathData.Points.Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddRectangles_SamePoints_Success() { Rectangle[] rectInt = new Rectangle[] { new Rectangle(1, 1, 0, 0), new Rectangle(1, 1, 2, 2), new Rectangle(1, 1, 2, 2) }; RectangleF[] rectFloat = new RectangleF[] { new RectangleF(1, 1, 0f, 0f), new RectangleF(1, 1, 2, 2), new RectangleF(1, 1, 2, 2) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddRectangles(rectInt); Assert.Equal(8, gpi.PathPoints.Length); Assert.Equal(8, gpi.PathTypes.Length); Assert.Equal(8, gpi.PathData.Points.Length); gpf.AddRectangles(rectFloat); Assert.Equal(8, gpf.PathPoints.Length); Assert.Equal(8, gpf.PathTypes.Length); Assert.Equal(8, gpf.PathData.Points.Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddRectangles_RectangleNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("rects", () => gp.AddRectangles((RectangleF[])null)); AssertExtensions.Throws<ArgumentNullException>("rects", () => gp.AddRectangles((Rectangle[])null)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddEllipse_Rectangle_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddEllipse(new Rectangle(1, 1, 2, 2)); // AssertEllipse() method expects added Ellipse with parameters x=1, y=1, width=2, height=2, here and below. AssertEllipse(gpi); gpf.AddEllipse(new RectangleF(1, 1, 2, 2)); AssertEllipse(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddEllipse_Values_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddEllipse(1, 1, 2, 2); AssertEllipse(gpi); gpf.AddEllipse(1f, 1f, 2f, 2f); AssertEllipse(gpf); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(0, 0)] [InlineData(2, 0)] [InlineData(0, 2)] public void AddEllipse_ZeroWidthHeight_Success(int width, int height) { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddEllipse(1, 1, width, height); Assert.Equal(13, gpi.PathData.Points.Length); gpf.AddEllipse(1f, 2f, (float)width, (float)height); Assert.Equal(13, gpf.PathData.Points.Length); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPie_Rectangle_Success() { using (GraphicsPath gpi = new GraphicsPath()) { gpi.AddPie(new Rectangle(1, 1, 2, 2), Pi4, Pi4); // AssertPie() method expects added Pie with parameters // x=1, y=1, width=2, height=2, startAngle=Pi4, seewpAngle=Pi4 here and below. AssertPie(gpi); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPie_Values_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddPie(1, 1, 2, 2, Pi4, Pi4); AssertPie(gpi); gpf.AddPie(1f, 1f, 2f, 2f, Pi4, Pi4); AssertPie(gpf); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(0, 0)] [InlineData(2, 0)] [InlineData(0, 2)] public void AddPie_ZeroWidthHeight_ThrowsArgumentException(int width, int height) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPie(1, 1, height, width, Pi4, Pi4)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPie(1f, 1f, height, width, Pi4, Pi4)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPie(new Rectangle(1, 1, height, width), Pi4, Pi4)); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPolygon_Points_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); // AssertPolygon() method expects added Polygon with points (1, 1), (2, 2), (3, 3), here and below. AssertPolygon(gpi); gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); AssertPolygon(gpf); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPolygon_SamePoints_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); Assert.Equal(3, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 129 }, gpi.PathTypes); gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); Assert.Equal(6, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129 }, gpi.PathTypes); gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); Assert.Equal(9, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpi.PathTypes); gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); Assert.Equal(12, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpi.PathTypes); gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); Assert.Equal(3, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 129 }, gpf.PathTypes); gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); Assert.Equal(6, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129 }, gpf.PathTypes); gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); Assert.Equal(9, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpf.PathTypes); gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); Assert.Equal(12, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpf.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPolygon_PointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddPolygon((Point[])null)); AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddPolygon((PointF[])null)); } } public static IEnumerable<object[]> AddPolygon_InvalidFloadPointsLength_TestData() { yield return new object[] { new PointF[0] }; yield return new object[] { new PointF[1] { new PointF(1f, 1f) } }; yield return new object[] { new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddPolygon_InvalidFloadPointsLength_TestData))] public void AddPolygon_InvalidFloadPointsLength_ThrowsArgumentException(PointF[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPolygon(points)); } } public static IEnumerable<object[]> AddPolygon_InvalidPointsLength_TestData() { yield return new object[] { new Point[0] }; yield return new object[] { new Point[1] { new Point(1, 1) } }; yield return new object[] { new Point[2] { new Point(1, 1), new Point(2, 2) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddPolygon_InvalidPointsLength_TestData))] public void AddPolygon_InvalidPointsLength_ThrowsArgumentException(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPolygon(points)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPath_Success() { using (GraphicsPath inner = new GraphicsPath()) using (GraphicsPath gp = new GraphicsPath()) { inner.AddRectangle(new Rectangle(1, 1, 2, 2)); gp.AddPath(inner, true); AssertRectangle(gp); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPath_PathNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("addingPath", () => new GraphicsPath().AddPath(null, false)); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddString_Point_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddString("mono", FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpi.PointCount, 0); gpf.AddString("mono", FontFamily.GenericMonospace, 0, 10, new PointF(10f, 10f), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpf.PointCount, 0); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddString_Rectangle_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddString("mono", FontFamily.GenericMonospace, 0, 10, new Rectangle(10, 10, 10, 10), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpi.PointCount, 0); gpf.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpf.PointCount, 0); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddString_NegativeSize_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddString("mono", FontFamily.GenericMonospace, 0, -10, new Point(10, 10), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpi.PointCount, 0); int gpiLenghtOld = gpi.PathPoints.Length; gpi.AddString("mono", FontFamily.GenericMonospace, 0, -10, new Rectangle(10, 10, 10, 10), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpi.PointCount, gpiLenghtOld); gpf.AddString("mono", FontFamily.GenericMonospace, 0, -10, new PointF(10f, 10f), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpf.PointCount, 0); int pgfLenghtOld = gpf.PathPoints.Length; gpf.AddString("mono", FontFamily.GenericMonospace, 0, -10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpf.PointCount, pgfLenghtOld); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddString_StringFormat_Success() { using (GraphicsPath gp1 = new GraphicsPath()) using (GraphicsPath gp2 = new GraphicsPath()) using (GraphicsPath gp3 = new GraphicsPath()) { gp1.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), null); AssertExtensions.GreaterThan(gp1.PointCount, 0); gp2.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault); Assert.Equal(gp1.PointCount, gp2.PointCount); gp3.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericTypographic); Assert.NotEqual(gp1.PointCount, gp3.PointCount); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddString_EmptyString_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddString(string.Empty, FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault); Assert.Equal(0, gpi.PointCount); gpi.AddString(string.Empty, FontFamily.GenericMonospace, 0, 10, new PointF(10f, 10f), StringFormat.GenericDefault); Assert.Equal(0, gpf.PointCount); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddString_StringNull_ThrowsNullReferenceException() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Throws<NullReferenceException>(() => gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault)); Assert.Throws<NullReferenceException>(() => gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new PointF(10f, 10f), StringFormat.GenericDefault)); Assert.Throws<NullReferenceException>(() => gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new Rectangle(10, 10, 10, 10), StringFormat.GenericDefault)); Assert.Throws<NullReferenceException>(() => gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddString_FontFamilyNull_ThrowsArgumentException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath().AddString("mono", null, 0, 10, new Point(10, 10), StringFormat.GenericDefault)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Transform_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix(1f, 1f, 2f, 2f, 3f, 3f)) { gp.AddRectangle(new Rectangle(1, 1, 2, 2)); AssertRectangle(gp); gp.Transform(matrix); Assert.Equal(new float[] { 1f, 1f, 2f, 2f, 3f, 3f }, matrix.Elements); Assert.Equal(new RectangleF(6f, 6f, 6f, 6f), gp.GetBounds()); Assert.Equal(new PointF[] { new PointF(6f, 6f), new PointF(8f, 8f), new PointF(12f, 12f), new PointF(10f, 10f) }, gp.PathPoints); Assert.Equal(new byte[] { 0, 1, 1, 129 }, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Transform_PathEmpty_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix(1f, 1f, 2f, 2f, 3f, 3f)) { gp.Transform(matrix); Assert.Equal(new float[] { 1f, 1f, 2f, 2f, 3f, 3f }, matrix.Elements); AssertEmptyGrahicsPath(gp); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Transform_MatrixNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("matrix", () => gp.Transform(null)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetBounds_PathEmpty_ReturnsExpected() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Equal(new RectangleF(0f, 0f, 0f, 0f), gp.GetBounds()); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetBounds_Rectangle_ReturnsExpected() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix()) { RectangleF rectangle = new RectangleF(1f, 1f, 2f, 2f); gp.AddRectangle(rectangle); Assert.Equal(rectangle, gp.GetBounds()); Assert.Equal(rectangle, gp.GetBounds(null)); Assert.Equal(rectangle, gp.GetBounds(matrix)); Assert.Equal(rectangle, gp.GetBounds(null, null)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetBounds_Pie_ReturnsExpected() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix()) { Rectangle rectangle = new Rectangle(10, 10, 100, 100); gp.AddPie(rectangle, 30, 45); AssertRectangleEqual(new RectangleF(60f, 60f, 43.3f, 48.3f), gp.GetBounds(), 0.1f); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Empty_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.Flatten(); Assert.Equal(gp.PointCount, clone.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_MatrixNull_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.Flatten(null); Assert.Equal(gp.PointCount, clone.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_MatrixNullFloat_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.Flatten(null, 1f); Assert.Equal(gp.PointCount, clone.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Arc_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddArc(0f, 0f, 100f, 100f, 30, 30); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Bezier_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddBezier(0, 0, 100, 100, 30, 30, 60, 60); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_ClosedCurve_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddClosedCurve(new Point[4] { new Point (0, 0), new Point (40, 20), new Point (20, 40), new Point (40, 40) }); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Curve_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddCurve(new Point[4] { new Point (0, 0), new Point (40, 20), new Point (20, 40), new Point (40, 40) }); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Ellipse_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddEllipse(10f, 10f, 100f, 100f); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Line_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddLine(10f, 10f, 100f, 100f); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Pie_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddPie(0, 0, 100, 100, 30, 30); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Polygon_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddPolygon(new Point[4] { new Point (0, 0), new Point (10, 10), new Point (20, 20), new Point (40, 40) }); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Rectangle_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddRectangle(new Rectangle(0, 0, 100, 100)); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Warp_DestinationPointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("destPoints", () => gp.Warp(null, new RectangleF())); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Warp_DestinationPointsZero_ThrowsArgumentException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath().Warp(new PointF[0], new RectangleF())); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Warp_PathEmpty_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix()) { Assert.Equal(0, gp.PointCount); gp.Warp(new PointF[1] { new PointF(0, 0) }, new RectangleF(10, 20, 30, 40), matrix); Assert.Equal(0, gp.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Warp_WarpModeInvalid_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix()) { gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) }); gp.Warp(new PointF[1] { new PointF(0, 0) }, new RectangleF(10, 20, 30, 40), matrix, (WarpMode)int.MinValue); Assert.Equal(0, gp.PointCount); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Warp_RectangleEmpty_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) }); gp.Warp(new PointF[1] { new PointF(0, 0) }, new Rectangle(), null); AssertWrapNaN(gp); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void SetMarkers_EmptyPath_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.SetMarkers(); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void SetMarkers_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(new Point(1, 1), new Point(2, 2)); Assert.Equal(1, gp.PathTypes[1]); gp.SetMarkers(); Assert.Equal(33, gp.PathTypes[1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void ClearMarkers_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(new Point(1, 1), new Point(2, 2)); Assert.Equal(1, gp.PathTypes[1]); gp.SetMarkers(); Assert.Equal(33, gp.PathTypes[1]); gp.ClearMarkers(); Assert.Equal(1, gp.PathTypes[1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void ClearMarkers_EmptyPath_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.ClearMarkers(); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void CloseFigure_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(new Point(1, 1), new Point(2, 2)); Assert.Equal(1, gp.PathTypes[1]); gp.CloseFigure(); Assert.Equal(129, gp.PathTypes[1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void CloseFigure_EmptyPath_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.CloseFigure(); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void CloseAllFigures_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(new Point(1, 1), new Point(2, 2)); gp.StartFigure(); gp.AddLine(new Point(3, 3), new Point(4, 4)); Assert.Equal(1, gp.PathTypes[1]); Assert.Equal(1, gp.PathTypes[3]); gp.CloseAllFigures(); Assert.Equal(129, gp.PathTypes[1]); Assert.Equal(129, gp.PathTypes[3]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void CloseAllFigures_EmptyPath_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.CloseAllFigures(); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddArc() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddArc(10, 10, 100, 100, 90, 180); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(3, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddBezier() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddBezier(10, 10, 100, 100, 20, 20, 200, 200); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(3, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddBeziers() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddBeziers(new Point[7] { new Point (10, 10), new Point (20, 10), new Point (20, 20), new Point (30, 20), new Point (40, 40), new Point (50, 40), new Point (50, 50) }); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(3, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddClosedCurve() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(131, types[gp.PointCount - 3]); Assert.Equal(0, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddCurve() { using (GraphicsPath path = new GraphicsPath()) { path.AddLine(1, 1, 2, 2); path.AddCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); path.AddLine(10, 10, 20, 20); byte[] types = path.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(3, types[path.PointCount - 3]); Assert.Equal(1, types[path.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddEllipse() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddEllipse(10, 10, 100, 100); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(131, types[gp.PointCount - 3]); Assert.Equal(0, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddLine() { using (GraphicsPath path = new GraphicsPath()) { path.AddLine(1, 1, 2, 2); path.AddLine(5, 5, 10, 10); path.AddLine(10, 10, 20, 20); byte[] types = path.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(1, types[path.PointCount - 3]); Assert.Equal(1, types[path.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddLines() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddLines(new Point[4] { new Point(10, 10), new Point(20, 10), new Point(20, 20), new Point(30, 20) }); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(1, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddPath_Connect() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath inner = new GraphicsPath()) { inner.AddArc(10, 10, 100, 100, 90, 180); gp.AddLine(1, 1, 2, 2); gp.AddPath(inner, true); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(3, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddPath_NoConnect() { using (GraphicsPath inner = new GraphicsPath()) using (GraphicsPath path = new GraphicsPath()) { inner.AddArc(10, 10, 100, 100, 90, 180); path.AddLine(1, 1, 2, 2); path.AddPath(inner, false); path.AddLine(10, 10, 20, 20); byte[] types = path.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(3, types[path.PointCount - 3]); Assert.Equal(1, types[path.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddPie() { using (GraphicsPath path = new GraphicsPath()) { path.AddLine(1, 1, 2, 2); path.AddPie(10, 10, 10, 10, 90, 180); path.AddLine(10, 10, 20, 20); byte[] types = path.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(128, (types[path.PointCount - 3] & 128)); Assert.Equal(0, types[path.PointCount - 2]); Assert.Equal(1, types[path.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddPolygon() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(129, types[gp.PointCount - 3]); Assert.Equal(0, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddRectangle() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddRectangle(new RectangleF(10, 10, 20, 20)); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(129, types[gp.PointCount - 3]); Assert.Equal(0, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddRectangles() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddRectangles(new RectangleF[2] { new RectangleF (10, 10, 20, 20), new RectangleF (20, 20, 10, 10) }); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(129, types[gp.PointCount - 3]); Assert.Equal(0, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddString() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddString("mono", FontFamily.GenericMonospace, 0, 10, new Point(20, 20), StringFormat.GenericDefault); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(163, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Widen_Pen_Success() { PointF[] expectedPoints = new PointF[] { new PointF(0.5f, 0.5f), new PointF(3.5f, 0.5f), new PointF(3.5f, 3.5f), new PointF(0.5f, 3.5f), new PointF(1.5f, 3.0f), new PointF(1.0f, 2.5f), new PointF(3.0f, 2.5f), new PointF(2.5f, 3.0f), new PointF(2.5f, 1.0f), new PointF(3.0f, 1.5f), new PointF(1.0f, 1.5f), new PointF(1.5f, 1.0f), }; byte[] expectedTypes = new byte[] { 0, 1, 1, 129, 0, 1, 1, 1, 1, 1, 1, 129 }; using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Blue)) { gp.AddRectangle(new Rectangle(1, 1, 2, 2)); Assert.Equal(4, gp.PointCount); gp.Widen(pen); Assert.Equal(12, gp.PointCount); AssertPointsSequenceEqual(expectedPoints, gp.PathPoints, Delta); Assert.Equal(expectedTypes, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Widen_EmptyPath_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Blue)) { Assert.Equal(0, gp.PointCount); gp.Widen(pen); Assert.Equal(0, gp.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Widen_PenNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.Widen(null)); AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.Widen(null, new Matrix())); AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.Widen(null, new Matrix(), 0.67f)); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Widen_MatrixNull_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Blue)) { gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) }); gp.Widen(pen, null); Assert.Equal(9, gp.PointCount); AssertWiden3(gp); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Widen_MatrixEmpty_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Blue)) using (Matrix matrix = new Matrix()) { gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) }); gp.Widen(pen, new Matrix()); Assert.Equal(9, gp.PointCount); AssertWiden3(gp); } } public static IEnumerable<object[]> Widen_PenSmallWidth_TestData() { yield return new object[] { new Rectangle(1, 1, 2, 2), 0f, new RectangleF(0.5f, 0.5f, 3.0f, 3.0f) }; yield return new object[] { new Rectangle(1, 1, 2, 2), 0.5f, new RectangleF(0.5f, 0.5f, 3.0f, 3.0f) }; yield return new object[] { new Rectangle(1, 1, 2, 2), 1.0f, new RectangleF(0.5f, 0.5f, 3.0f, 3.0f) }; yield return new object[] { new Rectangle(1, 1, 2, 2), 1.1f, new RectangleF(0.45f, 0.45f, 3.10f, 3.10f) }; } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Widen_PenSmallWidth_TestData))] public void Widen_Pen_SmallWidth_Succes( Rectangle rectangle, float penWidth, RectangleF expectedBounds) { using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Aqua, 0)) using (Matrix matrix = new Matrix()) { pen.Width = penWidth; gp.AddRectangle(rectangle); gp.Widen(pen); AssertRectangleEqual(expectedBounds, gp.GetBounds(null), Delta); AssertRectangleEqual(expectedBounds, gp.GetBounds(matrix), Delta); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_PenNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(1, 1, null)); AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(1.0f, 1.0f, null)); AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(new Point(), null)); AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(new PointF(), null)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineWithoutGraphics_ReturnsExpected() { AssertIsOutlineVisibleLine(null); } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineInsideGraphics_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(20, 20)) using (Graphics graphics = Graphics.FromImage(bitmap)) { AssertIsOutlineVisibleLine(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineOutsideGraphics_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(5, 5)) using (Graphics graphics = Graphics.FromImage(bitmap)) { AssertIsOutlineVisibleLine(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineWithGraphicsTransform_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(20, 20)) using (Graphics graphics = Graphics.FromImage(bitmap)) using (Matrix matrix = new Matrix(2, 0, 0, 2, 50, -50)) { graphics.Transform = matrix; AssertIsOutlineVisibleLine(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineWithGraphicsPageUnit_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(20, 20)) using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.PageUnit = GraphicsUnit.Millimeter; AssertIsOutlineVisibleLine(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineWithGraphicsPageScale_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(20, 20)) using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.PageScale = 2.0f; AssertIsOutlineVisibleLine(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_RectangleWithoutGraphics_ReturnsExpected() { AssertIsOutlineVisibleRectangle(null); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void IsVisible_RectangleWithoutGraphics_ReturnsExpected() { AssertIsVisibleRectangle(null); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void IsVisible_RectangleWithGraphics_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(40, 40)) using (Graphics graphics = Graphics.FromImage(bitmap)) { AssertIsVisibleRectangle(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsVisible_EllipseWithoutGraphics_ReturnsExpected() { AssertIsVisibleEllipse(null); } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsVisible_EllipseWithGraphics_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(40, 40)) using (Graphics graphics = Graphics.FromImage(bitmap)) { AssertIsVisibleEllipse(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Arc_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddArc(1f, 1f, 2f, 2f, Pi4, Pi4); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Bezier_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddBezier(1, 2, 3, 4, 5, 6, 7, 8); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } public static IEnumerable<object[]> Reverse_TestData() { yield return new object[] { new Point[] { new Point (1,2), new Point (3,4), new Point (5,6), new Point (7,8), new Point (9,10), new Point (11,12), new Point (13,14) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Reverse_TestData))] public void Reverse_Beziers_Succes(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddBeziers(points); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Reverse_TestData))] public void Reverse_ClosedCurve_Succes(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddClosedCurve(points); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Reverse_TestData))] public void Reverse_Curve_Succes(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddCurve(points); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Ellipse_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddEllipse(1, 2, 3, 4); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Line_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 2, 3, 4); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_LineClosed_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 2, 3, 4); gp.CloseFigure(); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Reverse_TestData))] public void Reverse_Lines_Succes(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLines(points); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Reverse_TestData))] public void Reverse_Polygon_Succes(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddPolygon(points); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Rectangle_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(1, 2, 3, 4)); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Rectangles_Succes() { using (GraphicsPath gp = new GraphicsPath()) { Rectangle[] rects = new Rectangle[] { new Rectangle(1, 2, 3, 4), new Rectangle(5, 6, 7, 8) }; gp.AddRectangles(rects); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Pie_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddPie(1, 2, 3, 4, 10, 20); byte[] expectedTypes = new byte[] { 0, 3, 3, 3, 129 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_ArcLineInnerPath_Succes() { using (GraphicsPath inner = new GraphicsPath()) using (GraphicsPath gp = new GraphicsPath()) { inner.AddArc(1f, 1f, 2f, 2f, Pi4, Pi4); inner.AddLine(1, 2, 3, 4); byte[] expectedTypes = new byte[] { 0, 1, 1, 3, 3, 3 }; gp.AddPath(inner, true); AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_EllipseRectangle_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddEllipse(50, 51, 50, 100); gp.AddRectangle(new Rectangle(200, 201, 60, 61)); byte[] expectedTypes = new byte[] { 0, 1, 1, 129, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 131 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_String_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddString("Mono::", FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault); byte[] expectedTypes = new byte[] { 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,129, 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,161, 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,129, 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,161, 0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,131,0,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,163,0,3,3,3, 3,3,3,3,3,3,3,3,3,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3, 3,3,3,3,3,3,3,3,3,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3, 3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,3,161,0,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,131,0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,163,0,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3, 3,3,3,3,3,3,3,3,3,3,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1, 1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3, 1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,129 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Marker_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(200, 201, 60, 61)); gp.SetMarkers(); byte[] expectedTypes = new byte[] { 0, 1, 1, 129 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_SubpathMarker_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(0, 1, 2, 3); gp.SetMarkers(); gp.CloseFigure(); gp.AddBezier(5, 6, 7, 8, 9, 10, 11, 12); gp.CloseFigure(); byte[] expectedTypes = new byte[] { 0, 3, 3, 163, 0, 129 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(0, 1, 2, 3); gp.SetMarkers(); gp.StartFigure(); gp.AddLine(20, 21, 22, 23); gp.AddBezier(5, 6, 7, 8, 9, 10, 11, 12); byte[] expectedTypes = new byte[] { 0, 3, 3, 3, 1, 33, 0, 1 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_PointsTypes_Succes() { int dX = 520; int dY = 320; Point[] expectedPoints = new Point[] { new Point(dX-64, dY-24), new Point(dX-59, dY-34), new Point(dX-52, dY-54), new Point(dX-18, dY-66), new Point(dX-34, dY-47), new Point(dX-43, dY-27), new Point(dX-44, dY-8), }; byte[] expectedTypes = new byte[] { (byte)PathPointType.Start, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier }; using (GraphicsPath path = new GraphicsPath(expectedPoints, expectedTypes)) { Assert.Equal(7, path.PointCount); byte[] actualTypes = path.PathTypes; Assert.Equal(expectedTypes, actualTypes); } } private void AssertEmptyGrahicsPath(GraphicsPath gp) { Assert.Equal(0, gp.PathData.Points.Length); Assert.Equal(0, gp.PathData.Types.Length); Assert.Equal(0, gp.PointCount); } private void AssertEqual(float expexted, float actual, float tollerance) { AssertExtensions.LessThanOrEqualTo(Math.Abs(expexted - actual), tollerance); } private void AssertLine(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(1f, 1f), new PointF(2f, 2f) }; Assert.Equal(2, path.PathPoints.Length); Assert.Equal(2, path.PathTypes.Length); Assert.Equal(2, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 1f, 1f), path.GetBounds()); Assert.Equal(expectedPoints, path.PathPoints); Assert.Equal(new byte[] { 0, 1 }, path.PathTypes); } private void AssertArc(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(2.99990582f, 2.01370716f), new PointF(2.99984312f, 2.018276f), new PointF(2.99974918f, 2.02284455f), new PointF(2.999624f, 2.027412f), }; Assert.Equal(4, path.PathPoints.Length); Assert.Equal(4, path.PathTypes.Length); Assert.Equal(4, path.PathData.Points.Length); Assert.Equal(new RectangleF(2.99962401f, 2.01370716f, 0f, 0.0137047768f), path.GetBounds()); Assert.Equal(expectedPoints, path.PathPoints); Assert.Equal(new byte[] { 0, 3, 3, 3 }, path.PathTypes); } private void AssertBezier(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(1f, 1f), new PointF(2f, 2f), new PointF(3f, 3f), new PointF(4f, 4f), }; Assert.Equal(4, path.PointCount); Assert.Equal(4, path.PathPoints.Length); Assert.Equal(4, path.PathTypes.Length); Assert.Equal(4, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 3f, 3f), path.GetBounds()); Assert.Equal(expectedPoints, path.PathPoints); Assert.Equal(new byte[] { 0, 3, 3, 3 }, path.PathTypes); } private void AssertCurve(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(1f, 1f), new PointF(1.16666663f, 1.16666663f), new PointF(1.83333325f, 1.83333325f), new PointF(2f, 2f) }; Assert.Equal(4, path.PathPoints.Length); Assert.Equal(4, path.PathTypes.Length); Assert.Equal(4, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 1f, 1f), path.GetBounds()); AssertPointsSequenceEqual(expectedPoints, path.PathPoints, Delta); Assert.Equal(new byte[] { 0, 3, 3, 3 }, path.PathTypes); } private void AssertClosedCurve(GraphicsPath path) { Assert.Equal(10, path.PathPoints.Length); Assert.Equal(10, path.PathTypes.Length); Assert.Equal(10, path.PathData.Points.Length); Assert.Equal(new RectangleF(0.8333333f, 0.8333333f, 2.33333278f, 2.33333278f), path.GetBounds()); Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3, 3, 3, 131 }, path.PathTypes); } private void AssertRectangle(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(1f, 1f), new PointF(3f, 1f), new PointF(3f, 3f), new PointF(1f, 3f) }; Assert.Equal(4, path.PathPoints.Length); Assert.Equal(4, path.PathTypes.Length); Assert.Equal(4, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 2f, 2f), path.GetBounds()); Assert.Equal(expectedPoints, path.PathPoints); Assert.Equal(new byte[] { 0, 1, 1, 129 }, path.PathTypes); } private void AssertEllipse(GraphicsPath path) { Assert.Equal(13, path.PathPoints.Length); Assert.Equal(13, path.PathTypes.Length); Assert.Equal(13, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 2f, 2f), path.GetBounds()); Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 131 }, path.PathTypes); } private void AssertPie(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(2f, 2f), new PointF(2.99990582f, 2.01370716f), new PointF(2.99984312f, 2.018276f), new PointF(2.99974918f, 2.02284455f), new PointF(2.999624f, 2.027412f) }; Assert.Equal(5, path.PathPoints.Length); Assert.Equal(5, path.PathTypes.Length); Assert.Equal(5, path.PathData.Points.Length); AssertRectangleEqual(new RectangleF(2f, 2f, 0.9999058f, 0.0274119377f), path.GetBounds(), Delta); AssertPointsSequenceEqual(expectedPoints, path.PathPoints, Delta); Assert.Equal(new byte[] { 0, 1, 3, 3, 131 }, path.PathTypes); } private void AssertPolygon(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(1f, 1f), new PointF(2f, 2f), new PointF(3f, 3f) }; Assert.Equal(3, path.PathPoints.Length); Assert.Equal(3, path.PathTypes.Length); Assert.Equal(3, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 2f, 2f), path.GetBounds()); Assert.Equal(expectedPoints, path.PathPoints); Assert.Equal(new byte[] { 0, 1, 129 }, path.PathTypes); } private void AssertFlats(GraphicsPath flat, GraphicsPath original) { AssertExtensions.GreaterThanOrEqualTo(flat.PointCount, original.PointCount); for (int i = 0; i < flat.PointCount; i++) { Assert.NotEqual(3, flat.PathTypes[i]); } } private void AssertWrapNaN(GraphicsPath path) { byte[] expectedTypes = new byte[] { 0, 1, 129 }; Assert.Equal(3, path.PointCount); Assert.Equal(float.NaN, path.PathPoints[0].X); Assert.Equal(float.NaN, path.PathPoints[0].Y); Assert.Equal(float.NaN, path.PathPoints[1].X); Assert.Equal(float.NaN, path.PathPoints[1].Y); Assert.Equal(float.NaN, path.PathPoints[2].X); Assert.Equal(float.NaN, path.PathPoints[2].Y); Assert.Equal(expectedTypes, path.PathTypes); } private void AssertWiden3(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(4.2f, 4.5f), new PointF(15.8f, 4.5f), new PointF(10.0f, 16.1f), new PointF(10.4f, 14.8f), new PointF(9.6f, 14.8f), new PointF(14.6f, 4.8f), new PointF(15.0f, 5.5f), new PointF(5.0f, 5.5f), new PointF(5.4f, 4.8f) }; AssertPointsSequenceEqual(expectedPoints, path.PathPoints, 0.25f); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 1, 1, 1, 129 }, path.PathTypes); } private void AssertIsOutlineVisibleLine(Graphics graphics) { using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Red, 3.0f)) { gp.AddLine(10, 1, 14, 1); Assert.True(gp.IsOutlineVisible(10, 1, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(10, 2, pen, graphics)); Assert.False(gp.IsOutlineVisible(10, 2, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(11.0f, 1.0f, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(11.0f, 1.0f, pen, graphics)); Assert.False(gp.IsOutlineVisible(11.0f, 2.0f, Pens.Red, graphics)); Point point = new Point(12, 2); Assert.False(gp.IsOutlineVisible(point, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(point, pen, graphics)); point.Y = 1; Assert.True(gp.IsOutlineVisible(point, Pens.Red, graphics)); PointF fPoint = new PointF(13.0f, 2.0f); Assert.False(gp.IsOutlineVisible(fPoint, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(fPoint, pen, graphics)); fPoint.Y = 1; Assert.True(gp.IsOutlineVisible(fPoint, Pens.Red, graphics)); } } private void AssertIsOutlineVisibleRectangle(Graphics graphics) { using (Pen pen = new Pen(Color.Red, 3.0f)) using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(10, 10, 20, 20)); Assert.True(gp.IsOutlineVisible(10, 10, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(10, 11, pen, graphics)); Assert.False(gp.IsOutlineVisible(11, 11, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(11.0f, 10.0f, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(11.0f, 11.0f, pen, graphics)); Assert.False(gp.IsOutlineVisible(11.0f, 11.0f, Pens.Red, graphics)); Point point = new Point(15, 10); Assert.True(gp.IsOutlineVisible(point, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(point, pen, graphics)); point.Y = 15; Assert.False(gp.IsOutlineVisible(point, Pens.Red, graphics)); PointF fPoint = new PointF(29.0f, 29.0f); Assert.False(gp.IsOutlineVisible(fPoint, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(fPoint, pen, graphics)); fPoint.Y = 31.0f; Assert.True(gp.IsOutlineVisible(fPoint, pen, graphics)); } } private void AssertIsVisibleRectangle(Graphics graphics) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(10, 10, 20, 20)); Assert.False(gp.IsVisible(9, 9, graphics)); Assert.True(gp.IsVisible(10, 10, graphics)); Assert.True(gp.IsVisible(20, 20, graphics)); Assert.True(gp.IsVisible(29, 29, graphics)); Assert.False(gp.IsVisible(30, 29, graphics)); Assert.False(gp.IsVisible(29, 30, graphics)); Assert.False(gp.IsVisible(30, 30, graphics)); Assert.False(gp.IsVisible(9.4f, 9.4f, graphics)); Assert.True(gp.IsVisible(9.5f, 9.5f, graphics)); Assert.True(gp.IsVisible(10f, 10f, graphics)); Assert.True(gp.IsVisible(20f, 20f, graphics)); Assert.True(gp.IsVisible(29.4f, 29.4f, graphics)); Assert.False(gp.IsVisible(29.5f, 29.5f, graphics)); Assert.False(gp.IsVisible(29.5f, 29.4f, graphics)); Assert.False(gp.IsVisible(29.4f, 29.5f, graphics)); } } private void AssertIsVisibleEllipse(Graphics graphics) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddEllipse(new Rectangle(10, 10, 20, 20)); Assert.False(gp.IsVisible(10, 10, graphics)); Assert.True(gp.IsVisible(20, 20, graphics)); Assert.False(gp.IsVisible(29, 29, graphics)); Assert.False(gp.IsVisible(10f, 10f, graphics)); Assert.True(gp.IsVisible(20f, 20f, graphics)); Assert.False(gp.IsVisible(29.4f, 29.4f, graphics)); } } private void AssertReverse(GraphicsPath gp, PointF[] expectedPoints, byte[] expectedTypes) { gp.Reverse(); PointF[] reversedPoints = gp.PathPoints; byte[] reversedTypes = gp.PathTypes; int count = gp.PointCount; Assert.Equal(expectedPoints.Length, gp.PointCount); Assert.Equal(expectedTypes, gp.PathTypes); for (int i = 0; i < count; i++) { Assert.Equal(expectedPoints[i], reversedPoints[count - i - 1]); Assert.Equal(expectedTypes[i], reversedTypes[i]); } } private void AssertPointsSequenceEqual(PointF[] expected, PointF[] actual, float tolerance) { int count = expected.Length; Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < count; i++) { AssertExtensions.LessThanOrEqualTo(Math.Abs(expected[i].X - actual[i].X), tolerance); AssertExtensions.LessThanOrEqualTo(Math.Abs(expected[i].Y - actual[i].Y), tolerance); } } private void AssertRectangleEqual(RectangleF expected, RectangleF actual, float tolerance) { AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.X - actual.X), tolerance); AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.Y - actual.Y), tolerance); AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.Width - actual.Width), tolerance); AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.Height - actual.Height), tolerance); } } }
39.987983
145
0.542716
[ "MIT" ]
Mattlk13/corefx
src/System.Drawing.Common/tests/Drawing2D/GraphicsPathTests.cs
109,809
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.EKS")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Elastic Container Service for Kubernetes. Amazon Elastic Container Service for Kubernetes (Amazon EKS) is a fully managed service that makes it easy to deploy, manage, and scale containerized applications using Kubernetes on AWS.Amazon EKS runs Kubernetes management infrastructure for you across multiple AWS availability zones to eliminate a single point of failure. Amazon EKS is certified Kubernetes conformant so you can use existing tooling and plugins from partners and the Kubernetes community. Applications running on any standard Kubernetes environment are fully compatible and can be easily migrated to Amazon EKS.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Elastic Container Service for Kubernetes. Amazon Elastic Container Service for Kubernetes (Amazon EKS) is a fully managed service that makes it easy to deploy, manage, and scale containerized applications using Kubernetes on AWS.Amazon EKS runs Kubernetes management infrastructure for you across multiple AWS availability zones to eliminate a single point of failure. Amazon EKS is certified Kubernetes conformant so you can use existing tooling and plugins from partners and the Kubernetes community. Applications running on any standard Kubernetes environment are fully compatible and can be easily migrated to Amazon EKS.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Amazon Elastic Container Service for Kubernetes. Amazon Elastic Container Service for Kubernetes (Amazon EKS) is a fully managed service that makes it easy to deploy, manage, and scale containerized applications using Kubernetes on AWS.Amazon EKS runs Kubernetes management infrastructure for you across multiple AWS availability zones to eliminate a single point of failure. Amazon EKS is certified Kubernetes conformant so you can use existing tooling and plugins from partners and the Kubernetes community. Applications running on any standard Kubernetes environment are fully compatible and can be easily migrated to Amazon EKS.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Amazon Elastic Container Service for Kubernetes. Amazon Elastic Container Service for Kubernetes (Amazon EKS) is a fully managed service that makes it easy to deploy, manage, and scale containerized applications using Kubernetes on AWS.Amazon EKS runs Kubernetes management infrastructure for you across multiple AWS availability zones to eliminate a single point of failure. Amazon EKS is certified Kubernetes conformant so you can use existing tooling and plugins from partners and the Kubernetes community. Applications running on any standard Kubernetes environment are fully compatible and can be easily migrated to Amazon EKS.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Amazon Elastic Container Service for Kubernetes. Amazon Elastic Container Service for Kubernetes (Amazon EKS) is a fully managed service that makes it easy to deploy, manage, and scale containerized applications using Kubernetes on AWS.Amazon EKS runs Kubernetes management infrastructure for you across multiple AWS availability zones to eliminate a single point of failure. Amazon EKS is certified Kubernetes conformant so you can use existing tooling and plugins from partners and the Kubernetes community. Applications running on any standard Kubernetes environment are fully compatible and can be easily migrated to Amazon EKS.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Amazon Elastic Container Service for Kubernetes. Amazon Elastic Container Service for Kubernetes (Amazon EKS) is a fully managed service that makes it easy to deploy, manage, and scale containerized applications using Kubernetes on AWS.Amazon EKS runs Kubernetes management infrastructure for you across multiple AWS availability zones to eliminate a single point of failure. Amazon EKS is certified Kubernetes conformant so you can use existing tooling and plugins from partners and the Kubernetes community. Applications running on any standard Kubernetes environment are fully compatible and can be easily migrated to Amazon EKS.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.101.9")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
101.525424
723
0.809516
[ "Apache-2.0" ]
hyandell/aws-sdk-net
sdk/src/Services/EKS/Properties/AssemblyInfo.cs
5,990
C#
using Newtonsoft.Json; using Paystack.Net.SDK.Models.Subaccounts.CreateSubAccount; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Paystack.Net.SDK.Subaccounts { public class PaystackSubaccounts : ISubAccounts { private string _secretKey; public PaystackSubaccounts(string secretKey) { this._secretKey = secretKey; } public async Task<SubAccountModel> CreateSubAccount(string business_name, string settlement_bank, string account_number, float percentage_charge, string primary_contact_email = null, string primary_contact_name = null, string primary_contact_phone = null, string settlement_schedule = "auto") { var client = HttpConnection.CreateClient(this._secretKey); var bodyKeyValues = new List<KeyValuePair<string, string>>(); bodyKeyValues.Add(new KeyValuePair<string, string>("business_name", business_name)); bodyKeyValues.Add(new KeyValuePair<string, string>("settlement_bank", settlement_bank)); bodyKeyValues.Add(new KeyValuePair<string, string>("account_number", account_number)); bodyKeyValues.Add(new KeyValuePair<string, string>("percentage_charge", percentage_charge.ToString())); if (!string.IsNullOrWhiteSpace(primary_contact_email)) { bodyKeyValues.Add(new KeyValuePair<string, string>("primary_contact_email", primary_contact_email)); } if (!string.IsNullOrWhiteSpace(primary_contact_name)) { bodyKeyValues.Add(new KeyValuePair<string, string>("primary_contact_name", primary_contact_name)); } if (!string.IsNullOrWhiteSpace(primary_contact_phone)) { bodyKeyValues.Add(new KeyValuePair<string, string>("primary_contact_phone", primary_contact_phone)); } if (!string.IsNullOrWhiteSpace(settlement_schedule)) { bodyKeyValues.Add(new KeyValuePair<string, string>("settlement_schedule", settlement_schedule)); } var formContent = new FormUrlEncodedContent(bodyKeyValues); var response = await client.PostAsync("subaccount", formContent); var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<SubAccountModel>(json); } public async Task<SubAccountModel> FetchSubAccount(string subaccount_code) { var client = HttpConnection.CreateClient(this._secretKey); var response = await client.GetAsync($"subaccount/{subaccount_code}"); var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<SubAccountModel>(json); } public async Task<SubAccountListModel> ListSubAccounts() { var client = HttpConnection.CreateClient(this._secretKey); var response = await client.GetAsync("subaccount"); var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<SubAccountListModel>(json); } public async Task<SubAccountModel> UpdateSubAccount(string subaccount_code,string business_name = null, string settlement_bank = null, string account_number = null, float percentage_charge = 0, string primary_contact_email = null, string primary_contact_name = null, string primary_contact_phone = null, string settlement_schedule = "auto") { var client = HttpConnection.CreateClient(this._secretKey); var bodyKeyValues = new List<KeyValuePair<string, string>>(); if (!string.IsNullOrWhiteSpace(business_name)) { bodyKeyValues.Add(new KeyValuePair<string, string>("business_name", business_name)); } if (!string.IsNullOrWhiteSpace(settlement_bank)) { bodyKeyValues.Add(new KeyValuePair<string, string>("settlement_bank", settlement_bank)); } if (!string.IsNullOrWhiteSpace(account_number)) { bodyKeyValues.Add(new KeyValuePair<string, string>("account_number", account_number)); } if (percentage_charge > 0) { bodyKeyValues.Add(new KeyValuePair<string, string>("percentage_charge", percentage_charge.ToString())); } if (!string.IsNullOrWhiteSpace(primary_contact_email)) { bodyKeyValues.Add(new KeyValuePair<string, string>("primary_contact_email", primary_contact_email)); } if (!string.IsNullOrWhiteSpace(primary_contact_name)) { bodyKeyValues.Add(new KeyValuePair<string, string>("primary_contact_name", primary_contact_name)); } if (!string.IsNullOrWhiteSpace(primary_contact_phone)) { bodyKeyValues.Add(new KeyValuePair<string, string>("primary_contact_phone", primary_contact_phone)); } if (!string.IsNullOrWhiteSpace(settlement_schedule)) { bodyKeyValues.Add(new KeyValuePair<string, string>("settlement_schedule", settlement_schedule)); } var formContent = new FormUrlEncodedContent(bodyKeyValues); var response = await client.PutAsync($"subaccount/{subaccount_code}", formContent); var json = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<SubAccountModel>(json); } } }
41.704225
349
0.635596
[ "MIT" ]
Ezeji/Paystack.Net.SDK
Paystack.Net.SDK/Subaccounts/PaystackSubaccounts.cs
5,924
C#
using System.Web; using System.Web.Optimization; namespace WebConsumeAPI { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
38.8125
112
0.574074
[ "Unlicense" ]
ernestoaguaysol/WebConsumeAPI
WebConsumeAPI/App_Start/BundleConfig.cs
1,244
C#
using System; using Xunit; namespace Jsonyte.Tests { public class ValidationTests { [Fact(Skip = "These tests are still to be written")] public void CheckValidation() { throw new Exception(); } } }
17.066667
60
0.574219
[ "MIT" ]
jsonyte/jsonyte
src/Jsonyte.Tests/ValidationTests.cs
258
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Health : MonoBehaviour { public int health; public int heartsCount; public Image[] hearts; public Sprite fullHeart; public Sprite noHeart; // Update is called once per frame void Update() { for (int i = 0; i < hearts.Length; i++) { if (i < health) { hearts[i].sprite = fullHeart; } else { hearts[i].sprite = noHeart; } if(i < heartsCount) { hearts[i].enabled = true; } else { hearts[i].enabled = false; } } } }
19.463415
47
0.469925
[ "MIT" ]
mguib/GamePlataforma2D
GamePlataforma2D/Assets/Scripts/Health.cs
798
C#
#pragma warning disable CS0672,CS0809,CS1591 namespace AlibabaCloud.SDK.ROS.CDK.Emr.Internal.DependencyResolution { public sealed class Anchor { public Anchor() { new AlibabaCloud.SDK.ROS.CDK.Core.Internal.DependencyResolution.Anchor(); new Constructs.Internal.DependencyResolution.Anchor(); } } }
25.642857
85
0.67688
[ "Apache-2.0" ]
aliyun/Resource-Orchestration-Service-Cloud-Development-K
multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Emr/AlibabaCloud/SDK/ROS/CDK/Emr/Internal/DependencyResolution/Anchor.cs
359
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DropNet.Samples.Web { public partial class About { } }
24.333333
81
0.408676
[ "Apache-2.0" ]
chenkai/DropNet
DropNet.Samples/DropNet.Samples.Web/About.aspx.designer.cs
440
C#
using System; using System.Collections; using Server; using Server.Items; namespace Server.Mobiles { [CorpseName( "a glowing yomotsu corpse" )] public class YomotsuPriest : BaseCreature { public override WeaponAbility GetWeaponAbility() { return WeaponAbility.DoubleStrike; } [Constructable] public YomotsuPriest() : base( AIType.AI_Mage, FightMode.Closest, 10, 1, 0.2, 0.4 ) { Name = "a yomotsu priest"; Body = 253; BaseSoundID = 0x452; SetStr( 486, 530 ); SetDex( 101, 115 ); SetInt( 601, 670 ); SetHits( 486, 530 ); SetDamage( 8, 10 ); SetDamageType( ResistanceType.Physical, 100 ); SetResistance( ResistanceType.Physical, 65, 85 ); SetResistance( ResistanceType.Fire, 30, 50 ); SetResistance( ResistanceType.Cold, 45, 65 ); SetResistance( ResistanceType.Poison, 35, 55 ); SetResistance( ResistanceType.Energy, 25, 50 ); SetSkill( SkillName.EvalInt, 92.6, 107.5 ); SetSkill( SkillName.Magery, 105.1, 115.0 ); SetSkill( SkillName.Meditation, 100.1, 110.0 ); SetSkill( SkillName.MagicResist, 112.6, 122.5 ); SetSkill( SkillName.Tactics, 55.1, 105.0 ); SetSkill( SkillName.Wrestling, 47.6, 57.5 ); Fame = 9000; Karma = -9000; PackItem( new GreenGourd() ); PackItem( new ExecutionersAxe() ); switch ( Utility.Random( 3 ) ) { case 0: PackItem( new LongPants() ); break; case 1: PackItem( new ShortPants() ); break; } switch ( Utility.Random( 6 ) ) { case 0: PackItem( new Shoes() ); break; case 1: PackItem( new Sandals() ); break; case 2: PackItem( new Boots() ); break; case 3: PackItem( new ThighBoots() ); break; } if ( Utility.RandomDouble() < .25 ) PackItem( Engines.Plants.Seed.RandomBonsaiSeed() ); } public override FoodType FavoriteFood{ get{ return FoodType.Fish; } } public override int Meat{ get{ return 1; } } public override void GenerateLoot() { AddLoot( LootPack.FilthyRich ); AddLoot( LootPack.Rich ); AddLoot( LootPack.Gems, 4); } public override bool CanRummageCorpses{ get{ return true; } } // TODO: Body Transformation public override void OnGaveMeleeAttack( Mobile defender ) { base.OnGaveMeleeAttack( defender ); if ( 0.1 > Utility.RandomDouble() ) { /* Maniacal laugh * Cliloc: 1070840 * Effect: Type: "3" From: "0x57D4F5B" To: "0x0" ItemId: "0x37B9" ItemIdName: "glow" FromLocation: "(884 715, 10)" ToLocation: "(884 715, 10)" Speed: "10" Duration: "5" FixedDirection: "True" Explode: "False" * Paralyzes for 4 seconds, or until hit */ defender.FixedEffect( 0x37B9, 10, 5 ); defender.SendLocalizedMessage( 1070840 ); // You are frozen as the creature laughs maniacally. defender.Paralyze( TimeSpan.FromSeconds( 4.0 ) ); } } public YomotsuPriest( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int GetIdleSound() { return 0x42A; } public override int GetAttackSound() { return 0x435; } public override int GetHurtSound() { return 0x436; } public override int GetDeathSound() { return 0x43A; } } }
23.587413
212
0.657278
[ "BSD-2-Clause" ]
greeduomacro/vivre-uo
Scripts/Mobiles/Monsters/SE/YomotsuPriest.cs
3,373
C#
using EdjCase.ICP.Candid.Crypto; using EdjCase.ICP.Candid.Utilities; using System; using System.Linq; namespace EdjCase.ICP.Candid.Models { public class Principal : IHashable, IEquatable<Principal> { private const byte anonymousSuffix = 4; private const byte selfAuthenticatingSuffix = 2; public byte[] Raw { get; } public Principal(byte[] raw) { this.Raw = raw; } public string ToText() { // Add checksum to beginning of byte array; var crc32 = new CRC32(); byte[] checksum = crc32.ComputeHash(this.Raw); byte[] bytesWithChecksum = checksum.Concat(this.Raw).ToArray(); string base32String = Base32EncodingUtil.ToString(bytesWithChecksum); base32String = base32String.Trim('='); // Add a dash every 5 characters int dashCount = base32String.Length / 5; char[] chars = new char[base32String.Length + dashCount]; int offset = 0; for (int i = 0; i < base32String.Length; i++) { if (i % 5 == 0 && i != 0) { chars[i + offset] = '-'; offset += 1; } chars[i + offset] = base32String[i]; } return new string(chars); } public override string ToString() { return this.ToText(); } public string ToHex() { return ByteUtil.ToHexString(this.Raw); } public bool IsAnonymous() { return this.Raw.Length == 1 && this.Raw[0] == anonymousSuffix; } public static Principal ICManagementCanisterId() { return new Principal(new byte[0]); } public static Principal FromHex(string hex) { // TODO validation byte[] bytes = ByteUtil.FromHexString(hex); return new Principal(bytes); } public static Principal Anonymous() { return new Principal(new byte[] { anonymousSuffix }); } public static Principal SelfAuthenticating(IPublicKey publicKey) { byte[] digest = new SHA224().GenerateDigest(publicKey.GetRawBytes()); // bytes = digest + selfAuthenticatingSuffix byte[] bytes = new byte[digest.Length + 1]; digest.CopyTo(bytes.AsSpan()); bytes[bytes.Length - 1] = selfAuthenticatingSuffix; return new Principal(bytes); } public static Principal FromText(string text) { string canisterIdNoDash = text .ToLower() .Replace("-", ""); byte[] bytes = Base32EncodingUtil.ToBytes(canisterIdNoDash); // Remove first 4 bytes which is the checksum bytes = bytes .AsSpan() .Slice(4) .ToArray(); var principal = new Principal(bytes); string parsedText = principal.ToText(); if (parsedText != text) { throw new Exception($"Principal '{parsedText}' does not have a valid checksum."); } return principal; } public static Principal FromRaw(byte[] raw) { // TODO any validation? return new Principal(raw); } public byte[] ComputeHash(IHashFunction hashFunction) { return hashFunction.ComputeHash(this.Raw); } public bool Equals(Principal? other) { if (other == null) { return false; } return this.Raw.SequenceEqual(other.Raw); } public override bool Equals(object? obj) { return this.Equals(obj as Principal); } public override int GetHashCode() { return HashCode.Combine(this.Raw); } } }
28.163121
97
0.528834
[ "MIT" ]
Gekctek/ICP.NET
src/Candid/Models/Principal.cs
3,971
C#
//{[{ using System.Threading.Tasks; using Param_RootNamespace.Core.Services; //}]} namespace Param_RootNamespace.Core.Tests.XUnit { public class Tests { //^^ //{[{ // TODO WTS: Remove or update this once your app is using real data and not the SampleDataService. // This test serves only as a demonstration of testing functionality in the Core library. [Fact] public async void EnsureSampleDataServiceReturnsGridDataAsync() { var actual = await SampleDataService.GetGridDataAsync(); Assert.NotEmpty(actual); } //}]} } }
26.24
107
0.605183
[ "MIT" ]
Alfian878787/WindowsTemplateStudio
templates/Uwp/_comp/_shared/Test.UnitTests.Core.SampleData.Grids.xUnit/Param_ProjectName.Core.Tests.xUnit/Tests_postaction.cs
634
C#
using System; using System.Collections.Generic; using System.Data; using JetBrains.Annotations; namespace Backend.Fx.EfCorePersistence.Tests { public static class DbConnectionEx { public static void ExecuteNonQuery(this IDbConnection openConnection, string cmd) { using (IDbCommand command = openConnection.CreateCommand()) { command.CommandText = cmd; command.ExecuteNonQuery(); } } public static T ExecuteScalar<T>(this IDbConnection openConnection, string cmd) { using (IDbCommand command = openConnection.CreateCommand()) { command.CommandText = cmd; object scalarResult = command.ExecuteScalar(); if (typeof(T) == typeof(int)) return (T) (object) Convert.ToInt32(scalarResult); return (T) scalarResult; } } [UsedImplicitly] public static IEnumerable<T> ExecuteReader<T>(this IDbConnection openConnection, string cmd, Func<IDataReader, T> forEachResultFunc) { using (IDbCommand command = openConnection.CreateCommand()) { command.CommandText = cmd; IDataReader reader = command.ExecuteReader(); while (reader.NextResult()) yield return forEachResultFunc(reader); } } } }
34.658537
140
0.599578
[ "MIT" ]
marcwittke/Backend.Fx
tests/Backend.Fx.EfCorePersistence.Tests/DbConnectionEx.cs
1,421
C#
using FluentNHibernate.Mapping; using EasyLOB.Security.Data; namespace EasyLOB.Security.Persistence { public class RoleMap : ClassMap<Role> { public RoleMap() { #region Class Table("AspNetRoles"); Id(x => x.Id) .Column("Id") .CustomSqlType("varchar") .GeneratedBy.Assigned() .Length(128) .Not.Nullable(); Not.LazyLoad(); // GetById() EntityProxy => Entity #endregion Class #region Properties Map(x => x.Name) .Column("Name") .CustomSqlType("varchar") .Length(256) .Not.Nullable(); Map(x => x.Discriminator) .Column("Discriminator") .CustomSqlType("varchar") .Length(128) .Not.Nullable(); #endregion Properties #region Collections (PK) HasMany(x => x.ActivityRoles) .KeyColumn("RoleId"); HasMany(x => x.UserRoles) .KeyColumn("RoleId"); #endregion Collections (PK) } } }
24.307692
63
0.443829
[ "MIT" ]
EasyLOB/EasyLOB-1
EasyLOB.Security/EasyLOB.Security.PersistenceNHibernate/Maps/RoleMap.cs
1,264
C#
// Copyright (C) Dmitry Yakimenko (detunized@gmail.com). // Licensed under the terms of the MIT license. See LICENCE for details. using System; using System.ComponentModel; using Newtonsoft.Json; namespace PasswordManagerAccess.ZohoVault.Response { internal struct ResponseEnvelope<T> { [JsonProperty("operation", Required = Required.Always)] public readonly Operation<T> Operation; public T Payload => Operation.Details; } internal struct Operation<T> { [JsonProperty("name", Required = Required.Always)] public readonly string Name; [JsonProperty("result", Required = Required.Always)] public readonly Result Result; [JsonProperty("details", Required = Required.Always)] public readonly T Details; } internal struct Result { [JsonProperty("status", Required = Required.Always)] public readonly string Status; [JsonProperty("message", Required = Required.Always)] public readonly string Message; } internal struct AuthInfo { [JsonProperty("LOGIN", Required = Required.Always)] public readonly string KdfMethod; [JsonProperty("ITERATION", Required = Required.Always)] public readonly int Iterations; [JsonProperty("PASSPHRASE", Required = Required.Always)] public readonly string Passphrase; [JsonProperty("SALT", Required = Required.Always)] public readonly string Salt; } internal struct Vault { [JsonProperty("SECRETS", Required = Required.Always)] public readonly Secret[] Secrets; [JsonProperty("PRIVATEKEY", DefaultValueHandling = DefaultValueHandling.Populate)] [DefaultValue("")] public readonly string PrivateKey; [JsonProperty("SHARINGKEY", DefaultValueHandling = DefaultValueHandling.Populate)] [DefaultValue("")] public readonly string SharingKey; } internal struct Secret { [JsonProperty("SECRETID", Required = Required.Always)] public readonly string Id; [JsonProperty("SECRETNAME")] public readonly string Name; [JsonProperty("SECRETURL")] public readonly string Url; [JsonProperty("SECURENOTE")] public readonly string Note; [JsonProperty("SECRETDATA")] public readonly string Data; [JsonProperty("ISSHARED")] public readonly string IsShared; } internal struct SecretData { [JsonProperty("username")] public readonly string Username; [JsonProperty("password")] public readonly string Password; } internal class Status { [JsonProperty("status_code", Required = Required.Always)] public readonly int StatusCode; [JsonProperty("code")] public readonly string Code; [JsonProperty("message")] public readonly string Message; [JsonProperty("errors")] public readonly StatusError[] Errors; } internal readonly struct StatusError { [JsonProperty("code", Required = Required.Always)] public readonly string Code; [JsonProperty("message")] public readonly string Message; } internal class Lookup: Status { [JsonProperty("lookup")] public readonly LookupResult Result; [JsonProperty("data")] public readonly LookupRedirect Redirect; } internal class LookupResult { [JsonProperty("loginid", Required = Required.Always)] public readonly string Username; [JsonProperty("identifier", Required = Required.Always)] public readonly string UserId; [JsonProperty("digest", Required = Required.Always)] public readonly string Digest; [JsonProperty("dc", Required = Required.Always)] public readonly string DataCenter; } internal class LookupRedirect { [JsonProperty("redirect_uri", DefaultValueHandling = DefaultValueHandling.Populate)] [DefaultValue("")] public readonly string RedirectUrl; [JsonProperty("dc", DefaultValueHandling = DefaultValueHandling.Populate)] [DefaultValue("")] public readonly string DataCenter; } internal class LogIn: Status { [JsonProperty("passwordauth")] public readonly LogInResult Result; } internal class LogInResult { [JsonProperty("code")] public readonly string Code; [JsonProperty("token")] public readonly string MfaToken; [JsonProperty("modes")] public readonly MfaMethods MfaMethods; } internal class MfaMethods { [JsonProperty("allowed_modes", Required = Required.Always)] public readonly string[] AllowedMethods; [JsonProperty("totp")] public readonly MfaTotp Totp; [JsonProperty("yubikey")] public readonly MfaYubikey Yubikey; } internal class MfaTotp { } internal class MfaYubikey { [JsonProperty("yub-name")] public readonly string Name; } internal class Totp: Status { [JsonProperty("totpsecauth")] public readonly TotpResult Result; } internal class TotpResult { [JsonProperty("status")] public readonly string Status; } internal class TrustMfa: Status { [JsonProperty("trustmfa")] public readonly TrustMfaResult Result; } internal class TrustMfaResult { [JsonProperty("code")] public readonly string Code; [JsonProperty("redirect_uri")] public readonly string RedirectUrl; } }
25.475556
92
0.636602
[ "MIT" ]
detunized/password-manager-access
src/ZohoVault/Response.cs
5,732
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.CodeDom.Compiler; using Microsoft.CSharp; namespace WindowsFormsApp2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { System.IO.StreamWriter objWriter; objWriter = new System.IO.StreamWriter("code.txt", true); objWriter.WriteLine(textBox1.Text); objWriter.Close(); var csc = new CSharpCodeProvider(); string programPath = @"C:\Users\Valued Customer\Documents\Visual Studio 2017\Projects\WindowsFormsApp2\WindowsFormsApp2"; var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, programPath, true) { GenerateExecutable = true }; var code = @"code.txt"; CompilerResults result = csc.CompileAssemblyFromSource(parameters, code); } private void label1_Click(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } } }
26.736842
134
0.597769
[ "MIT" ]
Brenden2008/c-ide
Form1.cs
1,526
C#
using CafeLib.Data.Persistence; using CafeLib.Data.Sources; namespace CafeLib.Data.UnitTest.Identity { public class IdentityStorage : Storage<IdentityDomain> { public IdentityStorage(string connectionUri, IConnectionOptions options) : base(connectionUri, options) { } } }
24.692308
80
0.691589
[ "MIT" ]
chrissolutions/CafeLib
Data/CafeLib.Data.UnitTest.Identity/IdentityStorage.cs
323
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace ZombieApocalypse { public class Car { public static string carName = string.Empty; public static double carFuel; public static double carDeffence; public static int carType = new Random().Next(1, 6); public void CarType() { switch (carType) { case 1: carName = "Volvo"; carFuel = 100; carDeffence = 50; break; case 2: carName = "Citroen"; carFuel = 95; carDeffence = 60; break; case 3: carName = "BMW"; carFuel = 80; carDeffence = 75; break; case 4: carName = "Mercedes"; carFuel = 75; carDeffence = 100; break; case 5: carName = "VW"; carFuel = 70; carDeffence = 130; break; case 6: carName = "Audi"; carFuel = 60; carDeffence = 150; break; } } } }
26.109091
60
0.374652
[ "MIT" ]
georgidelchev/Zombie-Apocalypse-Console-Game
[Zombie-Apocalypse Console-Game]/Car.cs
1,438
C#
using System.Collections.Generic; using NHamcrest.Core; namespace NHamcrest { public static class Matches { public static IMatcher<T> AllOf<T>(IEnumerable<IMatcher<T>> matchers) { return new AllOfMatcher<T>(matchers); } public static IMatcher<T> AllOf<T>(params IMatcher<T>[] matchers) { return new AllOfMatcher<T>(matchers); } public static IMatcher<T> AnyOf<T>(IEnumerable<IMatcher<T>> matchers) { return new AnyOfMatcher<T>(matchers); } public static IMatcher<T> AnyOf<T>(params IMatcher<T>[] matchers) { return new AnyOfMatcher<T>(matchers); } /// <summary> /// This is useful for fluently combining matchers that must both pass. For example: /// <pre> /// Assert.That("ab", Matches.Both(Contains.String("a")).And(Contains.String("b"))); /// </pre> /// </summary> public static CombinableMatcher<T> Both<T>(IMatcher<T> matcher) { return new CombinableMatcher<T>(matcher); } /// <summary> /// This is useful for fluently combining matchers where either may pass, for example: /// <pre> /// Assert.That("ac", Matches.Either(Contains.String("a")).Or(Contains.String("b"))); /// </pre> /// </summary> public static CombinableMatcher<T> Either<T>(IMatcher<T> matcher) { return new CombinableMatcher<T>(matcher); } } }
30.94
94
0.56755
[ "MIT" ]
Lashas83/NHamcrest
src/NHamcrest/Matches.cs
1,547
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.Encodings.Web; using System.Threading.Tasks; using SimpleBlogEngine.Services; namespace SimpleBlogEngine.Services { public static class EmailSenderExtensions { public static Task SendEmailConfirmationAsync(this IEmailSender emailSender, string email, string link) { return emailSender.SendEmailAsync(email, "Confirm your email", $"Please confirm your account by clicking this link: <a href='{HtmlEncoder.Default.Encode(link)}'>link</a>"); } } }
31.315789
125
0.721008
[ "Apache-2.0" ]
c-sharpcommunity/SimpleBlogEngine
SimpleBlogEngine/SimpleBlogEngine/Extensions/EmailSenderExtensions.cs
595
C#
using System.Threading; namespace Novell.Directory.Ldap { public interface IDebugIdentifier { DebugId DebugId { get; } } public struct DebugId { private static int _id; private static int GetNextId() { // Rollover is OK in case we somehow end up with more than 2147483647 calls to this... return Interlocked.Increment(ref _id); } /// <summary> /// A name that can identify an object instance. /// </summary> private string Name { get; } /// <summary> /// An incrementing Id for every new object. /// Note: This Id increments for every newly generated DebugId, /// regardless of the Name. /// </summary> private int Id { get; } public override string ToString() => "[#" + Id + "] " + Name; public DebugId(string name) { Name = name; Id = GetNextId(); } public static DebugId ForType<T>() => new DebugId(typeof(T).FullName); } }
24.818182
98
0.534799
[ "MIT" ]
dogguts/Novell.Directory.Ldap.NETStandard
src/Novell.Directory.Ldap.NETStandard/IDebugIdentifier.cs
1,094
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Newtonsoft.Json.Serialization; namespace RemoteInspector.Server { public class IgnorePropertiesContractResolver : DefaultContractResolver { protected override List<MemberInfo> GetSerializableMembers( Type objectType ) { return objectType.GetFields( BindingFlags.Instance | BindingFlags.Public ).Cast<MemberInfo>().ToList(); } } }
29.8125
115
0.742138
[ "MIT" ]
sebtoun/UnityRemoteInspector
Assets/RemoteInspector/Server/IgnorePropertiesContractResolver.cs
479
C#