content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Threading.Tasks; using AspnetRunBasics.Models; using AspnetRunBasics.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace AspnetRunBasics { public class ProductDetailModel : PageModel { private readonly ICatalogService _catalogService; private readonly IBasketService _basketService; public ProductDetailModel(ICatalogService catalogService, IBasketService basketService) { _catalogService = catalogService; _basketService = basketService; } public CatalogModel Product { get; set; } [BindProperty] public string Color { get; set; } [BindProperty] public int Quantity { get; set; } public async Task<IActionResult> OnGetAsync(string productId) { if (productId == null) { return NotFound(); } Product = await _catalogService.GetCatalog(productId); if (Product == null) { return NotFound(); } return Page(); } public async Task<IActionResult> OnPostAddToCartAsync(string productId) { var product = await _catalogService.GetCatalog(productId); var userName = "swn"; var basket = await _basketService.GetBasket(userName); basket.Items.Add(new BasketItemModel { ProductId = productId, ProductName = product.Name, Price = product.Price, Quantity = Quantity, Color = Color }); var basketUpdated = await _basketService.UpdateBasket(basket); return RedirectToPage("Cart"); } } }
28.78125
95
0.580347
[ "MIT" ]
elequipoderiki/AspNetMicroservices
src/WebApps/AspnetRunBasics/Pages/ProductDetail.cshtml.cs
1,844
C#
using System; using System.Collections.Generic; using System.Text; namespace Sitefinity_CLI.Model { /// <summary> /// Represents a file model /// </summary> internal class FileModel { /// <summary> /// The target absolute file path /// </summary> public string FilePath { get; set; } /// <summary> /// The template absolute file path /// </summary> public string TemplatePath { get; set; } } }
21.086957
48
0.56701
[ "Apache-2.0" ]
DarrinRobertson/Sitefinity-CLI
Sitefinity CLI/Model/FileModel.cs
487
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("6.ReplaceATag")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("6.ReplaceATag")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b8dfaaf4-be9b-49de-b379-86f870dd7853")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.675676
84
0.746772
[ "MIT" ]
rdineva/Programming-Fundamentals
RegEx-Lab/6.ReplaceATag/Properties/AssemblyInfo.cs
1,397
C#
namespace DroneDefender.Common { public interface INullResultDictionarywhere<TKey, TValue> where TKey : class { TValue this[TKey key] { get; } } }
25.666667
59
0.733766
[ "MIT" ]
tomhsmith/DroneIsTheLoneliestNumber
Assets/Scripts/Common/INullResultDictionary.cs
156
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.Net; using System.Net.WebSockets; using System.Net.Sockets; using System.IO; using System.Drawing.Imaging; using Screna; namespace Receiver { public partial class Form1 : Form { public Socket s; public Form1() { InitializeComponent(); Task.Run(async () => { int failCounter = 0; TcpListener listener = TcpListener.Create(3000); while (true) { listener.Start(); s = await listener.AcceptSocketAsync(); while (s.Connected) { try { MemoryStream ms = new MemoryStream(); byte[] buffer = ReceiveImage(s); ms.Write(buffer, 0, buffer.Length); using (Bitmap bmp = new Bitmap(ms)) { //lock the bmp var rect = new Rectangle(0, 0, bmp.Width, bmp.Height); var bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat); try { ChangeBackground((Image)bmp.Clone()); bmp.Dispose(); } catch (Exception ex) { //throw ex; } //unlock the bmp bmp.UnlockBits(bmpData); bmp.Dispose(); } ms.Flush(); failCounter = 0; } catch (Exception ex) { failCounter++; if (failCounter > 500) { failCounter = 0; this.BackgroundImage = Properties.Resources.receiverBG; Invoke(new Action(delegate () { this.Width = 564; this.Height = 380; })); break; } //throw ex; } } s.Disconnect(true); } }); } public void ChangeBackground(Image img) { if (InvokeRequired) { Invoke(new Action<Image>(ChangeBackground), new object[] { img }); return; } int width = (this.Width/img.Width > this.Height/img.Height) ? this.Width : img.Width; int height = (this.Width / img.Width > this.Height / img.Height) ? this.Height : img.Height; this.BackgroundImage = new Bitmap(img, new Size(width, height)); } private static byte[] ReceiveImage(Socket s) { int total = 0; int recv; byte[] datasize = new byte[4]; recv = s.Receive(datasize, 0, 4, 0); int size = BitConverter.ToInt32(datasize, 0); int dataleft = size; byte[] data = new byte[size]; while (total < size) { recv = s.Receive(data, total, dataleft, 0); if (recv == 0) { break; } total += recv; dataleft -= recv; } return data; } } }
33.736434
108
0.357077
[ "MIT" ]
idan22moral/SimpleScreen
Receiver/Form1.cs
4,354
C#
using System; using System.IO; using System.Text; using System.Collections; using System.Windows.Forms; using System.Diagnostics; class Script { const string usage = "Usage: cscscript sample [sampleIndex]:[sampleName] [outputFile]\n\tCreates copy of a sample file.\n\n"+ "Example: cscscript sample MailTo \n"+ " cscscript sample 3 \n"; static public void Main(string[] args) { if ((args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help"))) { Console.WriteLine(usage); } else { string sampleDir = Environment.GetEnvironmentVariable("CSSCRIPT_DIR"); if (sampleDir == null) { Console.WriteLine("Feature is not available.\nC# Script engine was not installed properly."); return; } ArrayList sampleFiles = null; GetSamples(Path.Combine(sampleDir, "Samples"), ref sampleFiles); if (args.Length == 0) { Console.WriteLine(usage); ShowSamples(sampleFiles); } else if (args[0] == "?") { Console.WriteLine(usage); } else { if ((IsNumeric(args[0]) && Convert.ToInt32(args[0]) == 0) || args[0].ToUpper() == "default") { CreateDefaultSample((args.Length > 1) ? args[1] : "default.cs"); } else { string sampleFile = null; if (IsNumeric(args[0])) { sampleFile = (string)sampleFiles[Convert.ToInt32(args[0]) - 1]; } else { string sampleName = args[0].EndsWith(".cs") ? args[0] : args[0] + ".cs"; foreach (string file in sampleFiles) { if (file.ToLower().EndsWith(Path.ChangeExtension(sampleName.ToLower(), ".cs"))) { sampleFile = file; } } } if (sampleFile != null) { FileInfo flInfo = new FileInfo(sampleFile); string outputFile = (args.Length > 1) ? args[1] : flInfo.Name; if (!sampleFile.EndsWith(".cs")) { sampleFile += ".cs"; } if (!outputFile.EndsWith(".cs")) { outputFile += ".cs"; } try { if (File.Exists(outputFile)) { DialogResult res = MessageBox.Show( "The file "+Path.GetFileName(outputFile)+" already exist. Do you want to replace it?\n\n"+ "Click 'Yes' to replace the file, 'No' to create a new copy of the "+Path.GetFileName(outputFile)+ " or 'Cancel' to cancel the operation.", "CS-Script", MessageBoxButtons.YesNoCancel); if (res == DialogResult.Cancel) return; else if (res == DialogResult.No) outputFile = Path.Combine(Path.GetDirectoryName(outputFile), "Copy of "+Path.GetFileName(outputFile)); else File.Delete(outputFile); } File.Copy(sampleFile, outputFile); Console.WriteLine("File {0} has been created.", outputFile); } catch(Exception e) { Console.WriteLine("File {0} cannot be created.\n{1}", outputFile, e.Message); } } else { Console.WriteLine("Error: invalid argument specified.\n"); } } } } } static void CreateDefaultSample(string outputFile) { Process myProcess = new Process(); myProcess.StartInfo.FileName = "cscs.exe"; myProcess.StartInfo.Arguments = "/s"; myProcess.StartInfo.UseShellExecute = false; myProcess.StartInfo.RedirectStandardOutput = true; myProcess.StartInfo.CreateNoWindow = true; myProcess.Start(); StringBuilder builder = new StringBuilder(); string line = null; while (null != (line = myProcess.StandardOutput.ReadLine())) { builder.Append(line); builder.Append("\r\n"); } myProcess.WaitForExit(); using (StreamWriter sw = new StreamWriter(outputFile)) { sw.Write(builder.ToString()); } Console.WriteLine("File {0} has been created.", outputFile); } static bool IsNumeric(string stringVal) { try { Convert.ToInt32(stringVal); return true; } catch { return false; } } static void ShowSamples(ArrayList sampleFiles) { Console.WriteLine("Available samples:\n"); Console.WriteLine("0\t- Default <dafault code sceleton>"); int index = 1; string currentSampleDir = null; foreach (string sampleFile in sampleFiles) { FileInfo flInfo = new FileInfo(sampleFile); string dir = flInfo.Directory.FullName; if (currentSampleDir == null || currentSampleDir != dir) { Console.WriteLine("\n{0}", dir); currentSampleDir = dir; } Console.WriteLine("{0}\t- {1}", index, flInfo.Name); index++; } } static void GetSamples(string sampleDir, ref ArrayList sampleFiles) { try { if (sampleFiles == null) { sampleFiles = new ArrayList(); } foreach(string fileName in Directory.GetFileSystemEntries(sampleDir, string.Format("*.cs"))) { sampleFiles.Add(fileName); } foreach (string subDir in Directory.GetDirectories(sampleDir)) { GetSamples(subDir, ref sampleFiles); } } catch (System.IO.IOException) { System.Console.WriteLine("An I/O error occurs."); } catch (System.Security.SecurityException) { System.Console.WriteLine("The caller does not have the " + "required permission."); } } }
26.83
127
0.597838
[ "MIT" ]
Diullei/Storm
Libs/cs-script/Lib/sample.cs
5,366
C#
namespace CavemanTools.Data { public enum JsonStatus { Ok, Error, Redirect } }
12.666667
27
0.526316
[ "Apache-2.0" ]
sapiens/cavemantools
src/CavemanTools/Data/JsonStatus.cs
114
C#
using System; using System.IO; 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; namespace LogApp { public partial class LogForm : Form { public LogForm() { InitializeComponent(); LoadForm(); } public void LoadForm() { version_new.Text = new PathInfor().Get_Version("New"); version_now.Text = new PathInfor().Get_Version("Now"); } public void LogForm_Load(object sender, EventArgs e){ Form.CheckForIllegalCrossThreadCalls = false; timer1.Start(); } private void bt_save_Click(object sender, EventArgs e) { if (GridArea.Rows.Count <= 0 || GridArea.Rows[0].Cells[1].Value == null) { MessageBox.Show("尚未輸入資料", "提示視窗", MessageBoxButtons.OK); return; } if (GridArea.Rows.Count > 0) { //取得來源路徑 string path =new PathInfor().Origin; if (!File.Exists(path)) File.WriteAllText(path, ""); //取得目前檔案內容 StringBuilder strData = new StringBuilder("").Append(File.ReadAllText(path)); //宣告要設定得資料 StringBuilder strDefault= new StringBuilder(""); strDefault.Append(version_new.Text + "\n\n" + Get_ColumsStr()) ; strDefault.Append("----------------------------------------------------------------------------\n"); foreach (DataGridViewRow dr in GridArea.Rows) { string Check = dr.Cells[0].Value != null && (bool)dr.Cells[0].Value == true ? "OK" : ""; string strFormat = string.Format("{0,-15}{1,-15}{2,-15}{3,-15}{4,-15}" , Check, dr.Cells[1].Value, dr.Cells[2].Value, dr.Cells[3].Value, dr.Cells[4].Value); strDefault.Append(strFormat+"\n"); } strDefault.Append("----------------------------------------------------------------------------\n\n\n"); if (MessageBox.Show("是否確定存檔", "訊息", MessageBoxButtons.OKCancel) == DialogResult.OK) { try { timer1.Stop(); File.WriteAllText(path, strDefault.ToString() + strData.ToString()); MessageBox.Show("存檔成功", "訊息", MessageBoxButtons.OK); GridArea.Rows.Clear(); timer1.Start(); } catch (Exception ex) { throw ex; } } } } private void GridArea_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { if(GridArea.Rows[e.RowIndex].Cells[1].Value != null) { GridArea.Rows[e.RowIndex].Cells[3].Value = e.RowIndex + 1; } } private void bt_Setting_Click(object sender, EventArgs e) { Setting setting = new Setting(); setting.Show(); } private void bt_open_Click(object sender, EventArgs e) { if (File.Exists(new PathInfor().Origin)) { System.Diagnostics.Process.Start(new PathInfor().Origin); } else { MessageBox.Show("無此檔案", "訊息", MessageBoxButtons.OK); } } private void bt_exit_Click(object sender, EventArgs e) => Application.Exit(); private string Get_ColumsStr() { string str = ""; foreach (DataGridViewColumn dr in GridArea.Columns) { str += string.Format("{0,-15}", dr.HeaderText); } return str + "\n"; } private void bt_rush_Click(object sender, EventArgs e) { LoadForm(); } private void timer1_Tick(object sender, EventArgs e) { bt_rush_Click(sender,e); } } }
37.419643
154
0.48628
[ "MIT" ]
JontCont/writeLogVersion
LogApp/LogApp/Form1.cs
4,297
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: ComplexType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Text.Json.Serialization; /// <summary> /// The type WindowsUpdateInstallScheduleType. /// </summary> [JsonConverter(typeof(DerivedTypeConverter<WindowsUpdateInstallScheduleType>))] public abstract partial class WindowsUpdateInstallScheduleType { /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData] public IDictionary<string, object> AdditionalData { get; set; } /// <summary> /// Gets or sets @odata.type. /// </summary> [JsonPropertyName("@odata.type")] public string ODataType { get; set; } } }
32.342105
153
0.571196
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/model/WindowsUpdateInstallScheduleType.cs
1,229
C#
using System.ComponentModel.DataAnnotations; namespace Kiwi_review.Models.UpdateDto { public class MovieUpdateModel { [Required] public int MovieId { get; set; } [MaxLength(200)] public string? MovieDescription { get; set; } public bool OnlyHighlightOnce { get; set; } } }
28.181818
70
0.680645
[ "MIT" ]
LANNDS18/Kiwi_Review
Models/UpdateDto/MovieUpdateModel.cs
312
C#
namespace CoolMvcTemplate.Data.Configurations { using CoolMvcTemplate.Data.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; public class AppUserConfiguration : IEntityTypeConfiguration<AppUser> { public void Configure(EntityTypeBuilder<AppUser> appUser) { appUser .HasMany(e => e.Claims) .WithOne() .HasForeignKey(e => e.UserId) .IsRequired() .OnDelete(DeleteBehavior.Restrict); appUser .HasMany(e => e.Logins) .WithOne() .HasForeignKey(e => e.UserId) .IsRequired() .OnDelete(DeleteBehavior.Restrict); appUser .HasMany(e => e.Roles) .WithOne() .HasForeignKey(e => e.UserId) .IsRequired() .OnDelete(DeleteBehavior.Restrict); } } }
28.857143
73
0.529703
[ "MIT" ]
georgy-kirilov/CoolMvcTemplate
src/Data/CoolMvcTemplate.Data/Configurations/AppUserConfiguration.cs
1,012
C#
using System; using DataLinq; using DataLinq.Interfaces; using DataLinq.Attributes; namespace DataLinq.MySql.Models { [Name("INNODB_CMP_RESET")] public interface INNODB_CMP_RESET : IViewModel { [Type("int")] int compress_ops { get; } [Type("int")] int compress_ops_ok { get; } [Type("int")] int compress_time { get; } [Type("int")] int page_size { get; } [Type("int")] int uncompress_ops { get; } [Type("int")] int uncompress_time { get; } } }
18.733333
50
0.560498
[ "MIT" ]
bazer/DataLinq
src/DataLinq.MySql/Models/information_schema/Views/INNODB_CMP_RESET.cs
562
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entities.Models { public class Employee { [Column("EmployeeId")] public Guid Id { get; set; } [Required(ErrorMessage = "Employee name is a required field.")] [MaxLength(30, ErrorMessage = "Maximum length for the Name is 30 characters.")] public string Name { get; set; } [Required(ErrorMessage = "Age is a required field.")] public int Age { get; set; } [Required(ErrorMessage = "Position is a required field.")] [MaxLength(20, ErrorMessage = "Maximum length for the Position is 20 characters.")] public string Position { get; set; } [ForeignKey(nameof(Company))] public Guid CompanyId { get; set; } public Company Company { get; set; } } }
30.8125
91
0.661258
[ "MIT" ]
Mohammad-Nour-Rezek/CompanyEmployeesComponent
backend/Entities/Models/Employee.cs
988
C#
namespace LottoLion.BaseLib.Models.Entity { public partial class TbLionSelect { public int SequenceNo { get; set; } public int SelectNo { get; set; } public short Digit1 { get; set; } public short Digit2 { get; set; } public short Digit3 { get; set; } public short Digit4 { get; set; } public short Digit5 { get; set; } public short Digit6 { get; set; } public bool? IsUsed { get; set; } public bool? IsLeft { get; set; } public short Ranking { get; set; } public decimal Amount { get; set; } public string Remark { get; set; } } }
14.628571
42
0.361328
[ "MIT" ]
lisa3907/lotto.lion
src/proxy/lion.baselib/Models/entities/TbLionSelect.cs
1,026
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EncompassREST.Data { public class Tax4506 { public bool? tax4506TIndicator { get; set; } public bool? historyIndicator { get; set; } public string person { get; set; } public string sendAddress { get; set; } public string sendCity { get; set; } public string sendState { get; set; } public string sendZip { get; set; } public bool? ifTaxRecordNotFound { get; set; } public bool? theseCopiesMustBeCertified { get; set; } public string first { get; set; } public string taxFormNumber { get; set; } public DateTime? requestYear1 { get; set; } public DateTime? requestYear2 { get; set; } public string requestorPhoneNumber { get; set; } public string requestorTitle { get; set; } public DateTime? requestYear3 { get; set; } public string last { get; set; } public DateTime? requestYear4 { get; set; } public int? numberOfPeriods { get; set; } public decimal? totalCost { get; set; } public string address { get; set; } public string city { get; set; } public string state { get; set; } public string zip { get; set; } public string currentFirst { get; set; } public string sSN { get; set; } public string currentLast { get; set; } public string returnAddress { get; set; } public string returnCity { get; set; } public string returnState { get; set; } public string returnZip { get; set; } public string sendPhone { get; set; } public bool? returnTranscript { get; set; } public bool? accountTranscript { get; set; } public bool? recordOfAccount { get; set; } public bool? verificationOfNonfiling { get; set; } public string spouseSSN { get; set; } public bool? formsSeriesTranscript { get; set; } public decimal? costForEachPeriod { get; set; } public DateTime? requestYear5 { get; set; } public DateTime? requestYear6 { get; set; } public DateTime? requestYear7 { get; set; } public DateTime? requestYear8 { get; set; } public bool? useEIN { get; set; } public bool? spouseUseEIN { get; set; } public bool? useWellsFargoRules { get; set; } public bool? notifiedIrsIdentityTheftIndicator { get; set; } public string spouseFirst { get; set; } public string spouseLast { get; set; } public string sendFirst { get; set; } public string sendLast { get; set; } public string selectedRecordNumber { get; set; } public bool? signatoryAttestation { get; set; } public bool? signatoryAttestationT { get; set; } public DateTime? lastUpdatedDate { get; set; } public string lastUpdatedTime { get; set; } public string historyId { get; set; } public int? lastUpdatedHistory { get; set; } public string id { get; set; } public int? tax4506Index { get; set; } } }
42.797297
68
0.615409
[ "MIT" ]
sgandewar/EncompassAPI
Data/Tax4506.cs
3,167
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using TranscendenceChat.ServerClient.Entities; namespace TranscendenceChat.ServerClient.Interfaces { public interface IUserManager { Task<User> GetUserViaEmail(int id); Task<User> GetUserViaEmail(string email); Task<UserFlag> FlagUser(int id, int flagid); Task<List<Flag>> GetFlags(); Task<bool> SendUserInvite(string email); Task<bool> SendLinkEmailToCurrentUser(string email); Task<bool> SendLinkPhoneToCurrentUser(string phone); Task<bool> LinkPhoneNumberToCurrentUser(string phone, string confirmKey); Task<bool> LinkEmailToCurrentUser(string email, string confirmKey); Task<bool> ChangeNickname(string nickname); Task<Avatar> SetAvatarFromList(int id); Task<Avatar> AddCustomAvatar(Stream image); Task<bool> UpdateUserProfile(User user); Task<bool> VerifyUserExistsViaEmail(string email); Task<bool> VerifyUserExistsViaPhone(string phone); } }
25.681818
81
0.714159
[ "MIT" ]
tamifist/Transcendence
TranscendenceChat.ServerClient/Interfaces/IUserManager.cs
1,132
C#
/* Copyright © Bryan Apellanes 2015 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bam.Net.Data.Repositories { [Serializable] public class MetaId { public ulong Value { get; set; } } }
15.388889
35
0.736462
[ "MIT" ]
BryanApellanes/bam.net.shared
Data/Repositories/MetaId.cs
278
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Serial_port_read_tests { static class Program { /// <summary> /// Point d'entrée principal de l'application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } } }
23.73913
66
0.59707
[ "MIT" ]
Thynkon/projet-heartBeat
Tests/Serial port/Program.cs
549
C#
using System; using System.Collections.Generic; using System.Text; namespace MarvinEde.CoreExtensions { /// <summary> /// Static class to hold all extensions for <see cref="System.Object"/>, so they can be called from anywhere with "this." /// </summary> public static class Object { /// <summary> /// Swaps the two references a and b. This method handles the temporary variable for you. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="justForSyntax"></param> /// <param name="a"></param> /// <param name="b"></param> public static void Swap<T>(this object justForSyntax, ref T a, ref T b) { T temp = b; b = a; a = temp; } /// <summary> /// Calls the action with the <paramref name="object"/> and then returns the <paramref name="object"/>. This can be useful for inline debugging or manipulating the object before calling other methods on it. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="object"></param> /// <param name="action"></param> /// <returns></returns> public static T Tab<T>(this T @object, Action<T> action) { action(@object); return @object; } } }
33.85
214
0.559823
[ "MIT" ]
AKnopf/MarvinEde.CoreExtensions
CoreExtensions/Object.cs
1,356
C#
using System; using System.Collections.Generic; namespace SensateIoT.Platform.Router.Contracts.DTO { public class GenericResponse<TValue> { public Guid Id { get; } public TValue Data { get; set; } public IEnumerable<string> Errors { get; set; } public GenericResponse() { this.Id = Guid.NewGuid(); } } }
18.055556
50
0.698462
[ "Apache-2.0" ]
sensate-iot/SensateService
SensateIoT.Platform.Router.Contracts/DTO/GenericResponse.cs
327
C#
using System; namespace Hanoi { public static class StreamElements { /// <summary> /// XMPP Stream XML root node name /// </summary> internal static readonly string XmppStreamName = "stream:stream"; /// <summary> /// XMPP Stream XML open node tag /// </summary> internal static readonly string XmppStreamOpen = String.Format("<{0} ", XmppStreamName); /// <summary> /// XMPP Stream XML close node tag /// </summary> internal static readonly string XmppStreamClose = String.Format("</{0}>", XmppStreamName); /// <summary> /// XMPP DNS SRV Record prefix /// </summary> internal static string XmppSrvRecordPrefix = "_xmpp-client._tcp"; } }
29.148148
98
0.578145
[ "BSD-3-Clause" ]
MustafaUzumcuCom/Hanoi
source/Hanoi/StreamElements.cs
787
C#
using FluentMigrator; namespace Bd.Icm.Migrations.Scripts { [Migration(201603110005)] public class CreateTableInstrument : Migration { public override void Up() { Create.Table("Instrument") .WithColumn("Id").AsInt32().NotNullable().PrimaryKey() .WithRowVersionIdentity() .WithColumn("Type").AsString(150).NotNullable() .WithColumn("NickName").AsString(150).Nullable() .WithColumn("SerialNumber").AsString(100).NotNullable() .WithAuditFields() .WithVersioningFields(); this.CreateUserForeignKeys("Instrument"); Create.ForeignKey("FK_Instrument_InstrumentVersion") .FromTable("Instrument").InSchema("dbo").ForeignColumn("Id") .ToTable("InstrumentVersion").InSchema("dbo").PrimaryColumn("InstrumentId"); } public override void Down() { this.DeleteUserForeignKeys("Instrument"); Delete.DefaultConstraint().OnTable("Instrument").InSchema("dbo").OnColumn("EffectiveTo"); Delete.ForeignKey("FK_Instrument_InstrumentVersion").OnTable("Instrument"); Delete.Table("Instrument"); } } }
36.685714
101
0.596573
[ "MIT" ]
aliostad/deep-learning-lang-detection
data/train/csharp/491e4aaab67881b22cc8651167dbad7384f58095CreateTableInstrument.cs
1,286
C#
using System; using System.Collections.Generic; using System.Linq; namespace Prism.Modularity { /// <summary> /// The <see cref="ModuleCatalog"/> holds information about the modules that can be used by the /// application. Each module is described in a <see cref="ModuleInfo"/> class, that records the /// name and type of the module. /// </summary> public class ModuleCatalog : IModuleCatalog { private readonly List<ModuleInfo> _items = new List<ModuleInfo>(); /// <summary> /// Gets all the <see cref="ModuleInfo"/> classes that are in the <see cref="ModuleCatalog"/>. /// </summary> public IEnumerable<ModuleInfo> Modules { get { return _items; } } /// <summary> /// Adds a <see cref="ModuleInfo"/> to the <see cref="ModuleCatalog"/>. /// </summary> /// <param name="moduleInfo">The <see cref="ModuleInfo"/> to add.</param> /// <returns>The <see cref="ModuleCatalog"/> for easily adding multiple modules.</returns> public IModuleCatalog AddModule(ModuleInfo moduleInfo) { if (_items.Any(mi => mi.ModuleName == moduleInfo.ModuleName)) throw new Exception($"A duplicated module with name {moduleInfo.ModuleName} has already been added."); if (_items.Any(mi => mi.ModuleType == moduleInfo.ModuleType)) throw new Exception($"A duplicate module of type {moduleInfo.ModuleType.Name} has already been added."); _items.Add(moduleInfo); return this; } /// <summary> /// Makes sure all modules have an Unique name. /// </summary> /// <exception cref="Exception"> /// Thrown if the names of one or more modules are not unique. /// </exception> protected virtual void ValidateUniqueModules() { List<string> moduleNames = this.Modules.Select(m => m.ModuleName).ToList(); string duplicateModule = moduleNames.FirstOrDefault(m => moduleNames.Count(m2 => m2 == m) > 1); if (duplicateModule != null) throw new Exception(String.Format("A duplicated module with name {0} has been found by the loader.", duplicateModule)); } /// <summary> /// Initializes the catalog, which may load and validate the modules. /// </summary> public virtual void Initialize() { } } }
37.772727
135
0.596069
[ "MIT" ]
dansiegel/Prism
Source/Xamarin/Prism.Forms/Modularity/ModuleCatalog.cs
2,495
C#
 using UnityEngine; using System.Collections; //this is an example of how to build a senario, later ideally we will have some editor tools that makes instances of this in an easier to use visual format public class PracticeSenario : MonoBehaviour { public int width, depth; float offset = 1f; [Tooltip("Set these for where gathering nodes will be, the grid builds down, so 0,0 is the top left where maxX/maxY is the bottom right")] public Vector2[] harvestingPoints; [Tooltip("Set these for where gathering nodes will be, the grid builds down, so 0,0 is the top left where maxX/maxY is the bottom right")] public Vector2[] OutPutPos; public Vector2[] blockagePos; public float startingReource; public void Init() { GameObject grid = new GameObject(); Grid myGrid = grid.AddComponent<Grid>().BuildGrid(grid, depth, width, offset); InitGridPieces myInit = new InitGridPieces(); myInit.PopulateGrid(myGrid, harvestingPoints, OutPutPos, blockagePos); ResourceManager.rManager.initReource(startingReource); } } /*modified code: This, gridPiece, prefabLib, initgridpieces */
28.833333
156
0.691164
[ "MIT" ]
vaccaris/NonStopWorkShop
Scripts/SandBox/PracticeSenario.cs
1,213
C#
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Avalonia.LogicalTree; namespace Avalonia.Controls { /// <summary> /// Extension methods for <see cref="INameScope"/>. /// </summary> public static class NameScopeExtensions { /// <summary> /// Finds a named element in an <see cref="INameScope"/>. /// </summary> /// <typeparam name="T">The element type.</typeparam> /// <param name="nameScope">The name scope.</param> /// <param name="name">The name.</param> /// <returns>The named element or null if not found.</returns> public static T Find<T>(this INameScope nameScope, string name) where T : class { Contract.Requires<ArgumentNullException>(nameScope != null); Contract.Requires<ArgumentNullException>(name != null); var result = nameScope.Find(name); if (result != null && !(result is T)) { throw new InvalidOperationException( $"Expected control '{name}' to be '{typeof(T)} but it was '{result.GetType()}'."); } return (T)result; } /// <summary> /// Gets a named element from an <see cref="INameScope"/> or throws if no element of the /// requested name was found. /// </summary> /// <typeparam name="T">The element type.</typeparam> /// <param name="nameScope">The name scope.</param> /// <param name="name">The name.</param> /// <returns>The named element.</returns> public static T Get<T>(this INameScope nameScope, string name) where T : class { Contract.Requires<ArgumentNullException>(nameScope != null); Contract.Requires<ArgumentNullException>(name != null); var result = nameScope.Find(name); if (result == null) { throw new KeyNotFoundException($"Could not find control '{name}'."); } if (!(result is T)) { throw new InvalidOperationException( $"Expected control '{name}' to be '{typeof(T)} but it was '{result.GetType()}'."); } return (T)result; } public static INameScope FindNameScope(this ILogical control) { Contract.Requires<ArgumentNullException>(control != null); return control.GetSelfAndLogicalAncestors() .OfType<StyledElement>() .Select(x => (x as INameScope) ?? NameScope.GetNameScope(x)) .FirstOrDefault(x => x != null); } } }
35.320988
104
0.564138
[ "MIT" ]
Karlyshev/Avalonia
src/Avalonia.Styling/Controls/NameScopeExtensions.cs
2,861
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from shared/mmreg.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="CONTRESCR10WAVEFORMAT" /> struct.</summary> public static unsafe partial class CONTRESCR10WAVEFORMATTests { /// <summary>Validates that the <see cref="CONTRESCR10WAVEFORMAT" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<CONTRESCR10WAVEFORMAT>(), Is.EqualTo(sizeof(CONTRESCR10WAVEFORMAT))); } /// <summary>Validates that the <see cref="CONTRESCR10WAVEFORMAT" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(CONTRESCR10WAVEFORMAT).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="CONTRESCR10WAVEFORMAT" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(CONTRESCR10WAVEFORMAT), Is.EqualTo(20)); } }
38.657143
145
0.727273
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/shared/mmreg/CONTRESCR10WAVEFORMATTests.cs
1,355
C#
using PhramacyLibrary.Model; using PharmacyLibrary.IRepository; using PharmacyLibrary.Model; using PharmacyLibrary.Repository; using System; using System.Collections.Generic; using System.Text; namespace PharmacyLibrary.Services { public class HospitalService { private readonly IHospitalRepository hospitalRepository; public HospitalService(DatabaseContext context) { hospitalRepository = new HospitalRepository(context); } public List<Hospital> GetAll() { return hospitalRepository.GetAll(); } public Hospital FindById(int id) { return hospitalRepository.FindById(id); } public void Add(Hospital hospital) { hospitalRepository.Add(hospital); } public void Update(Hospital hospital) { hospitalRepository.Update(hospital); } public void Delete(int id) { hospitalRepository.Delete(id); } public void Save() { hospitalRepository.Save(); } } }
25.340909
65
0.61435
[ "MIT" ]
magdalenaRA822018/slack
PharmacyLibrary/Services/HospitalService.cs
1,117
C#
using System; class URI { static void Main(string[] args) { var line = Console.ReadLine(); var data = line.Split(' '); var x = double.Parse(data[0]); var y = double.Parse(data[1]); if (x == 0 && y == 0) { Console.WriteLine("Origem"); } else if (x == 0) { Console.WriteLine("Eixo Y"); } else if (y == 0) { Console.WriteLine("Eixo X"); } else if (x > 0 && y > 0) { Console.WriteLine("Q1"); } else if (x > 0 && y < 0) { Console.WriteLine("Q4"); } else if (x < 0 && y > 0) { Console.WriteLine("Q2"); } else { Console.WriteLine("Q3"); } } }
22.266667
45
0.312375
[ "Unlicense" ]
Reilly27/Tasks
URI/BEGINNER/25.cs
1,002
C#
namespace Blobs.IO { using System; using Interfaces; public class ConsoleOutputWriter : IOutputWriter { public void Write(string output) { Console.WriteLine(output); } } }
16.428571
52
0.582609
[ "MIT" ]
Supbads/Softuni-Education
03. HighQualityCode 12.15/Homework/04. Code-Documentation-and-Comments-Homework/Interfaces Documentation/OOP_Exam_Blobs/Blobs/IO/ConsoleOutputWriter.cs
232
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("EasyWMIDemo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EasyWMIDemo")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("df40b6ba-22ff-4b97-ab5f-69d5858c799b")] // 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.675676
85
0.726066
[ "MIT" ]
aamay001/EasyWMI
EasyWMI/EasyWMIDemo/Properties/AssemblyInfo.cs
1,434
C#
using System; using PF; using UnityEngine; namespace ET { [ActorMessageHandler] public class G2M_CreateUnitHandler : AMActorRpcHandler<Scene, G2M_CreateUnit, M2G_CreateUnit> { protected override async ETTask Run(Scene scene, G2M_CreateUnit request, M2G_CreateUnit response, Action reply) { Unit unit = EntityFactory.CreateWithId<Unit>(scene, IdGenerater.GenerateId()); unit.AddComponent<MoveComponent>(); unit.AddComponent<UnitPathComponent>(); unit.Position = new Vector3(-10, 0, -10); unit.AddComponent<MailBoxComponent>(); await unit.AddLocation(); unit.AddComponent<UnitGateComponent, long>(request.GateSessionId); scene.GetComponent<UnitComponent>().Add(unit); response.UnitId = unit.Id; // 广播创建的unit M2C_CreateUnits createUnits = new M2C_CreateUnits(); Unit[] units = scene.GetComponent<UnitComponent>().GetAll(); foreach (Unit u in units) { UnitInfo unitInfo = new UnitInfo(); unitInfo.X = u.Position.x; unitInfo.Y = u.Position.y; unitInfo.Z = u.Position.z; unitInfo.UnitId = u.Id; createUnits.Units.Add(unitInfo); } MessageHelper.Broadcast(unit, createUnits); reply(); } } }
28.166667
113
0.715131
[ "MIT" ]
Ecstasyzzz/ET
Server/Hotfix/Demo/G2M_CreateUnitHandler.cs
1,195
C#
using System.Collections.Generic; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geometry; using ProSuite.QA.Container; using ProSuite.QA.Container.Geometry; using ProSuite.Commons.AO.Geometry; using ProSuite.Commons.Essentials.Assertions; using ProSuite.Commons.Essentials.CodeAnnotations; namespace ProSuite.QA.Tests.EdgeMatch { internal abstract class EdgeMatchBorderConnectionUnion<TNeighbors, TNeighborConnection, TBorderConnection> where TNeighbors : EdgeMatchNeighbors<TNeighborConnection, TBorderConnection> where TNeighborConnection : EdgeMatchNeighborConnection<TBorderConnection> where TBorderConnection : EdgeMatchSingleBorderConnection { private readonly Dictionary<FeatureKey, Dictionary<FeatureKey, TNeighbors>> _borderConnections; protected EdgeMatchBorderConnectionUnion() { _borderConnections = new Dictionary<FeatureKey, Dictionary<FeatureKey, TNeighbors>>( new FeatureKeyComparer()); } [NotNull] public TNeighbors GetNeighbors( [NotNull] TBorderConnection borderConnection) { Dictionary<FeatureKey, TNeighbors> neighborsByFeature; var geometryFeatureKey = new FeatureKey(borderConnection.Feature.OID, borderConnection.ClassIndex); if (! _borderConnections.TryGetValue(geometryFeatureKey, out neighborsByFeature)) { neighborsByFeature = new Dictionary<FeatureKey, TNeighbors>(new FeatureKeyComparer()); _borderConnections.Add(geometryFeatureKey, neighborsByFeature); } TNeighbors neighbors; var borderFeatureKey = new FeatureKey( borderConnection.BorderFeature.OID, borderConnection.BorderClassIndex); if (! neighborsByFeature.TryGetValue(borderFeatureKey, out neighbors)) { neighbors = CreateNeighbors(borderConnection); neighborsByFeature.Add(borderFeatureKey, neighbors); } return neighbors; } protected abstract TNeighbors CreateNeighbors(TBorderConnection borderConnection); [CanBeNull] public IPolyline GetUnmatchedBoundary([CanBeNull] IPolyline completeBoundary) { if (completeBoundary == null) { return null; } IPolyline toReduce = GeometryFactory.Clone(completeBoundary); foreach (TNeighbors neighbors in Neighbors) { foreach (TNeighborConnection neighbor in neighbors.NeighborConnections) { if (neighbor.IsGap) { continue; } toReduce = EdgeMatchUtils.GetDifference(toReduce, neighbor.CommonLine); } } return toReduce; } [CanBeNull] public IPolyline GetCompleteBorder([NotNull] TileInfo tileInfo) { IEnvelope tileEnvelope = Assert.NotNull(tileInfo.CurrentEnvelope); var boundaries = new List<IGeometry>(); foreach (TNeighbors neighbor in Neighbors) { EdgeMatchSingleBorderConnection borderConnection = neighbor.BorderConnection; if (IsDisjoint(borderConnection.GeometryAlongBoundary.Envelope, tileEnvelope)) { continue; } boundaries.Add(borderConnection.GeometryAlongBoundary); } if (boundaries.Count <= 0) { return null; } var completeBorder = (IPolyline) GeometryFactory.CreateUnion(boundaries, 0); return completeBorder; } public IEnumerable<TNeighbors> Neighbors { get { foreach ( Dictionary<FeatureKey, TNeighbors> neighborsDict in _borderConnections.Values) { foreach (TNeighbors neighbors in neighborsDict.Values) { yield return neighbors; } } } } public void Clear() { _borderConnections.Clear(); } public void Clear(WKSEnvelope tileEnvelope, WKSEnvelope allEnvelope) { var toRemove = new List<FeatureKey>(); foreach ( KeyValuePair<FeatureKey, Dictionary<FeatureKey, TNeighbors>> areaPair in _borderConnections) { Dictionary<FeatureKey, TNeighbors> borderPairs = areaPair.Value; var borderConnectionRemoves = new List<FeatureKey>(); foreach (KeyValuePair<FeatureKey, TNeighbors> borderPair in borderPairs) { TNeighbors neighbors = borderPair.Value; neighbors.Clear(tileEnvelope, allEnvelope); if (IsDone(neighbors.BorderConnection.Feature.Shape, tileEnvelope)) { borderConnectionRemoves.Add(borderPair.Key); } } foreach (FeatureKey borderConnectionRemove in borderConnectionRemoves) { borderPairs.Remove(borderConnectionRemove); } if (borderPairs.Count <= 0) { toRemove.Add(areaPair.Key); } } foreach (FeatureKey remove in toRemove) { _borderConnections.Remove(remove); } } private static bool IsDisjoint([NotNull] IGeometry geometry1, [NotNull] IGeometry geometry2) { return ((IRelationalOperator) geometry1).Disjoint(geometry2); } private static bool IsDone([NotNull] IGeometry geometry, WKSEnvelope tileEnvelope) { WKSEnvelope geometryEnvelope = QaGeometryUtils.GetWKSEnvelope(geometry); return geometryEnvelope.XMax < tileEnvelope.XMax && geometryEnvelope.YMax < tileEnvelope.YMax; } } }
27.358289
84
0.71638
[ "MIT" ]
ProSuite/ProSuite
src/ProSuite.QA.Tests/EdgeMatch/EdgeMatchBorderConnectionUnion.cs
5,116
C#
namespace Factory.Models { public class EngineerMachine { public int EngineerMachineId { get; set; } public int EngineerId { get; set; } public int MachineId { get; set; } public virtual Engineer Engineer { get; set; } public virtual Machine Machine { get; set; } } }
24.5
50
0.670068
[ "MIT" ]
wowgr8/Factory.Solution
Factory/Models/EngineerMachine.cs
294
C#
using Microsoft.EntityFrameworkCore; namespace Password.Desktop.Win.Data.Migration { public static class ModelBuilderExtensions { public static void UseMigrationsHistory(this ModelBuilder builder) { builder.ApplyConfiguration(new MigrationsHistoryConfiguration()); } } }
26.666667
77
0.715625
[ "MIT" ]
b-a-x/Password
src/Password.Desktop.Win/Data/Migration/ModelBuilderExtensions.cs
322
C#
using BEDA.CMB.Contracts.Responses; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace BEDA.CMB.Contracts.Requests { /// <summary> /// 12.5.4.汇入汇款综合查询请求主体 /// </summary> [XmlRoot("CMBSDKPGK")] public class RQ12_5_4 : CMBBase<RQINFO>, IRequest<RS12_5_4> { /// <summary> /// NTJZPQRY /// </summary> /// <returns></returns> public override string GetFUNNAM() => "NTJZPQRY"; /// <summary> /// 12.5.4.汇入汇款综合查询请求内容 /// </summary> public NTJZPQRYY NTJZPQRYY { get; set; } } /// <summary> /// 12.5.4.汇入汇款综合查询请求内容 /// </summary> public class NTJZPQRYY { /// <summary> /// 业务代码 C(6) 固定为N07111 /// </summary> public string BUSCOD { get; set; } /// <summary> /// 开始日期 D /// </summary> [XmlIgnore] public DateTime BGNDAT { get; set; } /// <summary> /// 开始日期 D, 对应<see cref="BGNDAT"/> /// </summary> [XmlElement("BGNDAT")] public string BGNDATStr { get { return this.BGNDAT.ToString("yyyyMMdd"); } set { if (DateTime.TryParseExact(value, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime tmp)) { this.BGNDAT = tmp; } } } /// <summary> /// 结束日期 D /// </summary> [XmlIgnore] public DateTime ENDDAT { get; set; } /// <summary> /// 结束日期 D, 对应<see cref="ENDDAT"/> /// </summary> [XmlElement("ENDDAT")] public string ENDDATStr { get { return this.ENDDAT.ToString("yyyyMMdd"); } set { if (DateTime.TryParseExact(value, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime tmp)) { this.ENDDAT = tmp; } } } /// <summary> /// 金额底限 M /// </summary> public decimal? MINAMT { get; set; } /// <summary> /// 金额上线 M /// </summary> public decimal? MAXAMT { get; set; } } }
26.344086
129
0.47551
[ "MIT" ]
fdstar/BankEnterpriseDirectAttach
src/BEDA.CMB/Contracts/Requests/12/RQ12_5_4.cs
2,594
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.5485 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Application_.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.354839
150
0.581221
[ "MIT" ]
bg1bgst333/Sample
wpf/Application/Exit/src/Application_/Application_/Properties/Settings.Designer.cs
1,067
C#
using System; using McMaster.Extensions.CommandLineUtils; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using McMaster.Extensions.CommandLineUtils.Abstractions; using McMaster.Extensions.CommandLineUtils.HelpText; namespace ServiceBusCopyValidation { using System.Globalization; using System.Runtime.CompilerServices; using System.Threading.Tasks; class Program { static int Main(string[] args) { // before we localize, make sure we have all the error // messages in en-us CultureInfo.CurrentUICulture = CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-us"); try { return CommandLineSettings.Run(args, (c) => Run(c, args)).GetAwaiter().GetResult(); } catch(CommandParsingException exception) { Console.WriteLine(exception.Message); return 1; } } static async Task<int> Run(CommandLineSettings settings, string[] args) { try { var plt = new ServiceBusCopyTest(settings.TargetNamespaceConnectionString, settings.SourceNamespaceConnectionString, settings.TargetQueue, settings.SourceQueue); await plt.RunTest(); } catch (Exception e) { Console.WriteLine(e.ToString()); return 1; } return 0; } } public class CommandLineSettings { [Option(CommandOptionType.SingleValue, ShortName = "t", Description = "Target namespace connection string")] public string TargetNamespaceConnectionString { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "s", Description = "Source namespace connection string")] public string SourceNamespaceConnectionString { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "qt", Description = "Target Queue")] public string TargetQueue { get; set; } [Option(CommandOptionType.SingleValue, ShortName = "qs", Description = "Source Queue")] public string SourceQueue { get; set; } public static async Task<int> Run(string[] args, Func<CommandLineSettings, Task<int>> callback) { CommandLineApplication<CommandLineSettings> app = new CommandLineApplication<CommandLineSettings> { ModelFactory = () => new CommandLineSettings() }; app.Conventions.UseDefaultConventions().SetAppNameFromEntryAssembly(); app.Parse(args); return await callback(app.Model); } } }
35.2375
116
0.619369
[ "MIT" ]
Azure-Samples/azure-messaging-replication-dotnet
test/ServiceBusCopyValidation/Program.cs
2,821
C#
using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace PublicTransport.Infrastructure.Migrations { public partial class AddIsDeletedAndImgUrlToNews : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Photo_AspNetUsers_AuthorId", table: "Photo"); migrationBuilder.DropForeignKey( name: "FK_Photo_Vehicle_VehicleId", table: "Photo"); migrationBuilder.DropForeignKey( name: "FK_PhotoComment_AspNetUsers_UserId", table: "PhotoComment"); migrationBuilder.DropForeignKey( name: "FK_PhotoComment_Photo_PhotoId", table: "PhotoComment"); migrationBuilder.DropPrimaryKey( name: "PK_Vehicle", table: "Vehicle"); migrationBuilder.DropPrimaryKey( name: "PK_PhotoComment", table: "PhotoComment"); migrationBuilder.DropPrimaryKey( name: "PK_Photo", table: "Photo"); migrationBuilder.RenameTable( name: "Vehicle", newName: "Vehicles"); migrationBuilder.RenameTable( name: "PhotoComment", newName: "PhotoComments"); migrationBuilder.RenameTable( name: "Photo", newName: "Photos"); migrationBuilder.RenameIndex( name: "IX_PhotoComment_UserId", table: "PhotoComments", newName: "IX_PhotoComments_UserId"); migrationBuilder.RenameIndex( name: "IX_PhotoComment_PhotoId", table: "PhotoComments", newName: "IX_PhotoComments_PhotoId"); migrationBuilder.RenameIndex( name: "IX_Photo_VehicleId", table: "Photos", newName: "IX_Photos_VehicleId"); migrationBuilder.RenameIndex( name: "IX_Photo_AuthorId", table: "Photos", newName: "IX_Photos_AuthorId"); migrationBuilder.AlterColumn<string>( name: "Title", table: "News", type: "nvarchar(50)", maxLength: 50, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(100)", oldMaxLength: 100); migrationBuilder.AddColumn<string>( name: "ImgUrl", table: "News", type: "nvarchar(max)", nullable: false, defaultValue: ""); migrationBuilder.AddColumn<bool>( name: "IsDeleted", table: "News", type: "bit", nullable: false, defaultValue: false); migrationBuilder.AddPrimaryKey( name: "PK_Vehicles", table: "Vehicles", column: "Id"); migrationBuilder.AddPrimaryKey( name: "PK_PhotoComments", table: "PhotoComments", column: "Id"); migrationBuilder.AddPrimaryKey( name: "PK_Photos", table: "Photos", column: "Id"); migrationBuilder.AddForeignKey( name: "FK_PhotoComments_AspNetUsers_UserId", table: "PhotoComments", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_PhotoComments_Photos_PhotoId", table: "PhotoComments", column: "PhotoId", principalTable: "Photos", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Photos_AspNetUsers_AuthorId", table: "Photos", column: "AuthorId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Photos_Vehicles_VehicleId", table: "Photos", column: "VehicleId", principalTable: "Vehicles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_PhotoComments_AspNetUsers_UserId", table: "PhotoComments"); migrationBuilder.DropForeignKey( name: "FK_PhotoComments_Photos_PhotoId", table: "PhotoComments"); migrationBuilder.DropForeignKey( name: "FK_Photos_AspNetUsers_AuthorId", table: "Photos"); migrationBuilder.DropForeignKey( name: "FK_Photos_Vehicles_VehicleId", table: "Photos"); migrationBuilder.DropPrimaryKey( name: "PK_Vehicles", table: "Vehicles"); migrationBuilder.DropPrimaryKey( name: "PK_Photos", table: "Photos"); migrationBuilder.DropPrimaryKey( name: "PK_PhotoComments", table: "PhotoComments"); migrationBuilder.DropColumn( name: "ImgUrl", table: "News"); migrationBuilder.DropColumn( name: "IsDeleted", table: "News"); migrationBuilder.RenameTable( name: "Vehicles", newName: "Vehicle"); migrationBuilder.RenameTable( name: "Photos", newName: "Photo"); migrationBuilder.RenameTable( name: "PhotoComments", newName: "PhotoComment"); migrationBuilder.RenameIndex( name: "IX_Photos_VehicleId", table: "Photo", newName: "IX_Photo_VehicleId"); migrationBuilder.RenameIndex( name: "IX_Photos_AuthorId", table: "Photo", newName: "IX_Photo_AuthorId"); migrationBuilder.RenameIndex( name: "IX_PhotoComments_UserId", table: "PhotoComment", newName: "IX_PhotoComment_UserId"); migrationBuilder.RenameIndex( name: "IX_PhotoComments_PhotoId", table: "PhotoComment", newName: "IX_PhotoComment_PhotoId"); migrationBuilder.AlterColumn<string>( name: "Title", table: "News", type: "nvarchar(100)", maxLength: 100, nullable: false, oldClrType: typeof(string), oldType: "nvarchar(50)", oldMaxLength: 50); migrationBuilder.AddPrimaryKey( name: "PK_Vehicle", table: "Vehicle", column: "Id"); migrationBuilder.AddPrimaryKey( name: "PK_Photo", table: "Photo", column: "Id"); migrationBuilder.AddPrimaryKey( name: "PK_PhotoComment", table: "PhotoComment", column: "Id"); migrationBuilder.AddForeignKey( name: "FK_Photo_AspNetUsers_AuthorId", table: "Photo", column: "AuthorId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Photo_Vehicle_VehicleId", table: "Photo", column: "VehicleId", principalTable: "Vehicle", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_PhotoComment_AspNetUsers_UserId", table: "PhotoComment", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_PhotoComment_Photo_PhotoId", table: "PhotoComment", column: "PhotoId", principalTable: "Photo", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
33.169118
71
0.50798
[ "MIT" ]
HNochev/PublicTransport
PublicTransport.Infrastructure/Migrations/20220324212058_AddIsDeletedAndImgUrlToNews.cs
9,024
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using MyDriving.DataObjects; using MyDriving.DataStore.Abstractions; using System.Threading.Tasks; using System.Collections.Generic; namespace MyDriving.DataStore.Azure.Stores { public class PhotoStore : BaseStore<Photo>, IPhotoStore { public override string Identifier => "Photo"; public override Task<bool> PullLatestAsync() { return Task.FromResult(true); } public override Task<bool> SyncAsync() { return Task.FromResult(true); } public Task<IEnumerable<Photo>> GetTripPhotos(string tripId) { return Table.Where(s => s.TripId == tripId).ToEnumerableAsync(); } } }
28.233333
84
0.661157
[ "MIT" ]
HydAu/MyDriving
src/MobileApps/MyDriving/MyDriving.DataStore.Azure/Stores/PhotoStore.cs
849
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Principal; using System.Web; using System.Web.Mvc; using Moq; using Xunit; namespace NuGetGallery { public class CuratedFeedsControllerFacts { public class TestableCuratedFeedsController : CuratedFeedsController { public TestableCuratedFeedsController() { StubCuratedFeed = new CuratedFeed { Key = 0, Name = "aName", Managers = new HashSet<User>(new[] { new User { Username = "aUsername" } }) }; StubCuratedFeedService = new Mock<ICuratedFeedService>(); StubIdentity = new Mock<IIdentity>(); StubIdentity.Setup(stub => stub.IsAuthenticated).Returns(true); StubIdentity.Setup(stub => stub.Name).Returns("aUsername"); StubCuratedFeedService .Setup(stub => stub.GetFeedByName(It.IsAny<string>(), It.IsAny<bool>())) .Returns(StubCuratedFeed); CuratedFeedService = StubCuratedFeedService.Object; StubSearchService = new Mock<ISearchService>(); SearchService = StubSearchService.Object; } public CuratedFeed StubCuratedFeed { get; set; } public Mock<ICuratedFeedService> StubCuratedFeedService { get; private set; } public Mock<ISearchService> StubSearchService { get; private set; } public Mock<IIdentity> StubIdentity { get; private set; } protected override IIdentity Identity { get { return StubIdentity.Object; } } protected override T GetService<T>() { if (typeof(T) == typeof(ICuratedFeedService)) { return (T)StubCuratedFeedService.Object; } throw new Exception("Tried to get an unexpected service."); } } public class TheGetCuratedFeedAction { [Fact] public void WillReturn404IfTheCuratedFeedDoesNotExist() { var controller = new TestableCuratedFeedsController(); controller.StubCuratedFeedService.Setup(stub => stub.GetFeedByName(It.IsAny<string>(), It.IsAny<bool>())).Returns((CuratedFeed)null); var result = controller.CuratedFeed("aFeedName"); Assert.IsType<HttpNotFoundResult>(result); } [Fact] public void WillReturn403IfTheCurrentUsersIsNotAManagerOfTheCuratedFeed() { var controller = new TestableCuratedFeedsController(); controller.StubIdentity.Setup(stub => stub.Name).Returns("notAManager"); var result = controller.CuratedFeed("aFeedName") as HttpStatusCodeResult; Assert.NotNull(result); Assert.Equal(403, result.StatusCode); } [Fact] public void WillPassTheCuratedFeedNameToTheView() { var controller = new TestableCuratedFeedsController(); controller.StubCuratedFeed.Name = "theCuratedFeedName"; var viewModel = (controller.CuratedFeed("aFeedName") as ViewResult).Model as CuratedFeedViewModel; Assert.NotNull(viewModel); Assert.Equal("theCuratedFeedName", viewModel.Name); } [Fact] public void WillPassTheCuratedFeedManagersToTheView() { var controller = new TestableCuratedFeedsController(); controller.StubIdentity.Setup(stub => stub.Name).Returns("theManager"); controller.StubCuratedFeed.Name = "aFeedName"; controller.StubCuratedFeed.Managers = new HashSet<User>(new[] { new User { Username = "theManager" } }); var viewModel = (controller.CuratedFeed("aFeedName") as ViewResult).Model as CuratedFeedViewModel; Assert.NotNull(viewModel); Assert.Equal("theManager", viewModel.Managers.First()); } [Fact] public void WillPassTheIncludedPackagesToTheView() { var controller = new TestableCuratedFeedsController(); controller.StubCuratedFeed.Packages = new HashSet<CuratedPackage>( new[] { new CuratedPackage { AutomaticallyCurated = true, Included = true, PackageRegistration = new PackageRegistration { Id = "theAutomaticallyCuratedId" } }, new CuratedPackage { AutomaticallyCurated = false, Included = true, PackageRegistration = new PackageRegistration { Id = "theManuallyCuratedId" } }, new CuratedPackage { AutomaticallyCurated = true, Included = false, PackageRegistration = new PackageRegistration { Id = "theExcludedId" } } }); var viewModel = (controller.CuratedFeed("aFeedName") as ViewResult).Model as CuratedFeedViewModel; Assert.NotNull(viewModel); Assert.Equal(2, viewModel.IncludedPackages.Count()); Assert.Equal("theAutomaticallyCuratedId", viewModel.IncludedPackages.ElementAt(0).Id); Assert.Equal("theManuallyCuratedId", viewModel.IncludedPackages.ElementAt(1).Id); } [Fact] public void WillPassTheExcludedPackagesToTheView() { var controller = new TestableCuratedFeedsController(); controller.StubCuratedFeed.Packages = new HashSet<CuratedPackage>( new[] { new CuratedPackage { AutomaticallyCurated = true, Included = true, PackageRegistration = new PackageRegistration { Id = "theAutomaticallyCuratedId" } }, new CuratedPackage { AutomaticallyCurated = false, Included = true, PackageRegistration = new PackageRegistration { Id = "theManuallyCuratedId" } }, new CuratedPackage { AutomaticallyCurated = true, Included = false, PackageRegistration = new PackageRegistration { Id = "theExcludedId" } } }); var viewModel = (controller.CuratedFeed("aFeedName") as ViewResult).Model as CuratedFeedViewModel; Assert.NotNull(viewModel); Assert.Equal(1, viewModel.ExcludedPackages.Count()); Assert.Equal("theExcludedId", viewModel.ExcludedPackages.First()); } } public class TheListPackagesAction { [Fact] public void WillSearchForAPackage() { var controller = new TestableCuratedFeedsController(); var redPill = new PackageRegistration { Id = "RedPill", Key = 2, DownloadCount = 0, Packages = new [] { new Package { Key = 89932, } }, Owners = new [] { new User { Key = 66, Username = "Morpheus", } } }; redPill.Packages.ElementAt(0).PackageRegistration = redPill; var mockPackageRegistrations = new [] { redPill }.AsQueryable(); var mockPackages = new[] { redPill.Packages.ElementAt(0) }.AsQueryable(); controller.StubCuratedFeedService .Setup(stub => stub.GetKey("TheMatrix")) .Returns(2); int totalHits; controller.StubSearchService .Setup(stub => stub.Search(It.IsAny<SearchFilter>(), out totalHits)) .Returns(mockPackages); var mockHttpContext = new Mock<HttpContextBase>(); TestUtility.SetupHttpContextMockForUrlGeneration(mockHttpContext, controller); // Act var result = controller.ListPackages("TheMatrix", ""); Assert.IsType<ViewResult>(result); Assert.IsType<PackageListViewModel>(((ViewResult)result).Model); var model = (result as ViewResult).Model as PackageListViewModel; Assert.Equal(1, model.Items.Count()); } } } }
41.57265
149
0.498458
[ "ECL-2.0", "Apache-2.0" ]
KuduApps/NuGetGallery
tests/NuGetGallery.Facts/Controllers/CuratedFeedsControllerFacts.cs
9,730
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace StreamJsonRpc { using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Pipelines; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft; using Nerdbank.Streams; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using StreamJsonRpc.Protocol; /// <summary> /// Uses Newtonsoft.Json serialization to serialize <see cref="JsonRpcMessage"/> as JSON (text). /// </summary> public class JsonMessageFormatter : IJsonRpcAsyncMessageTextFormatter { /// <summary> /// The key into an <see cref="Exception.Data"/> dictionary whose value may be a <see cref="JToken"/> that failed deserialization. /// </summary> internal const string ExceptionDataKey = "JToken"; /// <summary> /// A collection of supported protocol versions. /// </summary> private static readonly IReadOnlyCollection<Version> SupportedProtocolVersions = new Version[] { new Version(1, 0), new Version(2, 0) }; /// <summary> /// UTF-8 encoding without a preamble. /// </summary> private static readonly Encoding DefaultEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); /// <summary> /// The <see cref="char"/> array pool to use for each <see cref="JsonTextReader"/> instance. /// </summary> private static readonly IArrayPool<char> JsonCharArrayPool = new JsonArrayPool<char>(ArrayPool<char>.Shared); /// <summary> /// An exactly default instance of the <see cref="JsonSerializer"/> to use where no special settings /// are needed. /// </summary> /// <remarks> /// This is useful when calling such APIs as <see cref="JToken.FromObject(object, JsonSerializer)"/> /// because <see cref="JToken.FromObject(object)"/> allocates a new serializer with each invocation. /// </remarks> private static readonly JsonSerializer DefaultSerializer = JsonSerializer.CreateDefault(); /// <summary> /// The reusable <see cref="TextWriter"/> to use with newtonsoft.json's serializer. /// </summary> private readonly BufferTextWriter bufferTextWriter = new BufferTextWriter(); /// <summary> /// The reusable <see cref="TextReader"/> to use with newtonsoft.json's deserializer. /// </summary> private readonly SequenceTextReader sequenceTextReader = new SequenceTextReader(); /// <summary> /// The version of the JSON-RPC protocol being emulated by this instance. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] private Version protocolVersion = new Version(2, 0); /// <summary> /// Backing field for the <see cref="Encoding"/> property. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] private Encoding encoding; /// <summary> /// Initializes a new instance of the <see cref="JsonMessageFormatter"/> class /// that uses <see cref="Encoding.UTF8"/> (without the preamble) for its text encoding. /// </summary> public JsonMessageFormatter() : this(DefaultEncoding) { } /// <summary> /// Initializes a new instance of the <see cref="JsonMessageFormatter"/> class. /// </summary> /// <param name="encoding">The encoding to use for the JSON text.</param> public JsonMessageFormatter(Encoding encoding) { Requires.NotNull(encoding, nameof(encoding)); this.Encoding = encoding; } /// <summary> /// Gets or sets the encoding to use for transmitted messages. /// </summary> public Encoding Encoding { get => this.encoding; set { Requires.NotNull(value, nameof(value)); this.encoding = value; } } /// <summary> /// Gets or sets the version of the JSON-RPC protocol emulated by this instance. /// </summary> /// <value>The default value is 2.0.</value> public Version ProtocolVersion { get => this.protocolVersion; set { Requires.NotNull(value, nameof(value)); if (!SupportedProtocolVersions.Contains(value)) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Resources.UnsupportedJsonRpcProtocolVersion, value, string.Join(", ", SupportedProtocolVersions))); } this.protocolVersion = value; } } /// <summary> /// Gets the <see cref="Newtonsoft.Json.JsonSerializer"/> used when serializing and deserializing method arguments and return values. /// </summary> public JsonSerializer JsonSerializer { get; } = new JsonSerializer() { NullValueHandling = NullValueHandling.Ignore, ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, }; /// <inheritdoc/> public JsonRpcMessage Deserialize(ReadOnlySequence<byte> contentBuffer) => this.Deserialize(contentBuffer, this.Encoding); /// <inheritdoc/> public JsonRpcMessage Deserialize(ReadOnlySequence<byte> contentBuffer, Encoding encoding) { Requires.NotNull(encoding, nameof(encoding)); JToken json = this.ReadJToken(contentBuffer, encoding); return this.Deserialize(json); } /// <inheritdoc/> public async ValueTask<JsonRpcMessage> DeserializeAsync(PipeReader reader, Encoding encoding, CancellationToken cancellationToken) { Requires.NotNull(reader, nameof(reader)); Requires.NotNull(encoding, nameof(encoding)); using (var jsonReader = new JsonTextReader(new StreamReader(reader.AsStream(), encoding))) { this.ConfigureJsonTextReader(jsonReader); JToken json = await JToken.ReadFromAsync(jsonReader, cancellationToken).ConfigureAwait(false); return this.Deserialize(json); } } /// <inheritdoc/> public ValueTask<JsonRpcMessage> DeserializeAsync(PipeReader reader, CancellationToken cancellationToken) => this.DeserializeAsync(reader, this.Encoding, cancellationToken); /// <inheritdoc/> public void Serialize(IBufferWriter<byte> contentBuffer, JsonRpcMessage message) { JToken json = this.Serialize(message); this.WriteJToken(contentBuffer, json); } /// <summary> /// Deserializes a <see cref="JToken"/> to a <see cref="JsonRpcMessage"/>. /// </summary> /// <param name="json">The JSON to deserialize.</param> /// <returns>The deserialized message.</returns> public JsonRpcMessage Deserialize(JToken json) { Requires.NotNull(json, nameof(json)); try { switch (this.ProtocolVersion.Major) { case 1: this.VerifyProtocolCompliance(json["jsonrpc"] == null, json, "\"jsonrpc\" property not expected. Use protocol version 2.0."); this.VerifyProtocolCompliance(json["id"] != null, json, "\"id\" property missing."); return json["method"] != null ? this.ReadRequest(json) : json["error"]?.Type == JTokenType.Null ? this.ReadResult(json) : json["error"]?.Type != JTokenType.Null ? (JsonRpcMessage)this.ReadError(json) : throw this.CreateProtocolNonComplianceException(json); case 2: this.VerifyProtocolCompliance(json.Value<string>("jsonrpc") == "2.0", json, $"\"jsonrpc\" property must be set to \"2.0\", or set {nameof(this.ProtocolVersion)} to 1.0 mode."); return json["method"] != null ? this.ReadRequest(json) : json["result"] != null ? this.ReadResult(json) : json["error"] != null ? (JsonRpcMessage)this.ReadError(json) : throw this.CreateProtocolNonComplianceException(json); default: throw Assumes.NotReachable(); } } catch (JsonException exception) { var serializationException = new JsonSerializationException($"Unable to deserialize {nameof(JsonRpcMessage)}.", exception); if (json.GetType().GetTypeInfo().IsSerializable) { serializationException.Data[ExceptionDataKey] = json; } throw serializationException; } } /// <summary> /// Serializes a <see cref="JsonRpcMessage"/> to a <see cref="JToken"/>. /// </summary> /// <param name="message">The message to serialize.</param> /// <returns>The JSON of the message.</returns> public JToken Serialize(JsonRpcMessage message) { // Pre-tokenize the user data so we can use their custom converters for just their data and not for the base message. this.TokenizeUserData(message); var json = JToken.FromObject(message, DefaultSerializer); // Fix up dropped fields that are mandatory if (message is Protocol.JsonRpcResult && json["result"] == null) { json["result"] = JValue.CreateNull(); } if (this.ProtocolVersion.Major == 1 && json["id"] == null) { // JSON-RPC 1.0 requires the id property to be present even for notifications. json["id"] = JValue.CreateNull(); } return json; } /// <inheritdoc/> public object GetJsonText(JsonRpcMessage message) => JToken.FromObject(message); private static IReadOnlyDictionary<string, object> PartiallyParseNamedArguments(JObject args) { Requires.NotNull(args, nameof(args)); return args.Properties().ToDictionary(p => p.Name, p => (object)p.Value); } private static object[] PartiallyParsePositionalArguments(JArray args) { Requires.NotNull(args, nameof(args)); var jtokenArray = new JToken[args.Count]; for (int i = 0; i < jtokenArray.Length; i++) { jtokenArray[i] = args[i]; } return jtokenArray; } private static object GetNormalizedId(JToken idToken) { return idToken?.Type == JTokenType.Integer ? idToken.Value<long>() : idToken?.Type == JTokenType.String ? idToken.Value<string>() : idToken == null ? (object)null : throw new JsonSerializationException("Unexpected type for id property: " + idToken.Type); } private void VerifyProtocolCompliance(bool condition, JToken message, string explanation = null) { if (!condition) { throw this.CreateProtocolNonComplianceException(message, explanation); } } private Exception CreateProtocolNonComplianceException(JToken message, string explanation = null) { var builder = new StringBuilder(); builder.AppendFormat(CultureInfo.CurrentCulture, "Unrecognized JSON-RPC {0} message", this.ProtocolVersion); if (explanation != null) { builder.AppendFormat(" ({0})", explanation); } builder.Append(": "); builder.Append(message); return new JsonSerializationException(builder.ToString()); } private void WriteJToken(IBufferWriter<byte> contentBuffer, JToken json) { this.bufferTextWriter.Initialize(contentBuffer, this.Encoding); using (var jsonWriter = new JsonTextWriter(this.bufferTextWriter)) { json.WriteTo(jsonWriter); jsonWriter.Flush(); } } private JToken ReadJToken(ReadOnlySequence<byte> contentBuffer, Encoding encoding) { Requires.NotNull(encoding, nameof(encoding)); this.sequenceTextReader.Initialize(contentBuffer, encoding); using (var jsonReader = new JsonTextReader(this.sequenceTextReader)) { this.ConfigureJsonTextReader(jsonReader); JToken json = JToken.ReadFrom(jsonReader); return json; } } private void ConfigureJsonTextReader(JsonTextReader reader) { Requires.NotNull(reader, nameof(reader)); reader.ArrayPool = JsonCharArrayPool; reader.CloseInput = true; reader.Culture = this.JsonSerializer.Culture; reader.DateFormatString = this.JsonSerializer.DateFormatString; reader.DateParseHandling = this.JsonSerializer.DateParseHandling; reader.DateTimeZoneHandling = this.JsonSerializer.DateTimeZoneHandling; reader.FloatParseHandling = this.JsonSerializer.FloatParseHandling; reader.MaxDepth = this.JsonSerializer.MaxDepth; } /// <summary> /// Converts user data to <see cref="JToken"/> objects using all applicable user-provided <see cref="JsonConverter"/> instances. /// </summary> /// <param name="jsonRpcMessage">A JSON-RPC message.</param> private void TokenizeUserData(JsonRpcMessage jsonRpcMessage) { if (jsonRpcMessage is Protocol.JsonRpcRequest request) { if (request.ArgumentsList != null) { request.ArgumentsList = request.ArgumentsList.Select(this.TokenizeUserData).ToArray(); } else if (request.Arguments != null) { if (this.ProtocolVersion.Major < 2) { throw new NotSupportedException(Resources.ParameterObjectsNotSupportedInJsonRpc10); } // Tokenize the user data using the user-supplied serializer. var paramsObject = JObject.FromObject(request.Arguments, this.JsonSerializer); request.Arguments = paramsObject; } } else if (jsonRpcMessage is Protocol.JsonRpcResult result) { result.Result = this.TokenizeUserData(result.Result); } } /// <summary> /// Converts a single user data value to a <see cref="JToken"/>, using all applicable user-provided <see cref="JsonConverter"/> instances. /// </summary> /// <param name="value">The value to tokenize.</param> /// <returns>The <see cref="JToken"/> instance.</returns> private JToken TokenizeUserData(object value) { if (value is JToken token) { return token; } if (value == null) { return JValue.CreateNull(); } return JToken.FromObject(value, this.JsonSerializer); } private JsonRpcRequest ReadRequest(JToken json) { Requires.NotNull(json, nameof(json)); JToken id = json["id"]; // We leave arguments as JTokens at this point, so that we can try deserializing them // to more precise .NET types as required by the method we're invoking. JToken args = json["params"]; object arguments = args is JObject argsObject ? PartiallyParseNamedArguments(argsObject) : args is JArray argsArray ? (object)PartiallyParsePositionalArguments(argsArray) : null; return new JsonRpcRequest(this.JsonSerializer) { Id = GetNormalizedId(id), Method = json.Value<string>("method"), Arguments = arguments, }; } private JsonRpcResult ReadResult(JToken json) { Requires.NotNull(json, nameof(json)); JToken id = json["id"]; JToken result = json["result"]; return new JsonRpcResult(this.JsonSerializer) { Id = GetNormalizedId(id), Result = result, }; } private JsonRpcError ReadError(JToken json) { Requires.NotNull(json, nameof(json)); JToken id = json["id"]; JToken error = json["error"]; return new JsonRpcError { Id = GetNormalizedId(id), Error = new JsonRpcError.ErrorDetail { Code = (JsonRpcErrorCode)error.Value<long>("code"), Message = error.Value<string>("message"), Data = error["data"], // leave this as a JToken }, }; } [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] [DataContract] private class JsonRpcRequest : Protocol.JsonRpcRequest { private readonly JsonSerializer jsonSerializer; internal JsonRpcRequest(JsonSerializer jsonSerializer) { this.jsonSerializer = jsonSerializer ?? throw new ArgumentNullException(nameof(jsonSerializer)); } public override ArgumentMatchResult TryGetTypedArguments(ReadOnlySpan<ParameterInfo> parameters, Span<object> typedArguments) { // Special support for accepting a single JToken instead of all parameters individually. if (parameters.Length == 1 && parameters[0].ParameterType == typeof(JToken) && this.NamedArguments != null) { var obj = new JObject(); foreach (var property in this.NamedArguments) { obj.Add(new JProperty(property.Key, property.Value)); } typedArguments[0] = obj; return ArgumentMatchResult.Success; } return base.TryGetTypedArguments(parameters, typedArguments); } public override bool TryGetArgumentByNameOrIndex(string name, int position, Type typeHint, out object value) { if (base.TryGetArgumentByNameOrIndex(name, position, typeHint, out value)) { var token = (JToken)value; try { value = token.ToObject(typeHint, this.jsonSerializer); return true; } catch { return false; } } return false; } } [DebuggerDisplay("{" + nameof(DebuggerDisplay) + ",nq}")] [DataContract] private class JsonRpcResult : Protocol.JsonRpcResult { private readonly JsonSerializer jsonSerializer; internal JsonRpcResult(JsonSerializer jsonSerializer) { this.jsonSerializer = jsonSerializer ?? throw new ArgumentNullException(nameof(jsonSerializer)); } public override T GetResult<T>() { var result = (JToken)this.Result; if (result.Type == JTokenType.Null) { Verify.Operation(!typeof(T).GetTypeInfo().IsValueType || Nullable.GetUnderlyingType(typeof(T)) != null, "null result is not assignable to a value type."); return default; } return result.ToObject<T>(this.jsonSerializer); } } /// <summary> /// Adapts the .NET <see cref="ArrayPool{T}" /> to Newtonsoft.Json's <see cref="IArrayPool{T}" /> interface. /// </summary> private class JsonArrayPool<T> : IArrayPool<T> { private readonly ArrayPool<T> arrayPool; internal JsonArrayPool(ArrayPool<T> arrayPool) { this.arrayPool = arrayPool ?? throw new ArgumentNullException(nameof(arrayPool)); } public T[] Rent(int minimumLength) => this.arrayPool.Rent(minimumLength); public void Return(T[] array) => this.arrayPool.Return(array); } } }
39.558442
200
0.570725
[ "MIT" ]
tinaschrepfer/vs-streamjsonrpc
src/StreamJsonRpc/JsonMessageFormatter.cs
21,324
C#
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation.Tests { using System.Web.Mvc; using Mvc; using NUnit.Framework; using Results; [TestFixture] public class ValidationResultExtensionTests { private ValidationResult result; [SetUp] public void Setup() { result = new ValidationResult(new[] { new ValidationFailure("foo", "A foo error occurred", "x"), new ValidationFailure("bar", "A bar error occurred", "y"), }); } [Test] public void Should_persist_to_modelstate() { var modelstate = new ModelStateDictionary(); result.AddToModelState(modelstate, null); modelstate.IsValid.ShouldBeFalse(); modelstate["foo"].Errors[0].ErrorMessage.ShouldEqual("A foo error occurred"); modelstate["bar"].Errors[0].ErrorMessage.ShouldEqual("A bar error occurred"); modelstate["foo"].Value.AttemptedValue.ShouldEqual("x"); modelstate["bar"].Value.AttemptedValue.ShouldEqual("y"); } [Test] public void Should_persist_modelstate_with_empty_prefix() { var modelstate = new ModelStateDictionary(); result.AddToModelState(modelstate, ""); modelstate["foo"].Errors[0].ErrorMessage.ShouldEqual("A foo error occurred"); } [Test] public void Should_persist_to_modelstate_with_prefix() { var modelstate = new ModelStateDictionary(); result.AddToModelState(modelstate, "baz"); modelstate.IsValid.ShouldBeFalse(); modelstate["baz.foo"].Errors[0].ErrorMessage.ShouldEqual("A foo error occurred"); modelstate["baz.bar"].Errors[0].ErrorMessage.ShouldEqual("A bar error occurred"); } [Test] public void Should_do_nothing_if_result_is_valid() { var modelState = new ModelStateDictionary(); new ValidationResult().AddToModelState(modelState, null); modelState.IsValid.ShouldBeTrue(); } } }
34.72973
92
0.71284
[ "Apache-2.0" ]
xareas/FluentValidation
src/FluentValidation.Tests.Mvc4/ValidationResultExtensionTests.cs
2,570
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Reflection; using System.Resources; [assembly: AssemblyTitle("Microsoft Azure DataBox Edge Gateway Management Library")] [assembly: AssemblyDescription("Provides management functionality for Microsoft Azure DataBox Edge Gateway Management Resources.")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
43.210526
131
0.785627
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/databoxedge/Microsoft.Azure.Management.DataBoxEdge/src/Properties/AssemblyInfo.cs
821
C#
/* The MIT License (MIT) Copyright (c) 2014-2016 Marc de Verdelhan & respective authors (see AUTHORS) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace TA4N.Indicators.Simple { /// <summary> /// Maximum price indicator. /// <para> /// </para> /// </summary> public class MaxPriceIndicator : CachedIndicator<Decimal> { private readonly TimeSeries _series; public MaxPriceIndicator(TimeSeries series) : base(series) { _series = series; } protected override Decimal Calculate(int index) { return _series.GetTick(index).MaxPrice; } } }
35.227273
80
0.769032
[ "MIT" ]
chrisw000/TA4N
TA4N/Indicators/Simple/MaxPriceIndicator.cs
1,552
C#
/****************************************************************************** * Copyright (C) Ultraleap, Inc. 2011-2020. * * * * Use subject to the terms of the Apache License 2.0 available at * * http://www.apache.org/licenses/LICENSE-2.0, or another agreement * * between Ultraleap and you, your company or other organization. * ******************************************************************************/ using Leap.Unity.Query; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace Leap.Unity.Animation { [CanEditMultipleObjects] [CustomEditor(typeof(TransformTweenBehaviour))] public class TransformTweenBehaviourEditor : CustomEditorBase<TransformTweenBehaviour> { protected override void OnEnable() { base.OnEnable(); dontShowScriptField(); deferProperty("_eventTable"); specifyCustomDrawer("_eventTable", drawEventTable); } private EnumEventTableEditor _tableEditor; private void drawEventTable(SerializedProperty property) { if (_tableEditor == null) { _tableEditor = new EnumEventTableEditor(property, typeof(TransformTweenBehaviour.EventType)); } _tableEditor.DoGuiLayout(); } public override void OnInspectorGUI() { drawScriptField(); EditorGUI.BeginDisabledGroup(target.targetTransform == null || target.startTransform == null || Utils.IsObjectPartOfPrefabAsset(target.gameObject)); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button(new GUIContent("Set Target" + (targets.Length > 1 ? "s" : "") + " To Start", "If this TransformTweenBehaviour has a valid target and start transform, " + "you can press this button to set the target transform to the start state."))) { Undo.IncrementCurrentGroup(); Undo.SetCurrentGroupName("Set Target(s) To Start"); foreach (var individualTarget in targets) { Undo.RecordObject(individualTarget.targetTransform, "Move Target To Start"); individualTarget.SetTargetToStart(); } } EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(target.targetTransform == null || target.endTransform == null || Utils.IsObjectPartOfPrefabAsset(target.gameObject)); if (GUILayout.Button(new GUIContent("Set Target" + (targets.Length > 1 ? "s" : "") + " To End", "If this TransformTweenBehaviour has a valid target and end transform, " + "you can press this button to set the target transform to the end state."))) { Undo.IncrementCurrentGroup(); Undo.SetCurrentGroupName("Set Target(s) To End"); foreach (var individualTarget in targets) { Undo.RecordObject(individualTarget.targetTransform, "Move Target To End"); individualTarget.SetTargetToEnd(); } } EditorGUILayout.EndHorizontal(); EditorGUI.EndDisabledGroup(); base.OnInspectorGUI(); } } }
38.896552
122
0.576832
[ "MIT" ]
EricoVeriscimo/jogo_bolinha
Assets/Plugins/LeapMotion/Core/Editor/TransformTweenBehaviourEditor.cs
3,384
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectMenuManager : MonoBehaviour { public List<GameObject> objectList; //handled automatically at start public List<GameObject> objectPrefabList; // set manually in inspector and MUST match order of scene's menu objects public int currentObject = 0; //private GameObject newObject; //public SteamVR_LoadLevel loadLevel; // Use this for initialization void Start () { foreach (Transform child in transform) { objectList.Add (child.gameObject); } } public void SpawnCurrentObject() { // instantiate selected object, turn physics on, and scale up by 10x GameObject newObject = Instantiate (objectPrefabList [currentObject], objectList [currentObject].transform.position, objectList [currentObject].transform.rotation); newObject.GetComponent<Rigidbody> ().isKinematic = false; Vector3 scaleUp = newObject.transform.localScale; scaleUp.x *= 10f; scaleUp.y *= 10f; scaleUp.z *= 10f; newObject.transform.localScale = scaleUp; newObject.GetComponent<Collider> ().enabled = true; // Instantiate (objectPrefabList [currentObject], // objectList [currentObject].transform.position, // objectList [currentObject].transform.rotation); //loadLevel.Trigger (); } public void MenuLeft() { objectList [currentObject].SetActive (false); currentObject--; if (currentObject < 0) { currentObject = objectList.Count - 1; } objectList [currentObject].SetActive (true); } public void MenuRight() { objectList [currentObject].SetActive (false); currentObject++; if (currentObject > objectList.Count - 1) { currentObject = 0; } objectList [currentObject].SetActive (true); } // Update is called once per frame void Update () { } }
30.372881
116
0.736607
[ "MIT" ]
kevenson/KE_RubeGoldberg
Assets/Scripts/ObjectMenuManager.cs
1,794
C#
using Microsoft.AspNetCore.Http; using System.ComponentModel.DataAnnotations; namespace Sunioj.Core.Resources.Settings { public class ImageSettingForUpdateDTO { [Required] public string Name { get; set; } [Required] public IFormFile Image { get; set; } } }
20.266667
44
0.667763
[ "MIT" ]
brugner/sunioj
Sunioj/Core/Resources/Settings/ImageSettingForUpdateDTO.cs
306
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.Contracts; using System.Linq; using System.Linq.Expressions; using System.Security.Principal; using Revenj.Extensibility; namespace Revenj.Security { internal class PermissionManager : IPermissionManager, IDisposable { private readonly IObjectFactory ObjectFactory; private static bool DefaultPermissions; static PermissionManager() { var dp = ConfigurationManager.AppSettings["Permissions.OpenByDefault"]; DefaultPermissions = string.IsNullOrEmpty(dp) ? true : bool.Parse(dp); } private bool PermissionsChanged = true; private Dictionary<string, bool> GlobalPermissions; private Dictionary<string, List<Pair>> RolePermissions; private readonly Dictionary<Type, List<Filter>> RegisteredFilters = new Dictionary<Type, List<Filter>>(); private Dictionary<string, bool> Cache = new Dictionary<string, bool>(); private readonly IDisposable GlobalSubscription; private readonly IDisposable RoleSubscription; private class Filter { public object Expression; public object Predicate; public string Role; public bool Inverse; } private class Pair { public string Name; public bool IsAllowed; } public PermissionManager( IObjectFactory objectFactory, IObservable<Lazy<IGlobalPermission>> globalChanges, IObservable<Lazy<IRolePermission>> roleChanges) { Contract.Requires(objectFactory != null); Contract.Requires(globalChanges != null); Contract.Requires(roleChanges != null); this.ObjectFactory = objectFactory; GlobalSubscription = globalChanges.Subscribe(_ => PermissionsChanged = true); RoleSubscription = roleChanges.Subscribe(_ => PermissionsChanged = true); } private void CheckPermissions() { if (!PermissionsChanged) return; using (var scope = ObjectFactory.CreateInnerFactory()) { var globals = scope.Resolve<IQueryable<IGlobalPermission>>(); var roles = scope.Resolve<IQueryable<IRolePermission>>(); GlobalPermissions = globals.ToList() .ToDictionary(it => it.Name, it => it.IsAllowed); RolePermissions = (from dop in roles.ToList() group dop by dop.Name into g let values = g.Select(it => new Pair { Name = it.RoleID, IsAllowed = it.IsAllowed }) select new { g.Key, values }) .ToDictionary(it => it.Key, it => it.values.ToList()); } Cache = new Dictionary<string, bool>(); PermissionsChanged = false; } private bool CheckOpen(string[] parts, int len) { if (len < 1) return DefaultPermissions; bool isOpen; if (GlobalPermissions.TryGetValue(string.Join(".", parts.Take(len)), out isOpen)) return isOpen; return CheckOpen(parts, len - 1); } public bool CanAccess(string identifier, IPrincipal user) { CheckPermissions(); bool isAllowed; var target = identifier ?? string.Empty; var id = user.Identity.Name + ":" + target; if (Cache.TryGetValue(id, out isAllowed)) return isAllowed; var parts = target.Split('.'); isAllowed = CheckOpen(parts, parts.Length); List<Pair> permissions; for (int i = parts.Length; i > 0; i--) { var subName = string.Join(".", parts.Take(i)); if (RolePermissions.TryGetValue(subName, out permissions)) { var found = permissions.Find(it => user.Identity.Name == it.Name) ?? permissions.Find(it => user.IsInRole(it.Name)); if (found != null) { isAllowed = found.IsAllowed; break; } } } var newCache = new Dictionary<string, bool>(Cache); newCache[id] = isAllowed; Cache = newCache; return isAllowed; } public IQueryable<T> ApplyFilters<T>(IPrincipal user, IQueryable<T> data) { List<Filter> registered; if (RegisteredFilters.TryGetValue(typeof(T), out registered)) { var result = data; foreach (var r in registered) if (user.IsInRole(r.Role) != r.Inverse) result = result.Where((Expression<Func<T, bool>>)r.Expression); return result; } return data; } public T[] ApplyFilters<T>(IPrincipal user, T[] data) { List<Filter> registered; if (RegisteredFilters.TryGetValue(typeof(T), out registered)) { var result = new List<T>(data); foreach (var r in registered) if (user.IsInRole(r.Role) != r.Inverse) result = result.FindAll((Predicate<T>)r.Predicate); return result.ToArray(); } return data; } private class Unregister : IDisposable { private readonly Action Command; public Unregister(Action command) { this.Command = command; } public void Dispose() { Command(); } } public IDisposable RegisterFilter<T>(Expression<Func<T, bool>> filter, string role, bool inverse) { var target = typeof(T); List<Filter> registered; if (!RegisteredFilters.TryGetValue(target, out registered)) RegisteredFilters[target] = registered = new List<Filter>(); var func = filter.Compile(); Predicate<T> pred = arg => func(arg); var newFilter = new Filter { Expression = filter, Role = role, Inverse = inverse, Predicate = pred }; registered.Add(newFilter); return new Unregister(() => registered.Remove(newFilter)); } public void Dispose() { GlobalSubscription.Dispose(); RoleSubscription.Dispose(); } } }
30.098901
108
0.669222
[ "BSD-3-Clause" ]
hperadin/revenj
csharp/Core/Revenj.Security/PermissionManager.cs
5,480
C#
using System; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Google; using Owin; using _safe_project_name_.Models; namespace _safe_project_name_ { public partial class Startup { // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and signin manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); } } }
51.058824
160
0.660138
[ "Apache-2.0" ]
GoogleCloudPlatform/google-cloud-visualstudio
GoogleCloudExtension/ProjectTemplates/GcpProjectTemplate/Framework/MVC/App_Start/Startup.Auth.cs
3,474
C#
using StepsInSpace.Core.Abstractions.Math; using StepsInSpace.Core.Abstractions.Math.Extensions; using StepsInSpace.Core.Abstractions.Physics; namespace StepsInSpace.Core.Physics; public class Movable : IMovable { private Vector3d _position = Vector3d.Zero; public Vector3d Position => _position; private Quaternion _orientation = Quaternion.Identity; public Quaternion Orientation => _orientation; public void Pitch(float angleInDegree) => Rotate(Vector3d.UnitX, angleInDegree); public void Yaw(float angleInDegree) => Rotate(Vector3d.UnitY, angleInDegree); public void Roll(float angleInDegree) => Rotate(Vector3d.UnitZ, angleInDegree); private void Rotate(Vector3d axis, float angleInDegree) => _orientation = _orientation.Multiply(axis.CreateRotation(angleInDegree)).Normalize(); public void MoveX(float distance) => Move(new Vector3d(distance, 0F, 0F)); public void MoveY(float distance) => Move(new Vector3d(0F, distance, 0F)); public void MoveZ(float distance) => Move(new Vector3d(0F, 0F, distance)); public void Move(Vector3d direction) => _position = _position.Add(direction.Transform(_orientation)); public Matrix4d GetModelMatrix() => _orientation.ToRotation().Multiply(_position.ToTranslation()); }
33.439024
96
0.709701
[ "MIT" ]
SteffenRossberg/StepsInSpace
src/StepsInSpace.Core/Physics/Movable.cs
1,371
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; namespace CodeWars { /// <see cref="https://www.codewars.com/kata/52774a314c2333f0a7000688/train/csharp"/> [TestClass] public class VaildParentheses { [TestMethod] public void Test() { Assert.AreEqual(false, ValidParentheses(")")); Assert.AreEqual(false, ValidParentheses("(")); Assert.AreEqual(true, ValidParentheses("()")); Assert.AreEqual(false, ValidParentheses(")((((")); Assert.AreEqual(true, ValidParentheses("(())((()())())")); Assert.AreEqual(true, ValidParentheses("(c(b(a)))(d)")); } public bool ValidParentheses(string input) { Console.Write(input); var parentheses = new Stack<char>(); foreach (var parenthesis in input) { if (!IsParenthesis(parenthesis)) continue; if (parentheses.Count == 0) parentheses.Push(parenthesis); else { if (parenthesis.Equals(')')) parentheses.Pop(); else parentheses.Push(parenthesis); } } return parentheses.Count == 0; } private bool IsParenthesis(char character) { return character.Equals('(') || character.Equals(')'); } } }
29.113208
89
0.511342
[ "MIT" ]
Hyolog/CodeWars
CodeWars/CodeWars/VaildParentheses.cs
1,543
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.SecurityInsights.V20200101 { public static class GetAction { /// <summary> /// Action for alert rule. /// </summary> public static Task<GetActionResult> InvokeAsync(GetActionArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetActionResult>("azure-native:securityinsights/v20200101:getAction", args ?? new GetActionArgs(), options.WithVersion()); } public sealed class GetActionArgs : Pulumi.InvokeArgs { /// <summary> /// Action ID /// </summary> [Input("actionId", required: true)] public string ActionId { get; set; } = null!; /// <summary> /// The name of the resource group within the user's subscription. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// Alert rule ID /// </summary> [Input("ruleId", required: true)] public string RuleId { get; set; } = null!; /// <summary> /// The name of the workspace. /// </summary> [Input("workspaceName", required: true)] public string WorkspaceName { get; set; } = null!; public GetActionArgs() { } } [OutputType] public sealed class GetActionResult { /// <summary> /// Etag of the action. /// </summary> public readonly string? Etag; /// <summary> /// Azure resource Id /// </summary> public readonly string Id; /// <summary> /// Logic App Resource Id, /subscriptions/{my-subscription}/resourceGroups/{my-resource-group}/providers/Microsoft.Logic/workflows/{my-workflow-id}. /// </summary> public readonly string LogicAppResourceId; /// <summary> /// Azure resource name /// </summary> public readonly string Name; /// <summary> /// Azure resource type /// </summary> public readonly string Type; /// <summary> /// The name of the logic app's workflow. /// </summary> public readonly string? WorkflowId; [OutputConstructor] private GetActionResult( string? etag, string id, string logicAppResourceId, string name, string type, string? workflowId) { Etag = etag; Id = id; LogicAppResourceId = logicAppResourceId; Name = name; Type = type; WorkflowId = workflowId; } } }
28.980952
176
0.568518
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/SecurityInsights/V20200101/GetAction.cs
3,043
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Insights.Autoscale; using Microsoft.Azure.Management.Insights; using Microsoft.Azure.Management.Insights.Models; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Moq; using System; using System.Collections.Generic; using System.Management.Automation; using System.Net; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Microsoft.Azure.Commands.Insights.Test.Autoscale { public class GetAzureRmAutoscaleSettingTests { private readonly GetAzureRmAutoscaleSettingCommand cmdlet; private readonly Mock<InsightsManagementClient> insightsManagementClientMock; private readonly Mock<IAutoscaleOperations> insightsAutoscaleOperationsMock; private Mock<ICommandRuntime> commandRuntimeMock; private AutoscaleSettingGetResponse response; private AutoscaleSettingListResponse responseList; private string resourceGroup; private string settingName; private string targetResourceUri = Utilities.ResourceUri; public GetAzureRmAutoscaleSettingTests(Xunit.Abstractions.ITestOutputHelper output) { ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output)); insightsAutoscaleOperationsMock = new Mock<IAutoscaleOperations>(); insightsManagementClientMock = new Mock<InsightsManagementClient>(); commandRuntimeMock = new Mock<ICommandRuntime>(); cmdlet = new GetAzureRmAutoscaleSettingCommand() { CommandRuntime = commandRuntimeMock.Object, InsightsManagementClient = insightsManagementClientMock.Object }; response = new AutoscaleSettingGetResponse() { RequestId = Guid.NewGuid().ToString(), StatusCode = HttpStatusCode.OK, Id = "", Location = "", Name = "", Properties = null, Tags = null, }; responseList = new AutoscaleSettingListResponse() { RequestId = Guid.NewGuid().ToString(), StatusCode = HttpStatusCode.OK, AutoscaleSettingResourceCollection = new AutoscaleSettingResourceCollection() { Value = new List<AutoscaleSettingResource>() { new AutoscaleSettingResource(){ Id = "", Location = "", Name = "", Properties = null, Tags = null, }, } } }; insightsAutoscaleOperationsMock.Setup(f => f.GetSettingAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<AutoscaleSettingGetResponse>(response)) .Callback((string resourceGrp, string settingNm, CancellationToken t) => { resourceGroup = resourceGrp; settingName = settingNm; }); insightsAutoscaleOperationsMock.Setup(f => f.ListSettingsAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(Task.FromResult<AutoscaleSettingListResponse>(responseList)) .Callback((string resourceGrp, string targetResourceId, CancellationToken t) => { resourceGroup = resourceGrp; targetResourceUri = targetResourceId; }); insightsManagementClientMock.SetupGet(f => f.AutoscaleOperations).Returns(this.insightsAutoscaleOperationsMock.Object); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void GetAutoscaleSettingCommandParametersProcessing() { // Calling ListSettingsAsync cmdlet.ResourceGroup = Utilities.ResourceGroup; cmdlet.ExecuteCmdlet(); Assert.Equal(Utilities.ResourceGroup, this.resourceGroup); Assert.Null(this.settingName); Assert.Null(this.targetResourceUri); // Calling GetSettingAsync this.resourceGroup = null; this.targetResourceUri = Utilities.ResourceUri; cmdlet.Name = Utilities.Name; cmdlet.ExecuteCmdlet(); Assert.Equal(Utilities.ResourceGroup, this.resourceGroup); Assert.Equal(Utilities.Name, this.settingName); Assert.Equal(Utilities.ResourceUri, this.targetResourceUri); // Test deatiled output flag calling GetSettingAsync this.resourceGroup = null; this.settingName = null; cmdlet.DetailedOutput = true; cmdlet.ExecuteCmdlet(); Assert.Equal(Utilities.ResourceGroup, this.resourceGroup); Assert.Equal(Utilities.Name, this.settingName); Assert.Equal(Utilities.ResourceUri, this.targetResourceUri); } } }
44.627737
153
0.598626
[ "MIT" ]
hchungmsft/azure-powershell
src/ResourceManager/Insights/Commands.Insights.Test/Autoscale/GetAzureRmAutoscaleSettingTests.cs
5,980
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Azure.EventHub.Inputs { public sealed class EventSubscriptionStorageBlobDeadLetterDestinationArgs : Pulumi.ResourceArgs { /// <summary> /// Specifies the id of the storage account id where the storage blob is located. /// </summary> [Input("storageAccountId", required: true)] public Input<string> StorageAccountId { get; set; } = null!; /// <summary> /// Specifies the name of the Storage blob container that is the destination of the deadletter events. /// </summary> [Input("storageBlobContainerName", required: true)] public Input<string> StorageBlobContainerName { get; set; } = null!; public EventSubscriptionStorageBlobDeadLetterDestinationArgs() { } } }
34.78125
110
0.681941
[ "ECL-2.0", "Apache-2.0" ]
ScriptBox99/pulumi-azure
sdk/dotnet/EventHub/Inputs/EventSubscriptionStorageBlobDeadLetterDestinationArgs.cs
1,113
C#
using System.ComponentModel.DataAnnotations.Schema; namespace Caasiope.Explorer.Database.SQL.Entities { public class hashlock { [DatabaseGe‌​nerated(DatabaseGen‌​eratedOption.None)] public long declaration_id { get; set; } public byte[] account { get; set; } public short secret_type { get; set; } public byte[] secret_hash { get; set; } } }
28.285714
61
0.659091
[ "MIT" ]
caasiope/caasiope-blockchain
Caasiope.Explorer.Database.SQL/Entities/hashlock.cs
406
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Razor; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Test; using Microsoft.VisualStudio.Text; using Moq; using Xunit; namespace Microsoft.VisualStudio.Editor.Razor.Documents { public class EditorDocumentTest { public EditorDocumentTest() { DocumentManager = Mock.Of<EditorDocumentManager>(); ProjectFilePath = TestProjectData.SomeProject.FilePath; DocumentFilePath = TestProjectData.SomeProjectFile1.FilePath; TextLoader = TextLoader.From(TextAndVersion.Create(SourceText.From("FILE"), VersionStamp.Default)); FileChangeTracker = new DefaultFileChangeTracker(DocumentFilePath); TextBuffer = new TestTextBuffer(new StringTextSnapshot("Hello")); } private EditorDocumentManager DocumentManager { get; } private string ProjectFilePath { get; } private string DocumentFilePath { get; } private TextLoader TextLoader { get; } private FileChangeTracker FileChangeTracker { get; } private TestTextBuffer TextBuffer { get; } [Fact] public void EditorDocument_CreatedWhileOpened() { // Arrange & Act using (var document = new EditorDocument( DocumentManager, ProjectFilePath, DocumentFilePath, TextLoader, FileChangeTracker, TextBuffer, changedOnDisk: null, changedInEditor: null, opened: null, closed: null)) { // Assert Assert.True(document.IsOpenInEditor); Assert.Same(TextBuffer, document.EditorTextBuffer); Assert.NotNull(document.EditorTextContainer); } } [Fact] public void EditorDocument_CreatedWhileClosed() { // Arrange & Act using (var document = new EditorDocument( DocumentManager, ProjectFilePath, DocumentFilePath, TextLoader, FileChangeTracker, null, changedOnDisk: null, changedInEditor: null, opened: null, closed: null)) { // Assert Assert.False(document.IsOpenInEditor); Assert.Null(document.EditorTextBuffer); Assert.Null(document.EditorTextContainer); } } } }
32.264368
111
0.587104
[ "Apache-2.0" ]
JalilAzzad1993/ASPNET
src/Razor/test/Microsoft.VisualStudio.Editor.Razor.Test/Documents/EditorDocumentTest.cs
2,809
C#
using BWModLoader; namespace FlagReplacement { internal static class Log { static readonly public ModLogger logger = new ModLogger("[FlagReplacement]", ModLoader.LogPath + "\\FlagReplacement.txt"); } }
22.4
130
0.705357
[ "MIT" ]
Modwake/customFlags
FlagReplacement/Log.cs
226
C#
namespace FastHashesNet.MurmurHash { internal static class MurmurHashConstants { internal const uint C1_32 = 0xcc9e2d51; internal const uint C2_32 = 0x1b873593; internal const ulong C1_64 = 0x87c37b91114253d5UL; internal const ulong C2_64 = 0x4cf5ad432745937fUL; } }
26.083333
58
0.702875
[ "MIT" ]
Genbox/FastHashesNet
src/FastHashesNet/MurmurHash/MurmurHashConstants.cs
315
C#
using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using IngeniuxApiDemos.Target.IngeniuxCms.Model.Attributes; using IngeniuxApiDemos.Common.Extensions; namespace IngeniuxApiDemos.Target.IngeniuxCms.Model.Validation { internal static class BaseObjectValidator { internal static ValidationResults Validate(BaseIngeniuxModel baseIngeniuxModel) { var result = new ValidationResults(); if (baseIngeniuxModel.ComponentType != ComponentType.Create) { return result; } ValidateRequiredFields(baseIngeniuxModel, result); return result; } private static void ValidateRequiredFields(BaseIngeniuxModel baseIngeniuxModel, ValidationResults result) { var baseObjectType = baseIngeniuxModel.GetType(); var properties = baseObjectType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty).ToList(); foreach (var property in properties) { var value = property.GetValue(baseIngeniuxModel, null); if (property.GetCustomAttributes(typeof(IgnoreAttribute)).Any()) { continue; } var hasRequiredAttribute = property.GetCustomAttributes(typeof(RequiredAttribute)).Any(); if (hasRequiredAttribute && property.PropertyType.IsAssignableFrom(typeof(string)) && value != null && !value.ToString().IsNullOrWhiteSpace()) { result.Add(new ValidationResult(property.Name, value, true, baseObjectType.Name)); } else if (hasRequiredAttribute && (property.PropertyType.IsSubclassOf(typeof(BaseIngeniuxModel)) || property.PropertyType == typeof(BaseIngeniuxModel)) && value != null) { var obj = (BaseIngeniuxModel) value; result.Add(obj.Validate()); } else if (property.PropertyType.IsGenericType && (property.PropertyType.GetGenericTypeDefinition() == typeof(List<>))) { var modelValueList = (value as IEnumerable); // Value is not enumerable, move on if (modelValueList == null) { continue; } foreach (var item in modelValueList) { if (!item.GetType().IsSubclassOf(typeof(BaseIngeniuxModel))) { continue; } var obj = (BaseIngeniuxModel)item; ValidateAllowableComponents(property, baseIngeniuxModel, result); result.Add(obj.Validate()); } } else if (hasRequiredAttribute) { result.Add(new ValidationResult(property.Name, value, false, baseObjectType.Name)); } } } private static void ValidateAllowableComponents(PropertyInfo property, BaseIngeniuxModel baseIngeniuxModel, ValidationResults result) { var baseObjectType = baseIngeniuxModel.GetType(); var value = property.GetValue(baseIngeniuxModel, null); var attribute = property.GetCustomAttribute(typeof(AllowedComponentsAttribute)) as AllowedComponentsAttribute; if (attribute == null) { return; } if (!property.PropertyType.IsGenericType || (property.PropertyType.GetGenericTypeDefinition() != typeof(List<>))) { return; } var modelValueList = (value as IEnumerable); // Value is not enumerable, move on if (modelValueList == null) { return; } foreach (var item in modelValueList) { if (!item.GetType().IsSubclassOf(typeof(BaseIngeniuxModel))) { break; } var baseObj = (BaseIngeniuxModel) item; var hasMatch = attribute.Values.Any(x => x == baseObj.SchemaRootName); result.Add(new ValidationResult(property.Name, baseObj.SchemaRootName, hasMatch, $"{baseObjectType.Name}.{property.Name} does not allow {baseObj.SchemaRootName}")); } } } }
38.338843
184
0.564992
[ "MIT" ]
gwendolyngoetz/IngeniuxApiDemos
IngeniuxApiDemos/Target/IngeniuxCms/Model/Validation/BaseObjectValidator.cs
4,641
C#
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; namespace WindowsAccessBridgeInterop { /// <summary> /// Wrapper for an accessible context returned by the Java Access Bridge. /// </summary> public class AccessibleContextNode : AccessibleNode { private readonly JavaObjectHandle _ac; private Lazy<AccessibleContextInfo> _info; private readonly List<Lazy<AccessibleNode>> _childList = new List<Lazy<AccessibleNode>>(); private bool _isManagedDescendant; public AccessibleContextNode(AccessBridge accessBridge, JavaObjectHandle ac) : base(accessBridge) { _ac = ac; _info = new Lazy<AccessibleContextInfo>(FetchNodeInfo); } public override int JvmId { get { return _ac.JvmId; } } public JavaObjectHandle AccessibleContextHandle { get { return _ac; } } public override bool IsManagedDescendant { get { return _isManagedDescendant; } } public void SetManagedDescendant(bool value) { _isManagedDescendant = value; } public override void Dispose() { _ac.Dispose(); } public override AccessibleNode GetParent() { ThrowIfDisposed(); var parentAc = AccessBridge.Functions.GetAccessibleParentFromContext(JvmId, _ac); if (parentAc.IsNull) { return null; } var hwnd = AccessBridge.Functions.GetHWNDFromAccessibleContext(JvmId, parentAc); if (hwnd != IntPtr.Zero) { return new AccessibleWindow(AccessBridge, hwnd, parentAc); } return new AccessibleContextNode(AccessBridge, parentAc); } private void ThrowIfDisposed() { if (_ac.IsClosed) throw new ObjectDisposedException("accessibility context"); } /// <summary> /// Limit the size of a collection according to user-defined option <see /// cref="AccessBridge.CollectionSizeLimit"/>> /// </summary> /// <param name="count"></param> /// <returns></returns> private int LimitSize(int count) { return Math.Max(0, Math.Min(AccessBridge.CollectionSizeLimit, count)); } /// <summary> /// Limit the value of the arguments <paramref name="count1"/> and <paramref /// name="count2"/> so that their product does not exceed <see /// cref="AccessBridge.CollectionSizeLimit"/>. /// </summary> private KeyValuePair<int, int> LimitSize(int count1, int count2) { return LimitSizeToSquare(count1, count2); } /// <summary> /// Limit the value of the arguments <paramref name="count1"/> and <paramref /// name="count2"/> so that their product does not exceed <see /// cref="AccessBridge.CollectionSizeLimit"/>. If the argument values need /// to be adjusted, they are both adjusted so that they form a square. /// </summary> private KeyValuePair<int, int> LimitSizeToSquare(int count1, int count2) { Func<int, int, KeyValuePair<int, int>> result = (a, b) => new KeyValuePair<int, int>(a, b); Func<double, int> round = a => (int)Math.Round(a); Func<double, double, double> min = (a, b) => Math.Min(a, b); if (count1 <= 0 || count2 <= 0) return result(0, 0); double c1 = count1; double c2 = count2; double limit = AccessBridge.CollectionSizeLimit; var squareSideLength = Math.Sqrt(limit); // If either c1 or c2 is less than the side length, use exact division. if (c1 < squareSideLength) { return result(round(c1), round(min(c2, limit / c1))); } if (c2 < squareSideLength) { return result(round(min(c1, limit / c2)), round(c2)); } // Otherwise limit both c1 and c2 to the side length. return result(round(min(c1, squareSideLength)), round(min(c2, squareSideLength))); } /// <summary> /// Limit the value of the arguments <paramref name="count1"/> and <paramref /// name="count2"/> so that their product does not exceed <see /// cref="AccessBridge.CollectionSizeLimit"/>. If the argument values need /// to be adjusted, they are both adjusted by the same factor, so that their /// proportion remain the same. This is similar to decreasing the size of a /// rectangle so that its total surface is limited while maintaining the /// shape of the initial rectangle. /// </summary> // ReSharper disable once UnusedMember.Local private KeyValuePair<int, int> LimitSizeProportionally(int count1, int count2) { Func<int, int, KeyValuePair<int, int>> result = (a, b) => new KeyValuePair<int, int>(a, b); Func<double, int> round = a => (int)Math.Round(a); if (count1 <= 0 || count2 <= 0) return result(0, 0); double c1 = count1; double c2 = count2; double limit = AccessBridge.CollectionSizeLimit; // We have 2 variables and 2 equations: // x * y = limit <= we need to limit to the total size // x / y = c1 / c2 <= we want to make sure we have the same proportions // After a quick transformation, the equations become // y = sqrt(limit * c2 / c1) // x = limit / y double y = Math.Sqrt(limit * c2 / c1); y = Math.Max(1, y); double x = limit / y; x = Math.Max(1, x); int c1Max = round(x); int c2Max = round(y); return result(Math.Min(c1Max, count1), Math.Min(c2Max, count2)); } public AccessibleContextInfo FetchNodeInfo() { ThrowIfDisposed(); _childList.Clear(); AccessibleContextInfo info; if (Failed(AccessBridge.Functions.GetAccessibleContextInfo(JvmId, _ac, out info))) { //throw new ApplicationException("Error retrieving accessible context info"); return null; } _childList.AddRange( Enumerable .Range(0, LimitSize(info.childrenCount)) .Select(i => new Lazy<AccessibleNode>(() => FetchChildNode(i)))); return info; } public AccessibleNode FetchChildNode(int i) { ThrowIfDisposed(); var childhandle = AccessBridge.Functions.GetAccessibleChildFromContext(JvmId, _ac, i); if (childhandle.IsNull) { throw new ApplicationException(string.Format("Error retrieving accessible context for child {0}", i)); } var result = new AccessibleContextNode(AccessBridge, childhandle); if (_isManagedDescendant || _info.Value.states.Contains("manages descendants")) { result.SetManagedDescendant(true); } return result; } /// <summary> /// Return the <see cref="AccessibleContextNode"/> of the current selection /// that has its "indexInParent" equal to <paramref name="childIndex"/>. Returns /// <code>null</code> if there is no such child in the selection. /// </summary> private AccessibleContextNode FindNodeInSelection(int childIndex) { var selCount = AccessBridge.Functions.GetAccessibleSelectionCountFromContext(JvmId, _ac); if (selCount > 0) { for (var selIndex = 0; selIndex < LimitSize(selCount); selIndex++) { var selectedContext = AccessBridge.Functions.GetAccessibleSelectionFromContext(JvmId, _ac, selIndex); if (!selectedContext.IsNull) { var selectedNode = new AccessibleContextNode(AccessBridge, selectedContext); if (selectedNode.GetInfo().indexInParent == childIndex) { return selectedNode; } } } } return null; } public override void Refresh() { _info = new Lazy<AccessibleContextInfo>(FetchNodeInfo); } public AccessibleContextInfo GetInfo() { return _info.Value; } protected override int GetChildrenCount() { // We limit to 256 to avoid (almost) infinite loop when # of children // is really huge (e.g. an app exposing a worksheet with thousand of cells). return LimitSize(GetInfo().childrenCount); } protected override AccessibleNode GetChildAt(int i) { ThrowIfDisposed(); return _childList[i].Value; } public override Rectangle? GetScreenRectangle() { var info = GetInfo(); if (info == null) return null; if (info.x == -1 && info.y == -1 && info.width == -1 && info.height == -1) { return null; } return new Rectangle(info.x, info.y, info.width, info.height); } public override Path<AccessibleNode> GetNodePathAt(Point screenPoint) { return GetNodePathAtWorker(screenPoint); //return GetNodePathAtUsingAccessBridge(screenPoint); } /// <summary> /// Return the <see cref="Path{AccessibleNodePath}"/> of a node given a location on screen. /// Return <code>null</code> if there is no node at that location. /// </summary> public Path<AccessibleNode> GetNodePathAtWorker(Point screenPoint) { // Bail out early if the node is not visible var info = GetInfo(); if (info == null) return null; if (info.states != null && info.states.IndexOf("showing", StringComparison.InvariantCulture) < 0) { return null; } // Special case to avoid returning nodes from overlapping components: // If we are a viewport, we only return children contained inside our // containing rectangle. if (info.role != null && info.role.Equals("viewport", StringComparison.InvariantCulture)) { var rectangle = GetScreenRectangle(); if (rectangle != null) { if (!rectangle.Value.Contains(screenPoint)) return null; } } return base.GetNodePathAt(screenPoint); } /// <summary> /// Return the <see cref="Path{AccessibleNode}"/> of a node given a location /// on screen. Return <code>null</code> if there is no node at that /// location. /// /// Note: Experimental implementation using <see /// cref="AccessBridgeFunctions.GetAccessibleContextAt"/> /// /// Note: The problem with this experimental implementation is that there is /// no way to select what component to return if there are overlapping /// components. /// </summary> public Path<AccessibleNode> GetNodePathAtUsingAccessBridge(Point screenPoint) { JavaObjectHandle childHandle; if (Failed(AccessBridge.Functions.GetAccessibleContextAt(JvmId, _ac, screenPoint.X, screenPoint.Y, out childHandle))) { return null; } if (childHandle.IsNull) { return null; } var childNode = new AccessibleContextNode(AccessBridge, childHandle); Debug.WriteLine("Child found: {0}-{1}-{2}-{3}", childNode.GetInfo().x, childNode.GetInfo().y, childNode.GetInfo().width, childNode.GetInfo().height); var path = new Path<AccessibleNode>(); for (AccessibleNode node = childNode; node != null; node = node.GetParent()) { /*DEBUG*/ if (node is AccessibleContextNode) { ((AccessibleContextNode)node).GetInfo(); } path.AddRoot(node); if (node.Equals(this)) break; } return path; } public override string GetTitle() { var info = GetInfo(); if (info == null) return ""; var sb = new StringBuilder(); // Append role (if exists) if (!string.IsNullOrEmpty(info.role)) { if (sb.Length > 0) sb.Append(" "); sb.Append(info.role); } // Append name or description var caption = !string.IsNullOrEmpty(info.name) ? info.name : info.description; if (!string.IsNullOrEmpty(caption)) { if (sb.Length > 0) sb.Append(": "); sb.Append(caption); } // Append ephemeral state (if exists) if (_isManagedDescendant) { sb.Append("*"); } return sb.ToString(); } protected override void AddProperties(PropertyList list, PropertyOptions options) { if (AccessibleContextHandle.IsNull) { list.AddProperty("<None>", "No accessible context"); return; } AddContextProperties(list, options); AddParentContextProperties(list, options); AddChildrenProperties(list, options); AddTopLevelWindowProperties(list, options); AddActiveDescendentProperties(list, options); AddSelectionProperties(list, options); // AddKeyBindingsProperties(list, options); AddIconsProperties(list, options); AddActionProperties(list, options); AddVisibleChildrenProperties(list, options); AddRelationSetProperties(list, options); AddValueProperties(list, options); AddTableProperties(list, options); AddTextProperties(list, options); AddHyperTextProperties(list, options); } private void AddContextProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.AccessibleContextInfo) != 0) { var info = GetInfo(); if (info == null) return; list.AddProperty("Name", info.name ?? "-"); list.AddProperty("Description", info.description ?? "-"); list.AddProperty("Name (JAWS algorithm)", GetVirtualAccessibleName()); list.AddProperty("Role", info.role ?? "-"); list.AddProperty("Role_en_US", info.role_en_US ?? "-"); list.AddProperty("States", info.states ?? "-"); list.AddProperty("States_en_US", info.states_en_US ?? "-"); list.AddProperty("Bounds", new AccessibleRectInfo(this, info.x, info.y, info.width, info.height)); if ((options & PropertyOptions.ObjectDepth) != 0) { var depth = AccessBridge.Functions.GetObjectDepth(JvmId, _ac); list.AddProperty("Object Depth", depth); } list.AddProperty("Children count", info.childrenCount); list.AddProperty("Index in parent", info.indexInParent); list.AddProperty("AccessibleComponent supported", info.accessibleComponent); list.AddProperty("AccessibleAction supported", info.accessibleAction); list.AddProperty("AccessibleSelection supported", info.accessibleSelection); list.AddProperty("AccessibleText supported", info.accessibleText); list.AddProperty("AccessibleInterfaces supported", info.accessibleInterfaces); } } private void AddParentContextProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.ParentContext) != 0) { var parentContext = AccessBridge.Functions.GetAccessibleParentFromContext(JvmId, _ac); if (!parentContext.IsNull) { var group = list.AddGroup("Parent"); group.LoadChildren = () => { AddSubContextProperties(@group.Children, options, parentContext); }; } } } private void AddChildrenProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.Children) != 0) { var info = GetInfo(); if (info == null) return; var count = info.childrenCount; if (count > 0) { var group = list.AddGroup("Children"); group.LoadChildren = () => { group.AddProperty("Count", count); Enumerable.Range(0, LimitSize(count)).ForEach(index => { var childHandle = AccessBridge.Functions.GetAccessibleChildFromContext(JvmId, _ac, index); var childNode = new AccessibleContextNode(AccessBridge, childHandle); var childGroup = group.AddGroup(string.Format("{0} [{1} of {2}]", childNode.GetTitle(), index + 1, count)); childGroup.LoadChildren = () => { AddSubContextProperties(childGroup.Children, options, childNode); }; }); }; } } } private void AddTopLevelWindowProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.TopLevelWindowInfo) != 0) { var topLevel = AccessBridge.Functions.GetTopLevelObject(JvmId, _ac); if (!topLevel.IsNull) { var group = list.AddGroup("Top level window"); group.LoadChildren = () => { AddSubContextProperties(group.Children, options, topLevel); }; } } } private void AddActiveDescendentProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.ActiveDescendent) != 0) { var descendant = AccessBridge.Functions.GetActiveDescendent(JvmId, _ac); if (!descendant.IsNull) { var group = list.AddGroup("Active Descendant"); group.LoadChildren = () => { AddSubContextProperties(group.Children, options, descendant); }; } } } private void AddSelectionProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.AccessibleSelection) != 0) { var info = GetInfo(); if (info == null) return; if (info.accessibleSelection != 0) { var group = list.AddGroup("Selections"); group.LoadChildren = () => { var count = AccessBridge.Functions.GetAccessibleSelectionCountFromContext(JvmId, _ac); group.AddProperty("Count", count); Enumerable.Range(0, LimitSize(count)).ForEach(index => { var selGroup = group.AddGroup(string.Format("Selection {0} of {1}", index + 1, count)); selGroup.LoadChildren = () => { var selectedContext = AccessBridge.Functions.GetAccessibleSelectionFromContext(JvmId, _ac, index); AddSubContextProperties(selGroup.Children, options, selectedContext); }; }); }; } } } private void AddKeyBindingsProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.AccessibleKeyBindings) != 0) { AccessibleKeyBindings keyBindings; if (Failed(AccessBridge.Functions.GetAccessibleKeyBindings(JvmId, _ac, out keyBindings))) { var group = list.AddGroup("Key Bindings"); group.AddProperty("<Error>", "error retrieving key bindings"); } else { var count = keyBindings.keyBindingsCount; if (count > 0) { var group = list.AddGroup("Key Bindings"); group.LoadChildren = () => { group.AddProperty("Count", count); Enumerable.Range(0, LimitSize(count)).ForEach(index => { var keyGroup = group.AddGroup(string.Format("Key binding {0} of {1}", index + 1, keyBindings.keyBindingsCount)); keyGroup.AddProperty("Character", keyBindings.keyBindingInfo[index].character); keyGroup.AddProperty("Modifiers", keyBindings.keyBindingInfo[index].modifiers); }); }; } } } } private void AddIconsProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.AccessibleIcons) != 0) { AccessibleIcons icons; if (Failed(AccessBridge.Functions.GetAccessibleIcons(JvmId, _ac, out icons))) { var group = list.AddGroup("Icons"); group.AddProperty("<Error>", "error retrieving icons"); } else { var count = icons.iconsCount; if (count > 0) { var group = list.AddGroup("Icons"); group.LoadChildren = () => { group.AddProperty("Count", count); Enumerable.Range(0, LimitSize(count)).ForEach(index => { var iconGroup = group.AddGroup(string.Format("Icon {0} of {1}", index + 1, icons.iconsCount)); iconGroup.AddProperty("Height", icons.iconInfo[index].height); iconGroup.AddProperty("Width", icons.iconInfo[index].width); }); }; } } } } private void AddActionProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.AccessibleActions) != 0) { AccessibleActions actions; if (Failed(AccessBridge.Functions.GetAccessibleActions(JvmId, _ac, out actions))) { var group = list.AddGroup("Actions"); group.AddProperty("<Error>", "error retrieving actions"); } else { var count = actions.actionsCount; if (count > 0) { var group = list.AddGroup("Actions"); group.LoadChildren = () => { group.AddProperty("Count", count); Enumerable.Range(0, LimitSize(count)).ForEach(index => { group.AddProperty( string.Format("Action {0} of {1}", index + 1, actions.actionsCount), actions.actionInfo[index].name); }); }; } } } } private void AddVisibleChildrenProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.VisibleChildren) != 0) { var group = list.AddGroup("Visible Children"); group.LoadChildren = () => { // Note: This can be a very expensive calls on the JVM side! var visibleCount = AccessBridge.Functions.GetVisibleChildrenCount(JvmId, _ac); group.AddProperty("Count", visibleCount); if (visibleCount > 0) { VisibleChildrenInfo childrenInfo; if (Succeeded(AccessBridge.Functions.GetVisibleChildren(JvmId, _ac, 0, out childrenInfo))) { var childNodes = childrenInfo.children .Take(LimitSize(childrenInfo.returnedChildrenCount)) .Select(x => new AccessibleContextNode(AccessBridge, x)); var childIndex = 0; childNodes.ForEach(childNode => { var childGroup = group.AddGroup(string.Format("Child {0} of {1}", childIndex + 1, visibleCount)); childGroup.LoadChildren = () => { AddSubContextProperties(childGroup.Children, options, childNode); }; childIndex++; }); } } }; } } private void AddRelationSetProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.AccessibleRelationSet) != 0) { AccessibleRelationSetInfo relationSetInfo; if (Failed(AccessBridge.Functions.GetAccessibleRelationSet(JvmId, _ac, out relationSetInfo))) { var group = list.AddGroup("Relation Set"); group.AddProperty("<Error>", "error retrieving relation set"); } else { var count = relationSetInfo.relationCount; if (count > 0) { var group = list.AddGroup("Relation Set"); group.LoadChildren = () => { group.AddProperty("Count", count); Enumerable.Range(0, LimitSize(count)).ForEach(index => { var relationInfo = relationSetInfo.relations[index]; var relGroup = group.AddGroup(string.Format("Relation {0} of {1}", index + 1, relationSetInfo.relationCount)); relGroup.AddProperty("Key", relationInfo.key); var relSubGroup = relGroup.AddGroup("Targets", relationInfo.targetCount); relSubGroup.LoadChildren = () => { Enumerable.Range(0, LimitSize(relationInfo.targetCount)).ForEach(j => { var targetGroup = relSubGroup.AddGroup(string.Format("Target {0} of {1}", j + 1, relationInfo.targetCount)); AddSubContextProperties(targetGroup.Children, options, relationInfo.targets[j]); }); }; }); }; } } } } private void AddValueProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.AccessibleValue) != 0) { var info = GetInfo(); if (info == null) return; if ((info.accessibleInterfaces & AccessibleInterfaces.cAccessibleValueInterface) != 0) { var group = list.AddGroup("Value"); group.LoadChildren = () => { var sb = new StringBuilder(AccessBridge.TextBufferLengthLimit); if (Failed(AccessBridge.Functions.GetCurrentAccessibleValueFromContext(JvmId, _ac, sb, (short)sb.Capacity))) { sb.Clear(); sb.Append("<Error>"); } group.AddProperty("Current", sb); if (Failed(AccessBridge.Functions.GetMaximumAccessibleValueFromContext(JvmId, _ac, sb, (short)sb.Capacity))) { sb.Clear(); sb.Append("<Error>"); } group.AddProperty("Maximum", sb); if (Failed(AccessBridge.Functions.GetMinimumAccessibleValueFromContext(JvmId, _ac, sb, (short)sb.Capacity))) { sb.Clear(); sb.Append("<Error>"); } group.AddProperty("Minimum", sb); }; } } } private void AddTableProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.AccessibleTable) != 0) { var nodeInfo = GetInfo(); if (nodeInfo == null) return; if ((nodeInfo.accessibleInterfaces & AccessibleInterfaces.cAccessibleTableInterface) != 0) { var group = list.AddGroup("Table"); group.LoadChildren = () => { AccessibleTableInfo tableInfo; if (Failed(AccessBridge.Functions.GetAccessibleTableInfo(JvmId, _ac, out tableInfo))) { group.AddProperty("Error", "Error retrieving table info"); } else { AddTableInfo(group, options, tableInfo); AddTableColumnHeaderProperties(group, options); AddTableRowHeaderProperties(group, options); AddTableSelectedColumnsProperties(tableInfo, group); AddTableSelectedRowsProperties(tableInfo, group); AddTableCellsProperties(tableInfo, group, options); AddTableSelectCellsProperties(tableInfo, group, options); } }; } } } private void AddTextProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.AccessibleText) != 0) { var info = GetInfo(); if (info == null) return; if (info.accessibleText != 0) { var group = list.AddGroup("Accessible Text"); group.LoadChildren = () => { var point = new Point(0, 0); AccessibleTextInfo textInfo; if (Failed(AccessBridge.Functions.GetAccessibleTextInfo(JvmId, _ac, out textInfo, point.X, point.Y))) { group.AddProperty("<Error>", "Error retrieving text info"); } else { group.AddProperty("Character count", textInfo.charCount); group.AddProperty("Character index of caret", textInfo.caretIndex); group.AddProperty(string.Format("Character index of point ({0}, {1})", point.X, point.Y), textInfo.indexAtPoint); AccessibleTextSelectionInfo textSelection; if (Succeeded(AccessBridge.Functions.GetAccessibleTextSelectionInfo(JvmId, _ac, out textSelection))) { group.AddProperty("Selection start index", textSelection.selectionStartIndex); group.AddProperty("Selection end index", textSelection.selectionEndIndex); group.AddProperty("Selected text", textSelection.selectedText); } var caretGroup = group.AddGroup("Text attributes at caret"); caretGroup.LoadChildren = () => { AddTextAttributeAtIndex(caretGroup.Children, textInfo.caretIndex); }; var pointGroup = group.AddGroup(string.Format("Text attributes at point ({0}, {1})", point.X, point.Y)); pointGroup.LoadChildren = () => { AddTextAttributeAtIndex(pointGroup.Children, textInfo.indexAtPoint); }; var textGroup = group.AddGroup("Contents"); textGroup.LoadChildren = () => { bool isEmpty = true; var reader = new AccessibleTextReader(this, textInfo.charCount); var lines = reader .ReadFullLines(AccessBridge.TextLineLengthLimit) .Where(x => !x.IsContinuation) .Take(AccessBridge.TextLineCountLimit); foreach (var lineData in lines) { var lineEndOffset = lineData.Offset + lineData.Text.Length - 1; var name = string.Format("Line {0} [{1}, {2}]", lineData.Number + 1, lineData.Offset, lineEndOffset); var value = MakePrintable(lineData.Text) + (lineData.IsComplete ? "" : "..."); textGroup.AddProperty(name, value); isEmpty = false; } if (isEmpty) textGroup.AddProperty("<Empty>", "No text contents"); }; } }; } } } private void AddHyperTextProperties(PropertyList list, PropertyOptions options) { if ((options & PropertyOptions.AccessibleHyperText) != 0) { var info = GetInfo(); if (info == null) return; if ((info.accessibleInterfaces & AccessibleInterfaces.cAccessibleHypertextInterface) != 0) { var group = list.AddGroup("Accessible Hyper Text"); group.LoadChildren = () => { AccessibleHypertextInfo hyperTextInfo; if (Failed(AccessBridge.Functions.GetAccessibleHypertextExt(JvmId, _ac, 0, out hyperTextInfo))) { group.AddProperty("<Error>", "Error retrieving hyper text info"); } else { var linksGroup = group.AddGroup("Hyperlinks", hyperTextInfo.linkCount); linksGroup.LoadChildren = () => { var count = hyperTextInfo.linkCount; linksGroup.AddProperty("Count", count); Enumerable.Range(0, LimitSize(count)).ForEach(i => { var linkGroup = linksGroup.AddGroup(string.Format("Hyperlink {0} of {1}", i + 1, count)); linkGroup.LoadChildren = () => { linkGroup.AddProperty("Start index", hyperTextInfo.links[i].startIndex); linkGroup.AddProperty("End index", hyperTextInfo.links[i].endIndex); linkGroup.AddProperty("Text", hyperTextInfo.links[i].text); //AddSubContextProperties(linkGroup.Children, options, hyperTextInfo.links[i].accessibleHyperlink); }; }); }; } }; } } } private void AddTableColumnHeaderProperties(PropertyGroup group, PropertyOptions options) { var columnHeaderGroup = group.AddGroup("Column Headers"); columnHeaderGroup.LoadChildren = () => { AccessibleTableInfo columnInfo; if (Failed(AccessBridge.Functions.GetAccessibleTableColumnHeader(JvmId, _ac, out columnInfo))) { columnHeaderGroup.AddProperty("Error", "Error retrieving column header info"); } else { AddTableInfo(columnHeaderGroup, options, columnInfo); AddTableCellsProperties(columnInfo, columnHeaderGroup, options); } }; } private void AddTableRowHeaderProperties(PropertyGroup group, PropertyOptions options) { var rowHeaderGroup = group.AddGroup("Row Headers"); rowHeaderGroup.LoadChildren = () => { AccessibleTableInfo rowInfo; if (Failed(AccessBridge.Functions.GetAccessibleTableRowHeader(JvmId, _ac, out rowInfo))) { rowHeaderGroup.AddProperty("Error", "Error retrieving column header info"); } else { AddTableInfo(rowHeaderGroup, options, rowInfo); AddTableCellsProperties(rowInfo, rowHeaderGroup, options); } }; } private void AddTableSelectedColumnsProperties(AccessibleTableInfo tableInfo, PropertyGroup group) { var numColSelections = AccessBridge.Functions.GetAccessibleTableColumnSelectionCount(JvmId, tableInfo.accessibleTable); var selColGroup = group.AddGroup("Column selections", numColSelections); selColGroup.LoadChildren = () => { if (numColSelections <= 0) { selColGroup.AddProperty("<Empty>", "no selection"); } else { var selections = new int[numColSelections]; if (Failed(AccessBridge.Functions.GetAccessibleTableColumnSelections(JvmId, tableInfo.accessibleTable, numColSelections, selections))) { selColGroup.AddProperty("Error", "Error getting column selections"); } else { for (var j = 0; j < LimitSize(numColSelections); j++) { selColGroup.AddProperty(string.Format("Column index {0} of {1}", j + 1, numColSelections), selections[j]); } } } }; } private void AddTableSelectedRowsProperties(AccessibleTableInfo tableInfo, PropertyGroup group) { var numRowSelections = AccessBridge.Functions.GetAccessibleTableRowSelectionCount(JvmId, tableInfo.accessibleTable); var selRowGroup = group.AddGroup("Row selections", numRowSelections); selRowGroup.LoadChildren = () => { if (numRowSelections <= 0) { selRowGroup.AddProperty("<Empty>", "no selection"); } else { var selections = new int[numRowSelections]; if (Failed(AccessBridge.Functions.GetAccessibleTableRowSelections(JvmId, tableInfo.accessibleTable, numRowSelections, selections))) { selRowGroup.AddProperty("Error", "Error getting row selections"); } else { for (var j = 0; j < LimitSize(numRowSelections); j++) { selRowGroup.AddProperty(string.Format("Row index {0} of {1}", j + 1, numRowSelections), selections[j]); } } } }; } private void AddTableCellsProperties(AccessibleTableInfo tableInfo, PropertyGroup group, PropertyOptions options) { if ((options & PropertyOptions.AccessibleTableCells) != 0) { var cellsGroup = group.AddGroup("Cells", string.Format("{0} row(s), {1} column(s)", tableInfo.rowCount, tableInfo.columnCount)); cellsGroup.LoadChildren = () => { if (tableInfo.rowCount <= 0 || tableInfo.columnCount <= 0) { cellsGroup.AddProperty("<Empty>", ""); } else { foreach (var rowCol in EnumerateRowColunms(tableInfo.rowCount, tableInfo.columnCount)) { AddTableCellGroup(tableInfo, cellsGroup, options, rowCol.RowIndex, rowCol.ColumnIndex); } } }; } } private void AddTableCellGroup(AccessibleTableInfo tableInfo, PropertyGroup cellsGroup, PropertyOptions options, int rowIndex, int columnIndex) { var cellGroup = cellsGroup.AddGroup(GetCellGroupTitle(tableInfo, rowIndex, columnIndex)); cellGroup.LoadChildren = () => { AccessibleTableCellInfo tableCellInfo; if (Failed(AccessBridge.Functions.GetAccessibleTableCellInfo(tableInfo.accessibleTable.JvmId, tableInfo.accessibleTable, rowIndex, columnIndex, out tableCellInfo))) { cellGroup.AddProperty("<Error>", "Error retrieving cell info"); } else { var cellHandle = tableCellInfo.accessibleContext; cellGroup.AddProperty("Index", tableCellInfo.index); cellGroup.AddProperty("Row extent", tableCellInfo.rowExtent); cellGroup.AddProperty("Column extent", tableCellInfo.columnExtent); cellGroup.AddProperty("Is selected", tableCellInfo.isSelected); AddSubContextProperties(cellGroup.Children, options, cellHandle); } }; } private void AddTableSelectCellsProperties(AccessibleTableInfo tableInfo, PropertyGroup group, PropertyOptions options) { if ((options & PropertyOptions.AccessibleTableCellsSelect) != 0) { var cellsGroup = group.AddGroup("Select Cells", string.Format("{0} row(s), {1} column(s)", tableInfo.rowCount, tableInfo.columnCount)); cellsGroup.LoadChildren = () => { if (tableInfo.rowCount <= 0 || tableInfo.columnCount <= 0) { cellsGroup.AddProperty("<Empty>", ""); } else { foreach (var rowCol in EnumerateRowColunms(tableInfo.rowCount, tableInfo.columnCount)) { AddTableSelectCellGroup(tableInfo, cellsGroup, options, rowCol.RowIndex, rowCol.ColumnIndex); } } }; } } private void AddTableSelectCellGroup(AccessibleTableInfo tableInfo, PropertyGroup cellsGroup, PropertyOptions options, int rowIndex, int columnIndex) { var cellGroup = cellsGroup.AddGroup(GetCellGroupTitle(tableInfo, rowIndex, columnIndex)); cellGroup.LoadChildren = () => { var cellIndex = rowIndex * tableInfo.columnCount + columnIndex; var node = SelectAndGetTableCell(cellIndex); if (node == null) { cellGroup.AddProperty("<Error>", "Error retrieving cell info"); } else { AddSubContextProperties(cellGroup.Children, options, node); } }; } /// <summary> /// The only way we found to get the right info for a cell in a table is to /// set the selection to a single cell, then to get the accessible context /// for the selection. A side effect of this, of course, is that the table /// selection will change in the Java Application. /// /// Note: The default implementation for table is incorrect due to an /// defect in JavaAccessBridge: instead of returning the /// AccessbleJTableCell, the AccessBridge implemenentation, for some /// reason, has a hard-coded reference to JTable and calls /// "getCellRendered" directly instead of calling /// AccessibleContext.GetAccessibleChild(). So we need to call a custom /// method for tables. /// </summary> private AccessibleContextNode SelectAndGetTableCell(int childIndex) { // Get the current selection, just in case it contains "childIndex". var childNode = FindNodeInSelection(childIndex); if (childNode != null) return childNode; // Note that if the table only supports entire row selection, this call // may end up selecting an entire row. AccessBridge.Functions.ClearAccessibleSelectionFromContext(JvmId, _ac); AccessBridge.Functions.AddAccessibleSelectionFromContext(JvmId, _ac, childIndex); return FindNodeInSelection(childIndex); } private void AddTextAttributeAtIndex(PropertyList list, int index) { AccessibleTextRectInfo rectInfo; if (Succeeded(AccessBridge.Functions.GetAccessibleTextRect(JvmId, _ac, out rectInfo, index))) { list.AddProperty("Character bounding rectangle:", new AccessibleRectInfo(this, rectInfo)); } int start; int end; if (Succeeded(AccessBridge.Functions.GetAccessibleTextLineBounds(JvmId, _ac, index, out start, out end))) { list.AddProperty("Line bounds", string.Format("[{0},{1}]", start, end)); if (start >= 0 && end > start) { var buffer = new char[AccessBridge.TextBufferLengthLimit]; end = Math.Min(start + buffer.Length, end); if (Succeeded(AccessBridge.Functions.GetAccessibleTextRange(JvmId, _ac, start, end, buffer, (short)buffer.Length))) { list.AddProperty("Line text", new string(buffer, 0, end - start)); } } } AccessibleTextItemsInfo textItems; if (Succeeded(AccessBridge.Functions.GetAccessibleTextItems(JvmId, _ac, out textItems, index))) { list.AddProperty("Character", textItems.letter); list.AddProperty("Word", textItems.word); list.AddProperty("Sentence", textItems.sentence); } /* ===== AccessibleText attributes ===== */ AccessibleTextAttributesInfo attributeInfo; if (Succeeded(AccessBridge.Functions.GetAccessibleTextAttributes(JvmId, _ac, index, out attributeInfo))) { list.AddProperty("Core attributes", (attributeInfo.bold != 0 ? "bold" : "not bold") + ", " + (attributeInfo.italic != 0 ? "italic" : "not italic") + ", " + (attributeInfo.underline != 0 ? "underline" : "not underline") + ", " + (attributeInfo.strikethrough != 0 ? "strikethrough" : "not strikethrough") + ", " + (attributeInfo.superscript != 0 ? "superscript" : "not superscript") + ", " + (attributeInfo.subscript != 0 ? "subscript" : "not subscript")); list.AddProperty("Background color", attributeInfo.backgroundColor); list.AddProperty("Foreground color", attributeInfo.foregroundColor); list.AddProperty("Font family", attributeInfo.fontFamily); list.AddProperty("Font size", attributeInfo.fontSize); list.AddProperty("First line indent", attributeInfo.firstLineIndent); list.AddProperty("Left indent", attributeInfo.leftIndent); list.AddProperty("Right indent", attributeInfo.rightIndent); list.AddProperty("Line spacing", attributeInfo.lineSpacing); list.AddProperty("Space above", attributeInfo.spaceAbove); list.AddProperty("Space below", attributeInfo.spaceBelow); list.AddProperty("Full attribute string", attributeInfo.fullAttributesString); // get the attribute run length short runLength; if (Succeeded(AccessBridge.Functions.GetTextAttributesInRange(JvmId, _ac, index, index + 100, out attributeInfo, out runLength))) { list.AddProperty("Attribute run", runLength); } else { list.AddProperty("Attribute run", "<Error>"); } } } private void AddTableInfo(PropertyGroup group, PropertyOptions options, AccessibleTableInfo tableInfo) { group.AddProperty("Row count", tableInfo.rowCount); group.AddProperty("Column count", tableInfo.columnCount); var captionGroup = group.Children.AddGroup("Caption"); captionGroup.LoadChildren = () => { AddSubContextProperties(captionGroup.Children, options, tableInfo.caption); }; var summaryGroup = group.Children.AddGroup("Summary"); summaryGroup.LoadChildren = () => { AddSubContextProperties(summaryGroup.Children, options, tableInfo.summary); }; } protected void AddSubContextProperties(PropertyList list, PropertyOptions options, JavaObjectHandle contextHandle) { var contextNode = new AccessibleContextNode(AccessBridge, contextHandle); AddSubContextProperties(list, options, contextNode); } protected void AddSubContextProperties(PropertyList list, PropertyOptions options, AccessibleContextNode contextNode) { contextNode.AddSubContextProperties(list, options); } private void AddSubContextProperties(PropertyList list, PropertyOptions options) { try { // Now that we load all children lazily, we can affort to add all the properties. AddProperties(list, options); } catch (Exception e) { list.AddProperty("Error", e.Message); } } protected override void AddToolTipProperties(PropertyList list, PropertyOptions options) { try { var info = GetInfo(); if (info == null) return; // Limit string sizes to avoid making the tooltip too big const int stringMaxLength = 60; list.AddProperty("Role", LimitStringSize(info.role, stringMaxLength)); if ((options & PropertyOptions.AccessibleText) != 0) { if (info.accessibleText != 0) { list.AddProperty("Text", LimitStringSize(GetTextExtract(), stringMaxLength)); } } list.AddProperty("Name", LimitStringSize(info.name, stringMaxLength)); list.AddProperty("Description", LimitStringSize(info.description, stringMaxLength)); list.AddProperty("Name (JAWS algorithm)", LimitStringSize(GetVirtualAccessibleName(), stringMaxLength)); if ((options & PropertyOptions.ObjectDepth) != 0) { var depth = AccessBridge.Functions.GetObjectDepth(JvmId, _ac); list.AddProperty("Object Depth", depth); } list.AddProperty("Bounds", new AccessibleRectInfo(this, info.x, info.y, info.width, info.height)); list.AddProperty("States", info.states); list.AddProperty("accessibleInterfaces", info.accessibleInterfaces); } catch (Exception e) { list.AddProperty("Error", e.Message); } } private static string LimitStringSize(string value, int maxLength) { if (string.IsNullOrEmpty(value)) return ""; if (value.Length < maxLength) return value; return value.Substring(0, maxLength).Trim() + "..."; } public override bool Equals(AccessibleNode other) { if (!base.Equals(other)) return false; if (!(other is AccessibleContextNode)) return false; return AccessBridge.Functions.IsSameObject(JvmId, _ac, ((AccessibleContextNode)other)._ac); } /// <summary> /// Call the custom function <see /// cref="AccessBridgeFunctions.GetVirtualAccessibleName"/> to retrieve the /// spoken name of an accessible component supposedly according to the /// algorithm used by the Jaws screen reader. /// </summary> private string GetVirtualAccessibleName() { var sb = new StringBuilder(AccessBridge.TextBufferLengthLimit); if (Failed(AccessBridge.Functions.GetVirtualAccessibleName(JvmId, _ac, sb, sb.Capacity))) { return "<Error>"; } return sb.ToString(); } private string GetTextExtract() { var point = new Point(0, 0); AccessibleTextInfo textInfo; if (Failed(AccessBridge.Functions.GetAccessibleTextInfo(JvmId, _ac, out textInfo, point.X, point.Y))) { return "<Error>"; } using (var reader = new AccessibleTextReader(this, textInfo.charCount)) { return reader.ReadLine(); } } protected static bool Failed(bool accessBridgeReturnValue) { return accessBridgeReturnValue == false; } protected static bool Succeeded(bool accessBridgeReturnValue) { return !Failed(accessBridgeReturnValue); } public override string ToString() { try { var info = GetInfo(); if (info == null) return "AccessibleContextNode: ERROR!"; return string.Format("AccessibleContextNode(name={0},role={1},x={2},y={3},w={4},h={5})", info.name ?? " - ", info.role ?? " - ", info.x, info.y, info.width, info.height); } catch (Exception e) { return string.Format("AccessibleContextNode(Error={0})", e.Message); } } public override int GetIndexInParent() { var info = GetInfo(); if (info == null) return -1; return GetInfo().indexInParent; } private static string MakePrintable(string text) { var sb = new StringBuilder(); foreach (var ch in text) { if (ch == '\n') sb.Append("\\n"); else if (ch == '\r') sb.Append("\\r"); else if (ch == '\t') sb.Append("\\t"); else if (char.IsControl(ch)) sb.Append("#"); else sb.Append(ch); } return sb.ToString(); } private static string GetCellGroupTitle(AccessibleTableInfo tableInfo, int rowIndex, int columnIndex) { return string.Format("[Row {0}/{1}, Col {2}/{3}]", rowIndex + 1, tableInfo.rowCount, columnIndex + 1, tableInfo.columnCount); } private IEnumerable<RowColumn> EnumerateRowColunms(int rowCount, int columnCount) { var limits = LimitSize(rowCount, columnCount); for (var rowIndex = 0; rowIndex < limits.Key; rowIndex++) { for (var columnIndex = 0; columnIndex < limits.Value; columnIndex++) { yield return new RowColumn(rowIndex, columnIndex); } } } private struct RowColumn { private readonly int _rowIndex; private readonly int _columnIndex; public RowColumn(int rowIndex, int columnIndex) { _rowIndex = rowIndex; _columnIndex = columnIndex; } public int RowIndex { get { return _rowIndex; } } public int ColumnIndex { get { return _columnIndex; } } } } }
43.704266
180
0.509306
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
IBM/openrpa
WindowsAccessBridgeInterop/AccessibleContextNode.cs
60,445
C#
using System.Collections.Generic; using System.Threading.Tasks; using DotNet.Sdk.Extensions.Testing.Configuration; using DotNet.Sdk.Extensions.Tests.Options.ValidateEagerly.Auxiliary; using DotNet.Sdk.Extensions.Tests.Options.ValidateEagerly.Auxiliary.DataAnnotations; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration.Memory; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Shouldly; using Xunit; namespace DotNet.Sdk.Extensions.Tests.Options.ValidateEagerly { [Trait("Category", XUnitCategories.Options)] public class OptionsValidateEagerlyWithValidateDataAnnotationsTests { /// <summary> /// This tests that the <see cref="IHost"/> will throw an exception when starting if the options /// validation fails. /// </summary> [Fact] public async Task ServerFailsToStartIfOptionsValidationFails() { using var host = Host .CreateDefaultBuilder() .UseDefaultLogLevel(LogLevel.None) // expect critical error log so disabling all logs .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseLocalhostWithRandomPort() .UseStartup<StartupMyOptions2ValidateEagerly>(); }) .Build(); var validationException = await Should.ThrowAsync<OptionsValidationException>(host.StartAsync()); #if NET6_0 validationException.Message.ShouldBe("DataAnnotation validation failed for 'MyOptions2' members: 'SomeOption' with the error: 'The SomeOption field is required.'."); #else validationException.Message.ShouldBe("DataAnnotation validation failed for members: 'SomeOption' with the error: 'The SomeOption field is required.'."); #endif } /// <summary> /// This tests that the <see cref="IHost"/> will start as expected if the options validation succeeds. /// The validation is checking that the MyOptions2.SomeOption is not null or empty. /// </summary> [Fact] public void ServerStartsIfOptionsValidationSucceeds() { using var host = Host .CreateDefaultBuilder() .UseDefaultLogLevel(LogLevel.Critical) .ConfigureAppConfiguration((_, builder) => { var memoryConfigurationSource = new MemoryConfigurationSource { InitialData = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("SomeOption", "some value"), }, }; builder.Add(memoryConfigurationSource); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseLocalhostWithRandomPort() .UseStartup<StartupMyOptions2ValidateEagerly>(); }) .Build(); Should.NotThrow(async () => await host.StartAsync()); } } }
42.473684
177
0.609665
[ "MIT" ]
edumserranotest/dot-net-sdk-extensions
tests/DotNet.Sdk.Extensions.Tests/Options/ValidateEagerly/OptionsValidateEagerlyWithValidateDataAnnotationsTests.cs
3,228
C#
using System; using System.IO; using System.Threading.Tasks; using CorePhoto.Colors.PackedPixel; using CorePhoto.IO; using ImageSharp; namespace CorePhoto.Tiff { public static class TiffImageReader { public async static Task<Action<byte[], PixelAccessor<Rgb888>, Rectangle>> GetImageDecoderAsync(TiffIfd ifd, Stream stream, ByteOrder byteOrder) { var photometricInterpretation = ifd.GetPhotometricInterpretation(byteOrder); switch (photometricInterpretation) { case TiffPhotometricInterpretation.WhiteIsZero: { var bitsPerSample = await ifd.ReadBitsPerSampleAsync(stream, byteOrder); if (bitsPerSample.Length >= 1 && bitsPerSample[0] == 8) return (imageData, pixels, destination) => DecodeImageData_Grayscale_8(imageData, pixels, destination, true); } break; case TiffPhotometricInterpretation.BlackIsZero: { var bitsPerSample = await ifd.ReadBitsPerSampleAsync(stream, byteOrder); if (bitsPerSample.Length >= 1 && bitsPerSample[0] == 8) return (imageData, pixels, destination) => DecodeImageData_Grayscale_8(imageData, pixels, destination, false); } break; case TiffPhotometricInterpretation.Rgb: { var samplesPerPixel = (int)ifd.GetSamplesPerPixel(byteOrder); var bitsPerSample = await ifd.ReadBitsPerSampleAsync(stream, byteOrder); if (bitsPerSample.Length >= 3 && bitsPerSample[0] == 8 && bitsPerSample[1] == 8 && bitsPerSample[2] == 8) { if (samplesPerPixel == 3) return (imageData, pixels, destination) => DecodeImageData_Rgb_888(imageData, pixels, destination); else return (imageData, pixels, destination) => DecodeImageData_Rgb_888_ExtraSamples(imageData, pixels, destination, samplesPerPixel); } } break; default: throw new System.NotImplementedException(); } throw new System.NotImplementedException(); } public static bool SupportsPhotometricInterpretation(TiffPhotometricInterpretation photometricInterpretation) { switch (photometricInterpretation) { case TiffPhotometricInterpretation.WhiteIsZero: case TiffPhotometricInterpretation.BlackIsZero: case TiffPhotometricInterpretation.Rgb: return true; default: return false; } } private static void DecodeImageData_Rgb_888(byte[] imageData, PixelAccessor<Rgb888> pixels, Rectangle destination) { var srcPixels = new PixelArea<Rgb888>(destination.Width, destination.Height, imageData, ComponentOrder.Xyz); pixels.CopyFrom(srcPixels, destination.Y, destination.X); } private static void DecodeImageData_Rgb_888_ExtraSamples(byte[] imageData, PixelAccessor<Rgb888> pixels, Rectangle destination, int bytesPerPixel) { var offset = 0; for (var y = 0; y < destination.Height; y++) { for (var x = 0; x < destination.Width; x++) { var color = default(Rgb888); var r = imageData[offset]; var g = imageData[offset + 1]; var b = imageData[offset + 2]; color.PackFromBytes(r, g, b, 255); pixels[x + destination.Left, y + destination.Top] = color; offset += bytesPerPixel; } } } private static void DecodeImageData_Grayscale_8(byte[] imageData, PixelAccessor<Rgb888> pixels, Rectangle destination, bool whiteIsZero) { var offset = 0; for (var y = 0; y < destination.Height; y++) { for (var x = 0; x < destination.Width; x++) { var color = default(Rgb888); var i = whiteIsZero ? (byte)(255 - imageData[offset]) : imageData[offset]; color.PackFromBytes(i, i, i, 255); pixels[x + destination.Left, y + destination.Top] = color; offset++; } } } } }
41.692982
161
0.540501
[ "Apache-2.0" ]
Andy-Wilkinson/CorePhoto
src/CorePhoto/Tiff/TiffImageReader.cs
4,753
C#
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Activities.Debugger { using System; using System.Activities.Expressions; using System.Activities.Hosting; using System.Activities.Runtime; using System.Activities.Statements; using System.Activities.XamlIntegration; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Runtime; [DebuggerNonUserCode] class DebugManager { static StateManager.DynamicModuleManager dynamicModuleManager; WorkflowInstance host; StateManager stateManager; Dictionary<object, State> states; Dictionary<int, Stack<Activity>> runningThreads; InstrumentationTracker instrumentationTracker; List<string> temporaryFiles; public DebugManager(Activity root, string moduleNamePrefix, string typeNamePrefix, string auxiliaryThreadName, bool breakOnStartup, WorkflowInstance host, bool debugStartedAtRoot) : this(root, moduleNamePrefix, typeNamePrefix, auxiliaryThreadName, breakOnStartup, host, debugStartedAtRoot, false) { } internal DebugManager(Activity root, string moduleNamePrefix, string typeNamePrefix, string auxiliaryThreadName, bool breakOnStartup, WorkflowInstance host, bool debugStartedAtRoot, bool resetDynamicModule) { if (resetDynamicModule) { dynamicModuleManager = null; } if (dynamicModuleManager == null) { dynamicModuleManager = new StateManager.DynamicModuleManager(moduleNamePrefix); } this.stateManager = new StateManager( new StateManager.Properties { ModuleNamePrefix = moduleNamePrefix, TypeNamePrefix = typeNamePrefix, AuxiliaryThreadName = auxiliaryThreadName, BreakOnStartup = breakOnStartup }, debugStartedAtRoot, dynamicModuleManager); this.states = new Dictionary<object, State>(); this.runningThreads = new Dictionary<int, Stack<Activity>>(); this.instrumentationTracker = new InstrumentationTracker(root); this.host = host; } // Whether we're priming the background thread (in Attach To Process case). public bool IsPriming { set { this.stateManager.IsPriming = value; } } // Whether debugging is done from the start of the root workflow, // contrast to attaching into the middle of a running workflow. bool DebugStartedAtRoot { get { return this.stateManager.DebugStartedAtRoot; } } internal void Instrument(Activity activity) { bool isTemporaryFile = false; string sourcePath = null; bool instrumentationFailed = false; Dictionary<string, byte[]> checksumCache = null; try { byte[] checksum; Dictionary<object, SourceLocation> sourceLocations = SourceLocationProvider.GetSourceLocations(activity, out sourcePath, out isTemporaryFile, out checksum); if (checksum != null) { checksumCache = new Dictionary<string, byte[]>(); checksumCache.Add(sourcePath.ToUpperInvariant(), checksum); } Instrument(activity, sourceLocations, Path.GetFileNameWithoutExtension(sourcePath), checksumCache); } catch (Exception ex) { instrumentationFailed = true; Trace.WriteLine(SR.DebugInstrumentationFailed(ex.Message)); if (Fx.IsFatal(ex)) { throw; } } List<Activity> sameSourceActivities = this.instrumentationTracker.GetSameSourceSubRoots(activity); this.instrumentationTracker.MarkInstrumented(activity); foreach (Activity sameSourceActivity in sameSourceActivities) { if (!instrumentationFailed) { MapInstrumentationStates(activity, sameSourceActivity); } // Mark it as instrumentated, even though it fails so it won't be // retried. this.instrumentationTracker.MarkInstrumented(sameSourceActivity); } if (isTemporaryFile) { if (this.temporaryFiles == null) { this.temporaryFiles = new List<string>(); } Fx.Assert(!string.IsNullOrEmpty(sourcePath), "SourcePath cannot be null for temporary file"); this.temporaryFiles.Add(sourcePath); } } // Workflow rooted at rootActivity1 and rootActivity2 have same source file, but they // are two different instantiation. // rootActivity1 has been instrumented and its instrumentation states can be // re-used by rootActivity2. // // MapInstrumentationStates will walk both Workflow trees in parallel and map every // state for activities in rootActivity1 to corresponding activities in rootActivity2. void MapInstrumentationStates(Activity rootActivity1, Activity rootActivity2) { Queue<KeyValuePair<Activity, Activity>> pairsRemaining = new Queue<KeyValuePair<Activity, Activity>>(); pairsRemaining.Enqueue(new KeyValuePair<Activity, Activity>(rootActivity1, rootActivity2)); HashSet<Activity> visited = new HashSet<Activity>(); KeyValuePair<Activity, Activity> currentPair; State state; while (pairsRemaining.Count > 0) { currentPair = pairsRemaining.Dequeue(); Activity activity1 = currentPair.Key; Activity activity2 = currentPair.Value; if (this.states.TryGetValue(activity1, out state)) { if (this.states.ContainsKey(activity2)) { Trace.WriteLine("Workflow", SR.DuplicateInstrumentation(activity2.DisplayName)); } else { // Map activity2 to the same state. this.states.Add(activity2, state); } } //Some activities may not have corresponding Xaml node, e.g. ActivityFaultedOutput. visited.Add(activity1); // This to avoid comparing any value expression with DesignTimeValueExpression (in designer case). IEnumerator<Activity> enumerator1 = WorkflowInspectionServices.GetActivities(activity1).GetEnumerator(); IEnumerator<Activity> enumerator2 = WorkflowInspectionServices.GetActivities(activity2).GetEnumerator(); bool hasNextItem1 = enumerator1.MoveNext(); bool hasNextItem2 = enumerator2.MoveNext(); while (hasNextItem1 && hasNextItem2) { if (!visited.Contains(enumerator1.Current)) // avoid adding the same activity (e.g. some default implementation). { if (enumerator1.Current.GetType() != enumerator2.Current.GetType()) { // Give debugger log instead of just asserting; to help user find out mismatch problem. Trace.WriteLine( "Unmatched type: " + enumerator1.Current.GetType().FullName + " vs " + enumerator2.Current.GetType().FullName + "\n"); } pairsRemaining.Enqueue(new KeyValuePair<Activity, Activity>(enumerator1.Current, enumerator2.Current)); } hasNextItem1 = enumerator1.MoveNext(); hasNextItem2 = enumerator2.MoveNext(); } // If enumerators do not finish at the same time, then they have unmatched number of activities. // Give debugger log instead of just asserting; to help user find out mismatch problem. if (hasNextItem1 || hasNextItem2) { Trace.WriteLine("Workflow", "Unmatched number of children\n"); } } } // Main instrumentation. // Currently the typeNamePrefix is used to notify the Designer of which file to show. // This will no longer necessary when the callstack API can give us the source line // information. public void Instrument(Activity rootActivity, Dictionary<object, SourceLocation> sourceLocations, string typeNamePrefix, Dictionary<string, byte[]> checksumCache) { Queue<KeyValuePair<Activity, string>> pairsRemaining = new Queue<KeyValuePair<Activity, string>>(); string name; Activity activity = rootActivity; KeyValuePair<Activity, string> pair = new KeyValuePair<Activity, string>(activity, string.Empty); pairsRemaining.Enqueue(pair); HashSet<string> existingNames = new HashSet<string>(); HashSet<Activity> visited = new HashSet<Activity>(); SourceLocation sourceLocation; while (pairsRemaining.Count > 0) { pair = pairsRemaining.Dequeue(); activity = pair.Key; string parentName = pair.Value; string displayName = activity.DisplayName; // If no DisplayName, then use the type name. if (string.IsNullOrEmpty(displayName)) { displayName = activity.GetType().Name; } if (parentName == string.Empty) { // the root name = displayName; } else { name = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", parentName, displayName); } int i = 0; while (existingNames.Contains(name)) { ++i; name = string.Format(CultureInfo.InvariantCulture, "{0}.{1}{2}", parentName, displayName, i.ToString(CultureInfo.InvariantCulture)); } existingNames.Add(name); visited.Add(activity); if (sourceLocations.TryGetValue(activity, out sourceLocation)) { object[] objects = activity.GetType().GetCustomAttributes(typeof(DebuggerStepThroughAttribute), false); if ((objects == null || objects.Length == 0)) { Instrument(activity, sourceLocation, name); } } foreach (Activity childActivity in WorkflowInspectionServices.GetActivities(activity)) { if (!visited.Contains(childActivity)) { pairsRemaining.Enqueue(new KeyValuePair<Activity, string>(childActivity, name)); } } } this.stateManager.Bake(typeNamePrefix, checksumCache); } // Exiting the DebugManager. // Delete all temporary files public void Exit() { if (this.temporaryFiles != null) { foreach (string temporaryFile in this.temporaryFiles) { // Clean up published source. try { File.Delete(temporaryFile); } catch (IOException) { // ---- IOException silently. } this.temporaryFiles = null; } } this.stateManager.ExitThreads(); // State manager is still keep for the session in SessionStateManager this.stateManager = null; } void Instrument(Activity activity, SourceLocation sourceLocation, string name) { Fx.Assert(activity != null, "activity can't be null"); Fx.Assert(sourceLocation != null, "sourceLocation can't be null"); if (this.states.ContainsKey(activity)) { Trace.WriteLine(SR.DuplicateInstrumentation(activity.DisplayName)); } else { State activityState = this.stateManager.DefineStateWithDebugInfo(sourceLocation, name); this.states.Add(activity, activityState); } } // Test whether activity has been instrumented. // If not, try to instrument it. // It will return true if instrumentation is already done or // instrumentation is succesful. False otherwise. bool EnsureInstrumented(Activity activity) { // This is the most common case, we will find the instrumentation. if (this.states.ContainsKey(activity)) { return true; } // No states correspond to this yet. if (this.instrumentationTracker.IsUninstrumentedSubRoot(activity)) { Instrument(activity); return this.states.ContainsKey(activity); } else { return false; } } // Primitive EnterState void EnterState(int threadId, Activity activity, Dictionary<string, object> locals) { Fx.Assert(activity != null, "activity cannot be null"); this.Push(threadId, activity); State activityState; if (this.states.TryGetValue(activity, out activityState)) { this.stateManager.EnterState(threadId, activityState, locals); } else { Fx.Assert(false, "Uninstrumented activity is disallowed: " + activity.DisplayName); } } public void OnEnterState(ActivityInstance instance) { Fx.Assert(instance != null, "ActivityInstance cannot be null"); Activity activity = instance.Activity; if (this.EnsureInstrumented(activity)) { this.EnterState(GetOrCreateThreadId(activity, instance), activity, GenerateLocals(instance)); } } [SuppressMessage(FxCop.Category.Usage, FxCop.Rule.ReviewUnusedParameters)] public void OnEnterState(Activity expression, ActivityInstance instance, LocationEnvironment environment) { if (this.EnsureInstrumented(expression)) { this.EnterState(GetOrCreateThreadId(expression, instance), expression, GenerateLocals(instance)); } } void LeaveState(Activity activity) { Fx.Assert(activity != null, "Activity cannot be null"); int threadId = GetExecutingThreadId(activity, true); // If debugging was not started from the root, then threadId should not be < 0. Fx.Assert(!this.DebugStartedAtRoot || threadId >= 0, "Leaving from an unknown state"); if (threadId >= 0) { State activityState; if (this.states.TryGetValue(activity, out activityState)) { this.stateManager.LeaveState(threadId, activityState); } else { Fx.Assert(false, "Uninstrumented activity is disallowed: " + activity.DisplayName); } this.Pop(threadId); } } public void OnLeaveState(ActivityInstance activityInstance) { Fx.Assert(activityInstance != null, "ActivityInstance cannot be null"); if (this.EnsureInstrumented(activityInstance.Activity)) { this.LeaveState(activityInstance.Activity); } } static Dictionary<string, object> GenerateLocals(ActivityInstance instance) { Dictionary<string, object> locals = new Dictionary<string, object>(); locals.Add("debugInfo", new DebugInfo(instance)); return locals; } void Push(int threadId, Activity activity) { ((Stack<Activity>)this.runningThreads[threadId]).Push(activity); } void Pop(int threadId) { Stack<Activity> stack = this.runningThreads[threadId]; stack.Pop(); if (stack.Count == 0) { this.stateManager.Exit(threadId); this.runningThreads.Remove(threadId); } } // Given an activity, return the thread id where it is currently // executed (on the top of the callstack). // Boolean "strict" parameter determine whether the activity itself should // be on top of the stack. // Strict checking is needed in the case of "Leave"-ing a state. // Non-strict checking is needed for "Enter"-ing a state, since the direct parent of // the activity may not yet be executed (e.g. the activity is an argument of another activity, // the activity is "enter"-ed even though the direct parent is not yet "enter"-ed. int GetExecutingThreadId(Activity activity, bool strict) { int threadId = -1; foreach (KeyValuePair<int, Stack<Activity>> entry in this.runningThreads) { Stack<Activity> threadStack = entry.Value; if (threadStack.Peek() == activity) { threadId = entry.Key; break; } } if (threadId < 0 && !strict) { foreach (KeyValuePair<int, Stack<Activity>> entry in this.runningThreads) { Stack<Activity> threadStack = entry.Value; Activity topActivity = threadStack.Peek(); if (!IsParallelActivity(topActivity) && IsAncestorOf(threadStack.Peek(), activity)) { threadId = entry.Key; break; } } } return threadId; } static bool IsAncestorOf(Activity ancestorActivity, Activity activity) { Fx.Assert(activity != null, "IsAncestorOf: Cannot pass null as activity"); Fx.Assert(ancestorActivity != null, "IsAncestorOf: Cannot pass null as ancestorActivity"); activity = activity.Parent; while (activity != null && activity != ancestorActivity && !IsParallelActivity(activity)) { activity = activity.Parent; } return (activity == ancestorActivity); } static bool IsParallelActivity(Activity activity) { Fx.Assert(activity != null, "IsParallel: Cannot pass null as activity"); return activity is Parallel || (activity.GetType().IsGenericType && activity.GetType().GetGenericTypeDefinition() == typeof(ParallelForEach<>)); } // Get threads currently executing the parent of the given activity, // if none then create a new one and prep the call stack to current state. int GetOrCreateThreadId(Activity activity, ActivityInstance instance) { int threadId = -1; if (activity.Parent != null && !IsParallelActivity(activity.Parent)) { threadId = GetExecutingThreadId(activity.Parent, false); } if (threadId < 0) { threadId = CreateLogicalThread(activity, instance, false); } return threadId; } // Create logical thread and bring its call stack to reflect call from // the root up to (but not including) the instance. // If the activity is an expression though, then the call stack will also include the instance // (since it is the parent of the expression). int CreateLogicalThread(Activity activity, ActivityInstance instance, bool primeCurrentInstance) { Stack<ActivityInstance> ancestors = null; if (!this.DebugStartedAtRoot) { ancestors = new Stack<ActivityInstance>(); if (activity != instance.Activity || primeCurrentInstance) { // This mean that activity is an expression and // instance is the parent of this expression. Fx.Assert(primeCurrentInstance || (activity is ActivityWithResult), "Expect an ActivityWithResult"); Fx.Assert(primeCurrentInstance || (activity.Parent == instance.Activity), "Argument Expression is not given correct parent instance"); if (primeCurrentInstance || !IsParallelActivity(instance.Activity)) { ancestors.Push(instance); } } ActivityInstance instanceParent = instance.Parent; while (instanceParent != null && !IsParallelActivity(instanceParent.Activity)) { ancestors.Push(instanceParent); instanceParent = instanceParent.Parent; } if (instanceParent != null && IsParallelActivity(instanceParent.Activity)) { // Ensure thread is created for the parent (a Parallel activity). int parentThreadId = GetExecutingThreadId(instanceParent.Activity, false); if (parentThreadId < 0) { parentThreadId = CreateLogicalThread(instanceParent.Activity, instanceParent, true); Fx.Assert(parentThreadId > 0, "Parallel main thread can't be created"); } } } string threadName = "DebuggerThread:"; if (activity.Parent != null) { threadName += activity.Parent.DisplayName; } else // Special case for the root of WorklowService that does not have a parent. { threadName += activity.DisplayName; } int newThreadId = this.stateManager.CreateLogicalThread(threadName); Stack<Activity> newStack = new Stack<Activity>(); this.runningThreads.Add(newThreadId, newStack); if (!this.DebugStartedAtRoot && ancestors != null) { // Need to create callstack to current activity. PrimeCallStack(newThreadId, ancestors); } return newThreadId; } // Prime the call stack to contains all the ancestors of this instance. // Note: the call stack will not include the current instance. void PrimeCallStack(int threadId, Stack<ActivityInstance> ancestors) { Fx.Assert(!this.DebugStartedAtRoot, "Priming should not be called if the debugging is attached from the start of the workflow"); bool currentIsPrimingValue = this.stateManager.IsPriming; this.stateManager.IsPriming = true; while (ancestors.Count > 0) { ActivityInstance currentInstance = ancestors.Pop(); if (EnsureInstrumented(currentInstance.Activity)) { this.EnterState(threadId, currentInstance.Activity, GenerateLocals(currentInstance)); } } this.stateManager.IsPriming = currentIsPrimingValue; } } }
41.974533
172
0.556365
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/cdf/src/NetFx40/System.Activities/System/Activities/Debugger/DebugManager.cs
24,723
C#
using System; using System.Collections; using System.Collections.Generic; using Microsoft.Maui.Graphics; using Microsoft.Maui.Layouts; // This is a temporary namespace until we rename everything and move the legacy layouts namespace Microsoft.Maui.Controls.Layout2 { [ContentProperty(nameof(Children))] public abstract class Layout : View, Microsoft.Maui.ILayout, IEnumerable<IView> { ILayoutManager _layoutManager; ILayoutManager LayoutManager => _layoutManager ??= CreateLayoutManager(); readonly List<IView> _children = new List<IView>(); public IReadOnlyList<IView> Children { get => _children.AsReadOnly(); } public ILayoutHandler LayoutHandler => Handler as ILayoutHandler; protected abstract ILayoutManager CreateLayoutManager(); public IEnumerator<IView> GetEnumerator() => _children.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _children.GetEnumerator(); #pragma warning disable CS0672 // Member overrides obsolete member public override SizeRequest GetSizeRequest(double widthConstraint, double heightConstraint) #pragma warning restore CS0672 // Member overrides obsolete member { var size = (this as IFrameworkElement).Measure(widthConstraint, heightConstraint); return new SizeRequest(size); } protected override Size MeasureOverride(double widthConstraint, double heightConstraint) { var margin = (this as IView)?.Margin ?? Thickness.Zero; // Adjust the constraints to account for the margins widthConstraint -= margin.HorizontalThickness; heightConstraint -= margin.VerticalThickness; var sizeWithoutMargins = LayoutManager.Measure(widthConstraint, heightConstraint); DesiredSize = new Size(sizeWithoutMargins.Width + Margin.HorizontalThickness, sizeWithoutMargins.Height + Margin.VerticalThickness); return DesiredSize; } protected override Size ArrangeOverride(Rectangle bounds) { base.ArrangeOverride(bounds); LayoutManager.ArrangeChildren(Frame); foreach (var child in Children) { child.Handler?.NativeArrange(child.Frame); } return Frame.Size; } protected override void InvalidateMeasureOverride() { base.InvalidateMeasureOverride(); foreach (var child in Children) { child.InvalidateMeasure(); } } public virtual void Add(IView child) { if (child == null) return; _children.Add(child); if (child is Element element) element.Parent = this; InvalidateMeasure(); LayoutHandler?.Add(child); } public virtual void Remove(IView child) { if (child == null) return; _children.Remove(child); if (child is Element element) element.Parent = null; InvalidateMeasure(); LayoutHandler?.Remove(child); } } }
25.735849
93
0.747434
[ "MIT" ]
IgorPRZ/maui
src/Controls/src/Core/Layout/Layout.cs
2,728
C#
using System; using System.Collections.Generic; using System.Linq; namespace ConnectedGraph { internal class Program { private static bool[] visited; private static List<int>[] graph; static void Main(string[] args) { graph = ReadGraph(); CheckIfConnected(); } private static List<int>[] ReadGraph() { int n = int.Parse(Console.ReadLine()); var graph = new List<int>[n + 1]; for (int i = 0; i <= n; i++) { graph[i] = Console.ReadLine() .Split(" ", StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToList(); } return graph; } private static void CheckIfConnected() { visited = new bool[graph.Length]; DFS(0); for (int i = 0; i < visited.Length; i++) { if (!visited[i]) { Console.WriteLine("The graph is not connected."); return; } } Console.WriteLine("The graph is connected."); } private static void DFS(int vertex) { if (!visited[vertex]) { visited[vertex] = true; foreach (var child in graph[vertex]) { DFS(child); } } } } }
23.796875
70
0.428102
[ "MIT" ]
wuweisage/Softuni-Svetlina-Projects-and-Code
C#/DataStructuresAndAlgorithms/Graphs/Graphs-Exercise/ConnectedGraph/Program.cs
1,525
C#
// <auto-generated> using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace KyGunCo.Counterpoint.Sdk.Entities { // USER_ITEM_IMPORT public class UserItemImport { public int ItemNo { get; set; } // ITEM_NO (Primary key) public string Descr { get; set; } // DESCR (length: 30) public string LongDescr { get; set; } // LONG_DESCR (length: 50) public string AddlDescr1 { get; set; } // ADDL_DESCR_1 (length: 80) public string AddlDescr2 { get; set; } // ADDL_DESCR_2 (length: 80) public string ItemTyp { get; set; } // ITEM_TYP (length: 1) public decimal? Prc1 { get; set; } // PRC_1 public decimal? Prc2 { get; set; } // PRC_2 public decimal? Prc3 { get; set; } // PRC_3 public decimal? RegPrc { get; set; } // REG_PRC public string StkUnit { get; set; } // STK_UNIT (length: 15) public decimal? LstCost { get; set; } // LST_COST public string IsTxbl { get; set; } // IS_TXBL (length: 1) public string CategDescr { get; set; } // CATEG_DESCR (length: 30) public string SubcatDescr { get; set; } // SUBCAT_DESCR (length: 30) public string VendorNam { get; set; } // VENDOR_NAM (length: 40) public string VendItemNo { get; set; } // VEND_ITEM_NO (length: 20) public string Alt1Unit { get; set; } // ALT_1_UNIT (length: 15) public decimal? Alt1Numer { get; set; } // ALT_1_NUMER public decimal? Alt1Denom { get; set; } // ALT_1_DENOM public decimal? Alt1Prc1 { get; set; } // ALT_1_PRC_1 public string Alt2Unit { get; set; } // ALT_2_UNIT (length: 15) public decimal? Alt2Numer { get; set; } // ALT_2_NUMER public decimal? Alt2Denom { get; set; } // ALT_2_DENOM public decimal? Alt2Prc1 { get; set; } // ALT_2_PRC_1 public string Alt3Unit { get; set; } // ALT_3_UNIT (length: 15) public decimal? Alt3Numer { get; set; } // ALT_3_NUMER public decimal? Alt3Demon { get; set; } // ALT_3_DEMON public decimal? Alt3Prc1 { get; set; } // ALT_3_PRC_1 public string Barcod1 { get; set; } // BARCOD1 (length: 20) public string Barcod2 { get; set; } // BARCOD2 (length: 20) public string Barcod3 { get; set; } // BARCOD3 (length: 20) public string Dim1Tag { get; set; } // DIM_1_TAG (length: 10) public string Dim2Tag { get; set; } // DIM_2_TAG (length: 10) public string Dim3Tag { get; set; } // DIM_3_TAG (length: 10) public string Dim1 { get; set; } // DIM_1 (length: 15) public string Dim2 { get; set; } // DIM_2 (length: 15) public string Dim3 { get; set; } // DIM_3 (length: 15) public decimal? Weight { get; set; } // WEIGHT public string FreightCharge { get; set; } // FREIGHT_CHARGE (length: 1) public string TrackingMethod { get; set; } // TRACKING_METHOD (length: 1) public string IsWebItem { get; set; } // IS_WEB_ITEM (length: 1) public int StyleId { get; set; } // STYLE_ID public string CaliberGauge { get; set; } // CALIBER_GAUGE (length: 30) public string UserAction { get; set; } // USER_ACTION (length: 30) public string MagCapacity { get; set; } // MAG_CAPACITY (length: 10) public string BarrelLength { get; set; } // BARREL_LENGTH (length: 10) public string IsFirearm { get; set; } // IS_FIREARM (length: 1) public string UserModel { get; set; } // USER_MODEL (length: 30) public string UserImporter { get; set; } // USER_IMPORTER (length: 30) public string UserManufacturer { get; set; } // USER_MANUFACTURER (length: 30) public string UserStateType { get; set; } // USER_STATE_TYPE (length: 30) public string UserAtfType { get; set; } // USER_ATF_TYPE (length: 30) public string Attr1Cod { get; set; } // ATTR_1_COD public string Attr1CodDescr { get; set; } // ATTR_1_COD_DESCR public string Attr2Cod { get; set; } // ATTR_2_COD public string Attr2CodDescr { get; set; } // ATTR_2_COD_DESCR public string Attr3Cod { get; set; } // ATTR_3_COD public string Attr3CodDescr { get; set; } // ATTR_3_COD_DESCR public string Attr4Cod { get; set; } // ATTR_4_COD public string Attr4CodDescr { get; set; } // ATTR_4_COD_DESCR public string CategCod { get; set; } // CATEG_COD (length: 100) public string SubcatCod { get; set; } // SUBCAT_COD (length: 100) public int Id { get; set; } // ID public string ItemVendNo { get; set; } // ITEM_VEND_NO (length: 15) } } // </auto-generated>
57.036585
86
0.619414
[ "MIT" ]
kygunco/KyGunCo.Counterpoint
Source/KyGunCo.Counterpoint.Sdk/Entities/UserItemImport.cs
4,677
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type Credential User Registration Details. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class CredentialUserRegistrationDetails : Entity { ///<summary> /// The CredentialUserRegistrationDetails constructor ///</summary> public CredentialUserRegistrationDetails() { this.ODataType = "microsoft.graph.credentialUserRegistrationDetails"; } /// <summary> /// Gets or sets auth methods. /// Represents the authentication method that the user has registered. Possible values are: email, mobilePhone, officePhone, securityQuestion (only used for self-service password reset), appNotification, appCode, and alternateMobilePhone (supported only in registration). /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "authMethods", Required = Newtonsoft.Json.Required.Default)] public IEnumerable<RegistrationAuthMethod> AuthMethods { get; set; } /// <summary> /// Gets or sets is capable. /// Indicates whether the user is ready to perform self-service password reset or MFA. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "isCapable", Required = Newtonsoft.Json.Required.Default)] public bool? IsCapable { get; set; } /// <summary> /// Gets or sets is enabled. /// Indiciates whether the user enabled to perform self-service password reset. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "isEnabled", Required = Newtonsoft.Json.Required.Default)] public bool? IsEnabled { get; set; } /// <summary> /// Gets or sets is mfa registered. /// Indiciates whether the user is registered for MFA. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "isMfaRegistered", Required = Newtonsoft.Json.Required.Default)] public bool? IsMfaRegistered { get; set; } /// <summary> /// Gets or sets is registered. /// Indicates whether the user has registered any authentication methods for self-service password reset. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "isRegistered", Required = Newtonsoft.Json.Required.Default)] public bool? IsRegistered { get; set; } /// <summary> /// Gets or sets user display name. /// Provides the user name of the corresponding user. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "userDisplayName", Required = Newtonsoft.Json.Required.Default)] public string UserDisplayName { get; set; } /// <summary> /// Gets or sets user principal name. /// Provides the user principal name of the corresponding user. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "userPrincipalName", Required = Newtonsoft.Json.Required.Default)] public string UserPrincipalName { get; set; } } }
46.176471
279
0.645096
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/model/CredentialUserRegistrationDetails.cs
3,925
C#
// Copyright (c) SimpleIdServer. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using Newtonsoft.Json.Linq; using SimpleIdServer.Scim.Builder; using SimpleIdServer.Scim.Domain; using SimpleIdServer.Scim.DTOs; using System.Collections.Generic; using System.Linq; using Xunit; namespace SimpleIdServer.Scim.Tests { public class SCIMRepresentationPatchFixture { [Fact] public void When_Apply_Patch_To_SCIM_Representation() { var userSchema = SCIMSchemaBuilder.Create("urn:ietf:params:scim:schemas:core:2.0:User", "User", "User Account") .AddStringAttribute("userName", caseExact: true, uniqueness: SCIMSchemaAttributeUniqueness.SERVER) .AddComplexAttribute("phones", opt => { opt.AddStringAttribute("phoneNumber", description: "Phone number"); opt.AddStringAttribute("type", description: "Type"); }, multiValued: true, mutability: SCIMSchemaAttributeMutabilities.READWRITE) .Build(); var userRepresentation = SCIMRepresentationBuilder.Create(new List<SCIMSchema> { userSchema }) .AddStringAttribute("userName", "urn:ietf:params:scim:schemas:core:2.0:User", new List<string> { "john" }) .AddComplexAttribute("phones", "urn:ietf:params:scim:schemas:core:2.0:User", (b) => { b.AddStringAttribute("phoneNumber", new List<string> { "01" }); b.AddStringAttribute("type", new List<string> { "mobile" }); }) .AddComplexAttribute("phones", "urn:ietf:params:scim:schemas:core:2.0:User", (b) => { b.AddStringAttribute("phoneNumber", new List<string> { "02" }); b.AddStringAttribute("type", new List<string> { "home" }); }) .Build(); userRepresentation.ApplyPatches(new List<PatchOperationParameter> { new PatchOperationParameter { Operation = SCIMPatchOperations.REPLACE, Path = "userName", Value = "cassandra" }, new PatchOperationParameter { Operation = SCIMPatchOperations.ADD, Path = "phones", Value = JArray.Parse("[{ phoneNumber : '03', type: 'type1' }, { phoneNumber : '05', type: 'type2' }]") }, new PatchOperationParameter { Operation = SCIMPatchOperations.REMOVE, Path = "phones[phoneNumber eq 01]" } }, false); Assert.Equal("cassandra", userRepresentation.Attributes.First(a => a.SchemaAttribute.Name == "userName").ValuesString.First()); Assert.True(userRepresentation.Attributes.Any(a => a.SchemaAttribute.Name == "phones" && a.Values.Any(b => b.SchemaAttribute.Name == "phoneNumber" && b.ValuesString.Contains("03"))) == true); Assert.True(userRepresentation.Attributes.Any(a => a.SchemaAttribute.Name == "phones" && a.Values.Any(b => b.SchemaAttribute.Name == "phoneNumber" && b.ValuesString.Contains("05"))) == true); Assert.True(userRepresentation.Attributes.Any(a => a.SchemaAttribute.Name == "phones" && a.Values.Any(b => b.SchemaAttribute.Name == "phoneNumber" && b.ValuesString.Contains("01"))) == false); } } }
52.676471
204
0.587381
[ "Apache-2.0" ]
gengle/SimpleIdServer
tests/SimpleIdServer.Scim.Tests/SCIMRepresentationPatchFixture.cs
3,584
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.PlayerLoop; public class DamageRegistration : MonoBehaviour { public bool colliding; private CountDown reset = new CountDown(0.5f); void Update() { if (colliding) reset.Start(Reset); } private void Reset() { colliding = false; } private void OnCollisionEnter2D(Collision2D other) { var layer = other.gameObject.layer; colliding = (layer == 8 || layer == 9 || layer == 15 || layer == 16 || layer == 17 || layer == 18); reset.Reset(); } private void OnCollisionStay2D(Collision2D other) { var layer = other.gameObject.layer; colliding = (layer == 19); reset.Reset(); } public void Collide() { colliding = true; reset.Reset(); } }
21.285714
107
0.600671
[ "MIT" ]
TimvHal/Minor-Restless-Shadows-mirror
Assets/Scripts/Player/DamageRegistration.cs
896
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Gcp.Storage.Inputs { public sealed class TransferJobTransferSpecAwsS3DataSourceGetArgs : Pulumi.ResourceArgs { /// <summary> /// AWS credentials block. /// </summary> [Input("awsAccessKey")] public Input<Inputs.TransferJobTransferSpecAwsS3DataSourceAwsAccessKeyGetArgs>? AwsAccessKey { get; set; } /// <summary> /// S3 Bucket name. /// </summary> [Input("bucketName", required: true)] public Input<string> BucketName { get; set; } = null!; /// <summary> /// The Amazon Resource Name (ARN) of the role to support temporary credentials via 'AssumeRoleWithWebIdentity'. For more information about ARNs, see [IAM ARNs](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-arns). When a role ARN is provided, Transfer Service fetches temporary credentials for the session using a 'AssumeRoleWithWebIdentity' call for the provided role using the [GoogleServiceAccount][] for this project. /// </summary> [Input("roleArn")] public Input<string>? RoleArn { get; set; } public TransferJobTransferSpecAwsS3DataSourceGetArgs() { } } }
40.815789
471
0.686654
[ "ECL-2.0", "Apache-2.0" ]
pjbizon/pulumi-gcp
sdk/dotnet/Storage/Inputs/TransferJobTransferSpecAwsS3DataSourceGetArgs.cs
1,551
C#
#pragma warning disable 1591 // ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Mono Runtime Version: 4.0.30319.17020 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ [assembly: Android.Runtime.ResourceDesignerAttribute("OpenGLApplication1.Resource", IsApplication=true)] namespace ${Namespace} { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int Icon = 2130837504; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } public partial class Id { static Id() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Id() { } } public partial class Layout { static Layout() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Layout() { } } public partial class String { // aapt resource value: 0x7f040001 public const int ApplicationName = 2130968577; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } } } #pragma warning restore 1591
18.403846
104
0.591432
[ "MIT" ]
06needhamt/MonoGame
IDE/MonoDevelop/MonoDevelop.MonoGame.Android/templates/Android/Resource.cs
1,914
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110 { using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell; /// <summary>A2A cloud creation input.</summary> [System.ComponentModel.TypeConverter(typeof(A2AContainerCreationInputTypeConverter))] public partial class A2AContainerCreationInput { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.A2AContainerCreationInput" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal A2AContainerCreationInput(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReplicationProviderSpecificContainerCreationInputInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReplicationProviderSpecificContainerCreationInputInternal)this).InstanceType, global::System.Convert.ToString); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.A2AContainerCreationInput" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal A2AContainerCreationInput(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReplicationProviderSpecificContainerCreationInputInternal)this).InstanceType = (string) content.GetValueForProperty("InstanceType",((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IReplicationProviderSpecificContainerCreationInputInternal)this).InstanceType, global::System.Convert.ToString); AfterDeserializePSObject(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.A2AContainerCreationInput" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IA2AContainerCreationInput" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IA2AContainerCreationInput DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new A2AContainerCreationInput(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.A2AContainerCreationInput" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IA2AContainerCreationInput" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IA2AContainerCreationInput DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new A2AContainerCreationInput(content); } /// <summary> /// Creates a new instance of <see cref="A2AContainerCreationInput" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IA2AContainerCreationInput FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// A2A cloud creation input. [System.ComponentModel.TypeConverter(typeof(A2AContainerCreationInputTypeConverter))] public partial interface IA2AContainerCreationInput { } }
63.145038
385
0.692819
[ "MIT" ]
3quanfeng/azure-powershell
src/Migrate/generated/api/Models/Api20180110/A2AContainerCreationInput.PowerShell.cs
8,142
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Le informazioni generali relative a un assembly sono controllate dal seguente // set di attributi. Modificare i valori di questi attributi per modificare le informazioni // associate a un assembly. [assembly: AssemblyTitle("UnitTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnitTest")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili // ai componenti COM. Se è necessario accedere a un tipo in questo assembly da // COM, impostare su true l'attributo ComVisible per tale tipo. [assembly: ComVisible(false)] // Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi [assembly: Guid("5f9785f9-2da8-4987-b163-190c2f941de2")] // Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: // // Versione principale // Versione secondaria // Numero di build // Revisione // // È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build // usando l'asterisco '*' come illustrato di seguito: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
41.405405
127
0.760444
[ "MIT" ]
umbertocilia/MSC_refactoring_interview
UnitTest/UnitTest/Properties/AssemblyInfo.cs
1,538
C#
using Android.Content; using Android.Views; using Android.Widget; using Xamarin.Forms; using Xamarin.Forms.Material.Android; using Xamarin.Forms.Platform.Android; using AView = Android.Views.View; namespace Xamarin.Forms.Material.Android { public class MaterialDatePickerRenderer : DatePickerRendererBase<MaterialPickerTextInputLayout>, ITabStop { MaterialPickerTextInputLayout _textInputLayout; MaterialPickerEditText _textInputEditText; public MaterialDatePickerRenderer(Context context) : base(MaterialContextThemeWrapper.Create(context)) { } protected override AView ControlUsedForAutomation => EditText; protected override EditText EditText => _textInputEditText; protected override MaterialPickerTextInputLayout CreateNativeControl() { LayoutInflater inflater = LayoutInflater.FromContext(Context); var view = inflater.Inflate(Resource.Layout.MaterialPickerTextInput, null); _textInputLayout = (MaterialPickerTextInputLayout)view; _textInputEditText = _textInputLayout.FindViewById<MaterialPickerEditText>(Resource.Id.materialformsedittext); return _textInputLayout; } protected override void OnElementChanged(ElementChangedEventArgs<DatePicker> e) { base.OnElementChanged(e); _textInputLayout.SetHint(string.Empty, Element); UpdateBackgroundColor(); } protected override void UpdateBackgroundColor() => _textInputLayout?.ApplyBackgroundColor(Element.BackgroundColor, Element.TextColor); protected override void UpdateTextColor() => ApplyTheme(); void ApplyTheme() => _textInputLayout?.ApplyTheme(Element.TextColor, Color.Default); AView ITabStop.TabStop => EditText; } }
33.04
113
0.809322
[ "MIT" ]
AlleSchonWeg/Xamarin.Forms
Xamarin.Forms.Material.Android/MaterialDatePickerRenderer.cs
1,652
C#
using System.Collections.Generic; using Godot; using MTW7DRL2021.scenes.components; using MTW7DRL2021.scenes.entities; namespace MTW7DRL2021.scenes { public class EncounterViewportContainer : Godot.ViewportContainer { private Texture moveNCursor = ResourceLoader.Load<Texture>("res://resources/cursors/move_n_24x24.png"); private Texture moveNECursor = ResourceLoader.Load<Texture>("res://resources/cursors/move_ne_24x24.png"); private Texture moveECursor = ResourceLoader.Load<Texture>("res://resources/cursors/move_e_24x24.png"); private Texture moveSECursor = ResourceLoader.Load<Texture>("res://resources/cursors/move_se_24x24.png"); private Texture moveSCursor = ResourceLoader.Load<Texture>("res://resources/cursors/move_s_24x24.png"); private Texture moveSWCursor = ResourceLoader.Load<Texture>("res://resources/cursors/move_sw_24x24.png"); private Texture moveWCursor = ResourceLoader.Load<Texture>("res://resources/cursors/move_w_24x24.png"); private Texture moveNWCursor = ResourceLoader.Load<Texture>("res://resources/cursors/move_nw_24x24.png"); private int CursorWidth { get => this.moveNCursor.GetWidth(); } private int CursorHeight { get => this.moveNCursor.GetHeight(); } [Signal] public delegate void ActionSelected(string actionMapping); [Signal] public delegate void MousedOverPosition(int x, int y); private void ResizeViewport() { var viewport = GetNode<Viewport>("EncounterViewport"); viewport.Size = RectSize; } public override void _Ready() { ResizeViewport(); } public override void _Input(InputEvent @event) { if (@event is InputEventMouseButton eventMouseButton) { Input.SetMouseMode(Input.MouseMode.Visible); // We only want to move on release of left click (think Tangledeep but with mouse) (probably will change this later) // Possibly we can add a hold but that runs the risk of you flying right into the middle of an encounter, since movement // is so insanely fast. if (eventMouseButton.Pressed || eventMouseButton.ButtonIndex != 1) { return; } var viewportRect = this.GetRect(); var position = eventMouseButton.Position; var movementIndicator = GetNode<Sprite>("MovementIndicator"); if (viewportRect.HasPoint(position)) { movementIndicator.Show(); var dx = position.x - (viewportRect.Size.x / 2); var dy = position.y - (viewportRect.Size.y / 2); var unitVectorToMouse = new Vector2(dx + CursorWidth / 2, dy + CursorHeight / 2).Normalized(); var unitYVec = new Vector2(0, -1); var deg = Mathf.Rad2Deg(unitYVec.AngleTo(unitVectorToMouse)); if (deg >= -22.5f && deg <= 22.5f) { EmitSignal(nameof(ActionSelected), InputHandler.ActionMapping.MOVE_N); } else if (deg >= 22.5f && deg <= 67.5f) { EmitSignal(nameof(ActionSelected), InputHandler.ActionMapping.MOVE_NE); } else if (deg >= 67.5f && deg <= 112.5f) { EmitSignal(nameof(ActionSelected), InputHandler.ActionMapping.MOVE_E); } else if (deg >= 112.5f && deg <= 157.5f) { EmitSignal(nameof(ActionSelected), InputHandler.ActionMapping.MOVE_SE); } else if (deg >= 157.5f || deg <= -157.5f) { EmitSignal(nameof(ActionSelected), InputHandler.ActionMapping.MOVE_S); } else if (deg >= -157.5f && deg <= -112.5f) { EmitSignal(nameof(ActionSelected), InputHandler.ActionMapping.MOVE_SW); } else if (deg >= -112.5f && deg <= -67.5f) { EmitSignal(nameof(ActionSelected), InputHandler.ActionMapping.MOVE_W); } else if (deg >= -67.5f && deg <= -22.5f) { EmitSignal(nameof(ActionSelected), InputHandler.ActionMapping.MOVE_NW); } } else { movementIndicator.Hide(); } } else if (@event is InputEventMouseMotion eventMouseMotion) { Input.SetMouseMode(Input.MouseMode.Visible); var viewportRect = this.GetRect(); var position = eventMouseMotion.Position; var movementIndicator = GetNode<Sprite>("MovementIndicator"); if (viewportRect.HasPoint(position)) { movementIndicator.Show(); var player = GetTree().GetNodesInGroup(PlayerComponent.ENTITY_GROUP)[0] as Entity; var spritePos = player.GetComponent<PositionComponent>().GetNode<Sprite>("Sprite").Position; var dx = position.x - (viewportRect.Size.x / 2); var dy = position.y - (viewportRect.Size.y / 2); // Determine which octant the player's mouse moved over and set the cursor appropriately var unitVectorToMouse = new Vector2(dx + CursorWidth / 2, dy + CursorHeight / 2).Normalized(); var unitYVec = new Vector2(0, -1); var deg = Mathf.Rad2Deg(unitYVec.AngleTo(unitVectorToMouse)); if (deg >= -22.5f && deg <= 22.5f) { movementIndicator.Texture = moveNCursor; movementIndicator.Position = new Vector2(viewportRect.Size.x / 2, viewportRect.Size.y / 2 - 28); } else if (deg >= 22.5f && deg <= 67.5f) { movementIndicator.Texture = moveNECursor; movementIndicator.Position = new Vector2(viewportRect.Size.x / 2 + 28, viewportRect.Size.y / 2 - 28); } else if (deg >= 67.5f && deg <= 112.5f) { movementIndicator.Texture = moveECursor; movementIndicator.Position = new Vector2(viewportRect.Size.x / 2 + 28, viewportRect.Size.y / 2); } else if (deg >= 112.5f && deg <= 157.5f) { movementIndicator.Texture = moveSECursor; movementIndicator.Position = new Vector2(viewportRect.Size.x / 2 + 28, viewportRect.Size.y / 2 + 28); } else if (deg >= 157.5f || deg <= -157.5f) { movementIndicator.Texture = moveSCursor; movementIndicator.Position = new Vector2(viewportRect.Size.x / 2, viewportRect.Size.y / 2 + 28); } else if (deg >= -157.5f && deg <= -112.5f) { movementIndicator.Texture = moveSWCursor; movementIndicator.Position = new Vector2(viewportRect.Size.x / 2 - 28, viewportRect.Size.y / 2 + 28); } else if (deg >= -112.5f && deg <= -67.5f) { movementIndicator.Texture = moveWCursor; movementIndicator.Position = new Vector2(viewportRect.Size.x / 2 - 28, viewportRect.Size.y / 2); } else if (deg >= -67.5f && deg <= -22.5f) { movementIndicator.Texture = moveNWCursor; movementIndicator.Position = new Vector2(viewportRect.Size.x / 2 - 28, viewportRect.Size.y / 2 - 28); } var selectedPosition = PositionComponent.VectorToIndex(dx + spritePos.x, dy + spritePos.y); EmitSignal(nameof(MousedOverPosition), selectedPosition.X, selectedPosition.Y); } else { movementIndicator.Hide(); } } else if (@event is InputEventKey) { GetNode<Sprite>("MovementIndicator").Hide(); } } private void OnEncounterViewportContainerResized() { ResizeViewport(); } } }
52.851852
128
0.647652
[ "MIT" ]
MoyTW/7DRL2021
scenes/EncounterViewportContainer.cs
7,135
C#
using LogParsers.Base.Parsers; using System.Collections.Generic; namespace LogParsers.Base { public interface IParserFactory { /// <summary> /// Create an instance of the correct parser type for a given log file. /// </summary> /// <param name="fileName">The logfile to be parsed.</param> /// <returns>Parser that can parse the log.</returns> IParser GetParser(string fileName); /// <summary> /// Create an instance of the correct parser type for a given log file. /// </summary> /// <param name="fileContext">Context object for the logfile to be parsed.</param> /// <returns>Parser that can parse the log.</returns> IParser GetParser(LogFileContext fileContext); /// <summary> /// Get a set of all parsers from this ParserFactory /// </summary> /// <returns>Set of all parsers from this factory</returns> ISet<IParser> GetAllParsers(); /// <summary> /// Determines whether a given log file is supported as a parsable file type. /// </summary> /// <param name="fileName">The absolute filepath/name of the log file.</param> /// <returns>True if the file is parsable.</returns> bool IsSupported(string fileName); } }
37.542857
90
0.61796
[ "MIT" ]
bermetj/Logshark
LogParsers.Base/IParserFactory.cs
1,314
C#
using Dfc.DiscoverSkillsAndCareers.AssessmentFunctionApp.Services; using Dfc.DiscoverSkillsAndCareers.Models; using System; using System.Collections.Generic; using Xunit; using System.Linq; using Dfc.DiscoverSkillsAndCareers.Repositories; using Microsoft.Extensions.Logging; using NSubstitute; using System.Threading.Tasks; namespace Dfc.UnitTests { public class AssessmentCalculationServiceTests { private static List<Trait> Traits; private static List<JobCategory> JobFamilies; private static List<QuestionSet> QuestionSets; private static Dictionary<AnswerOption, int> AnswerOptions; private IJobCategoryRepository _jobCategoryRepository; private IShortTraitRepository _shortTraitRepository; private IQuestionSetRepository _questionSetRepository; private ILogger _logger; private AssessmentCalculationService _sut; private IQuestionRepository _questionRepository; public AssessmentCalculationServiceTests() { _jobCategoryRepository = Substitute.For<IJobCategoryRepository>(); _shortTraitRepository = Substitute.For<IShortTraitRepository>(); _questionRepository = Substitute.For<IQuestionRepository>(); _questionSetRepository = Substitute.For<IQuestionSetRepository>(); _logger = Substitute.For<ILogger>(); _sut = new AssessmentCalculationService( _jobCategoryRepository, _shortTraitRepository, _questionRepository, _questionSetRepository); Traits = new List<Trait>() { new Trait() { TraitCode = "LEADER", TraitName = "Leader", Texts = new [] { new TraitText() { LanguageCode = "en", Text = "You like to lead other people and are good at taking control of situations." } } }, new Trait() { TraitCode = "DRIVER", TraitName = "Driver", Texts = new [] { new TraitText() { LanguageCode = "en", Text = "You enjoy setting targets and are comfortable competing with other people." } } }, new Trait() { TraitCode = "DOER", TraitName = "Doer", Texts = new [] { new TraitText() { LanguageCode = "en", Text = "You’re a practical person and enjoy working with your hands." } } }, new Trait() { TraitCode = "ORGANISER", TraitName = "Organiser", Texts = new [] { new TraitText() { LanguageCode = "en", Text = "You like to plan things and are well organised." } } }, new Trait() { TraitCode = "HELPER", TraitName = "Helper", Texts = new [] { new TraitText() { LanguageCode = "en", Text = "You enjoy helping and listening to other people." } } }, new Trait() { TraitCode = "ANALYST", TraitName = "Analyst", Texts = new [] { new TraitText() { LanguageCode = "en", Text = "You like dealing with complicated problems or working with numbers." } } }, new Trait() { TraitCode = "CREATOR", TraitName = "Creator", Texts = new [] { new TraitText() { LanguageCode = "en", Text = "You’re a creative person and enjoy coming up with new ways of doing things." } } }, new Trait() { TraitCode = "INFLUENCER", TraitName = "Influencer", Texts = new [] { new TraitText() { LanguageCode = "en", Text = "You are sociable and find it easy to understand people." } } } }; JobFamilies = new List<JobCategory>() { new JobCategory() { Name = "Managerial", Traits = new [] { "LEADER", "DRIVER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do managerial jobs, you might need leadership skills, the ability to motivate and manage staff, and the ability to monitor your own performance and that of your colleagues.", Url = "https://nationalcareers.service.gov.uk/job-categories/managerial" } } }, new JobCategory() { Name = "Beauty and wellbeing", Traits = new []{ "DRIVER", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do beauty and wellbeing jobs, you might need customer service skills, sensitivity and understanding, or the ability to work well with your hands.", Url = "https://nationalcareers.service.gov.uk/job-categories/beauty-and-wellbeing" } } }, new JobCategory() { Name = "Science and research", Traits = new [] { "DRIVER", "ANALYST", "ORGANISER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do science and research jobs, you might need the ability to operate and control equipment, or to be thorough and pay attention to detail, or observation and recording skills.", Url = "https://nationalcareers.service.gov.uk/job-categories/science-and-research" } } }, new JobCategory() { Name = "Manufacturing", Traits = new [] { "DRIVER", "ANALYST", "ORGANISER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do manufacturing jobs, you might need to be thorough and pay attention to detail, physical skills like movement, coordination, dexterity and grace, or the ability to work well with your hands.", Url = "https://nationalcareers.service.gov.uk/job-categories/manufacturing" } } }, new JobCategory() { Name = "Teaching and education", Traits = new [] { "LEADER", "HELPER", "ORGANISER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do teaching and education jobs, you might need counselling skills including active listening and a non-judgemental approach, knowledge of teaching and the ability to design courses, or sensitivity and understanding.", Url = "https://nationalcareers.service.gov.uk/job-categories/teaching-and-education" } } }, new JobCategory() { Name = "Business and finance", Traits = new [] { "DRIVER", "ORGANISER", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do business and finance jobs, you might need to be thorough and pay attention to detail, administration skills, or maths knowledge.", Url = "https://nationalcareers.service.gov.uk/job-categories/business-and-finance" } } }, new JobCategory() { Name = "Law and legal", Traits = new [] { "DRIVER", "ORGANISER", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do law and legal jobs, you might need persuading and negotiating skills, active listening skills the ability to accept criticism and work well under pressure, or to be thorough and pay attention to detail.", Url = "https://nationalcareers.service.gov.uk/job-categories/law-and-legal" } } }, new JobCategory() { Name = "Computing, technology and digital", Traits = new [] { "ANALYST", "CREATOR" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do computing, technology and digital jobs, you might need analytical thinking skills, the ability to come up with new ways of doing things, or a thorough understanding of computer systems and applications.", Url = "https://nationalcareers.service.gov.uk/job-categories/computing-technology-and-digital" } } }, new JobCategory() { Name = "Social care", Traits = new [] { "HELPER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do social care jobs, you might need sensitivity and understanding patience and the ability to remain calm in stressful situations, the ability to work well with others, or excellent verbal communication skills.", Url = "https://nationalcareers.service.gov.uk/job-categories/social-care" } } }, new JobCategory() { Name = "Healthcare", Traits = new [] { "HELPER", "ANALYST", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do healthcare jobs, you might need sensitivity and understanding, the ability to work well with others, or excellent verbal communication skills.", Url = "https://nationalcareers.service.gov.uk/job-categories/healthcare" } } }, new JobCategory() { Name = "Animal care", Traits = new [] { "HELPER", "ANALYST", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do animal care jobs, you might need the ability to use your initiative, patience and the ability to remain calm in stressful situations, or the ability to accept criticism and work well under pressure.", Url = "https://nationalcareers.service.gov.uk/job-categories/animal-care" } } }, new JobCategory() { Name = "Emergency and uniform services", Traits = new [] { "LEADER", "HELPER", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do emergency and uniform service jobs, you might need knowledge of public safety and security, the ability to accept criticism and work well under pressure, or patience and the ability to remain calm in stressful situations.", Url = "https://nationalcareers.service.gov.uk/job-categories/emergency-and-uniform-services" } } }, new JobCategory() { Name = "Sports and leisure", Traits = new [] { "DRIVER", "CREATOR" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do sports and leisure jobs, you might need the ability to work well with others, to enjoy working with other people, or knowledge of teaching and the ability to design courses.", Url = "https://nationalcareers.service.gov.uk/job-categories/sports-and-leisure" } } }, new JobCategory() { Name = "Travel and tourism", Traits = new [] { "HELPER", "ORGANISER", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do travel and tourism jobs, you might need excellent verbal communication skills, the ability to sell products and services, or active listening skills.", Url = "https://nationalcareers.service.gov.uk/job-categories/travel-and-tourism" } } }, new JobCategory() { Name = "Administration", Traits = new [] { "ANALYST", "ORGANISER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do administration jobs, you might need administration skills, the ability to work well with others, or customer service skills.", Url = "https://nationalcareers.service.gov.uk/job-categories/administration" } } }, new JobCategory() { Name = "Government services", Traits = new [] { "ORGANISER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do government services jobs, you might need the ability to accept criticism and work well under pressure, to be thorough and pay attention to detail, and customer service skills.", Url = "https://nationalcareers.service.gov.uk/job-categories/government-services" } } }, new JobCategory() { Name = "Home services", Traits = new [] { "ORGANISER", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do home services jobs, you might need customer service skills, business management skills, or administration skills, or the ability to accept criticism and work well under pressure.", Url = "https://nationalcareers.service.gov.uk/job-categories/home-services" } } }, new JobCategory() { Name = "Environment and land", Traits = new [] { "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do environment and land jobs, you might need thinking and reasoning skills, to be thorough and pay attention to detail, or analytical thinking skills.", Url = "https://nationalcareers.service.gov.uk/job-categories/environment-and-land" } } }, new JobCategory() { Name = "Construction and trades", Traits = new [] { "ANALYST", "CREATOR", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do construction and trades jobs, you might need knowledge of building and construction, patience and the ability to remain calm in stressful situations, and the ability to work well with your hands.", Url = "https://nationalcareers.service.gov.uk/job-categories/construction-and-trades" } } }, new JobCategory() { Name = "Creative and media", Traits = new [] { "ANALYST", "CREATOR", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do creative and media jobs, you might need the ability to come up with new ways of doing things, the ability to use your initiative, or the ability to organise your time and workload.", Url = "https://nationalcareers.service.gov.uk/job-categories/creative-and-media" } } }, new JobCategory() { Name = "Retail and sales", Traits = new [] { "INFLUENCER", "HELPER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do retail and sales jobs, you might need customer service skills, the ability to work well with others, or the ability to sell products and services.", Url = "https://nationalcareers.service.gov.uk/job-categories/retail-and-sales" } } }, new JobCategory() { Name = "Hospitality and food", Traits = new [] { "INFLUENCER", "HELPER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do hospitality and food jobs, you might need customer service skills, the ability to sell products and services, or to enjoy working with other people.", Url = "https://nationalcareers.service.gov.uk/job-categories/hospitality-and-food" } } }, new JobCategory() { Name = "Engineering and maintenance", Traits = new [] { "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do engineering and maintenance jobs, you might need knowledge of engineering science and technology, to be thorough and pay attention to detail, or analytical thinking skills.", Url = "https://nationalcareers.service.gov.uk/job-categories/engineering-and-maintenance" } } }, new JobCategory() { Name = "Transport", Traits = new [] { "ORGANISER", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do transport jobs, you might need customer service skills, knowledge of public safety and security, or the ability to operate and control equipment.", Url = "https://nationalcareers.service.gov.uk/job-categories/transport" } } }, new JobCategory() { Name = "Delivery and storage", Traits = new [] { "ORGANISER", "DOER" }, Texts = new [] { new JobCategoryText() { LanguageCode = "en", Text = "To do delivery and storage jobs, you might need the ability to work well with others, customer service skills, or knowledge of transport methods, costs and benefits.", Url = "https://nationalcareers.service.gov.uk/job-categories/delivery-and-storage" } } }, }; AnswerOptions = new Dictionary<AnswerOption, int>() { { AnswerOption.StronglyDisagree, -2 }, { AnswerOption.Disagree, -1 }, { AnswerOption.Neutral, 0 }, { AnswerOption.Agree, 1 }, { AnswerOption.StronglyAgree, 2 }, }; QuestionSets = JobFamilies .Select(jf => new QuestionSet { Title = jf.Name, MaxQuestions = 3, QuestionSetKey = jf.Name.Replace(" ", "-").ToLower(), }) .ToList(); _questionSetRepository.GetCurrentFilteredQuestionSets().Returns(Task.FromResult( JobFamilies.Select(jf => new QuestionSet { Title = jf.Name, QuestionSetKey = jf.Name.Replace(" ", "-").ToLower(), MaxQuestions = 3 }).ToList())); } [Fact] public async Task CalculateAssessment_ShouldThrow_ExceptionOnNoJobFamilies() { _jobCategoryRepository.GetJobCategories().Returns(Task.FromResult(new JobCategory[] {})); await Assert.ThrowsAsync<Exception>(() => _sut.CalculateAssessment(new UserSession(), _logger)); } [Fact] public async Task CalculateAssessment_ShouldThrow_ExceptionOnNoTraits() { _jobCategoryRepository.GetJobCategories().Returns(Task.FromResult(new [] { new JobCategory(), })); _shortTraitRepository.GetTraits().Returns(Task.FromResult(new Trait[] {})); await Assert.ThrowsAsync<Exception>(() => _sut.CalculateAssessment(new UserSession(), _logger)); } [Fact] public async Task CalculateAssessment_ShouldThrow_ExceptionOnNoQuestions() { _jobCategoryRepository.GetJobCategories().Returns(Task.FromResult(new [] { new JobCategory(), })); _shortTraitRepository.GetTraits().Returns(Task.FromResult(new[] { new Trait(), })); _questionSetRepository.GetCurrentQuestionSet("filtered").Returns(Task.FromResult(new QuestionSet { QuestionSetVersion = "qs-1" })); _questionRepository.GetQuestions("qs-1").Returns(Task.FromResult(new Question[] {})); await Assert.ThrowsAsync<Exception>(() => _sut.CalculateAssessment(new UserSession(), _logger)); } [Fact] public async Task CalculateAssessment_ShouldThrow_ExceptionOnNoUserSessionAssessmentState() { _jobCategoryRepository.GetJobCategories().Returns(Task.FromResult(new [] { new JobCategory(), })); _shortTraitRepository.GetTraits().Returns(Task.FromResult(new[] { new Trait(), })); _questionSetRepository.GetCurrentQuestionSet("filtered").Returns(Task.FromResult(new QuestionSet { QuestionSetVersion = "qs-1" })); _questionRepository.GetQuestions("qs-1").Returns(Task.FromResult(new[] { new Question(), })); await Assert.ThrowsAsync<Exception>(() => _sut.CalculateAssessment(new UserSession(), _logger)); } [Fact] public void PrepareFilterAssessmentState_ShouldAdd_CorrectCategories() { var questions = new [] { new Question {TraitCode = "A", Order = 1}, new Question {TraitCode = "B", Order = 1}, }; var categories = new[] { new JobCategory { Name = "Animal Care", Skills = new List<JobProfileSkillMapping> { new JobProfileSkillMapping {ONetAttribute = "A"} } }, }; var session = new UserSession { ResultData = new ResultData { JobCategories = new[] { new JobCategoryResult {JobCategoryName = "Animal Care"}, } } }; _sut.PrepareFilterAssessmentState("QS-1", session, categories, questions); Assert.Contains(session.FilteredAssessmentState.JobCategoryStates, a => a.JobCategoryCode == "AC"); } [Fact] public void RunShortAssessment_WithAllNeutral_SHouldHaveNoTraits() { var userSession = new UserSession() { LanguageCode = "en", AssessmentState = new AssessmentState("qs-1",8) { RecordedAnswers = new [] { new Answer() { TraitCode = "LEADER", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "DRIVER", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "HELPER", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "ANALYST", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "CREATOR", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "ORGANISER", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "DOER", SelectedOption = AnswerOption.Neutral } } } }; _sut.RunShortAssessment(userSession, JobFamilies, AnswerOptions, Traits); var traits = userSession.ResultData.Traits.ToList(); Assert.Empty(traits); } [Fact] public void RunShortAssessment_WithDoer_SHouldHaveDoerTrait() { var userSession = new UserSession() { LanguageCode = "en", AssessmentState = new AssessmentState("qs-1",8) { RecordedAnswers = new[] { new Answer() { TraitCode = "LEADER", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "DRIVER", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "HELPER", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "ANALYST", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "CREATOR", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "ORGANISER", SelectedOption = AnswerOption.Neutral }, new Answer() { TraitCode = "DOER", SelectedOption = AnswerOption.Agree } } } }; _sut.RunShortAssessment(userSession, JobFamilies, AnswerOptions, Traits); var traits = userSession.ResultData.Traits.ToList(); Assert.Single(traits); } [Fact] public void RunShortAssessment_WithAllAgree_ShouldHaveAllTraits() { var userSession = new UserSession() { LanguageCode = "en", AssessmentState = new AssessmentState("qs-1",8) { RecordedAnswers = new[] { new Answer() { TraitCode = "LEADER", SelectedOption = AnswerOption.Agree }, new Answer() { TraitCode = "DRIVER", SelectedOption = AnswerOption.Agree }, new Answer() { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.Agree }, new Answer() { TraitCode = "HELPER", SelectedOption = AnswerOption.Agree }, new Answer() { TraitCode = "ANALYST", SelectedOption = AnswerOption.Agree }, new Answer() { TraitCode = "CREATOR", SelectedOption = AnswerOption.Agree }, new Answer() { TraitCode = "ORGANISER", SelectedOption = AnswerOption.Agree }, new Answer() { TraitCode = "DOER", SelectedOption = AnswerOption.Agree } } } }; _sut.RunShortAssessment(userSession, JobFamilies, AnswerOptions, Traits); var traits = userSession.ResultData.Traits.ToList(); Assert.Equal(8, traits.Count); } [Fact] public void RunShortAssessment_WithAllDisagree_ShouldHaveNoTraits() { var userSession = new UserSession() { LanguageCode = "en", AssessmentState = new AssessmentState("qs-1",8) { RecordedAnswers = new[] { new Answer() { TraitCode = "LEADER", SelectedOption = AnswerOption.Disagree }, new Answer() { TraitCode = "DRIVER", SelectedOption = AnswerOption.Disagree }, new Answer() { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.Disagree }, new Answer() { TraitCode = "HELPER", SelectedOption = AnswerOption.Disagree }, new Answer() { TraitCode = "ANALYST", SelectedOption = AnswerOption.Disagree }, new Answer() { TraitCode = "CREATOR", SelectedOption = AnswerOption.Disagree }, new Answer() { TraitCode = "ORGANISER", SelectedOption = AnswerOption.Disagree }, new Answer() { TraitCode = "DOER", SelectedOption = AnswerOption.Disagree } } } }; _sut.RunShortAssessment(userSession, JobFamilies, AnswerOptions, Traits); var traits = userSession.ResultData.Traits.ToList(); Assert.Empty(traits); } [Fact] public void RunShortAssessment_WithAllStronglyDisagree_ShouldHaveNoTraits() { var userSession = new UserSession() { LanguageCode = "en", AssessmentState = new AssessmentState("qs-1",8) { RecordedAnswers = new[] { new Answer() { TraitCode = "LEADER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "DRIVER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "HELPER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "ANALYST", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "CREATOR", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "ORGANISER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyDisagree } } } }; _sut.RunShortAssessment(userSession, JobFamilies, AnswerOptions, Traits); var traits = userSession.ResultData.Traits.ToList(); Assert.Empty(traits); } [Fact] public void RunShortAssessment_WithAllStronglyDisagreeWithDoerNegative_ShouldHaveNoTraits() { var userSession = new UserSession() { LanguageCode = "en", AssessmentState = new AssessmentState("qs-1",12) { RecordedAnswers = new[] { new Answer() { TraitCode = "LEADER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "DRIVER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "HELPER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "ANALYST", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "CREATOR", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "ORGANISER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyDisagree }, new Answer() { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = true }, } } }; _sut.RunShortAssessment(userSession, JobFamilies, AnswerOptions, Traits); var traits = userSession.ResultData.Traits.ToList(); Assert.Empty(traits); var doerScore = userSession.ResultData.TraitScores.Where(x => x.TraitCode == "DOER").Sum(x => x.TotalScore); Assert.Equal(-6, doerScore); } [Fact] public void RunShortAssessment_UMB337_DiametricallyOpposedAnswers_StronglyAgreeToStronglyDisagree_ShouldEqualZero() { var session = new UserSession() { LanguageCode = "en", AssessmentState = new AssessmentState("qs-1",40) { RecordedAnswers = new [] { new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.Agree, IsNegative = true}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = true}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = true}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = true}, } } }; _sut.RunShortAssessment(session, JobFamilies, AnswerOptions, Traits); int? getTraitScore(string trait) { return session.ResultData.TraitScores.SingleOrDefault(t => t.TraitCode == trait)?.TotalScore; } Assert.Equal(0, getTraitScore("LEADER")); Assert.Equal(0, getTraitScore("DRIVER")); Assert.Equal(0, getTraitScore("INFLUENCER")); Assert.Equal(0, getTraitScore("HELPER")); Assert.Equal(0, getTraitScore("ANALYST")); Assert.Equal(0, getTraitScore("CREATOR")); Assert.Equal(0, getTraitScore("ORGANISER")); Assert.Equal(0, getTraitScore("DOER")); } [Fact] public void RunShortAssessment_UMB337_DiametricallyOpposedAnswers_StronglyDisagreeToStronglyAgree_ShouldEqualZero() { var session = new UserSession() { LanguageCode = "en", AssessmentState = new AssessmentState("qs-1",40) { RecordedAnswers = new [] { new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.Disagree, IsNegative = true}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = true}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = true}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.Disagree, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.Neutral, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.Agree, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = true}, } } }; _sut.RunShortAssessment(session, JobFamilies, AnswerOptions, Traits); int? getTraitScore(string trait) { return session.ResultData.TraitScores.SingleOrDefault(t => t.TraitCode == trait)?.TotalScore; } Assert.Equal(0, getTraitScore("LEADER")); Assert.Equal(0, getTraitScore("DRIVER")); Assert.Equal(0, getTraitScore("INFLUENCER")); Assert.Equal(0, getTraitScore("HELPER")); Assert.Equal(0, getTraitScore("ANALYST")); Assert.Equal(0, getTraitScore("CREATOR")); Assert.Equal(0, getTraitScore("ORGANISER")); Assert.Equal(0, getTraitScore("DOER")); } [Fact] public void RunShortAssessment_UMB335_MissingOrganiserTrait() { var session = new UserSession() { LanguageCode = "en", AssessmentState = new AssessmentState("qs-1",40) { RecordedAnswers = new [] { new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = true}, new Answer { TraitCode = "LEADER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "DRIVER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "INFLUENCER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = true}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "HELPER", SelectedOption = AnswerOption.StronglyDisagree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ANALYST", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "CREATOR", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "ORGANISER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = true}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = false}, new Answer { TraitCode = "DOER", SelectedOption = AnswerOption.StronglyAgree, IsNegative = true}, } } }; _sut.RunShortAssessment(session, JobFamilies, AnswerOptions, Traits); IDictionary<string, TraitResult> traitLookup = session.ResultData.Traits.ToDictionary(r => r.TraitCode, r => r); Assert.Contains("DOER", traitLookup); Assert.Contains("ORGANISER", traitLookup); Assert.Contains("CREATOR", traitLookup); Assert.Contains("ANALYST", traitLookup); Assert.Equal(4, session.ResultData.Traits.Length); } } }
57.987234
265
0.521281
[ "MIT" ]
Muthuramana/dfc-discoverskillsandcareers
src/Dfc.DiscoverSkillsAndCareers.UnitTests/AssessmentCalculationServiceTests.cs
54,514
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Konsole { public interface IWrite { /// <summary> /// writes out to the console using the requested color, resetting the color back to the console afterwards. /// </summary> void WriteLine(ConsoleColor color, string format, params object[] args); void WriteLine(string format, params object[] args); /// <summary> /// writes out to the console using the requested color, resetting the color back to the console afterwards. /// </summary> void Write(ConsoleColor color, string format, params object[] args); void Write(string format, params object[] args); } }
33.913043
116
0.669231
[ "Apache-2.0" ]
avsnarayan/progress-bar
Goblinfactory.ProgressBar/Konsole/IWrite.cs
782
C#
using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; namespace Matr.Utilities.Test.Attributes.UnitTests { [TestClass] public class JsonTestMethodAttributeTests { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureCelsius { get; set; } #if NETFRAMEWORK || NETSTANDARD2_0 || NETSTANDARD2_1 public string Summary { get; set; } #else public string? Summary { get; set; } #endif } [JsonTestMethod("data.json", typeof(WeatherForecast))] public void Test(WeatherForecast forecast) { forecast.Should().NotBeNull(); } [TestMethod] public void JsonTestMethod_RandomStringAsFile_ShouldThrow() { Action act = () => _ = new JsonTestMethodAttribute($"{Guid.NewGuid()}", typeof(WeatherForecast)); act.Should().Throw<FileNotFoundException>(); } } }
28.971429
109
0.630178
[ "MIT" ]
MatrTech/MatrTech.TestUtilities
tests/Utilities.Test.MSTest.UnitTests/JsonTestMethodAttributeTests.cs
1,014
C#
/* Program : WSPBuilderCustomActions * Created by: Tom Clarkson * Date : 2007 * * The WSPBuilder comes under GNU GENERAL PUBLIC LICENSE (GPL). * * Modified by Carsten Keutmann * Date : 2009 */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using WSPTools.BaseLibrary.VisualStudio; namespace WSPBuilderTemplates { public partial class FeatureSettingsForm : Form { private Dictionary<string, string> _replacements = new Dictionary<string, string>(); /// <summary> /// /// </summary> public Dictionary<string, string> Replacements { get { return _replacements; } set { _replacements = value; } } public FeatureSettingsForm(Dictionary<string, string> replacements) { InitializeComponent(); this.Replacements = replacements; } private void btnOK_Click(object sender, EventArgs e) { // Validate the Name! //string projectPath = this.Replacements[ItemPropertyValues.FullPath]; //ProjectPaths paths = new ProjectPaths(projectPath); //string featureXmlPath = paths.PathFeatures + this.FeatureTitle+ @"\Feature.xml"; //if (File.Exists(featureXmlPath)) //{ // MessageBox.Show("The feature " + this.FeatureTitle + " already exist. Please specify an other name.", "Feature already exist", MessageBoxButtons.OK, MessageBoxIcon.Error); //} //else //{ // this.Close(); //} this.Close(); } public string FeatureTitle { get { return txtTitle.Text; } set { txtTitle.Text = value; } } public string FeatureDesc { get { return txtDesc.Text; } set { txtDesc.Text = value; } } public string FeatureScope { get { return cbScope.Text as string; } set { cbScope.Text = value; } } } }
27.64557
189
0.580128
[ "MIT" ]
keutmann/wspbuilder
WSPTools/App/WSPBuilderTemplates/Framework/Forms/FeatureSettingsForm.cs
2,184
C#
namespace Gift4U.BlazorApp.Data { public enum RequestStateEnum { Pending, RequestApproved, RequestDenied, RequestStarted, Completed } }
16.166667
32
0.57732
[ "MIT" ]
Gukaratsa/Gift4U
Gift4U.BlazorApp/Data/RequestStateEnum.cs
196
C#
// ------------------------------------------------------------------------------ // <copyright file="Campaign.cs" company="Drake53"> // Licensed under the MIT license. // See the LICENSE file in the project root for more information. // </copyright> // ------------------------------------------------------------------------------ using System; using System.IO; using War3Net.Build.Extensions; using War3Net.Build.Import; using War3Net.Build.Info; using War3Net.Build.Object; using War3Net.Build.Script; using War3Net.IO.Mpq; namespace War3Net.Build { public sealed class Campaign { /// <summary> /// Initializes a new instance of the <see cref="Campaign"/> class. /// </summary> public Campaign() { } /// <summary> /// Initializes a new instance of the <see cref="Campaign"/> class. /// </summary> /// <param name="campaignInfo"></param> [Obsolete] public Campaign(CampaignInfo? campaignInfo) { Info = campaignInfo; } private Campaign(string campaignFolder, CampaignFiles campaignFiles) { if (campaignFiles.HasFlag(CampaignFiles.ImportedFiles) && File.Exists(Path.Combine(campaignFolder, CampaignImportedFiles.FileName))) { using var fileStream = File.OpenRead(Path.Combine(campaignFolder, CampaignImportedFiles.FileName)); using var reader = new BinaryReader(fileStream); ImportedFiles = reader.ReadCampaignImportedFiles(); } if (campaignFiles.HasFlag(CampaignFiles.Info) && File.Exists(Path.Combine(campaignFolder, CampaignInfo.FileName))) { using var fileStream = File.OpenRead(Path.Combine(campaignFolder, CampaignInfo.FileName)); using var reader = new BinaryReader(fileStream); Info = reader.ReadCampaignInfo(); } if (campaignFiles.HasFlag(CampaignFiles.AbilityObjectData) && File.Exists(Path.Combine(campaignFolder, CampaignAbilityObjectData.FileName))) { using var fileStream = File.OpenRead(Path.Combine(campaignFolder, CampaignAbilityObjectData.FileName)); using var reader = new BinaryReader(fileStream); AbilityObjectData = reader.ReadCampaignAbilityObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.BuffObjectData) && File.Exists(Path.Combine(campaignFolder, CampaignBuffObjectData.FileName))) { using var fileStream = File.OpenRead(Path.Combine(campaignFolder, CampaignBuffObjectData.FileName)); using var reader = new BinaryReader(fileStream); BuffObjectData = reader.ReadCampaignBuffObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.DestructableObjectData) && File.Exists(Path.Combine(campaignFolder, CampaignDestructableObjectData.FileName))) { using var fileStream = File.OpenRead(Path.Combine(campaignFolder, CampaignDestructableObjectData.FileName)); using var reader = new BinaryReader(fileStream); DestructableObjectData = reader.ReadCampaignDestructableObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.DoodadObjectData) && File.Exists(Path.Combine(campaignFolder, CampaignDoodadObjectData.FileName))) { using var fileStream = File.OpenRead(Path.Combine(campaignFolder, CampaignDoodadObjectData.FileName)); using var reader = new BinaryReader(fileStream); DoodadObjectData = reader.ReadCampaignDoodadObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.ItemObjectData) && File.Exists(Path.Combine(campaignFolder, CampaignItemObjectData.FileName))) { using var fileStream = File.OpenRead(Path.Combine(campaignFolder, CampaignItemObjectData.FileName)); using var reader = new BinaryReader(fileStream); ItemObjectData = reader.ReadCampaignItemObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.UnitObjectData) && File.Exists(Path.Combine(campaignFolder, CampaignUnitObjectData.FileName))) { using var fileStream = File.OpenRead(Path.Combine(campaignFolder, CampaignUnitObjectData.FileName)); using var reader = new BinaryReader(fileStream); UnitObjectData = reader.ReadCampaignUnitObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.UpgradeObjectData) && File.Exists(Path.Combine(campaignFolder, CampaignUpgradeObjectData.FileName))) { using var fileStream = File.OpenRead(Path.Combine(campaignFolder, CampaignUpgradeObjectData.FileName)); using var reader = new BinaryReader(fileStream); UpgradeObjectData = reader.ReadCampaignUpgradeObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.TriggerStrings) && File.Exists(Path.Combine(campaignFolder, CampaignTriggerStrings.FileName))) { using var fileStream = File.OpenRead(Path.Combine(campaignFolder, CampaignTriggerStrings.FileName)); using var reader = new StreamReader(fileStream); TriggerStrings = reader.ReadCampaignTriggerStrings(); } } private Campaign(MpqArchive campaignArchive, CampaignFiles campaignFiles) { if (campaignFiles.HasFlag(CampaignFiles.ImportedFiles) && MpqFile.Exists(campaignArchive, CampaignImportedFiles.FileName)) { using var fileStream = MpqFile.OpenRead(campaignArchive, CampaignImportedFiles.FileName); using var reader = new BinaryReader(fileStream); ImportedFiles = reader.ReadCampaignImportedFiles(); } if (campaignFiles.HasFlag(CampaignFiles.Info) && MpqFile.Exists(campaignArchive, CampaignInfo.FileName)) { using var fileStream = MpqFile.OpenRead(campaignArchive, CampaignInfo.FileName); using var reader = new BinaryReader(fileStream); Info = reader.ReadCampaignInfo(); } if (campaignFiles.HasFlag(CampaignFiles.AbilityObjectData) && MpqFile.Exists(campaignArchive, CampaignAbilityObjectData.FileName)) { using var fileStream = MpqFile.OpenRead(campaignArchive, CampaignAbilityObjectData.FileName); using var reader = new BinaryReader(fileStream); AbilityObjectData = reader.ReadCampaignAbilityObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.BuffObjectData) && MpqFile.Exists(campaignArchive, CampaignBuffObjectData.FileName)) { using var fileStream = MpqFile.OpenRead(campaignArchive, CampaignBuffObjectData.FileName); using var reader = new BinaryReader(fileStream); BuffObjectData = reader.ReadCampaignBuffObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.DestructableObjectData) && MpqFile.Exists(campaignArchive, CampaignDestructableObjectData.FileName)) { using var fileStream = MpqFile.OpenRead(campaignArchive, CampaignDestructableObjectData.FileName); using var reader = new BinaryReader(fileStream); DestructableObjectData = reader.ReadCampaignDestructableObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.DoodadObjectData) && MpqFile.Exists(campaignArchive, CampaignDoodadObjectData.FileName)) { using var fileStream = MpqFile.OpenRead(campaignArchive, CampaignDoodadObjectData.FileName); using var reader = new BinaryReader(fileStream); DoodadObjectData = reader.ReadCampaignDoodadObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.ItemObjectData) && MpqFile.Exists(campaignArchive, CampaignItemObjectData.FileName)) { using var fileStream = MpqFile.OpenRead(campaignArchive, CampaignItemObjectData.FileName); using var reader = new BinaryReader(fileStream); ItemObjectData = reader.ReadCampaignItemObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.UnitObjectData) && MpqFile.Exists(campaignArchive, CampaignUnitObjectData.FileName)) { using var fileStream = MpqFile.OpenRead(campaignArchive, CampaignUnitObjectData.FileName); using var reader = new BinaryReader(fileStream); UnitObjectData = reader.ReadCampaignUnitObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.UpgradeObjectData) && MpqFile.Exists(campaignArchive, CampaignUpgradeObjectData.FileName)) { using var fileStream = MpqFile.OpenRead(campaignArchive, CampaignUpgradeObjectData.FileName); using var reader = new BinaryReader(fileStream); UpgradeObjectData = reader.ReadCampaignUpgradeObjectData(); } if (campaignFiles.HasFlag(CampaignFiles.TriggerStrings) && MpqFile.Exists(campaignArchive, CampaignTriggerStrings.FileName)) { using var fileStream = MpqFile.OpenRead(campaignArchive, CampaignTriggerStrings.FileName); using var reader = new StreamReader(fileStream); TriggerStrings = reader.ReadCampaignTriggerStrings(); } } public CampaignImportedFiles? ImportedFiles { get; set; } public CampaignInfo? Info { get; set; } public CampaignAbilityObjectData? AbilityObjectData { get; set; } public CampaignBuffObjectData? BuffObjectData { get; set; } public CampaignDestructableObjectData? DestructableObjectData { get; set; } public CampaignDoodadObjectData? DoodadObjectData { get; set; } public CampaignItemObjectData? ItemObjectData { get; set; } public CampaignUnitObjectData? UnitObjectData { get; set; } public CampaignUpgradeObjectData? UpgradeObjectData { get; set; } public CampaignTriggerStrings? TriggerStrings { get; set; } /// <summary> /// Opens the campaign from the specified file or folder path. /// </summary> public static Campaign Open(string path, CampaignFiles campaignFiles = CampaignFiles.All) { if (File.Exists(path)) { using var campaignArchive = MpqArchive.Open(path); return new Campaign(campaignArchive, campaignFiles); } else if (Directory.Exists(path)) { return new Campaign(path, campaignFiles); } else { throw new ArgumentException("Could not find a file or folder at the specified path."); } } public static Campaign Open(Stream stream, CampaignFiles campaignFiles = CampaignFiles.All) { using var campaignArchive = MpqArchive.Open(stream); return new Campaign(campaignArchive, campaignFiles); } public static Campaign Open(MpqArchive archive, CampaignFiles campaignFiles = CampaignFiles.All) { return new Campaign(archive, campaignFiles); } } }
48.817797
162
0.643781
[ "MIT" ]
YakaryBovine/War3Net
src/War3Net.Build.Core/Campaign.cs
11,523
C#
using AutoMapper; namespace DAL.APP.EF.Mappers { public class RestaurantSubscriptionMapper : BaseMapper<DAL.App.DTO.OrderModels.RestaurantSubscription, Domain.OrderModels.RestaurantSubscription> { public RestaurantSubscriptionMapper(IMapper mapper) : base(mapper) { } } }
28.090909
149
0.731392
[ "MIT" ]
Flexplicit/Restofy
AspSolutionBackend/DAL.App.EF/Mappers/RestaurantSubscriptionMapper.cs
311
C#
using System; using UnityEngine; public class ElementEmitter : SimComponent { [SerializeField] public ElementConverter.OutputElement outputElement; [SerializeField] public float emissionFrequency = 1f; [SerializeField] public byte emitRange = 1; [SerializeField] public float maxPressure = 1f; private Guid statusHandle = Guid.Empty; public bool showDescriptor = true; private HandleVector<Game.CallbackInfo>.Handle onBlockedHandle = HandleVector<Game.CallbackInfo>.InvalidHandle; private HandleVector<Game.CallbackInfo>.Handle onUnblockedHandle = HandleVector<Game.CallbackInfo>.InvalidHandle; public bool isEmitterBlocked { get; private set; } protected override void OnSpawn() { onBlockedHandle = Game.Instance.callbackManager.Add(new Game.CallbackInfo(OnEmitterBlocked, manually_release: true)); onUnblockedHandle = Game.Instance.callbackManager.Add(new Game.CallbackInfo(OnEmitterUnblocked, manually_release: true)); base.OnSpawn(); } protected override void OnCleanUp() { Game.Instance.ManualReleaseHandle(onBlockedHandle); Game.Instance.ManualReleaseHandle(onUnblockedHandle); base.OnCleanUp(); } public void SetEmitting(bool emitting) { SetSimActive(emitting); } protected override void OnSimActivate() { int game_cell = Grid.OffsetCell(Grid.PosToCell(base.transform.GetPosition()), (int)outputElement.outputElementOffset.x, (int)outputElement.outputElementOffset.y); if (outputElement.elementHash != 0 && outputElement.massGenerationRate > 0f && emissionFrequency > 0f) { float emit_temperature = ((outputElement.minOutputTemperature == 0f) ? GetComponent<PrimaryElement>().Temperature : outputElement.minOutputTemperature); SimMessages.ModifyElementEmitter(simHandle, game_cell, emitRange, outputElement.elementHash, emissionFrequency, outputElement.massGenerationRate, emit_temperature, maxPressure, outputElement.addedDiseaseIdx, outputElement.addedDiseaseCount); } if (showDescriptor) { statusHandle = GetComponent<KSelectable>().ReplaceStatusItem(statusHandle, Db.Get().BuildingStatusItems.ElementEmitterOutput, this); } } protected override void OnSimDeactivate() { int game_cell = Grid.OffsetCell(Grid.PosToCell(base.transform.GetPosition()), (int)outputElement.outputElementOffset.x, (int)outputElement.outputElementOffset.y); SimMessages.ModifyElementEmitter(simHandle, game_cell, emitRange, SimHashes.Vacuum, 0f, 0f, 0f, 0f, byte.MaxValue, 0); if (showDescriptor) { statusHandle = GetComponent<KSelectable>().RemoveStatusItem(statusHandle); } } public void ForceEmit(float mass, byte disease_idx, int disease_count, float temperature = -1f) { if (!(mass <= 0f)) { float temperature2 = ((temperature > 0f) ? temperature : outputElement.minOutputTemperature); Element element = ElementLoader.FindElementByHash(outputElement.elementHash); if (element.IsGas || element.IsLiquid) { SimMessages.AddRemoveSubstance(Grid.PosToCell(base.transform.GetPosition()), outputElement.elementHash, CellEventLogger.Instance.ElementConsumerSimUpdate, mass, temperature2, disease_idx, disease_count); } else if (element.IsSolid) { element.substance.SpawnResource(base.transform.GetPosition() + new Vector3(0f, 0.5f, 0f), mass, temperature2, disease_idx, disease_count, prevent_merge: false, forceTemperature: true); } PopFXManager.Instance.SpawnFX(PopFXManager.Instance.sprite_Resource, ElementLoader.FindElementByHash(outputElement.elementHash).name, base.gameObject.transform); } } private void OnEmitterBlocked() { isEmitterBlocked = true; Trigger(1615168894, this); } private void OnEmitterUnblocked() { isEmitterBlocked = false; Trigger(-657992955, this); } protected override void OnSimRegister(HandleVector<Game.ComplexCallbackInfo<int>>.Handle cb_handle) { Game.Instance.simComponentCallbackManager.GetItem(cb_handle); SimMessages.AddElementEmitter(maxPressure, cb_handle.index, onBlockedHandle.index, onUnblockedHandle.index); } protected override void OnSimUnregister() { StaticUnregister(simHandle); } private static void StaticUnregister(int sim_handle) { Debug.Assert(Sim.IsValidHandle(sim_handle)); SimMessages.RemoveElementEmitter(-1, sim_handle); } private void OnDrawGizmosSelected() { int cell = Grid.OffsetCell(Grid.PosToCell(base.transform.GetPosition()), (int)outputElement.outputElementOffset.x, (int)outputElement.outputElementOffset.y); Gizmos.color = Color.green; Gizmos.DrawSphere(Grid.CellToPos(cell) + Vector3.right / 2f + Vector3.up / 2f, 0.2f); } protected override Action<int> GetStaticUnregister() { return StaticUnregister; } }
35.776923
244
0.783917
[ "MIT" ]
undancer/oni-data
Managed/main/ElementEmitter.cs
4,651
C#
namespace Switchvox.Extensions.Phones.Analog { class Add { } }
10.857143
45
0.631579
[ "MIT" ]
bfranklin825/SwitchvoxAPI
SwitchvoxAPI/_Unimplemented/extensions/Phones/Analog/Add.cs
78
C#
namespace Basic.Azure.Storage.Communications.BlobService { public class BlobCopyProgress { public int BytesCopied { get; protected set; } public int BytesTotal { get; protected set; } public double PercentComplete { get { return (double)BytesCopied/BytesTotal; } } public BlobCopyProgress(int bytesCopied, int bytesTotal) { BytesCopied = bytesCopied; BytesTotal = bytesTotal; } } }
29.25
88
0.643162
[ "BSD-3-Clause" ]
tarwn/BasicAzureStorageSDK
Basic.Azure.Storage/Communications/BlobService/BlobCopyProgress.cs
470
C#
namespace PointInRectangle { using System; using System.Linq; public class Program { public static void Main(string[] args) { int[] coordinates = Console.ReadLine() .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); int topLeftX = coordinates[0]; int topLeftY = coordinates[1]; int bottomRightX = coordinates[2]; int bottomRightY = coordinates[3]; Point topLeft = new Point(topLeftX, topLeftY); Point bottomRight = new Point(bottomRightX, bottomRightY); Rectangle rectangle = new Rectangle(topLeft, bottomRight); int inputLines = int.Parse(Console.ReadLine()); for (int i = 0; i < inputLines; i++) { int[] currentPointCoordinates = Console.ReadLine() .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); int x = currentPointCoordinates[0]; int y = currentPointCoordinates[1]; Point currentPoint = new Point(x, y); Console.WriteLine(rectangle.Contains(currentPoint)); } } } }
31.204545
80
0.520757
[ "MIT" ]
GeorgenaGeorgieva/OOP-CSharp
01. Working with Abstraction Lab/2. Point in Rectangle/Program.cs
1,373
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IMethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IWorkbookFunctionsRank_AvgRequest. /// </summary> public partial interface IWorkbookFunctionsRank_AvgRequest : IBaseRequest { /// <summary> /// Gets the request body. /// </summary> WorkbookFunctionsRank_AvgRequestBody RequestBody { get; } /// <summary> /// Issues the POST request. /// </summary> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(); /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IWorkbookFunctionsRank_AvgRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IWorkbookFunctionsRank_AvgRequest Select(string value); } }
35.603448
153
0.588378
[ "MIT" ]
DamienTehDemon/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IWorkbookFunctionsRank_AvgRequest.cs
2,065
C#
using System.Web.Http; namespace ALS.Glance.Api.Security.Filters { public class ApiAuthorizeAttribute : AuthorizeAttribute { private ApiAuthorizeAttribute(string[] roles) { Roles = string.Join(",", roles); } public ApiAuthorizeAttribute() : this(new string[0]) { } public ApiAuthorizeAttribute(string role) : this(new[] { role }) { } public ApiAuthorizeAttribute(string role1, string role2) : this(new[] { role1, role2 }) { } public ApiAuthorizeAttribute(string role1, string role2, string role3) : this(new[] { role1, role2, role3}) { } public ApiAuthorizeAttribute(string role1, string role2, string role3, string role4) : this(new[] { role1, role2, role3, role4 }) { } } }
35.045455
141
0.645914
[ "ECL-2.0", "Apache-2.0" ]
smeegoan/als-glance
ALS.Glance.Api/Security/Filters/ApiAuthorizeAttribute.cs
773
C#
namespace VSCC.Roll20.Macros.SpellLinks { using System; using System.Collections.Generic; using System.IO; using System.Windows.Documents; using VSCC.DataType; using VSCC.Roll20.Macros.Basic; public class MacroActionSLIsConcentration : MacroActionSpellLinkBase { private readonly MacroAction[] _backend = new MacroAction[1]; public override string Name => this.Translate("Macro_SLIsConcentration_Name"); public override string Category => this.Translate("Macro_Category_SL"); public override MacroAction[] Params => this._backend; public override Type[] ParamTypes => new Type[] { typeof(string) }; public override Type ReturnType => typeof(bool); public override string[] CreateFormattedText() => new string[] { this.Params[0].CreateFullInnerText() }; public override string CreateFullInnerText() => this.Translate("Macro_SLIsConcentration_FullInnerText", this.Params[0].CreateFullInnerText()); public override IEnumerable<Inline> CreateInnerText() { yield return new Hyperlink(new Run()) { Tag = 0 }; yield return new Run(this.Translate("Macro_SLIsConcentration_Text_0")); } public override void Deserialize(BinaryReader br) => this.Params[0] = MacroSerializer.ReadMacroAction(br); public override object Execute(Macro m, List<string> errors) { string n = (string)this.Params[0].Execute(m, errors); if (this.TryGetSpellLink(m, n, out Spell s)) { return s.SpellComponents.HasFlag(SpellComponents.Concentration); } errors.Add(this.Translate("Macro_Error_NoLink")); return false; } public override void Serialize(BinaryWriter bw) => MacroSerializer.WriteMacroAction(bw, this.Params[0]); public override void SetDefaults() { this.Params[0] = new MacroActionStringConstant(); this.Params[0].SetDefaults(); } } }
36.553571
150
0.657059
[ "MIT" ]
skyloutyr/VSCC
VSCC/Roll20/Macros/SpellLinks/MacroActionSLIsConcentration.cs
2,049
C#
using CommandLine; using System; using System.Collections.Generic; using System.IO; using Unicorn.FontTools.Afm; namespace Unicorn.FontTools.Afm2Cs { class Program { static void Main(string[] args) { Parser.Default.ParseArguments<Options>(args) .WithParsed(o => { const int classContentIndent = 8; List<string> discoveredFonts = new List<string>(); ClassCoder coder = new ClassCoder(o.NameSpace, o.ClassName); string output = string.IsNullOrWhiteSpace(o.Output) ? o.ClassName + ".cs" : o.Output; using StreamWriter writer = new StreamWriter(output); writer.Write(coder.OutputStart(args)); foreach (string input in args) { using StreamReader reader = new StreamReader(input); AfmFontMetrics metrics = AfmFontMetrics.FromReader(reader); foreach (string line in FontMetricsCoder.PropertyCoder(metrics, SafeFontName(metrics.FontName), input, classContentIndent)) { writer.WriteLine(line); } reader.Close(); discoveredFonts.Add(metrics.FontName); } writer.Write(ClassCoder.OutputSupportedFonts(discoveredFonts, classContentIndent)); writer.Write(ClassCoder.OutputEnd()); writer.Close(); }) .WithNotParsed(o => Environment.Exit(1)); } private static string SafeFontName(string fn) { return fn.Replace("-", "", StringComparison.InvariantCulture); } } }
39.847826
147
0.53246
[ "MIT" ]
willsalt/unicorn
src/Unicorn.FontTools.Afm2Cs/Program.cs
1,835
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace KarteikartenDesktop { static class Program { /// <summary> /// Der Haupteinstiegspunkt für die Anwendung. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Hauptform()); } } }
22.73913
65
0.625239
[ "MIT" ]
jbeezy24/KarteikartenDesktop
Program.cs
526
C#
using System.Globalization; using System.Text.Json; using System.Text.Json.Serialization; namespace WebApi.Utils; // Note: Current .NET 6 runtime cannot (de)serialize DateOnly. See https://github.com/dotnet/runtime/issues/53539 public class DateOnlyJsonConverter : JsonConverter<DateOnly> { private const string DateFormat = "yyyy-MM-dd"; public override DateOnly Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var value = reader.GetString()!; var succes = DateOnly.TryParseExact(value, DateFormat, out var date); if (succes) { return date; } throw new JsonException($"'{value}' cannot be parsed as date. Format should be '{DateFormat}'"); } public override void Write( Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString(DateFormat, CultureInfo.InvariantCulture)); } }
29.085714
113
0.675835
[ "MIT" ]
BenjaminSchmitt/Doggos
src/WebApi/Utils/DateOnlyJsonConverter.cs
1,020
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 personalize-2018-05-22.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.Personalize.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Personalize.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DefaultCategoricalHyperParameterRange Object /// </summary> public class DefaultCategoricalHyperParameterRangeUnmarshaller : IUnmarshaller<DefaultCategoricalHyperParameterRange, XmlUnmarshallerContext>, IUnmarshaller<DefaultCategoricalHyperParameterRange, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> DefaultCategoricalHyperParameterRange IUnmarshaller<DefaultCategoricalHyperParameterRange, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public DefaultCategoricalHyperParameterRange Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; DefaultCategoricalHyperParameterRange unmarshalledObject = new DefaultCategoricalHyperParameterRange(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("isTunable", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.IsTunable = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Name = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("values", targetDepth)) { var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance); unmarshalledObject.Values = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static DefaultCategoricalHyperParameterRangeUnmarshaller _instance = new DefaultCategoricalHyperParameterRangeUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static DefaultCategoricalHyperParameterRangeUnmarshaller Instance { get { return _instance; } } } }
39.153846
225
0.631876
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Personalize/Generated/Model/Internal/MarshallTransformations/DefaultCategoricalHyperParameterRangeUnmarshaller.cs
4,072
C#
using System; using System.Collections.Generic; using System.Text; namespace CXuesong.Shims.VisualBasic.Devices { public static class ComputerExtensions { private static readonly object portsKey = new object(); /// <summary> /// Gets an object that provides a property and a method for accessing the computer's serial ports. /// </summary> public static Ports Ports(this ServerComputer computer) { return computer.GetOrCreateExtensionSlot<Ports>(portsKey); } } }
22.916667
107
0.663636
[ "MIT" ]
CXuesong/Shims.VisualBasic
CXuesong.Shims.VisualBasic.Devices.Ports/ComputerExtensions.cs
552
C#
namespace HemaVideoLib.Models { public interface IUser { int? UserKey { get; } } }
13
30
0.576923
[ "MIT" ]
Grauenwolf/HemaVideoWiki
HemaVideo/HemaVideoLib/Models/IUser.cs
106
C#
 namespace Servya { public interface IHttpContext { IHttpRequest Request { get; } IHttpResponse Response { get; } } }
12.6
33
0.698413
[ "MIT" ]
returnString/Servya
Servya.Http/Listening/IHttpContext.cs
128
C#
using System; using UnityEngine; using System.Xml; using System.Collections.Generic; using GameDefine; using BlGame.Resource; using System.Linq; public class ReadHeroConfig { XmlDocument xmlDoc = null; public ReadHeroConfig(string xmlFilePath) { //TextAsset xmlfile = Resources.Load(xmlFilePath) as TextAsset; ResourceUnit xmlfileUnit = ResourcesManager.Instance.loadImmediate(xmlFilePath, ResourceType.ASSET); TextAsset xmlfile = xmlfileUnit.Asset as TextAsset; if(!xmlfile) { //Debug.LogError(" error infos: 没有找到指定的xml文件:"+xmlFilePath); } xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlfile.text); XmlNodeList infoNodeList = xmlDoc.SelectSingleNode("herocfg ").ChildNodes; for(int i = 0;i < infoNodeList.Count;i++)//XmlNode xNode in infoNodeList) { if((infoNodeList[i] as XmlElement).GetAttributeNode("un32ID") == null) continue; string typeName = (infoNodeList[i] as XmlElement).GetAttributeNode("un32ID").InnerText; HeroConfigInfo HeroSelectInfo = new HeroConfigInfo(); HeroSelectInfo.HeroName = Convert.ToString(typeName); foreach(XmlElement xEle in infoNodeList[i].ChildNodes) { #region 搜索 switch(xEle.Name) { case "szNOStr": HeroSelectInfo.HeroNum = Convert.ToInt32(xEle.InnerText); break; case "eMagicCate": HeroSelectInfo.HeroMgicCate = Convert.ToInt32(xEle.InnerText); break; case "XuetiaoHeight": HeroSelectInfo.HeroXueTiaoHeight = Convert.ToInt32(xEle.InnerText); break; case "n32AttackDist": HeroSelectInfo.HeroAtkDis = Convert.ToSingle(xEle.InnerText); break; case "n32BaseExp": HeroSelectInfo.HeroBaseExp = Convert.ToSingle(xEle.InnerText); break; case "n32BasePhyAttPower": HeroSelectInfo.HeroPhyAtt = Convert.ToSingle(xEle.InnerText); break; case "n32BaseMagAttPower": HeroSelectInfo.HeroMagAtt = Convert.ToSingle(xEle.InnerText); break; case "n32BasePhyDef": HeroSelectInfo.HeroPhyDef = Convert.ToSingle(xEle.InnerText); break; case "n32BaseMagDef": HeroSelectInfo.HeroMagDef = Convert.ToSingle(xEle.InnerText); break; case "n32BaseMoveSpeed": HeroSelectInfo.HeroMoveSpeed = Convert.ToSingle(xEle.InnerText); break; case "n32BaseMoveSpeedScaling": HeroSelectInfo.n32BaseMoveSpeedScaling = Convert.ToSingle(xEle.InnerText); break; case "n32BaseAttackCD": HeroSelectInfo.HeorBaseAtkCd = Convert.ToSingle(xEle.InnerText); break; case "n32BaseMaxHP": HeroSelectInfo.HeroMaxHp = Convert.ToSingle(xEle.InnerText); break; case "n32BaseMaxMP": HeroSelectInfo.HeroMaxMp = Convert.ToSingle(xEle.InnerText); break; case "n32BaseHPRecover": HeroSelectInfo.HeroHpRecover = Convert.ToSingle(xEle.InnerText); break; case "n32BaseMPRecover": HeroSelectInfo.HeroMpRecover = Convert.ToSingle(xEle.InnerText); break; case "n32BaseReliveTime": HeroSelectInfo.HeroRelieveTime = Convert.ToSingle(xEle.InnerText); break; case "n32ExpGrowth": HeroSelectInfo.HeroExpGrowth = Convert.ToSingle(xEle.InnerText); break; case "n32PhyAttGrowth": HeroSelectInfo.HeroPhyAttGrowth = Convert.ToSingle(xEle.InnerText); break; case "n32MagAttGrowth": HeroSelectInfo.HeroMagAttGrowth = Convert.ToSingle(xEle.InnerText); break; case "n32PhyDefGrowth": HeroSelectInfo.HeroPhyDefGrowth = Convert.ToSingle(xEle.InnerText); break; case "n32MagDefGrowth": HeroSelectInfo.HeroMagDefGrowth = Convert.ToSingle(xEle.InnerText); break; case "n32AttackCDGrowth": HeroSelectInfo.HeroAtkCdGrowth = Convert.ToSingle(xEle.InnerText); break; case "32MaxHPGrowth": HeroSelectInfo.HeroMaxHpGrowth = Convert.ToSingle(xEle.InnerText); break; case "32MaxMPGrowth": HeroSelectInfo.HeroMaxMpGrowth = Convert.ToSingle(xEle.InnerText); break; case "n32HPRecoverGrowth": HeroSelectInfo.HeroHpRecoverGrowth = Convert.ToSingle(xEle.InnerText); break; case "n32MPRecoverGrowth": HeroSelectInfo.HeroHpRecoverGrowth = Convert.ToSingle(xEle.InnerText); break; case "n32ReliveGrowth": HeroSelectInfo.HeroHpRecoverGrowth = Convert.ToSingle(xEle.InnerText); break; case "n32CPRecover": HeroSelectInfo.HeroCpRecover = Convert.ToSingle(xEle.InnerText); break; case "n32CollideRadious": HeroSelectInfo.HeroCollideRadious = Convert.ToSingle(xEle.InnerText); break; case "un32DeathSould": HeroSelectInfo.HeroDeathSould = Convert.ToString(xEle.InnerText); break; case "un32WalkSound": HeroSelectInfo.un32WalkSound = xEle.InnerText; break; case "un32Script1": HeroSelectInfo.HeroScript1 = Convert.ToString(xEle.InnerText); break; case "n32Script1Rate": HeroSelectInfo.HeroScript1Rate = Convert.ToString(xEle.InnerText); break; case "un32SkillType1": HeroSelectInfo.HeroSkillType1 = Convert.ToInt32(xEle.InnerText); break; case "un32SkillType2": HeroSelectInfo.HeroSkillType2 = Convert.ToInt32(xEle.InnerText); break; case "un32SkillType3": HeroSelectInfo.HeroSkillType3 = Convert.ToInt32(xEle.InnerText); break; case "un32SkillType4": HeroSelectInfo.HeroSkillType4 = Convert.ToInt32(xEle.InnerText); break; case "un32SkillType5": HeroSelectInfo.HeroSkillType5 = Convert.ToInt32(xEle.InnerText); break; case "un32SkillType6": HeroSelectInfo.HeroSkillType6 = Convert.ToInt32(xEle.InnerText); break; case "n32LockRadious": HeroSelectInfo.n32LockRadious = Convert.ToSingle(xEle.InnerText); break; case "n32RandomAttack": HeroSelectInfo.n32RandomAttack = GameDefine.GameMethod.ResolveToStrList(xEle.InnerText); break; case "un32PreItem": { string str = Convert.ToString(xEle.InnerText); if (str.CompareTo("0") != 0) { HeroSelectInfo.HeroPreEquip = GameMethod.ResolveToIntList(str, ','); } } break; case "un32MidItem": { string str = Convert.ToString(xEle.InnerText); if (str.CompareTo("0") != 0) { HeroSelectInfo.HeroMidEquip = GameMethod.ResolveToIntList(str, ','); } } break; case "un32ProItem": { string str = Convert.ToString(xEle.InnerText); if (str.CompareTo("0") != 0) { HeroSelectInfo.HeroLatEquip = GameMethod.ResolveToIntList(str, ','); } } break; case "HeroKind": { string str = Convert.ToString(xEle.InnerText); List<int> list = GameMethod.ResolveToIntList(str, ','); for (int j = 0; j < list.Count; j++) { HeroSelectInfo.heroKind.Add((HeroType)list.ElementAt(j)); } } break; case "un32SkillTypeP": HeroSelectInfo.HeroSkillTypeP = Convert.ToInt32(xEle.InnerText); break; } #endregion } ConfigReader.heroXmlInfoDict.Add(HeroSelectInfo.HeroNum,HeroSelectInfo); } } } public class HeroConfigInfo:System.Object { #region 道具信息 public string HeroName; public int HeroNum; public int HeroMgicCate; public float HeroXueTiaoHeight; public float HeroAtkDis; public float HeroBaseExp; public float HeroPhyAtt; public float HeroMagAtt; public float HeroPhyDef; public float HeroMagDef; public float HeroMoveSpeed; public float n32BaseMoveSpeedScaling; public float HeorBaseAtkCd; public float HeroMaxHp; public float HeroMaxMp; public float HeroHpRecover; public float HeroMpRecover; public float HeroRelieveTime; public float HeroExpGrowth; public float HeroPhyAttGrowth; public float HeroMagAttGrowth; public float HeroPhyDefGrowth; public float HeroMagDefGrowth; public float HeroAtkCdGrowth; public float HeroMaxHpGrowth; public float HeroMaxMpGrowth; public float HeroHpRecoverGrowth; public float HeroMpRecoverGrowth; public float HeroReliveGrowth; public float HeroCpRecover; public float HeroCollideRadious; public float n32LockRadious; public string un32WalkSound; public string HeroDeathSould; public string HeroScript1; public string HeroScript1Rate; public int HeroSkillType1; public int HeroSkillType2; public int HeroSkillType3; public int HeroSkillType4; public int HeroSkillType5; public int HeroSkillType6; public int HeroSkillTypeP; public List<string> n32RandomAttack; public List<int> HeroPreEquip = new List<int>(); public List<int> HeroMidEquip = new List<int>(); public List<int> HeroLatEquip = new List<int>(); public List<HeroType> heroKind = new List<HeroType>(); #endregion }
35.896679
108
0.635588
[ "Unlicense" ]
tsymiar/----
Client/Assets/Scripts/ConfigReader/ReadHeroConfig.cs
9,762
C#
namespace Eto.SkiaDraw.Demo { using Eto.Forms; public partial class MainForm : Form { public MainForm() { this.InitializeComponent(); this.Content = new TableLayout(new TableRow(new TableCell(new TestView(), true), new TableCell(new TestView2(), true))); } } }
17.5
123
0.696429
[ "MIT" ]
rafntor/Eto.SkiaDraw
Eto.SkiaDraw.Demo/MainForm.cs
280
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. namespace Microsoft.Xml.Serialization { using System; /// <include file='doc\XmlTextAttribute.uex' path='docs/doc[@for="XmlTextAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public class XmlTextAttribute : System.Attribute { private Type _type; private string _dataType; /// <include file='doc\XmlTextAttribute.uex' path='docs/doc[@for="XmlTextAttribute.XmlTextAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlTextAttribute() { } /// <include file='doc\XmlTextAttribute.uex' path='docs/doc[@for="XmlTextAttribute.XmlTextAttribute1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlTextAttribute(Type type) { _type = type; } /// <include file='doc\XmlTextAttribute.uex' path='docs/doc[@for="XmlTextAttribute.Type"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Type Type { get { return _type; } set { _type = value; } } /// <include file='doc\XmlTextAttribute.uex' path='docs/doc[@for="XmlTextAttribute.DataType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string DataType { get { return _dataType == null ? string.Empty : _dataType; } set { _dataType = value; } } } }
33.719298
132
0.568678
[ "MIT" ]
Bencargs/wcf
src/dotnet-svcutil/lib/src/FrameworkFork/Microsoft.Xml/Xml/Serialization/XmlTextAttribute.cs
1,922
C#