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 NetDist.ServerAdmin.WebApi; using Wpf.Shared; namespace WpfServerAdmin.Models { public class ServerModel { public WebApiServerAdmin Server { get; private set; } private readonly PortableConfiguration _conf = new PortableConfiguration(new JsonNetSerializer()); public ServerModel() { var settings = _conf.Load<WebApiServerAdminSettings>("AdminSettings"); Server = new WebApiServerAdmin(settings); } } }
25.684211
106
0.67623
[ "MIT" ]
Roemer/NetDist
src/WpfServerAdmin/Models/ServerModel.cs
490
C#
namespace mainForm { partial class bookAvailablefrm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.bookAvailableListdgv = new System.Windows.Forms.DataGridView(); this.searchtxt = new System.Windows.Forms.TextBox(); this.memberrdo = new System.Windows.Forms.RadioButton(); this.bookrdo = new System.Windows.Forms.RadioButton(); this.clearbtn = new System.Windows.Forms.Button(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.searchbtn = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.bookAvailableListdgv)).BeginInit(); this.SuspendLayout(); // // bookAvailableListdgv // this.bookAvailableListdgv.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.bookAvailableListdgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.bookAvailableListdgv.Location = new System.Drawing.Point(113, 225); this.bookAvailableListdgv.Margin = new System.Windows.Forms.Padding(5); this.bookAvailableListdgv.Name = "bookAvailableListdgv"; this.bookAvailableListdgv.Size = new System.Drawing.Size(880, 391); this.bookAvailableListdgv.TabIndex = 7; // // searchtxt // this.searchtxt.Location = new System.Drawing.Point(323, 102); this.searchtxt.Margin = new System.Windows.Forms.Padding(5); this.searchtxt.Name = "searchtxt"; this.searchtxt.Size = new System.Drawing.Size(527, 27); this.searchtxt.TabIndex = 5; this.toolTip1.SetToolTip(this.searchtxt, "Enter keyword to search"); this.searchtxt.KeyDown += new System.Windows.Forms.KeyEventHandler(this.searchtxt_KeyDown); // // memberrdo // this.memberrdo.AutoSize = true; this.memberrdo.Location = new System.Drawing.Point(203, 102); this.memberrdo.Margin = new System.Windows.Forms.Padding(5); this.memberrdo.Name = "memberrdo"; this.memberrdo.Size = new System.Drawing.Size(94, 25); this.memberrdo.TabIndex = 9; this.memberrdo.Text = "Member"; this.toolTip1.SetToolTip(this.memberrdo, "Select to search by member"); this.memberrdo.UseVisualStyleBackColor = true; // // bookrdo // this.bookrdo.AutoSize = true; this.bookrdo.Checked = true; this.bookrdo.Location = new System.Drawing.Point(113, 102); this.bookrdo.Margin = new System.Windows.Forms.Padding(5); this.bookrdo.Name = "bookrdo"; this.bookrdo.Size = new System.Drawing.Size(65, 25); this.bookrdo.TabIndex = 10; this.bookrdo.TabStop = true; this.bookrdo.Text = "Book"; this.toolTip1.SetToolTip(this.bookrdo, "Select to search by book"); this.bookrdo.UseVisualStyleBackColor = true; // // clearbtn // this.clearbtn.Location = new System.Drawing.Point(879, 181); this.clearbtn.Margin = new System.Windows.Forms.Padding(5); this.clearbtn.Name = "clearbtn"; this.clearbtn.Size = new System.Drawing.Size(114, 34); this.clearbtn.TabIndex = 11; this.clearbtn.Text = "Clear results"; this.toolTip1.SetToolTip(this.clearbtn, "Clear results"); this.clearbtn.UseVisualStyleBackColor = true; this.clearbtn.Click += new System.EventHandler(this.clearbtn_Click); // // searchbtn // this.searchbtn.Image = global::mainForm.Properties.Resources.search_flat; this.searchbtn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.searchbtn.Location = new System.Drawing.Point(879, 92); this.searchbtn.Name = "searchbtn"; this.searchbtn.Size = new System.Drawing.Size(114, 46); this.searchbtn.TabIndex = 13; this.searchbtn.Text = "Search"; this.searchbtn.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.searchbtn.UseVisualStyleBackColor = true; this.searchbtn.Click += new System.EventHandler(this.searchbtn_Click); // // bookAvailablefrm // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 21F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1084, 661); this.Controls.Add(this.searchbtn); this.Controls.Add(this.clearbtn); this.Controls.Add(this.bookrdo); this.Controls.Add(this.memberrdo); this.Controls.Add(this.bookAvailableListdgv); this.Controls.Add(this.searchtxt); this.Font = new System.Drawing.Font("Century Gothic", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Margin = new System.Windows.Forms.Padding(5); this.Name = "bookAvailablefrm"; this.Text = "Book Availabality Query"; this.Load += new System.EventHandler(this.bookAvailablefrm_Load); ((System.ComponentModel.ISupportInitialize)(this.bookAvailableListdgv)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.DataGridView bookAvailableListdgv; private System.Windows.Forms.TextBox searchtxt; private System.Windows.Forms.RadioButton memberrdo; private System.Windows.Forms.RadioButton bookrdo; private System.Windows.Forms.Button clearbtn; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.Button searchbtn; } }
48.534247
153
0.615157
[ "Unlicense" ]
brlala/Library-Management-System
mainForm/Search/QueryAvailablefrm.designer.cs
7,088
C#
namespace Python.Runtime { using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; /// <summary> /// Should only be used for the arguments of Python C API functions, that steal references, /// and internal <see cref="PyObject"/> constructors. /// </summary> [NonCopyable] readonly ref struct StolenReference { internal readonly IntPtr Pointer; [DebuggerHidden] StolenReference(IntPtr pointer) { Pointer = pointer; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static StolenReference Take(ref IntPtr ptr) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); return TakeNullable(ref ptr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [DebuggerHidden] public static StolenReference TakeNullable(ref IntPtr ptr) { var stolenAddr = ptr; ptr = IntPtr.Zero; return new StolenReference(stolenAddr); } [Pure] public static bool operator ==(in StolenReference reference, NullOnly? @null) => reference.Pointer == IntPtr.Zero; [Pure] public static bool operator !=(in StolenReference reference, NullOnly? @null) => reference.Pointer != IntPtr.Zero; [Pure] public override bool Equals(object obj) { if (obj is IntPtr ptr) return ptr == Pointer; return false; } [Pure] public override int GetHashCode() => Pointer.GetHashCode(); [Pure] public static StolenReference DangerousFromPointer(IntPtr ptr) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); return new StolenReference(ptr); } } static class StolenReferenceExtensions { [Pure] [DebuggerHidden] public static IntPtr DangerousGetAddressOrNull(this in StolenReference reference) => reference.Pointer; [Pure] [DebuggerHidden] public static IntPtr DangerousGetAddress(this in StolenReference reference) => reference.Pointer == IntPtr.Zero ? throw new NullReferenceException() : reference.Pointer; [DebuggerHidden] public static StolenReference AnalyzerWorkaround(this in StolenReference reference) { IntPtr ptr = reference.DangerousGetAddressOrNull(); return StolenReference.TakeNullable(ref ptr); } } }
31.86747
105
0.617769
[ "MIT" ]
FilamentGames/pythonnet
src/runtime/StolenReference.cs
2,645
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network.Fluent.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Fluent; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// VpnClientConfiguration for P2S client. /// </summary> public partial class VpnClientConfiguration { /// <summary> /// Initializes a new instance of the VpnClientConfiguration class. /// </summary> public VpnClientConfiguration() { CustomInit(); } /// <summary> /// Initializes a new instance of the VpnClientConfiguration class. /// </summary> /// <param name="vpnClientAddressPool">The reference of the address /// space resource which represents Address space for P2S /// VpnClient.</param> /// <param name="vpnClientRootCertificates">VpnClientRootCertificate /// for virtual network gateway.</param> /// <param /// name="vpnClientRevokedCertificates">VpnClientRevokedCertificate for /// Virtual network gateway.</param> /// <param name="vpnClientProtocols">VpnClientProtocols for Virtual /// network gateway.</param> /// <param name="radiusServerAddress">The radius server address /// property of the VirtualNetworkGateway resource for vpn client /// connection.</param> /// <param name="radiusServerSecret">The radius secret property of the /// VirtualNetworkGateway resource for vpn client connection.</param> public VpnClientConfiguration(AddressSpace vpnClientAddressPool = default(AddressSpace), IList<VpnClientRootCertificateInner> vpnClientRootCertificates = default(IList<VpnClientRootCertificateInner>), IList<VpnClientRevokedCertificateInner> vpnClientRevokedCertificates = default(IList<VpnClientRevokedCertificateInner>), IList<string> vpnClientProtocols = default(IList<string>), string radiusServerAddress = default(string), string radiusServerSecret = default(string)) { VpnClientAddressPool = vpnClientAddressPool; VpnClientRootCertificates = vpnClientRootCertificates; VpnClientRevokedCertificates = vpnClientRevokedCertificates; VpnClientProtocols = vpnClientProtocols; RadiusServerAddress = radiusServerAddress; RadiusServerSecret = radiusServerSecret; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the reference of the address space resource which /// represents Address space for P2S VpnClient. /// </summary> [JsonProperty(PropertyName = "vpnClientAddressPool")] public AddressSpace VpnClientAddressPool { get; set; } /// <summary> /// Gets or sets vpnClientRootCertificate for virtual network gateway. /// </summary> [JsonProperty(PropertyName = "vpnClientRootCertificates")] public IList<VpnClientRootCertificateInner> VpnClientRootCertificates { get; set; } /// <summary> /// Gets or sets vpnClientRevokedCertificate for Virtual network /// gateway. /// </summary> [JsonProperty(PropertyName = "vpnClientRevokedCertificates")] public IList<VpnClientRevokedCertificateInner> VpnClientRevokedCertificates { get; set; } /// <summary> /// Gets or sets vpnClientProtocols for Virtual network gateway. /// </summary> [JsonProperty(PropertyName = "vpnClientProtocols")] public IList<string> VpnClientProtocols { get; set; } /// <summary> /// Gets or sets the radius server address property of the /// VirtualNetworkGateway resource for vpn client connection. /// </summary> [JsonProperty(PropertyName = "radiusServerAddress")] public string RadiusServerAddress { get; set; } /// <summary> /// Gets or sets the radius secret property of the /// VirtualNetworkGateway resource for vpn client connection. /// </summary> [JsonProperty(PropertyName = "radiusServerSecret")] public string RadiusServerSecret { get; set; } } }
44.137615
479
0.675743
[ "MIT" ]
abharath27/azure-libraries-for-net
src/ResourceManagement/Network/Generated/Models/VpnClientConfiguration.cs
4,811
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; namespace Aop.Api.Domain { /// <summary> /// ColumnMoreInfoModel Data Structure. /// </summary> [Serializable] public class ColumnMoreInfoModel : AopObject { /// <summary> /// 选择opennative的时候必须填写descs的内容 /// </summary> [XmlArray("descs")] [XmlArrayItem("string")] public List<string> Descs { get; set; } /// <summary> /// 扩展参数,需要URL地址回带的值,JSON格式(openweb时填) /// </summary> [XmlElement("params")] public string Params { get; set; } /// <summary> /// 二级页面标题 /// </summary> [XmlElement("title")] public string Title { get; set; } /// <summary> /// 超链接(选择openweb的时候必须填写url参数内容) /// </summary> [XmlElement("url")] public string Url { get; set; } } }
23.692308
48
0.541126
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Domain/ColumnMoreInfoModel.cs
1,028
C#
namespace Pekka.Core.Contracts { public interface IFilter { // Marker interface } }
14.857143
31
0.615385
[ "MIT" ]
Blind-Striker/clash-royale-client-dotnet
src/Pekka.Core/Contracts/IFilter.cs
106
C#
using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Magis.School.Administration.ApiClient.Enums { [JsonConverter(typeof(StringEnumConverter))] public enum NodeBranch { Stable = 0, Beta = 1 } }
18.538462
53
0.688797
[ "MIT" ]
MagisIT/Magis.School.Administration.ApiClient
Magis.School.Administration.ApiClient/Enums/NodeBranch.cs
241
C#
// DesignatorUtility.cs // Copyright Karel Kroeze, 2018-2018 using System.Collections.Generic; using Harmony; using RimWorld; using Verse; namespace StuffedFloors { public static class DesignatorUtility { public static void RemoveDesignators( IEnumerable<TerrainDef> terrains ) { HashSet<DesignationCategoryDef> affectedCategories = new HashSet<DesignationCategoryDef>(); foreach ( var terrain in terrains ) { affectedCategories.Add(terrain.designationCategory); terrain.designatorDropdown = null; terrain.designationCategory = null; }; foreach ( var affectedCategory in affectedCategories ) RecacheDesignationCategory( affectedCategory ); } public static void MergeDesignationCategories( DesignationCategoryDef target, DesignationCategoryDef source ) { // change designation category for all build designators in source foreach ( var terrain in DefDatabase<TerrainDef>.AllDefs ) if ( terrain.designationCategory == source ) terrain.designationCategory = target; // add specials that don't exist in target yet foreach ( var designator in source.specialDesignatorClasses ) if ( !target.specialDesignatorClasses.Contains( designator ) ) target.specialDesignatorClasses.Add( designator ); // recache target RecacheDesignationCategory( target ); // remove source RemoveDesignationCategory( source ); } private static void RemoveDesignationCategory( DesignationCategoryDef category ) { ( DefDatabase<DesignationCategoryDef>.AllDefs as List<DesignationCategoryDef> )?.Remove( category ); RecacheDesignationCategories(); } private static void RecacheDesignationCategory( DesignationCategoryDef category ) { category.ResolveReferences(); // calls ResolveDesignators, recreating cache; } private static void RecacheDesignationCategories() { Traverse.Create( MainButtonDefOf.Architect.TabWindow ).Method( "CacheDesPanels" ).GetValue(); } } }
36.746032
117
0.64838
[ "MIT" ]
JortonMV/StuffedFloors
Source/StuffedFloors/DesignatorUtility.cs
2,317
C#
using System; using FeatureSwitch.Strategies.Implementations; namespace FeatureSwitch.Strategies { public class AlwaysTrue : FeatureStrategyAttribute { public AlwaysTrue() { Key = "C6A5582C-4E1B-4E01-913C-E68307AE9098"; } public override Type DefaultImplementation { get { return typeof(AlwaysTrueStrategyImpl); } } } }
20.318182
57
0.577181
[ "MIT" ]
valdisiljuconoks/FeatureSwitch
FeatureSwitch/Strategies/AlwaysTrue.cs
449
C#
using NbaApp.Common.Entities; using NbaApp.Persistance; using NbaApp.Services.NbaNetClasses; using System; using System.Linq; using System.Text.Json; using System.Threading.Tasks; using System.Net; using Microsoft.Extensions.Configuration; using Microsoft.EntityFrameworkCore; namespace NbaApp.Services { public class NbaNetService : BaseService { private readonly NbaNetPlayersData _playersData; private readonly NbaNetTeamsData _teamsData; private readonly NbaNetStandingsData _standingsData; private readonly JsonSerializerOptions _options; public NbaNetService(Context context, IConfiguration configuration) : base(context, configuration) { _options = new JsonSerializerOptions { IgnoreNullValues = true, WriteIndented = true }; using var client = new WebClient(); var playersJson = client.DownloadString(_configuration["NbaNetDataUrls:Players"]); var teamsJson = client.DownloadString(_configuration["NbaNetDataUrls:Teams"]); var standingsJson = client.DownloadString(_configuration["NbaNetDataUrls:Standings"]); _playersData = JsonSerializer.Deserialize<NbaNetPlayersData>(playersJson, _options); _teamsData = JsonSerializer.Deserialize<NbaNetTeamsData>(teamsJson, _options); _standingsData = JsonSerializer.Deserialize<NbaNetStandingsData>(standingsJson, _options); } public async Task UpdateDatabase() { await _context.Database.EnsureDeletedAsync(); await _context.Database.EnsureCreatedAsync(); await LoadTeams(); await LoadPlayers(true); await _context.AppInfo.AddAsync(new AppInfo()); await _context.SaveChangesAsync(); } public async Task LoadTeams() { var teams = await Task.FromResult(_teamsData.League.Teams .Where(x => x.IsNbaFranchise == true) .Select(x => new Team( x.Name, x.NickName, x.Abbreviation, x.Conference == "West" ? "Western" : "Eastern", x.Division, x.Id.ToString() ))); foreach (var team in teams) { _context.Teams.Add(team); //Stats var stats = await Task.FromResult(_standingsData.League.Standard.Conference.West.Concat(_standingsData.League.Standard.Conference.East) .Where(x => x.TeamId == team.NbaNetId) .Select(x => new TeamStats(x.TeamId, x.Wins, x.Losses, x.GamesBehind, x.ConferenceRank, x.HomeWins, x.HomeLosses, x.AwayWins, x.AwayLosses, x.WinningStreak)) .FirstOrDefault()); team.Stats = stats; await _context.TeamStats.AddAsync(stats); } await _context.SaveChangesAsync(); } public async Task LoadPlayerDataByName(string firstName, string lastName) { var player = await Task.FromResult(_playersData.League.Players .Where(x => x.FirstName == firstName && x.LastName == lastName) .Select(x => new PlayerInfo( new Player( x.FirstName, x.LastName, x.DateOfBirth, x.HeightMetric, x.WeightLbs, GetTeamID(x.TeamID).Result, x.PersonID ), new PlayerCareerInfo( x.College, x.Country, x.JerseyNumber, x.Position, x.Draft.Year, x.Draft.Round, x.Draft.Pick, x.NbaDebutYear, GetTeamID(x.Draft.TeamID).Result ) )) .FirstOrDefault()); player.Player.CareerInfo = player.PlayerCareerInfo; await _context.Players.AddAsync(player.Player); await _context.PlayerCareerInfos.AddAsync(player.PlayerCareerInfo); await _context.SaveChangesAsync(); /* Stats */ LoadPlayerStats(player.Player.NbaNetId).Wait(); } public async Task LoadPlayers(bool loggingEnabled = false) { var players = await Task.FromResult(_playersData.League.Players .Where(x => x.IsActive == true) .Select(x => new PlayerInfo( new Player( x.FirstName, x.LastName, x.DateOfBirth, x.HeightMetric, x.WeightLbs, GetTeamID(x.TeamID).Result, x.PersonID ), new PlayerCareerInfo( x.College, x.Country, x.JerseyNumber, x.Position, x.Draft.Year, x.Draft.Round, x.Draft.Pick, x.NbaDebutYear, GetTeamID(x.Draft.TeamID).Result ) ))); foreach (var player in players) { if (loggingEnabled) { Console.WriteLine($" - loading player {player.Player.FirstName} {player.Player.LastName}"); } player.Player.CareerInfo = player.PlayerCareerInfo; /* Stats */ using WebClient client = new WebClient(); var statsJson = client.DownloadString(string.Format("https://data.nba.net/prod/v1/2019/players/{0}_profile.json", player.Player.NbaNetId)); var statsData = JsonSerializer.Deserialize<NbaNetStatsData>(statsJson, _options); var stats = new PlayerStats( statsData.League.Standard.Stats.Latest.GamesPlayed, statsData.League.Standard.Stats.Latest.GamesStarted, statsData.League.Standard.Stats.Latest.Minutes, statsData.League.Standard.Stats.Latest.FGA, statsData.League.Standard.Stats.Latest.FGM, statsData.League.Standard.Stats.Latest.TPA, statsData.League.Standard.Stats.Latest.TPM, statsData.League.Standard.Stats.Latest.FTA, statsData.League.Standard.Stats.Latest.FTM, statsData.League.Standard.Stats.Latest.OffReb, statsData.League.Standard.Stats.Latest.DefReb, statsData.League.Standard.Stats.Latest.Assists, statsData.League.Standard.Stats.Latest.Blocks, statsData.League.Standard.Stats.Latest.Steals, statsData.League.Standard.Stats.Latest.Fouls, statsData.League.Standard.Stats.Latest.Turnovers); player.Player.Stats = stats; await _context.Players.AddAsync(player.Player); await _context.PlayerCareerInfos.AddAsync(player.PlayerCareerInfo); await _context.PlayerStats.AddAsync(stats); await _context.SaveChangesAsync(); } } public async Task LoadPlayerStats(string nbaNetID) { using WebClient client = new WebClient(); var statsJson = client.DownloadString(string.Format("https://data.nba.net/prod/v1/2019/players/{0}_profile.json", nbaNetID)); var statsData = JsonSerializer.Deserialize<NbaNetStatsData>(statsJson, _options); var stats = new PlayerStats( statsData.League.Standard.Stats.Latest.GamesPlayed, statsData.League.Standard.Stats.Latest.GamesStarted, statsData.League.Standard.Stats.Latest.Minutes, statsData.League.Standard.Stats.Latest.FGA, statsData.League.Standard.Stats.Latest.FGM, statsData.League.Standard.Stats.Latest.TPA, statsData.League.Standard.Stats.Latest.TPM, statsData.League.Standard.Stats.Latest.FTA, statsData.League.Standard.Stats.Latest.FTM, statsData.League.Standard.Stats.Latest.OffReb, statsData.League.Standard.Stats.Latest.DefReb, statsData.League.Standard.Stats.Latest.Assists, statsData.League.Standard.Stats.Latest.Blocks, statsData.League.Standard.Stats.Latest.Steals, statsData.League.Standard.Stats.Latest.Fouls, statsData.League.Standard.Stats.Latest.Turnovers); var player = await _context.Players.Where(x => x.NbaNetId == nbaNetID).FirstOrDefaultAsync(); player.Stats = stats; await _context.PlayerStats.AddAsync(stats); await _context.SaveChangesAsync(); } public async Task<Guid> GetTeamID(string nbaNetId) { return await _context.Teams .Where(x => x.NbaNetId == nbaNetId) .Select(x => x.Id) .FirstOrDefaultAsync(); } } }
41.233766
177
0.551286
[ "MIT" ]
RawMajkel/NbaApp
NbaApp.Services/NbaNetService.cs
9,527
C#
using System.Collections.Generic; using System.Runtime.Serialization; using Uk.CompaniesHouse.Api.Data.Common; using Uk.CompaniesHouse.Api.Data.DisqualifiedOfficerNatural; namespace Uk.CompaniesHouse.Api.Data.DisqualifiedOfficerCorporate { /// <summary> /// The officer's disqualifications. /// </summary> [DataContract] public class Disqualifications { /// <summary> /// The address of the disqualified officer as provided by the disqualifying authority. /// </summary> [DataMember(Name = "address")] public Address Address { get; set; } = new(); /// <summary> /// The case identifier of the disqualification. /// </summary> [DataMember(Name = "case_identifier")] public string? CaseIdentifier { get; set; } /// <summary> /// The companies in which the misconduct took place. /// </summary> [DataMember(Name = "company_names")] public List<string>? CompanyNames { get; set; } /// <summary> /// The name of the court that handled the disqualification case. /// </summary> [DataMember(Name = "court_name")] public string? CourtName { get; set; } /// <summary> /// An enumeration type that provides the disqualifying authority that handled the disqualification case. /// </summary> [DataMember(Name = "disqualification_type")] public string DisqualificationType { get; set; } = string.Empty; /// <summary> /// The date that the disqualification starts. /// </summary> [DataMember(Name = "disqualified_from")] public string DisqualifiedFrom { get; set; } = string.Empty; /// <summary> /// The date that the disqualification ends. /// </summary> [DataMember(Name = "disqualified_until")] public string DisqualifiedUntil { get; set; } = string.Empty; /// <summary> /// The date the disqualification hearing was on. /// </summary> [DataMember(Name = "heard_on")] public string? HeardOn { get; set; } /// <summary> /// The latest variation made to the disqualification. /// </summary> [DataMember(Name = "last_variation")] public List<LastVariation>? LastVariation { get; set; } /// <summary> /// The reason for the disqualification. /// </summary> [DataMember(Name = "reason")] public Reason Reason { get; set; } = new(); /// <summary> /// The date the disqualification undertaking was agreed on. /// </summary> [DataMember(Name = "undertaken_on")] public string? UndertakenOn { get; set; } } }
29.851852
107
0.680314
[ "MIT" ]
panoramicdata/Uk.CompaniesHouse.Api
Uk.CompaniesHouse.Api/Data/DisqualifiedOfficerCorporate/Disqualifications.cs
2,420
C#
using System; using UnityEditor.Graphing; namespace UnityEditor.ShaderGraph { [Serializable] enum SlotValueType { SamplerState, DynamicMatrix, Matrix4, Matrix3, Matrix2, Texture2D, Texture2DArray, Texture3D, Cubemap, Gradient, DynamicVector, Vector4, Vector3, Vector2, Vector1, Dynamic, Boolean } enum ConcreteSlotValueType { SamplerState, Matrix4, Matrix3, Matrix2, Texture2D, Texture2DArray, Texture3D, Cubemap, Gradient, Vector4, Vector3, Vector2, Vector1, Boolean } static class SlotValueHelper { public static int GetChannelCount(this ConcreteSlotValueType type) { switch (type) { case ConcreteSlotValueType.Vector4: return 4; case ConcreteSlotValueType.Vector3: return 3; case ConcreteSlotValueType.Vector2: return 2; case ConcreteSlotValueType.Vector1: return 1; default: return 0; } } public static int GetMatrixDimension(ConcreteSlotValueType type) { switch (type) { case ConcreteSlotValueType.Matrix4: return 4; case ConcreteSlotValueType.Matrix3: return 3; case ConcreteSlotValueType.Matrix2: return 2; default: return 0; } } public static ConcreteSlotValueType ConvertMatrixToVectorType(ConcreteSlotValueType matrixType) { switch (matrixType) { case ConcreteSlotValueType.Matrix4: return ConcreteSlotValueType.Vector4; case ConcreteSlotValueType.Matrix3: return ConcreteSlotValueType.Vector3; default: return ConcreteSlotValueType.Vector2; } } static readonly string[] k_ConcreteSlotValueTypeClassNames = { null, "typeMatrix", "typeMatrix", "typeMatrix", "typeTexture2D", "typeTexture2DArray", "typeTexture3D", "typeCubemap", "typeGradient", "typeFloat4", "typeFloat3", "typeFloat2", "typeFloat1", "typeBoolean" }; public static string ToClassName(this ConcreteSlotValueType type) { return k_ConcreteSlotValueTypeClassNames[(int)type]; } public static string ToString(this ConcreteSlotValueType type, AbstractMaterialNode.OutputPrecision precision) { return NodeUtils.ConvertConcreteSlotValueTypeToString(precision, type); } } }
25.516393
118
0.51301
[ "MIT" ]
AcquaWh/MuseoLeapmotion
Library/PackageCache/com.unity.shadergraph@5.7.2/Editor/Data/Nodes/SlotValue.cs
3,113
C#
// Copyright 2006 Herre Kuijpers - <herre@xs4all.nl> // // This source file(s) may be redistributed, altered and customized // by any means PROVIDING the authors name and all copyright // notices remain intact. // THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED. USE IT AT YOUR OWN RISK. THE AUTHOR ACCEPTS NO // LIABILITY FOR ANY DATA DAMAGE/LOSS THAT THIS PRODUCT MAY CAUSE. //----------------------------------------------------------------------- /* Copyright (c) 2014, Lars Brubaker All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using MatterHackers.Agg; using MatterHackers.VectorMath; using System; namespace MatterHackers.RayTracer.Light { /// <summary> /// a point light /// </summary> public class PointLight : Axis3D, ILight { public ColorF Color; public double strength; public PointLight(Vector3 pos, ColorF color) : base(pos) { Color = color; strength = 10; } public ColorF Illumination() { return Color; } public double Strength(double distance) { if (distance >= strength) return 0; return Math.Pow((strength - distance) / strength, .2); } public override string ToString() { return string.Format("Light ({0})", Transform.ToString()); } } }
34.101266
79
0.742762
[ "BSD-2-Clause" ]
0000duck/agg-sharp
RayTracer/Light/PointLight.cs
2,694
C#
using Foundation; using PanCardView; using PanCardView.iOS; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using PanCardView.Enums; using System.ComponentModel; using static System.Math; [assembly: ExportRenderer(typeof(CardsView), typeof(CardsViewRenderer))] namespace PanCardView.iOS { [Preserve(AllMembers = true)] public class CardsViewRenderer : VisualElementRenderer<CardsView> { private UISwipeGestureRecognizer _leftSwipeGesture; private UISwipeGestureRecognizer _rightSwipeGesture; private UISwipeGestureRecognizer _upSwipeGesture; private UISwipeGestureRecognizer _downSwipeGesture; public static void Preserve() => Preserver.Preserve(); public CardsViewRenderer() { _leftSwipeGesture = new UISwipeGestureRecognizer(OnSwiped) { Direction = UISwipeGestureRecognizerDirection.Left }; _rightSwipeGesture = new UISwipeGestureRecognizer(OnSwiped) { Direction = UISwipeGestureRecognizerDirection.Right }; _upSwipeGesture = new UISwipeGestureRecognizer(OnSwiped) { Direction = UISwipeGestureRecognizerDirection.Up }; _downSwipeGesture = new UISwipeGestureRecognizer(OnSwiped) { Direction = UISwipeGestureRecognizerDirection.Down }; } public override void AddGestureRecognizer(UIGestureRecognizer gestureRecognizer) { base.AddGestureRecognizer(gestureRecognizer); if (gestureRecognizer is UIPanGestureRecognizer panGestureRecognizer) { gestureRecognizer.ShouldBeRequiredToFailBy = ShouldBeRequiredToFailBy; gestureRecognizer.ShouldRecognizeSimultaneously = ShouldRecognizeSimultaneously; } } protected override void OnElementChanged(ElementChangedEventArgs<CardsView> e) { base.OnElementChanged(e); if (e.NewElement != null) { SetSwipeGestures(); } } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == CardsView.IsVerticalSwipeEnabledProperty.PropertyName) { SetSwipeGestures(); return; } } protected override void Dispose(bool disposing) { if (disposing) { _leftSwipeGesture?.Dispose(); _rightSwipeGesture?.Dispose(); _upSwipeGesture?.Dispose(); _downSwipeGesture?.Dispose(); _leftSwipeGesture = null; _rightSwipeGesture = null; _upSwipeGesture = null; _downSwipeGesture = null; } base.Dispose(disposing); } protected virtual void ResetSwipeGestureRecognizer(UISwipeGestureRecognizer swipeGestureRecognizer, bool isForceRemove = false) { RemoveGestureRecognizer(swipeGestureRecognizer); if (isForceRemove) { return; } AddGestureRecognizer(swipeGestureRecognizer); } protected void SetSwipeGestures() { ResetSwipeGestureRecognizer(_leftSwipeGesture); ResetSwipeGestureRecognizer(_rightSwipeGesture); var shouldRemoveVerticalSwipes = !(Element?.IsVerticalSwipeEnabled ?? false); ResetSwipeGestureRecognizer(_upSwipeGesture, shouldRemoveVerticalSwipes); ResetSwipeGestureRecognizer(_downSwipeGesture, shouldRemoveVerticalSwipes); } private void OnSwiped(UISwipeGestureRecognizer gesture) { var swipeDirection = gesture.Direction == UISwipeGestureRecognizerDirection.Left ? ItemSwipeDirection.Left : gesture.Direction == UISwipeGestureRecognizerDirection.Right ? ItemSwipeDirection.Right : gesture.Direction == UISwipeGestureRecognizerDirection.Up ? ItemSwipeDirection.Up : ItemSwipeDirection.Down; Element?.OnSwiped(swipeDirection); } private bool ShouldBeRequiredToFailBy(UIGestureRecognizer gestureRecognizer, UIGestureRecognizer otherGestureRecognizer) => IsPanGestureHandled() && otherGestureRecognizer.View != this; private bool ShouldRecognizeSimultaneously(UIGestureRecognizer gestureRecognizer, UIGestureRecognizer otherGestureRecognizer) { if (!(gestureRecognizer is UIPanGestureRecognizer panGesture)) { return true; } var parent = Element?.Parent; while (parent != null) { if (parent is MasterDetailPage && (Element?.IsHorizontalOrientation ?? false)) { var velocity = panGesture.VelocityInView(this); return Abs(velocity.Y) > Abs(velocity.X); } parent = parent.Parent; } return !IsPanGestureHandled(); } private bool IsPanGestureHandled() => Abs(Element?.CurrentDiff ?? 0) >= Element?.MoveThresholdDistance; } }
37.866667
136
0.597007
[ "MIT" ]
Bhekinkosi12/CardView
PanCardView.iOS/CardsViewRenderer.cs
5,682
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Threading.Tasks; using Cnblogs.Droid.Model; namespace Cnblogs.Droid.Presenter { public interface IArticleCommentsPresenter { Task GetComment(AccessToken token, string blogApp, int id, int pageIndex = 1); void PostComment(AccessToken token, string blogApp, int id, string content); } }
24.5
86
0.764378
[ "Apache-2.0" ]
JoesWeek/Cnblogs
Cnblogs.Droid/Presenter/IArticleCommentsPresenter.cs
539
C#
namespace codessentials.CGM.Commands { /// <remarks> /// Class=0, ElementId=13 /// </remarks> public class BeginProtectionRegion : Command { public int RegionIndex { get; private set; } public BeginProtectionRegion(CgmFile container) : base(new CommandConstructorArguments(ClassCode.DelimiterElement, 13, container)) { } public BeginProtectionRegion(CgmFile container, int index) : this(container) { RegionIndex = index; } public override void ReadFromBinary(IBinaryReader reader) { RegionIndex = reader.ReadIndex(); } public override void WriteAsBinary(IBinaryWriter writer) { writer.WriteIndex(RegionIndex); } public override void WriteAsClearText(IClearTextWriter writer) { writer.WriteLine($" BEGPROTREGION {WriteIndex(RegionIndex)};"); } } }
26.405405
94
0.601842
[ "MIT" ]
twenzel/CGM
src/Commands/BeginProtectionRegion.cs
979
C#
namespace Bitbucket.Net.Models.Core.Projects { public enum LineTypes { Added, Removed, Context } }
13.6
45
0.566176
[ "MIT" ]
ADHUI/Bitbucket.Net
src/Bitbucket.Net/Models/Core/Projects/LineTypes.cs
138
C#
using System; #if V4 using Microsoft.Practices.ObjectBuilder2; using Microsoft.Practices.Unity; #else using Unity; using Unity.Resolution; #endif namespace Unity.Regression.Tests { public class ValidatingResolverFactory #if !NET45 : IResolverFactory<Type> #endif { private object _value; public ValidatingResolverFactory(object value) { _value = value; } public Type Type { get; private set; } public string Name { get; private set; } #if !NET45 public ResolveDelegate<TContext> GetResolver<TContext>(Type info) where TContext : IResolveContext { return (ref TContext context) => { Type = context.Type; Name = context.Name; return _value; }; } #endif } }
20.5
73
0.587689
[ "Apache-2.0" ]
unitycontainer/regression-tests
Test Data/ValidatingResolverFactory.cs
863
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("Website Tracker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Website Tracker")] [assembly: AssemblyCopyright("Copyright © 2019 AriK")] [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("786f7317-bfa1-4703-bf58-ae2f6b07478f")] // 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.2.5")] [assembly: AssemblyFileVersion("1.0.2.5")]
37.891892
84
0.748217
[ "MIT" ]
arikankainen/website-tracker-windows
WebsiteTracker/Properties/AssemblyInfo.cs
1,405
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Aspose" file="ApiTester.cs"> // Copyright (c) 2018-2019 Aspose Pty Ltd. All rights reserved. // </copyright> // <summary> // 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. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Aspose.Imaging.Cloud.Sdk.Test.Base { using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Linq; using Aspose.Imaging.Cloud.Sdk.Api; using Aspose.Imaging.Cloud.Sdk.Model; using Aspose.Imaging.Cloud.Sdk.Model.Requests; using Newtonsoft.Json; using NUnit.Framework; using Aspose.Imaging.Cloud.Sdk.Client; using System.Net; using System.Threading; /// <summary> /// Base class for API tester /// </summary> public abstract class ApiTester { #region Consts /// <summary> /// The server access file /// </summary> private const string ServerAccessFile = "serverAccess.json"; /// <summary> /// The API version /// </summary> private const string ApiVersion = "v3.0"; /// <summary> /// The base URL /// </summary> private const string BaseUrl = "http://api.aspose.cloud/"; /// <summary> /// The default storage /// </summary> protected const string DefaultStorage = "Imaging-CI"; #endregion #region Fields /// <summary> /// If any test failed /// </summary> protected static bool FailedAnyTest = false; /// <summary> /// The local test folder /// </summary> protected readonly string LocalTestFolder = Path.Combine(Assembly.GetExecutingAssembly().Location, "..\\..\\..\\..\\..\\..\\TestData\\"); /// <summary> /// The temporary folder /// </summary> protected string TempFolder; /// <summary> /// The input test files /// </summary> protected List<StorageFile> InputTestFiles; /// <summary> /// The basic input test files /// </summary> protected List<StorageFile> BasicInputTestFiles; /// <summary> /// The multipage input test files /// </summary> protected List<StorageFile> MultipageInputTestFiles; /// <summary> /// Aspose.Imaging API /// </summary> protected ImagingApi ImagingApi; /// <summary> /// The basic export formats /// </summary> protected readonly string[] BasicExportFormats = new string[] { "bmp", "gif", "jpg", "png", "psd", "tiff", "webp" }; #endregion #region Delegates /// <summary> /// Delegate that tests properties. /// </summary> /// <param name="originalProperties">The original properties.</param> /// <param name="resultProperties">The result properties.</param> /// <param name="resultStream">The result stream.</param> protected delegate void PropertiesTesterDelegate(ImagingResponse originalProperties, ImagingResponse resultProperties, Stream resultStream); /// <summary> /// Typical POST request delegate that accepts input image stream. /// </summary> /// <param name="inputStream">The input image stream.</param> /// <returns></returns> protected delegate Stream PostRequestInvokerDelegate(Stream inputStream, string outPath); #endregion #region Properties /// <summary> /// The cloud test folder prefix /// </summary> protected virtual string CloudTestFolderPrefix => "ImagingCloudTestDotNet"; /// <summary> /// Original test data folder /// </summary> protected virtual string OriginalDataFolder => "ImagingIntegrationTestData"; /// <summary> /// The default storage /// </summary> protected string TestStorage { get; private set; } /// <summary> /// Gets or sets a value indicating whether resulting images should be removed from cloud storage. /// </summary> /// <value> /// <c>true</c> if resulting images should be removed from cloud storage; otherwise, <c>false</c>. /// </value> public bool RemoveResult { get; set; } = true; #endregion #region Configuration [OneTimeSetUp] public virtual void InitFixture() { this.TempFolder = $"{this.CloudTestFolderPrefix}_{this.GetEnvironmentVariable("BUILD_NUMBER") ?? Environment.UserName}"; this.TestStorage = this.GetEnvironmentVariable("StorageName"); if (string.IsNullOrEmpty(this.TestStorage)) { WriteLineEverywhere("Storage name is not set by environment variable. Using the default one."); this.TestStorage = DefaultStorage; } this.CreateApiInstances(); if (!FailedAnyTest && this.RemoveResult && this.ImagingApi.ObjectExists(new ObjectExistsRequest(this.TempFolder, this.TestStorage)).Exists.Value) { this.ImagingApi.DeleteFolder(new DeleteFolderRequest(this.TempFolder, this.TestStorage, true)); this.ImagingApi.CreateFolder(new CreateFolderRequest(this.TempFolder, this.TestStorage)); } } [OneTimeTearDown] public virtual void FinalizeFixture() { if (!FailedAnyTest && this.RemoveResult && this.ImagingApi.ObjectExists(new ObjectExistsRequest(this.TempFolder, this.TestStorage)).Exists.Value) { this.ImagingApi.DeleteFolder(new DeleteFolderRequest(this.TempFolder, this.TestStorage, true)); } } #endregion #region Methods /// <summary> /// Creates the API instances using given access parameters. /// </summary> /// <exception cref="System.ArgumentException">Please, specify valid access data (AppKey, AppSid, Base URL)</exception> protected void CreateApiInstances() { WriteLineEverywhere("Trying to obtain configuration from environment variables."); string onPremiseString = this.GetEnvironmentVariable("OnPremise"); bool onPremise = !string.IsNullOrEmpty(onPremiseString) && bool.Parse(this.GetEnvironmentVariable("OnPremise")); string appKey = onPremise ? string.Empty : this.GetEnvironmentVariable("AppKey"); string appSid = onPremise ? string.Empty : this.GetEnvironmentVariable("AppSid"); string baseUrl = this.GetEnvironmentVariable("ApiEndpoint"); string apiVersion = this.GetEnvironmentVariable("ApiVersion"); if ((!onPremise && (string.IsNullOrEmpty(appKey) || string.IsNullOrEmpty(appSid))) || string.IsNullOrEmpty(baseUrl) || string.IsNullOrEmpty(apiVersion)) { WriteLineEverywhere("Access data isn't set completely by environment variables. " + "Filling unset data with default values."); } if (string.IsNullOrEmpty(apiVersion)) { apiVersion = ApiVersion; WriteLineEverywhere("Set default API version"); } string serverAccessPath = Path.Combine(LocalTestFolder, ServerAccessFile); FileInfo serverFileInfo = new FileInfo(serverAccessPath); if (serverFileInfo.Exists && serverFileInfo.Length > 0) { var accessData = JsonConvert.DeserializeObject<ServerAccessData>(File.ReadAllText(serverAccessPath)); if (string.IsNullOrEmpty(appKey) && !onPremise) { appKey = accessData.AppKey; WriteLineEverywhere("Set default App key"); } if (string.IsNullOrEmpty(appSid) && !onPremise) { appSid = accessData.AppSid; WriteLineEverywhere("Set default App SID"); } if (string.IsNullOrEmpty(baseUrl)) { baseUrl = accessData.BaseURL; WriteLineEverywhere("Set default base URL"); } } else if (!onPremise) { throw new ArgumentException("Please, specify valid access data (AppKey, AppSid, Base URL)"); } WriteLineEverywhere($"On-premise: {onPremise}"); WriteLineEverywhere($"App key: {appKey}"); WriteLineEverywhere($"App SID: {appSid}"); WriteLineEverywhere($"Storage: {this.TestStorage}"); WriteLineEverywhere($"Base URL: {baseUrl}"); WriteLineEverywhere($"API version: {apiVersion}"); this.ImagingApi = onPremise ? new ImagingApi(baseUrl, apiVersion, false) : new ImagingApi(appKey, appSid, baseUrl, apiVersion); InputTestFiles = this.FetchInputTestFilesInfo(); BasicInputTestFiles = InputTestFiles.Where(p => !p.Name.StartsWith("multipage_")).ToList(); MultipageInputTestFiles = InputTestFiles.Where(p => p.Name.StartsWith("multipage_")).ToList(); } /// <summary> /// Tests the typical GET request. /// </summary> /// <param name="testMethodName">Name of the test method.</param> /// <param name="parametersLine">The parameters line.</param> /// <param name="inputFileName">Name of the input file.</param> /// <param name="requestInvoker">The request invoker.</param> /// <param name="propertiesTester">The properties tester.</param> /// <param name="folder">The folder.</param> /// <param name="storage">The storage.</param> protected void TestGetRequest(string testMethodName, string parametersLine, string inputFileName, #if NET20 Newtonsoft.Json.Serialization.Func<Stream> requestInvoker, #else System.Func<Stream> requestInvoker, #endif PropertiesTesterDelegate propertiesTester, string folder, string storage = DefaultStorage) { this.TestRequest( testMethodName, false, parametersLine, inputFileName, null, () => this.ObtainGetResponse(requestInvoker), propertiesTester, folder, storage); } /// <summary> /// Execute test command /// </summary> /// <param name="testCommand">Test command</param> /// <param name="testMethodName">Test method name</param> /// <param name="parametersLine">Parameters line</param> /// <param name="inputFileName">Input file name</param> /// <param name="folder">Folder</param> /// <param name="storage">Storage</param> protected void ExecuteTestCommand( ITestCommand testCommand, string testMethodName, string parametersLine, string inputFileName, string folder, string storage = DefaultStorage) { WriteLineEverywhere(testMethodName); if (!CheckInputFileExists(inputFileName)) { throw new ArgumentException( $"Input file {inputFileName} doesn't exist in the specified storage folder: {folder}. Please, upload it first."); } if (!this.ImagingApi.ObjectExists(new ObjectExistsRequest(folder + "/" + inputFileName, storage)).Exists.Value) { this.ImagingApi.CopyFile( new CopyFileRequest(OriginalDataFolder + "/" + inputFileName, folder + "/" + inputFileName, storage, storage)); } bool passed = false; try { WriteLineEverywhere(parametersLine); InvokeRequestWithRetry(testCommand, 5); testCommand.AssertResponse(); passed = true; } catch (Exception ex) { FailedAnyTest = true; WriteLineEverywhere(ex.Message); throw; } finally { WriteLineEverywhere($"Test passed: {passed}"); } } private void InvokeRequestWithRetry(ITestCommand testCommand, int retryCount) { try { testCommand.InvokeRequest(); } catch (ApiException ex) { if(retryCount <= 1) { throw; } else { //if(ex.ErrorCode == (int)HttpStatusCode.BadGateway) //{ Thread.Sleep(3000); InvokeRequestWithRetry(testCommand, --retryCount); //} //throw; } } } /// <summary> /// Tests the typical PUT request. /// </summary> /// <param name="testMethodName">Name of the test method.</param> /// <param name="parametersLine">The parameters line.</param> /// <param name="inputFileName">Name of the input file.</param> /// <param name="requestInvoker">The request invoker.</param> /// <param name="propertiesTester">The properties tester.</param> /// <param name="folder">The folder.</param> /// <param name="storage">The storage.</param> protected void TestPutRequest(string testMethodName, string parametersLine, string inputFileName, #if NET20 Newtonsoft.Json.Serialization.Func<Stream> requestInvoker, #else System.Func<Stream> requestInvoker, #endif PropertiesTesterDelegate propertiesTester, string folder, string storage = DefaultStorage) { this.TestRequest(testMethodName, false, parametersLine, inputFileName, null, () => this.ObtainPutResponse(requestInvoker), propertiesTester, folder, storage); } /// <summary> /// Tests the typical POST request. /// </summary> /// <param name="testMethodName">Name of the test method.</param> /// <param name="saveResultToStorage">if set to <c>true</c> [save result to storage].</param> /// <param name="parametersLine">The parameters line.</param> /// <param name="inputFileName">Name of the input file.</param> /// <param name="resultFileName">Name of the result file.</param> /// <param name="requestInvoker">The request invoker.</param> /// <param name="propertiesTester">The properties tester.</param> /// <param name="folder">The folder.</param> /// <param name="storage">The storage.</param> protected void TestPostRequest(string testMethodName, bool saveResultToStorage, string parametersLine, string inputFileName, string resultFileName, PostRequestInvokerDelegate requestInvoker, PropertiesTesterDelegate propertiesTester, string folder, string storage = DefaultStorage) { this.TestRequest(testMethodName, saveResultToStorage, parametersLine, inputFileName, resultFileName, () => this.ObtainPostResponse(folder + "/" + inputFileName, saveResultToStorage ? $"{folder}/{resultFileName}" : null, storage, requestInvoker), propertiesTester, folder, storage); } /// <summary> /// Checks if input file exists. /// </summary> /// <param name="inputFileName">Name of the input file.</param> /// <returns></returns> protected bool CheckInputFileExists(string inputFileName) { foreach (StorageFile storageFileInfo in InputTestFiles) { if (storageFileInfo.Name == inputFileName) { return true; } } return false; } /// <summary> /// Gets the storage file information. /// </summary> /// <param name="folder">The folder which contains a file.</param> /// <param name="fileName">Name of the file.</param> /// <param name="storage">The storage.</param> /// <returns></returns> protected StorageFile GetStorageFileInfo(string folder, string fileName, string storage) { FilesList fileListResponse = this.ImagingApi.GetFilesList(new GetFilesListRequest(folder, storage)); foreach (StorageFile storageFileInfo in fileListResponse.Value) { if (storageFileInfo.Name == fileName) { return storageFileInfo; } } return null; } /// <summary> /// Fetches the input test files info. /// </summary> /// <returns></returns> private List<StorageFile> FetchInputTestFilesInfo() { var filesResponse = this.ImagingApi.GetFilesList( new GetFilesListRequest(OriginalDataFolder, this.TestStorage)); return filesResponse.Value; } /// <summary> /// Obtains the typical GET request response. /// </summary> /// <param name="requestInvoker">The request invoker.</param> private Stream ObtainGetResponse( #if NET20 Newtonsoft.Json.Serialization.Func<Stream> requestInvoker #else System.Func<Stream> requestInvoker #endif ) { var response = requestInvoker.Invoke(); Assert.NotNull(response); Assert.Greater(response.Length, 0); return response; } /// <summary> /// Obtains the typical PUT request response. /// </summary> /// <param name="requestInvoker">The request invoker.</param> private Stream ObtainPutResponse( #if NET20 Newtonsoft.Json.Serialization.Func<Stream> requestInvoker #else System.Func<Stream> requestInvoker #endif ) { var response = requestInvoker.Invoke(); Assert.NotNull(response); Assert.Greater(response.Length, 0); return response; } /// <summary> /// Obtains the typical POST request response. /// </summary> /// <param name="inputPath">The input path.</param> /// <param name="requestInvoker">The request invoker.</param> /// <param name="outPath">The output path to save the result.</param> /// <param name="storage">The storage.</param> private Stream ObtainPostResponse(string inputPath, string outPath, string storage, PostRequestInvokerDelegate requestInvoker) { using (Stream iStream = this.ImagingApi.DownloadFile(new DownloadFileRequest(inputPath, storage))) { var response = requestInvoker.Invoke(iStream, outPath); if (string.IsNullOrEmpty(outPath)) { Assert.NotNull(response); Assert.Greater(response.Length, 0); return response; } return null; } } /// <summary> /// Tests the typical request. /// </summary> /// <param name="testMethodName">Name of the test method.</param> /// <param name="saveResultToStorage">if set to <c>true</c> [save result to storage].</param> /// <param name="parametersLine">The parameters line.</param> /// <param name="inputFileName">Name of the input file.</param> /// <param name="resultFileName">Name of the result file.</param> /// <param name="invokeRequestAction">The invoke request action.</param> /// <param name="propertiesTester">The properties tester.</param> /// <param name="folder">The folder.</param> /// <param name="storage">The storage.</param> private void TestRequest(string testMethodName, bool saveResultToStorage, string parametersLine, string inputFileName, string resultFileName, #if NET20 Newtonsoft.Json.Serialization.Func<Stream> invokeRequestAction, #else System.Func<Stream> invokeRequestAction, #endif PropertiesTesterDelegate propertiesTester, string folder, string storage = DefaultStorage) { WriteLineEverywhere(testMethodName); CopyInputFileToTestFolder(inputFileName, folder, storage); bool passed = false; string outPath = null; try { WriteLineEverywhere(parametersLine); if (saveResultToStorage) { outPath = folder + "/" + resultFileName; // remove output file from the storage (if exists) if (this.ImagingApi.ObjectExists(new ObjectExistsRequest(outPath, storage)).Exists.Value) { this.ImagingApi.DeleteFile(new DeleteFileRequest(outPath, storage)); } } ImagingResponse resultProperties = null; using (Stream response = invokeRequestAction.Invoke()) { if (saveResultToStorage) { StorageFile resultInfo = this.GetStorageFileInfo(folder, resultFileName, storage); if (resultInfo == null) { throw new ArgumentException( $"Result file {resultFileName} doesn't exist in the specified storage folder: {folder}. " + $"Result isn't present in the storage by an unknown reason."); } if (!resultFileName.EndsWith(".pdf")) { resultProperties = this.ImagingApi.GetImageProperties( new GetImagePropertiesRequest(resultFileName, folder, storage)); Assert.NotNull(resultProperties); } } else { if (!FileIsPdf(response)) { resultProperties = this.ImagingApi.ExtractImageProperties(new ExtractImagePropertiesRequest(response)); Assert.NotNull(resultProperties); } } ImagingResponse originalProperties = this.ImagingApi.GetImageProperties(new GetImagePropertiesRequest(inputFileName, folder, storage)); Assert.NotNull(originalProperties); if (resultProperties != null) { propertiesTester?.Invoke(originalProperties, resultProperties, response); } } passed = true; } catch (Exception ex) { FailedAnyTest = true; WriteLineEverywhere(ex.Message); throw; } finally { if (passed && saveResultToStorage && this.RemoveResult && this.ImagingApi.ObjectExists( new ObjectExistsRequest(outPath, storage)).Exists.Value) { this.ImagingApi.DeleteFile(new DeleteFileRequest(outPath, storage)); } WriteLineEverywhere($"Test passed: {passed}"); } } /// <summary> /// Copies original input file to test folder /// </summary> /// <param name="inputFileName">The original input file</param> /// <param name="folder">The folder</param> /// <param name="storage">The storage</param> protected void CopyInputFileToTestFolder(string inputFileName, string folder, string storage) { if (!CheckInputFileExists(inputFileName)) { throw new ArgumentException( $"Input file {inputFileName} doesn't exist in the specified storage folder: {folder}. Please, upload it first."); } if (!this.ImagingApi.ObjectExists(new ObjectExistsRequest(folder + "/" + inputFileName, storage)).Exists.GetValueOrDefault(false)) { this.ImagingApi.CopyFile( new CopyFileRequest(OriginalDataFolder + "/" + inputFileName, folder + "/" + inputFileName, storage, storage)); } } /// <summary> /// Writes the line everywhere to support different use-cases. /// </summary> /// <param name="line">The line.</param> protected void WriteLineEverywhere(string line) { Console.WriteLine(line); TestContext.WriteLine(line); TestContext.Progress.WriteLine(line); } /// <summary> /// Returns environment variable value /// </summary> /// <param name="variableName"></param> /// <returns>Environment variable value</returns> private string GetEnvironmentVariable(string variableName) { return (Environment.GetEnvironmentVariable(variableName, EnvironmentVariableTarget.Process) ?? Environment.GetEnvironmentVariable(variableName, EnvironmentVariableTarget.User)) ?? Environment.GetEnvironmentVariable(variableName, EnvironmentVariableTarget.Machine); } /// <summary> /// Checks that stream represents PDF file /// </summary> /// <param name="file">The file stream</param> /// <returns><c>true</c> - if file is a PDF, <c>false</c> otherwise</returns> /// <exception cref="ArgumentNullException"><paramref name="file"/> is null</exception> private bool FileIsPdf(Stream file) { if(file == null) throw new ArgumentNullException(nameof(file)); var buffer = new byte[5]; var originalPosition = file.Position; file.Seek(0, SeekOrigin.Begin); file.Read(buffer, 0, 5); file.Seek(originalPosition, SeekOrigin.Begin); // That's the direct magic bytes check return buffer[0] == 0x25 && buffer[1] == 0x50 && buffer[2] == 0x44 && buffer[3] == 0x46 && buffer[4] == 0x2d; } #endregion } }
39.213205
160
0.560299
[ "MIT" ]
JTOne123/aspose-imaging-cloud-dotnet
src/Aspose.Imaging.Cloud.Sdk.Test/Base/ApiTester.cs
28,508
C#
 namespace ExampleApplication.Worker { internal class WorkerImpl : IWorker { public void DoWork() { } } }
13.916667
40
0.473054
[ "MIT" ]
ColmBhandal/ExcelQuery
ExampleApplication/Worker/WorkerImpl.cs
169
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Twilio; using Twilio.Rest.Api.V2010.Account; using Twilio.Types; namespace MatthiWare.SmsAndCallClient.Api { public class TwilioWrapperClient : IClient { /// <summary> /// the authentication items /// </summary> private readonly string m_sid, m_auth; public TwilioWrapperClient(string sid, string auth) { m_sid = sid; m_auth = auth; } public bool CanCall { get { return true; } } public bool CanSendSms { get { return true; } } public bool FromNumberRequired { get { return true; } } public bool IsInitialized { get; set; } public void Init() { TwilioClient.Init(m_sid, m_auth); IsInitialized = true; } public async Task<IResponse> CallAsync(string from, string to, string msg) { var pnFrom = new PhoneNumber(from); var pnTo = new PhoneNumber(to); var body = WebUtility.UrlEncode(msg); var call = await CallResource.CreateAsync( pnTo, pnFrom, url: new Uri($"https://handler.twilio.com/twiml/EH551ae48b51b996d131ebe9a19372ad6f?body={body}")); return new CallResponse(call); } public async Task<IResponse> SendSmsAsync(string form, string to, string msg) { var pnFrom = new PhoneNumber(form); var pnTo = new PhoneNumber(to); var text = await MessageResource.CreateAsync( pnTo, from: pnFrom, body: msg); return new TextResponse(text); } public override string ToString() { return "Twilio API"; } public class CallResponse : IResponse { private string m_sid; public bool CanUpdate { get { return true; } } public string Status { get; set; } public CallResponse(CallResource call) { SetCall(call); } private void SetCall(CallResource call) { m_sid = call.Sid; Status = call.Status.ToString(); } public async Task UpdateAsync() { var call = await CallResource.FetchAsync(m_sid); SetCall(call); } } public class TextResponse : IResponse { private string m_sid; public bool CanUpdate { get { return true; } } public string Status { get; set; } public TextResponse(MessageResource call) { SetMessage(call); } private void SetMessage(MessageResource call) { m_sid = call.Sid; Status = call.Status.ToString(); } public async Task UpdateAsync() { var call = await MessageResource.FetchAsync(m_sid); SetMessage(call); } } } }
25.304688
114
0.524853
[ "MIT" ]
MatthiWare/SmsAndCall
SmsAndCallClient/SmsAndCallClient/Api/TwilioWrapperClient.cs
3,241
C#
namespace CakesWebApp.Services.Contracts { using System.Collections.Generic; using InputModels.Product; using ViewModels.Product; public interface IProductService { void Create(AddProductInputModel model); ICollection<ProductViewModel> All(string searchTerm = null); ICollection<ProductShowViewModel> ShowAll(); ProductDetailsViewModel Find(int id); bool Exists(int id); ICollection<ProductViewModel> FindProductsInCart(IEnumerable<int> ids); } }
22.913043
79
0.70778
[ "Apache-2.0" ]
genadi60/SISWebServer
SIS/SIS.Apps/Cakes/CakesWebApp/Services/Contracts/IProductService.cs
529
C#
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2015, MPL Ali Taheri Moghaddar ali.taheri.m@gmail.com */ using System; using System.Collections.Generic; using System.Linq; namespace Pablo.Graphics { /// <summary> /// Displays a block described by a <see cref="GeometryGroup"/>. /// </summary> public sealed class Block : Shape<GeometryGroup> { /// <summary> /// Gets the geometries describing this <see cref="Block"/>. /// </summary> public IEnumerable<Geometry> Geometries => Geometry.Geometries; /// <summary> /// Initializes a new instance of <see cref="Block"/>. /// </summary> public Block() { } /// <summary> /// Initializes a new instance of <see cref="Block"/> with the provided geometries. /// </summary> /// <exception cref="ArgumentNullException">geometries is null</exception> public Block(IEnumerable<Geometry> geometries) { if (geometries == null) throw new ArgumentNullException(nameof(geometries)); Geometry = new GeometryGroup { Geometries = geometries, IsReadOnly = true, }; } /// <summary> /// Initializes a new instance of <see cref="Block"/> with the provided geometries. /// </summary> /// <exception cref="ArgumentNullException">geometries is null</exception> public Block(params Geometry[] geometries) : this(geometries.AsEnumerable()) { } } }
32.357143
92
0.572296
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
pabloengine/pablo
Pablo/Graphics/Shape/Block.cs
1,814
C#
using System; namespace Automation.Concord { public enum DeviceStatus : int { Ok = 0, Failed = 1, Undocumented_7 = 7, Undocumented_33, Undocumented_158 = 158, Undocumented_216 = 216 } }
15.75
34
0.555556
[ "MIT" ]
markberndt/concord2mqtt
Concord/Enums/DeviceStatus.cs
254
C#
using System.Web.Mvc; namespace CmsShop.Areas.Admin { public class AdminAreaRegistration : AreaRegistration { public override string AreaName { get { return "Admin"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Admin_default", "Admin/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } } }
23.416667
75
0.498221
[ "MIT" ]
zbikowskiL/CmsShop
CmsShop/Areas/Admin/AdminAreaRegistration.cs
564
C#
namespace Instagraph.DataProcessor.DTOs { public class PictureImportDto { public string Path { get; set; } public decimal Size { get; set; } } }
17.5
41
0.617143
[ "MIT" ]
IvelinMarinov/SoftUni
08. Database Advanced - EF Core/10. Exam Preparation 1/10. DB-Advanced-EF-Core-Exam-Preparation-1-Instagraph-Skeleton/Instagraph.DataProcessor/DTOs/PictureImportDto.cs
177
C#
namespace ClearHl7.Codes.V230 { /// <summary> /// HL7 Version 2 Table 0200 - Name Type. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0200</remarks> public enum CodeNameType { /// <summary> /// A - Assigned. /// </summary> Assigned, /// <summary> /// C - Adopted Name. /// </summary> AdoptedName, /// <summary> /// D - Customary Name. /// </summary> CustomaryName, /// <summary> /// L - Official Registry Name. /// </summary> OfficialRegistryName, /// <summary> /// M - Maiden Name. /// </summary> MaidenName, /// <summary> /// O - Other. /// </summary> Other } }
21.512821
59
0.419547
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7.Codes/V230/CodeNameType.cs
841
C#
using System; using System.Threading.Tasks; namespace Admin.Core.Common.Cache { /// <summary> /// 缓存接口 /// </summary> public interface ICache { /// <summary> /// 用于在 key 存在时删除 key /// </summary> /// <param name="key">键</param> long Del(params string[] key); /// <summary> /// 用于在 key 存在时删除 key /// </summary> /// <param name="key">键</param> /// <returns></returns> Task<long> DelAsync(params string[] key); /// <summary> /// 用于在 key 模板存在时删除 /// </summary> /// <param name="pattern">key模板</param> /// <returns></returns> Task<long> DelByPatternAsync(string pattern); /// <summary> /// 检查给定 key 是否存在 /// </summary> /// <param name="key">键</param> /// <returns></returns> bool Exists(string key); /// <summary> /// 检查给定 key 是否存在 /// </summary> /// <param name="key">键</param> /// <returns></returns> Task<bool> ExistsAsync(string key); /// <summary> /// 获取指定 key 的值 /// </summary> /// <param name="key">键</param> /// <returns></returns> string Get(string key); /// <summary> /// 获取指定 key 的值 /// </summary> /// <typeparam name="T">数据类型</typeparam> /// <param name="key">键</param> /// <returns></returns> T Get<T>(string key); /// <summary> /// 获取指定 key 的值 /// </summary> /// <param name="key">键</param> /// <returns></returns> Task<string> GetAsync(string key); /// <summary> /// 获取指定 key 的值 /// </summary> /// <typeparam name="T">数据类型</typeparam> /// <param name="key">键</param> /// <returns></returns> Task<T> GetAsync<T>(string key); /// <summary> /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> bool Set(string key, object value); /// <summary> /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expire">有效期</param> bool Set(string key, object value, TimeSpan expire); /// <summary> /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <returns></returns> Task<bool> SetAsync(string key, object value); /// <summary> /// 设置指定 key 的值,所有写入参数object都支持string | byte[] | 数值 | 对象 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expire">有效期</param> /// <returns></returns> Task<bool> SetAsync(string key, object value, TimeSpan expire); /// <summary> /// 获取或设置缓存 /// </summary> /// <typeparam name="T">数据类型</typeparam> /// <param name="key">键</param> /// <param name="func">获取数据的方法</param> /// <param name="expire">有效期</param> /// <returns></returns> Task<T> GetOrSetAsync<T>(string key, Func<Task<T>> func, TimeSpan? expire = null); } }
29.384615
90
0.482839
[ "MIT" ]
Twtcer/Admin.Core
Admin.Core.Common/Cache/ICache.cs
3,848
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 s3control-2018-08-20.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.S3Control.Model { /// <summary> /// This is the response object from the GetAccessPoint operation. /// </summary> public partial class GetAccessPointResponse : AmazonWebServiceResponse { private string _bucket; private DateTime? _creationDate; private string _name; private NetworkOrigin _networkOrigin; private PublicAccessBlockConfiguration _publicAccessBlockConfiguration; private VpcConfiguration _vpcConfiguration; /// <summary> /// Gets and sets the property Bucket. /// <para> /// The name of the bucket associated with the specified access point. /// </para> /// </summary> [AWSProperty(Min=3, Max=255)] public string Bucket { get { return this._bucket; } set { this._bucket = value; } } // Check to see if Bucket property is set internal bool IsSetBucket() { return this._bucket != null; } /// <summary> /// Gets and sets the property CreationDate. /// <para> /// The date and time when the specified access point was created. /// </para> /// </summary> public DateTime CreationDate { get { return this._creationDate.GetValueOrDefault(); } set { this._creationDate = value; } } // Check to see if CreationDate property is set internal bool IsSetCreationDate() { return this._creationDate.HasValue; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the specified access point. /// </para> /// </summary> [AWSProperty(Min=3, Max=50)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property NetworkOrigin. /// <para> /// Indicates whether this access point allows access from the public internet. If <code>VpcConfiguration</code> /// is specified for this access point, then <code>NetworkOrigin</code> is <code>VPC</code>, /// and the access point doesn't allow access from the public internet. Otherwise, <code>NetworkOrigin</code> /// is <code>Internet</code>, and the access point allows access from the public internet, /// subject to the access point and bucket access policies. /// </para> /// /// <para> /// This will always be true for an Amazon S3 on Outposts access point /// </para> /// </summary> public NetworkOrigin NetworkOrigin { get { return this._networkOrigin; } set { this._networkOrigin = value; } } // Check to see if NetworkOrigin property is set internal bool IsSetNetworkOrigin() { return this._networkOrigin != null; } /// <summary> /// Gets and sets the property PublicAccessBlockConfiguration. /// </summary> public PublicAccessBlockConfiguration PublicAccessBlockConfiguration { get { return this._publicAccessBlockConfiguration; } set { this._publicAccessBlockConfiguration = value; } } // Check to see if PublicAccessBlockConfiguration property is set internal bool IsSetPublicAccessBlockConfiguration() { return this._publicAccessBlockConfiguration != null; } /// <summary> /// Gets and sets the property VpcConfiguration. /// <para> /// Contains the virtual private cloud (VPC) configuration for the specified access point. /// </para> /// </summary> public VpcConfiguration VpcConfiguration { get { return this._vpcConfiguration; } set { this._vpcConfiguration = value; } } // Check to see if VpcConfiguration property is set internal bool IsSetVpcConfiguration() { return this._vpcConfiguration != null; } } }
33.90566
121
0.585791
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/S3Control/Generated/Model/GetAccessPointResponse.cs
5,391
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.AzureStack.Commands.StorageAdmin { class Nouns { public const string Prefix = "ACS"; public const string Metric = "Metric"; public const string MetricDefinition = "MetricDefinition"; // farm public const string AdminFarm = Prefix + "Farm"; public const string AdminFarmMetric = AdminFarm + Metric; public const string AdminFarmMetricDefinition = AdminFarm + MetricDefinition; public const string AdminFarmEvent = Prefix + "Event"; public const string AdminFarmEventQuery = Prefix + "EventQuery"; // LogCollect public const string Log = Prefix + "Log"; // node public const string AdminNode = Prefix + "Node"; public const string AdminNodeMetric = AdminNode + Metric; public const string AdminNodeMetricDefinition = AdminNode + MetricDefinition; // blob server role instance public const string AdminBlobServerRoleInstance = Prefix + "BlobServerRoleInstance"; // role instance public const string AdminRoleInstance = Prefix + "RoleInstance"; // role instance public const string AdminRoleInstanceSettingsPullNow = Prefix + "RoleInstancePullSettings"; public const string AdminRoleInstanceMetric = AdminRoleInstance + Metric; public const string AdminRoleInstanceMetricDefinition = AdminRoleInstance + MetricDefinition; // service public const string AdminTableService = Prefix + "TableService"; public const string AdminBlobService = Prefix + "BlobService"; public const string AdminManagementService = Prefix + "ManagementService"; public const string AdminTableServiceMetric = AdminTableService + Metric; public const string AdminTableServiceMetricDefinition = AdminTableService + MetricDefinition; public const string AdminBlobServiceMetric = AdminBlobService + Metric; public const string AdminBlobServiceMetricDefinition = AdminBlobService + MetricDefinition; public const string AdminManagementServiceMetric = AdminManagementService + Metric; public const string AdminManagementServiceMetricDefinition = AdminManagementService + MetricDefinition; // share public const string AdminShare = Prefix + "Share"; public const string AdminShareMetric = AdminShare + Metric; public const string AdminShareMetricDefinition = AdminShare + MetricDefinition; // fault public const string AdminFault = Prefix + "Fault"; // role instance public const string AdminInstance = Prefix + "Instance"; // storage account public const string AdminStorageAccount = Prefix + "StorageAccount"; // storage account deletion operation public const string AdminStorageAccountDeletion = Prefix + "StorageAccountDeletion"; } }
40.12766
112
0.663043
[ "MIT" ]
Peter-Schneider/azure-powershell
src/ResourceManager/AzureStackStorage/Commands.AzureStackStorage/Nouns.cs
3,679
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using SFA.DAS.Payments.Application.Infrastructure.Logging; using SFA.DAS.Payments.Application.Infrastructure.Telemetry; using SFA.DAS.Payments.Monitoring.Jobs.Messages.Commands; using SFA.DAS.Payments.Monitoring.Jobs.Model; namespace SFA.DAS.Payments.Monitoring.Jobs.Application.JobProcessing { public interface ICommonJobService { Task RecordNewJobAdditionalMessages(RecordJobAdditionalMessages jobRequest, CancellationToken cancellationToken); } public class JobService : ICommonJobService { protected IPaymentLogger Logger { get; } protected IJobStorageService JobStorageService { get; } protected ITelemetry Telemetry { get; } public JobService(IPaymentLogger logger, IJobStorageService jobStorageService, ITelemetry telemetry) { this.Logger = logger ?? throw new ArgumentNullException(nameof(logger)); this.JobStorageService = jobStorageService ?? throw new ArgumentNullException(nameof(jobStorageService)); this.Telemetry = telemetry ?? throw new ArgumentNullException(nameof(telemetry)); } protected virtual async Task RecordNewJob(JobModel jobDetails, List<GeneratedMessage> generatedMessages, CancellationToken cancellationToken = default(CancellationToken)) { if (!jobDetails.DcJobId.HasValue) throw new InvalidOperationException("No DcJob Id found on the job."); var isNewJob = await JobStorageService.StoreNewJob(jobDetails, CancellationToken.None); Logger.LogDebug($"Finished storing new job: {jobDetails.Id} for dc job id: {jobDetails.DcJobId}. Now storing the job messages."); await RecordJobInProgressMessages(jobDetails.DcJobId.Value, generatedMessages, cancellationToken).ConfigureAwait(false); Logger.LogDebug($"Finished storing new job messages for job: {jobDetails.Id} for dc job id: {jobDetails.DcJobId}."); if (isNewJob) SendTelemetry(jobDetails); Logger.LogInfo($"Finished saving the job info. DC Job Id: {jobDetails.DcJobId}"); } public async Task RecordNewJobAdditionalMessages(RecordJobAdditionalMessages jobRequest, CancellationToken cancellationToken) { await RecordJobInProgressMessages(jobRequest.JobId, jobRequest.GeneratedMessages, cancellationToken).ConfigureAwait(false); Logger.LogInfo($"Finished storing new job messages for job: {jobRequest.JobId}"); } protected async Task RecordJobInProgressMessages(long jobId, List<GeneratedMessage> generatedMessages, CancellationToken cancellationToken) { await JobStorageService.StoreInProgressMessages(jobId, generatedMessages.Select(message => new InProgressMessage { MessageId = message.MessageId, JobId = jobId, MessageName = message.MessageName }).ToList(), cancellationToken); } private void SendTelemetry(JobModel jobDetails) { Telemetry.TrackEvent("Started Job", new Dictionary<string, string> { { TelemetryKeys.JobType, jobDetails.JobType.ToString("G") }, { TelemetryKeys.Ukprn, (jobDetails.Ukprn ?? 0).ToString() }, { TelemetryKeys.InternalJobId , jobDetails.Id.ToString() }, { TelemetryKeys.JobId, jobDetails.DcJobId.ToString() }, { TelemetryKeys.CollectionPeriod , jobDetails.CollectionPeriod.ToString() }, { TelemetryKeys.AcademicYear , jobDetails.AcademicYear.ToString() } }, new Dictionary<string, double> { { "LearnerCount", jobDetails.LearnerCount ?? 0 } } ); } } }
49.7
178
0.675553
[ "MIT" ]
PJChamley/das-payments-V2
src/SFA.DAS.Payments.Monitoring.Jobs.Application/JobProcessing/JobService.cs
3,978
C#
using System; using System.IO; namespace Kentico.KInspector.Core { public class InstanceInfo { private Lazy<DatabaseService> dbService; private Lazy<Version> version; private Lazy<Uri> uri; private Lazy<DirectoryInfo> directory; /// <summary> /// URI of the application instance /// </summary> public Uri Uri { get { return uri.Value; } } /// <summary> /// Directory of the application instance /// </summary> public DirectoryInfo Directory { get { return directory.Value; } } /// <summary> /// Version of the intance based on the database setting key. /// </summary> public Version Version { get { return version.Value; } } /// <summary> /// Configuration with instance information. /// </summary> public InstanceConfig Config { get; private set; } /// <summary> /// Database service to communicate with the instance database. /// </summary> public DatabaseService DBService { get { return dbService.Value; } } /// <summary> /// Creates instance information based on configuration. /// </summary> /// <param name="config">Instance configuration</param> public InstanceInfo(InstanceConfig config) { if (config == null) { throw new ArgumentNullException("version"); } Config = config; dbService = new Lazy<DatabaseService>(() => new DatabaseService(Config)); version = new Lazy<Version>(() => GetKenticoVersion()); // Ensure backslash to the Config.Url to support VirtualPath URLs. // Sometimes the website is running under virtual path and // the URL looks like this http://localhost/kentico8 // Some modules (RobotsTxtModule, CacheItemsModle, ...) try // to append the relative path to the base URL but // without trailing slash, the relative path is replaced. // E.g.: // var uri = new Uri("http://localhost/kentico8"); // new Uri(uri, "robots.txt"); -> http://localhost/robots.txt // // With trailing slash, the relative path is appended as expected. // var uri = new Uri("http://localhost/kentico8/"); // new Uri(uri, "robots.txt"); -> http://localhost/kentico8/robots.txt uri = new Lazy<Uri>(() => new Uri(Config.Url.EndsWith("/") ? Config.Url : Config.Url + "/")); directory = new Lazy<DirectoryInfo>(() => new DirectoryInfo(Config.Path)); } /// <summary> /// Gets the version of Kentico. /// </summary> private Version GetKenticoVersion() { string version = DBService.ExecuteAndGetScalar<string>("SELECT KeyValue FROM CMS_SettingsKey WHERE KeyName = 'CMSDBVersion'"); return new Version(version); } } }
29.6875
138
0.521805
[ "MIT" ]
ezimaxtechnologies/KenticoInspector
KInspector.Core/InstanceInfo.cs
3,327
C#
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class EnemyDesignerWindow : EditorWindow { Texture2D headerSectionTexture; Texture2D mageSectionTexture; Texture2D warriorSectionTexture; Texture2D rogueSectionTexture; Texture2D mageTexture; Texture2D warriorTexture; Texture2D rogueTexture; Color headerSectionColor = new Color(13f / 255f, 32f / 255f, 44f / 255f, 1f); Rect headerSection; Rect mageSection; Rect warriorSection; Rect rogueSection; Rect mageIconSection; Rect warriorIconSection; Rect rogueIconSection; GUISkin skin; static MageData mageData; static WarriorData warriorData; static RogueData rogueData; public static MageData MageInfo { get { return mageData; } } public static WarriorData WarriorInfo { get { return warriorData; } } public static RogueData RogueInfo { get { return rogueData; } } float iconSize = 80; [MenuItem("My Tools/Enemy Designer")] static void OpenWindow() { EnemyDesignerWindow window = (EnemyDesignerWindow)GetWindow(typeof(EnemyDesignerWindow)); window.minSize = new Vector2(600, 300); window.Show(); } //Similar to Start() / Awake() void OnEnable() { InitTextures(); InitData(); skin = Resources.Load<GUISkin>("GUI Styles/EnemyDesignerSkin"); } public static void InitData() { mageData = (MageData)ScriptableObject.CreateInstance(typeof(MageData)); warriorData = (WarriorData)ScriptableObject.CreateInstance(typeof(WarriorData)); rogueData = (RogueData)ScriptableObject.CreateInstance(typeof(RogueData)); } //Initialize Texture2D values void InitTextures() { headerSectionTexture = new Texture2D(1, 1); headerSectionTexture.SetPixel(0, 0, headerSectionColor); headerSectionTexture.Apply(); mageSectionTexture = Resources.Load<Texture2D>("Icons/editor_mage_gradient"); warriorSectionTexture = Resources.Load<Texture2D>("Icons/editor_warrior_gradient"); rogueSectionTexture = Resources.Load<Texture2D>("Icons/editor_rogue_gradient"); mageTexture = Resources.Load<Texture2D>("Icons/editor_mage_icon"); warriorTexture = Resources.Load<Texture2D>("Icons/editor_warrior_icon"); rogueTexture = Resources.Load<Texture2D>("Icons/editor_rogue_icon"); } //Similar to Update function, Not called once per frame. Called 1 or more times per interaction void OnGUI() { DrawLayouts(); DrawHeader(); DrawMageSettings(); DrawWarriorSettings(); DrawRogueSettings(); } //Defines Rect Values and paint textures void DrawLayouts() { headerSection.x = 0; headerSection.y = 0; headerSection.width = Screen.width; headerSection.height = 50; mageSection.x = 0; mageSection.y = 50; mageSection.width = Screen.width / 3f; mageSection.height = Screen.width - 50f; mageIconSection.x = (mageSection.x + mageSection.width / 2f) - iconSize / 2; mageIconSection.y = mageSection.y + 8; mageIconSection.width = iconSize; mageIconSection.height = iconSize; warriorSection.x = Screen.width / 3f; warriorSection.y = 50; warriorSection.width = Screen.width / 3f; warriorSection.height = Screen.width - 50f; warriorIconSection.x = (warriorSection.x + warriorSection.width / 2f) - iconSize / 2; warriorIconSection.y = warriorSection.y + 8; warriorIconSection.width = iconSize; warriorIconSection.height = iconSize; rogueSection.x = (Screen.width / 3f) * 2; rogueSection.y = 50; rogueSection.width = Screen.width / 3f; rogueSection.height = Screen.width - 50f; rogueIconSection.x = (rogueSection.x + rogueSection.width / 2f) - iconSize / 2; rogueIconSection.y = rogueSection.y + 8; rogueIconSection.width = iconSize; rogueIconSection.height = iconSize; GUI.DrawTexture(headerSection, headerSectionTexture); GUI.DrawTexture(mageSection, mageSectionTexture); GUI.DrawTexture(warriorSection, warriorSectionTexture); GUI.DrawTexture(rogueSection, rogueSectionTexture); GUI.DrawTexture(mageIconSection, mageTexture); GUI.DrawTexture(warriorIconSection, warriorTexture); GUI.DrawTexture(rogueIconSection, rogueTexture); } //Draw contents of header void DrawHeader() { GUILayout.BeginArea(headerSection); //Every begin needs an end just like using "{}" GUILayout.Label("Enemy Class Creator", skin.GetStyle("Header1")); GUILayout.EndArea(); } //Draw contents of mage region void DrawMageSettings() { GUILayout.BeginArea(mageSection); //Every begin needs an end just like using "{}" GUILayout.Space(iconSize + 8); GUILayout.Label("Mage", skin.GetStyle("MageHeader")); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Damage", skin.GetStyle("MageField")); mageData.dmgType = (Types.MageDmgType)EditorGUILayout.EnumPopup(mageData.dmgType); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Weapon", skin.GetStyle("MageField")); mageData.wpnType = (Types.MageWpnType)EditorGUILayout.EnumPopup(mageData.wpnType); EditorGUILayout.EndHorizontal(); if (GUILayout.Button("Create! ", GUILayout.Height(40))) { GeneralSettings.OpenWindow(GeneralSettings.SettingsType.MAGE); } GUILayout.EndArea(); } //Draw contents of warrior region void DrawWarriorSettings() { GUILayout.BeginArea(warriorSection); //Every begin needs an end just like using "{}" GUILayout.Space(iconSize + 8); GUILayout.Label("Warrior", skin.GetStyle("MageHeader")); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Damage", skin.GetStyle("MageField")); warriorData.classType = (Types.WarriorClassType)EditorGUILayout.EnumPopup(warriorData.classType); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Weapon", skin.GetStyle("MageField")); warriorData.wpnType = (Types.WarriorWpnType)EditorGUILayout.EnumPopup(warriorData.wpnType); EditorGUILayout.EndHorizontal(); if (GUILayout.Button("Create! ", GUILayout.Height(40))) { GeneralSettings.OpenWindow(GeneralSettings.SettingsType.WARRIOR); } GUILayout.EndArea(); } //Draw contents of rogue region void DrawRogueSettings() { GUILayout.BeginArea(rogueSection); //Every begin needs an end just like using "{}" GUILayout.Space(iconSize + 8); GUILayout.Label("Rogue", skin.GetStyle("MageHeader")); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Damage", skin.GetStyle("MageField")); rogueData.strategyType = (Types.RogueStrategyType)EditorGUILayout.EnumPopup(rogueData.strategyType); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Weapon", skin.GetStyle("MageField")); rogueData.wpnType = (Types.RogueWpnType)EditorGUILayout.EnumPopup(rogueData.wpnType); EditorGUILayout.EndHorizontal(); // GUILayout.FlexibleSpace(); if (GUILayout.Button("Create! ", GUILayout.Height(40))) { GeneralSettings.OpenWindow(GeneralSettings.SettingsType.ROGUE); } GUILayout.EndArea(); } } public class GeneralSettings : EditorWindow { public enum SettingsType { MAGE, WARRIOR, ROGUE } static SettingsType dataSetting; static GeneralSettings window; public static void OpenWindow(SettingsType setting) { dataSetting = setting; window = (GeneralSettings)GetWindow(typeof(GeneralSettings)); window.minSize = new Vector2(250, 200); window.Show(); } void OnGUI() { switch (dataSetting) { case SettingsType.MAGE: DrawSettings((CharacterData)EnemyDesignerWindow.MageInfo); break; case SettingsType.WARRIOR: DrawSettings((CharacterData)EnemyDesignerWindow.WarriorInfo); break; case SettingsType.ROGUE: DrawSettings((CharacterData)EnemyDesignerWindow.RogueInfo); break; } } void DrawSettings(CharacterData charData) { EditorGUILayout.BeginHorizontal(); GUILayout.Label("Prefab"); charData.prefab = (GameObject)EditorGUILayout.ObjectField(charData.prefab, typeof(GameObject), false); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Name"); charData.name = EditorGUILayout.TextField(charData.name); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Max Health"); charData.maxHealth = EditorGUILayout.FloatField(charData.maxHealth); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Max Energy"); charData.maxEnergy = EditorGUILayout.FloatField(charData.maxEnergy); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Power"); charData.power = EditorGUILayout.Slider(charData.power, 0, 100); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("% Crit Chance"); charData.critChance = EditorGUILayout.Slider(charData.critChance, 0, charData.power); EditorGUILayout.EndHorizontal(); if (charData.prefab == null) { EditorGUILayout.HelpBox("This enemy needs a [Prefab] before it can be created.", MessageType.Warning); } else if (charData.name == null || charData.name.Length < 1) { EditorGUILayout.HelpBox("This enemy needs a [Name] before it can be created.", MessageType.Warning); } else if (GUILayout.Button("Finish and Save", GUILayout.Height(30))) { SaveCharacterData(); window.Close(); } } void SaveCharacterData() { string prefabPath; //path to base prefab string newPrefabPath = "Assets/Prefabs/Characters/"; string dataPath = "Assets/Resources/Character Data/data/"; switch (dataSetting) { case SettingsType.MAGE: //Create the .asset file dataPath += "Mage/" + EnemyDesignerWindow.MageInfo.name + ".asset"; AssetDatabase.CreateAsset(EnemyDesignerWindow.MageInfo, dataPath); newPrefabPath += "Mage/" + EnemyDesignerWindow.MageInfo.name + ".prefab"; //get prefab path prefabPath = AssetDatabase.GetAssetPath(EnemyDesignerWindow.MageInfo.prefab); AssetDatabase.CopyAsset(prefabPath, newPrefabPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); GameObject magePrefab = (GameObject)AssetDatabase.LoadAssetAtPath(newPrefabPath, typeof(GameObject)); if (!magePrefab.GetComponent<Mage>()) { magePrefab.AddComponent(typeof(Mage)); } magePrefab.GetComponent<Mage>().mageData = EnemyDesignerWindow.MageInfo; break; case SettingsType.WARRIOR: //Create the .asset file dataPath += "Warrior/" + EnemyDesignerWindow.WarriorInfo.name + ".asset"; AssetDatabase.CreateAsset(EnemyDesignerWindow.WarriorInfo, dataPath); newPrefabPath += "Warrior/" + EnemyDesignerWindow.WarriorInfo.name + ".prefab"; //get prefab path prefabPath = AssetDatabase.GetAssetPath(EnemyDesignerWindow.WarriorInfo.prefab); AssetDatabase.CopyAsset(prefabPath, newPrefabPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); GameObject warriorPrefab = (GameObject)AssetDatabase.LoadAssetAtPath(newPrefabPath, typeof(GameObject)); if (!warriorPrefab.GetComponent<Warrior>()) { warriorPrefab.AddComponent(typeof(Warrior)); } warriorPrefab.GetComponent<Warrior>().warriorData = EnemyDesignerWindow.WarriorInfo; break; case SettingsType.ROGUE: //Create the .asset file dataPath += "Rogue/" + EnemyDesignerWindow.RogueInfo.name + ".asset"; AssetDatabase.CreateAsset(EnemyDesignerWindow.RogueInfo, dataPath); newPrefabPath += "Rogue/" + EnemyDesignerWindow.RogueInfo.name + ".prefab"; //get prefab path prefabPath = AssetDatabase.GetAssetPath(EnemyDesignerWindow.RogueInfo.prefab); AssetDatabase.CopyAsset(prefabPath, newPrefabPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); GameObject roguePrefab = (GameObject)AssetDatabase.LoadAssetAtPath(newPrefabPath, typeof(GameObject)); if (!roguePrefab.GetComponent<Rogue>()) { roguePrefab.AddComponent(typeof(Rogue)); } roguePrefab.GetComponent<Rogue>().rogueData = EnemyDesignerWindow.RogueInfo; break; } } }
35.501285
120
0.643954
[ "MIT" ]
AndrewAndronikou/Edit-Scripting-Unity
Assets/Editor/EnemyDesignerWindow.cs
13,812
C#
using ENCO.DDD.Repositories; using IFPS.Factory.Domain.Model; namespace IFPS.Factory.Domain.Repositories { public interface IWorkStationTypeRepository : IRepository<WorkStationType> { } }
18.454545
78
0.768473
[ "MIT" ]
encosoftware/ifps
ButorRevolutionWebAPI/src/backend/factory/IFPS.Factory.Domain/Repositories/IWorkStationTypeRepository.cs
205
C#
using System.Web.Mvc; using Abp.Web.Mvc.Authorization; using LearningMpaAbp.Authorization; using LearningMpaAbp.MultiTenancy; namespace LearningMpaAbp.Web.Controllers { [AbpMvcAuthorize(PermissionNames.Pages_Tenants)] public class TenantsController : LearningMpaAbpControllerBase { private readonly ITenantAppService _tenantAppService; public TenantsController(ITenantAppService tenantAppService) { _tenantAppService = tenantAppService; } public ActionResult Index() { var output = _tenantAppService.GetTenants(); return View(output); } } }
27.166667
68
0.699387
[ "MIT" ]
Sisen/LearningMpaAbp
LearningMpaAbp.Web/Controllers/TenantsController.cs
654
C#
using nyom.domain.core.EntityFramework.Interfaces; using nyom.domain.Crm.Templates; namespace nyom.domain.EntityFramework.Crm.Templates { public interface ITemplateService : IServiceBase<Template> { } }
23.888889
60
0.781395
[ "MIT" ]
AlessandroSilveira/nyom
nyom/nyom.domain/EntityFramework/Crm/Templates/ITemplateService.cs
217
C#
//----------------------------------------------------------------------- // <copyright file="JsonCreationConverter.cs" company="James Chaldecott"> // Copyright (c) 2012-2013 James Chaldecott. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Tivo.Connect { internal abstract class JsonCreationConverter<T> : JsonConverter { /// <summary> /// Create an instance of objectType, based properties in the JSON object /// </summary> /// <param name="objectType">type of object expected</param> /// <param name="jObject">contents of JSON object that will be deserialized</param> /// <returns></returns> protected abstract T Create(Type objectType, JObject jObject); public override bool CanConvert(Type objectType) { #if WINDOWS_PHONE || NETFX return typeof(T).IsAssignableFrom(objectType); #else return typeof(T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()); #endif } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // Load JObject from stream JObject jObject = JObject.Load(reader); // Create target object based on JObject T target = Create(objectType, jObject); // Populate the object properties serializer.Populate(jObject.CreateReader(), target); return target; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } }
35.188679
125
0.583914
[ "MIT" ]
swythan/showlist-tivo
Src/Tivo.Connect/JsonCreationConverter.cs
1,867
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using WEngine; using DoozyUI; using DoozyUI.Gestures; public class InterfaceUiData : MonoBehaviour { [Header("UI")] public UIElement InterfaceUi; public GameSettingsUiData GameSettingsUi; public UIElement WorldsUi; public AvatarMakerUiData AvatarMakerUi; public UIElement InterfaceHomescreenUi; public UIElement InterfacesGridUi; [Header("Shared")] public UIButton InterfacePrevButton; public UIButton InterfaceNextButton; public UIButton InterfaceBackButton; public InterfaceUiButton InterfaceUiButtonPrefab; public Text UserNameText; public Text LocationText; [Header("Settings")] public Text AppVersionNumberText; [Header("Worlds")] public EnumerableUiElements Interfaces = new EnumerableUiElements(); public EnumerableUiElements Worlds = new EnumerableUiElements(); public UIElement WorldHomespace; public UIElement WorldUserId; public UIButton WorldHomespaceGo; public InputField WorldUserNameInputField; public UIButton WorldUserNameGo; public WorldInfoUiElement WorldInfoPrefab; public UIButton WorldsPrevButton; public UIButton WorldsNextButton; }
30.571429
72
0.778816
[ "MIT" ]
wishfuldroplet/unity-projecta
Assets/Sources/Mono/Data/Ui/InterfaceUiData.cs
1,286
C#
using System.ComponentModel; using System.Globalization; using BrawlLib.SSBB.ResourceNodes; namespace System { internal class UserDataConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is UserDataClass) return ((UserDataClass)value).ToString(); return base.ConvertTo(context, culture, value, destType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { try { string s = (string)value; string[] s2 = s.Split(':'); string[] s3 = s2[1].Split(','); UserDataClass d = new UserDataClass(); d.Name = s2[0]; foreach (string i in s3) d._entries.Add(i); return d; } catch { } } return base.ConvertFrom(context, culture, value); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destType) { return (destType == typeof(UserDataClass)) ? true : base.CanConvertTo(context, destType); } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return (sourceType == typeof(string)) ? true : base.CanConvertFrom(context, sourceType); } } internal class ExpandableObjectCustomConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { string s = (string)base.ConvertTo(context, culture, value, destType); return s.Substring(s.LastIndexOf('.') + 1); } } }
35.724138
143
0.585425
[ "MIT" ]
Birdthulu/Legacy-Costume-Manager
brawltools/BrawlLib/System/TypeConverters.cs
2,074
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Http; using Steppenwolf.Contracts; using Steppenwolf.Pages.Admin.Category; using Steppenwolf.Services; using Steppenwolf.Shared; namespace Steppenwolf.Pages.Admin { public class ManagePostBase : ComponentBase { [Parameter] public Guid Id { get; set; } protected BlogPostModel BlogPostModel { get; set; } = new BlogPostModel(); protected BlogPost EditBlogPost { get; set; } protected bool Preview { get; set; } = false; [Inject] private HeadState HeadState { get; set; } [Inject] private BlogPostService BlogPostService { get; set; } [Inject] private CategoryService CategoryService { get; set; } [Inject] private IMapper Mapper { get; set; } [Inject] private IHttpContextAccessor HttpContextAccessor { get; set; } = default!; [Inject] private NavigationManager Navigation { get; set; } protected async Task<IEnumerable<CategoryModel>> SearchCategories(string searchText) { var result = await this.CategoryService.SearchCategoriesAsync(searchText); result = result .Where(c1 => this.BlogPostModel.Categories.All(c2 => c2.Id != c1.Id)) .ToList(); var categories = this.Mapper.Map<IList<CategoryModel>>(result); return categories; } protected override async void OnInitialized() { this.HeadState.AddStyleItem("_content/LoreSoft.Blazor.Controls/BlazorControls.css"); var blog = new BlogPost() { Author = new Author() { Name = this.HttpContextAccessor.HttpContext.User.Identity.Name } }; if (this.Id != default) { var apiBlog = await this.BlogPostService.GetById(this.Id); if (apiBlog != null) { blog = apiBlog; } } this.EditBlogPost = blog; this.BlogPostModel = this.Mapper.Map<BlogPostModel>(this.EditBlogPost); } protected async Task Submit() { var blog = this.Mapper.Map(this.BlogPostModel, this.EditBlogPost); var authorId = this.HttpContextAccessor.HttpContext.User.Claims .FirstOrDefault(c => c.Type.Contains("nameidentifier"))?.Value; var id = await this.BlogPostService.Upsert(blog, authorId); this.Navigation.NavigateTo($"/post/{id.ToString()}"); } protected BlogPost GetBlogPostPreviewModel() { var blog = this.Mapper.Map(this.BlogPostModel, this.EditBlogPost); return blog; } } }
30.9375
96
0.591582
[ "MIT" ]
043Tech/Steppenwolf
src/Steppenwolf/Pages/Admin/ManagePostBase.cs
2,970
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CAIMonsterIdleLie : CAIMonsterIdleAction { public CAIMonsterIdleLie(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAIMonsterIdleLie(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
32.130435
129
0.748309
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CAIMonsterIdleLie.cs
739
C#
/** * Copyright 2017 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace IBM.WatsonDeveloperCloud.NaturalLanguageUnderstanding.v1.Model { /// <summary> /// The hierarchical 5-level taxonomy the content is categorized into. /// </summary> public class CategoriesOptions { } }
30.071429
74
0.733967
[ "MIT" ]
parismiguel/Crm103Core1x
AbpCompanyName.AbpProjectName.Web.Mvc/Services/WatsonNLU/Model/CategoriesOptions.cs
842
C#
using System; using System.Collections.Generic; namespace DotNext.Reflection { /// <summary> /// Indicates that requested constructor doesn't exist. /// </summary> public sealed class MissingConstructorException : ConstraintViolationException { /// <summary> /// Initializes a new exception indicating that requested constructor doesn't exist. /// </summary> /// <param name="target">The inspected type.</param> /// <param name="parameters">An array of types representing constructor parameters.</param> public MissingConstructorException(Type target, params Type[] parameters) : base(target, ExceptionMessages.MissingCtor(target, parameters)) { Parameters = parameters; } /// <summary> /// An array of types representing constructor parameters. /// </summary> public IReadOnlyList<Type> Parameters { get; } internal static MissingConstructorException Create<TSignature>() where TSignature : Delegate { var invokeMethod = DelegateType.GetInvokeMethod<TSignature>(); return new MissingConstructorException(invokeMethod.ReturnType, invokeMethod.GetParameterTypes()); } internal static MissingConstructorException Create<T, TArgs>() where TArgs : struct => new(typeof(T), Signature.Reflect(typeof(TArgs)).Parameters); } }
37.435897
110
0.65411
[ "MIT" ]
NanoFabricFX/dotNext
src/DotNext.Reflection/Reflection/MissingConstructorException.cs
1,462
C#
// // Copyright (c) 2010-2018 Antmicro // Copyright (c) 2011-2015 Realtime Embedded // // This file is licensed under the MIT License. // Full license text is available in 'licenses/MIT.txt'. // using System; using Antmicro.Renode.Peripherals.UART; using Antmicro.Renode.Core; namespace Antmicro.Renode.Backends.Terminals { public abstract class BackendTerminal : IExternal, IConnectable<IUART> { public virtual event Action<byte> CharReceived; public abstract void WriteChar(byte value); public virtual void AttachTo(IUART uart) { CharReceived += uart.WriteChar; uart.CharReceived += WriteChar; } public virtual void DetachFrom(IUART uart) { CharReceived -= uart.WriteChar; uart.CharReceived -= WriteChar; } protected void CallCharReceived(byte value) { var charReceived = CharReceived; if(charReceived != null) { charReceived(value); } } } }
25.261905
74
0.614515
[ "MIT" ]
UPBIoT/renode-iot
src/Infrastructure/src/Emulator/Main/Backends/Terminals/BackendTerminal.cs
1,061
C#
// ********************************************************************** // // Copyright (c) ZeroC, Inc. All rights reserved. // // ********************************************************************** using System.Collections.Generic; using System.Composition; using System.Threading.Tasks; using Microsoft.VisualStudio.ProjectSystem; using System.Collections.Immutable; using Microsoft.VisualStudio.ProjectSystem.VS.Properties; using System; namespace IceBuilder { class SliceCompilePageMetadata : IPageMetadata { string IPageMetadata.Name => "Ice Builder"; Guid IPageMetadata.PageGuid => new Guid("1E2800FE-37C5-4FD3-BC2E-969342EE08AF"); int IPageMetadata.PageOrder => 3; bool IPageMetadata.HasConfigurationCondition => false; } [Export(typeof(IVsProjectDesignerPageProvider))] [AppliesTo("SliceCompile")] internal class ProjectDesignerPageProvider : IVsProjectDesignerPageProvider { public Task<IReadOnlyCollection<IPageMetadata>> GetPagesAsync() { return Task.FromResult((IReadOnlyCollection<IPageMetadata>)ImmutableArray.Create(SliceCompile)); } private static SliceCompilePageMetadata SliceCompile = new SliceCompilePageMetadata(); } }
31.525
108
0.651864
[ "BSD-3-Clause" ]
pepone/ice-builder-visualstudio
IceBuilder_Common/ProjectDesignerPageProvider.cs
1,263
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Abp.Authorization.Roles; using Abp.AutoMapper; using CarPlusGo.CVAS.Authorization.Roles; namespace CarPlusGo.CVAS.Roles.Dto { [AutoMapTo(typeof(Role))] public class CreateRoleDto { [Required] [StringLength(AbpRoleBase.MaxNameLength)] public string Name { get; set; } [Required] [StringLength(AbpRoleBase.MaxDisplayNameLength)] public string DisplayName { get; set; } public string NormalizedName { get; set; } [StringLength(Role.MaxDescriptionLength)] public string Description { get; set; } public List<string> Permissions { get; set; } } }
26.571429
56
0.669355
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
MakingBugs/carplusgo.cvas
src/CarPlusGo.CVAS.Application/Roles/Dto/CreateRoleDto.cs
744
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System.Runtime.CompilerServices; using Microsoft.Scripting.Runtime; [assembly: ExtensionType(typeof(IronPythonTest.ExtendedClass), typeof(IronPythonTest.ExtensionClass))] namespace IronPythonTest { public class OperatorTest { public object Value; public string Name; [SpecialName] public object GetBoundMember(string name) { Name = name; return 42; } [SpecialName] public void SetMember(string name, object value) { Name = name; Value = value; } } public class ExtendedClass { public object Value; public string Name; } public class ExtensionClass { [SpecialName] public static object GetBoundMember(ExtendedClass self, string name) { self.Name = name; return 42; } [SpecialName] public static void SetMember(ExtendedClass self, string name, object value) { self.Name = name; self.Value = value; } } }
32.163636
102
0.583946
[ "Apache-2.0" ]
0xFireball/exascript2
Src/IronPythonTest/OperatorTest.cs
1,769
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 4.0.2 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace libsbml { using System; using System.Runtime.InteropServices; /** * @sbmlpackage{core} * @htmlinclude pkg-marker-core.html A single configuration setting for an SBML converter. * * @htmlinclude libsbml-facility-only-warning.html * * LibSBML provides a number of converters that can perform transformations * on SBML documents. These converters allow their behaviors to be * controlled by setting property values. Converter properties are * communicated using objects of class ConversionProperties, and within * such objects, individual options are encapsulated using ConversionOption * objects. * * A ConversionOption @if conly structure @else object@endif consists of * four parts: * @li A @em key, acting as the name of the option. * @li A @em value of this option. * @li A @em type for the value; the type code is chosen from @if clike * an enumeration @else a set of integer constants@endif whose names all * begin with the prefix <code>CNV_TYPE_</code>. (See the separate <a * class='el' href='#ConversionOptionType_t'>subsection</a> below for more * information.) * @li A @em description consisting of a text string that describes the * option in some way. * * There are no constraints on the values of keys or descriptions; * authors of SBML converters are free to choose them as they see fit. * * @section ConversionOptionType_t Conversion option data types * * An option in ConversionOption must have a data type declared, to * indicate whether it is a string value, an integer, and so forth. The * possible types of values are taken from * @if clike the enumeration #ConversionOptionType_t @else a set of * constants whose symbol names begin with the prefix * <code>CNV_TYPE_</code>@endif. The following are the possible values: * * <p> * <center> * <table width='90%' cellspacing='1' cellpadding='1' border='0' class='normal-font'> * <tr style='background: lightgray' class='normal-font'> * <td><strong>Enumerator</strong></td> * <td><strong>Meaning</strong></td> * </tr> * <tr> * <td><code>@link libsbml#CNV_TYPE_BOOL CNV_TYPE_BOOL@endlink</code></td> * <td>Indicates the value type is a Boolean.</td> * </tr> * <tr> * <td><code>@link libsbml#CNV_TYPE_DOUBLE CNV_TYPE_DOUBLE@endlink</code></td> * <td>Indicates the value type is a double-sized float.</td> * </tr> * <tr> * <td><code>@link libsbml#CNV_TYPE_INT CNV_TYPE_INT@endlink</code></td> * <td>Indicates the value type is an integer.</td> * </tr> * <tr> * <td><code>@link libsbml#CNV_TYPE_SINGLE CNV_TYPE_SINGLE@endlink</code></td> * <td>Indicates the value type is a float.</td> * </tr> * <tr> * <td><code>@link libsbml#CNV_TYPE_STRING CNV_TYPE_STRING@endlink</code></td> * <td>Indicates the value type is a string.</td> * </tr> * </table> * </center> * * @see ConversionProperties */ public class ConversionOption : global::System.IDisposable { private HandleRef swigCPtr; protected bool swigCMemOwn; internal ConversionOption(IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = new HandleRef(this, cPtr); } internal static HandleRef getCPtr(ConversionOption obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } internal static HandleRef getCPtrAndDisown (ConversionOption obj) { HandleRef ptr = new HandleRef(null, IntPtr.Zero); if (obj != null) { ptr = obj.swigCPtr; obj.swigCMemOwn = false; } return ptr; } ~ConversionOption() { Dispose(false); } public void Dispose() { Dispose(true); global::System.GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; libsbmlPINVOKE.delete_ConversionOption(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } } } /** * Creates a new ConversionOption. * * This is the general constructor, taking arguments for all aspects of * an option. Other constructors exist with different arguments. * * * * The conversion @p type argument value must be one of * @if clike the values defined in the enumeration * #ConversionOptionType_t.@endif@if java the constants whose names begin * with the characters <code>CNV_TYPE_</code> in the interface class * {@link libsbmlConstants}.@endif@if python the constants whose names begin * with the characters <code>CNV_TYPE_</code> in the interface class * @link libsbml libsbml@endlink.@endif * * @param key the key for this option. * @param value an optional value for this option. * @param type the type of this option. * @param description the description for this option. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, string value, int type, string description) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_0(key, value, type, description), true) { } /** * Creates a new ConversionOption. * * This is the general constructor, taking arguments for all aspects of * an option. Other constructors exist with different arguments. * * * * The conversion @p type argument value must be one of * @if clike the values defined in the enumeration * #ConversionOptionType_t.@endif@if java the constants whose names begin * with the characters <code>CNV_TYPE_</code> in the interface class * {@link libsbmlConstants}.@endif@if python the constants whose names begin * with the characters <code>CNV_TYPE_</code> in the interface class * @link libsbml libsbml@endlink.@endif * * @param key the key for this option. * @param value an optional value for this option. * @param type the type of this option. * @param description the description for this option. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, string value, int type) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_1(key, value, type), true) { } /** * Creates a new ConversionOption. * * This is the general constructor, taking arguments for all aspects of * an option. Other constructors exist with different arguments. * * * * The conversion @p type argument value must be one of * @if clike the values defined in the enumeration * #ConversionOptionType_t.@endif@if java the constants whose names begin * with the characters <code>CNV_TYPE_</code> in the interface class * {@link libsbmlConstants}.@endif@if python the constants whose names begin * with the characters <code>CNV_TYPE_</code> in the interface class * @link libsbml libsbml@endlink.@endif * * @param key the key for this option. * @param value an optional value for this option. * @param type the type of this option. * @param description the description for this option. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, string value) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_2(key, value), true) { } /** * Creates a new ConversionOption. * * This is the general constructor, taking arguments for all aspects of * an option. Other constructors exist with different arguments. * * * * The conversion @p type argument value must be one of * @if clike the values defined in the enumeration * #ConversionOptionType_t.@endif@if java the constants whose names begin * with the characters <code>CNV_TYPE_</code> in the interface class * {@link libsbmlConstants}.@endif@if python the constants whose names begin * with the characters <code>CNV_TYPE_</code> in the interface class * @link libsbml libsbml@endlink.@endif * * @param key the key for this option. * @param value an optional value for this option. * @param type the type of this option. * @param description the description for this option. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_3(key), true) { } /** * Creates a new ConversionOption specialized for string-type options. * * @param key the key for this option. * @param value the value for this option. * @param description an optional description. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, string value, string description) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_4(key, value, description), true) { } /** * Creates a new ConversionOption specialized for Boolean-type options. * * @param key the key for this option. * @param value the value for this option. * @param description an optional description. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, bool value, string description) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_6(key, value, description), true) { } /** * Creates a new ConversionOption specialized for Boolean-type options. * * @param key the key for this option. * @param value the value for this option. * @param description an optional description. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, bool value) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_7(key, value), true) { } /** * Creates a new ConversionOption specialized for double-type options. * * @param key the key for this option. * @param value the value for this option. * @param description an optional description. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, double value, string description) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_8(key, value, description), true) { } /** * Creates a new ConversionOption specialized for double-type options. * * @param key the key for this option. * @param value the value for this option. * @param description an optional description. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, double value) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_9(key, value), true) { } /** * Creates a new ConversionOption specialized for float-type options. * * @param key the key for this option. * @param value the value for this option. * @param description an optional description. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, float value, string description) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_10(key, value, description), true) { } /** * Creates a new ConversionOption specialized for float-type options. * * @param key the key for this option. * @param value the value for this option. * @param description an optional description. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, float value) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_11(key, value), true) { } /** * Creates a new ConversionOption specialized for integer-type options. * * @param key the key for this option. * @param value the value for this option. * @param description an optional description. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, int value, string description) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_12(key, value, description), true) { } /** * Creates a new ConversionOption specialized for integer-type options. * * @param key the key for this option. * @param value the value for this option. * @param description an optional description. * * @ifnot hasDefaultArgs @htmlinclude warn-default-args-in-docs.html @endif */ public ConversionOption(string key, int value) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_13(key, value), true) { } /** * Copy constructor; creates a copy of an ConversionOption object. * * @param orig the ConversionOption object to copy. */ public ConversionOption(ConversionOption orig) : this(libsbmlPINVOKE.new_ConversionOption__SWIG_14(ConversionOption.getCPtr(orig)), true) { if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); } /** * Creates and returns a deep copy of this ConversionOption object. * * @return the (deep) copy of this ConversionOption object. */ public new ConversionOption clone() { global::System.IntPtr cPtr = libsbmlPINVOKE.ConversionOption_clone(swigCPtr); ConversionOption ret = (cPtr == global::System.IntPtr.Zero) ? null : new ConversionOption(cPtr, true); return ret; } /** * Returns the key for this option. * * @return the key, as a string. */ public string getKey() { string ret = libsbmlPINVOKE.ConversionOption_getKey(swigCPtr); return ret; } /** * Sets the key for this option. * * @param key a string representing the key to set. */ public void setKey(string key) { libsbmlPINVOKE.ConversionOption_setKey(swigCPtr, key); } /** * Returns the value of this option. * * @return the value of this option, as a string. */ public string getValue() { string ret = libsbmlPINVOKE.ConversionOption_getValue(swigCPtr); return ret; } /** * Sets the value for this option. * * @param value the value to set, as a string. */ public void setValue(string value) { libsbmlPINVOKE.ConversionOption_setValue(swigCPtr, value); } /** * Returns the description string for this option. * * @return the description of this option. */ public string getDescription() { string ret = libsbmlPINVOKE.ConversionOption_getDescription(swigCPtr); return ret; } /** * Sets the description text for this option. * * @param description the description to set for this option. */ public void setDescription(string description) { libsbmlPINVOKE.ConversionOption_setDescription(swigCPtr, description); } /** * Returns the type of this option * * @return the type of this option. */ public int getType() { int ret = libsbmlPINVOKE.ConversionOption_getType(swigCPtr); return ret; } /** * Sets the type of this option. * * * * The conversion @p type argument value must be one of * @if clike the values defined in the enumeration * #ConversionOptionType_t.@endif@if java the constants whose names begin * with the characters <code>CNV_TYPE_</code> in the interface class * {@link libsbmlConstants}.@endif@if python the constants whose names begin * with the characters <code>CNV_TYPE_</code> in the interface class * @link libsbml libsbml@endlink.@endif * * @param type the type value to use. */ public void setType(int type) { libsbmlPINVOKE.ConversionOption_setType(swigCPtr, type); } /** * Returns the value of this option as a Boolean. * * @return the value of this option. */ public new bool getBoolValue() { bool ret = libsbmlPINVOKE.ConversionOption_getBoolValue(swigCPtr); return ret; } /** * Set the value of this option to a given Boolean value. * * Invoking this method will also set the type of the option to * @link libsbml#CNV_TYPE_BOOL CNV_TYPE_BOOL@endlink. * * @param value the Boolean value to set. */ public new void setBoolValue(bool value) { libsbmlPINVOKE.ConversionOption_setBoolValue(swigCPtr, value); } /** * Returns the value of this option as a @c double. * * @return the value of this option. */ public new double getDoubleValue() { double ret = libsbmlPINVOKE.ConversionOption_getDoubleValue(swigCPtr); return ret; } /** * Set the value of this option to a given @c double value. * * Invoking this method will also set the type of the option to * @link libsbml#CNV_TYPE_DOUBLE CNV_TYPE_DOUBLE@endlink. * * @param value the value to set. */ public new void setDoubleValue(double value) { libsbmlPINVOKE.ConversionOption_setDoubleValue(swigCPtr, value); } /** * Returns the value of this option as a @c float. * * @return the value of this option as a float. */ public new float getFloatValue() { float ret = libsbmlPINVOKE.ConversionOption_getFloatValue(swigCPtr); return ret; } /** * Set the value of this option to a given @c float value. * * Invoking this method will also set the type of the option to * @link libsbml#CNV_TYPE_SINGLE CNV_TYPE_SINGLE@endlink. * * @param value the value to set. */ public new void setFloatValue(float value) { libsbmlPINVOKE.ConversionOption_setFloatValue(swigCPtr, value); } /** * Returns the value of this option as an @c integer. * * @return the value of this option, as an int. */ public new int getIntValue() { int ret = libsbmlPINVOKE.ConversionOption_getIntValue(swigCPtr); return ret; } /** * Set the value of this option to a given @c int value. * * Invoking this method will also set the type of the option to * @link libsbml#CNV_TYPE_INT CNV_TYPE_INT@endlink. * * @param value the value to set. */ public new void setIntValue(int value) { libsbmlPINVOKE.ConversionOption_setIntValue(swigCPtr, value); } } }
31.579861
164
0.701759
[ "Unlicense" ]
copasi/copasi-dependencies
src/libSBML/src/bindings/csharp/csharp-files-win/ConversionOption.cs
18,190
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Xigadee { public static class ConfigureTcpTlsMessagingHelper { } }
14.857143
54
0.759615
[ "Apache-2.0" ]
xigadee/Microservice
Src/Xigadee.Platform/Communication/FabricBridge/TcpTlsChannel/Pipeline/ConfigureTcpTlsMessagingHelper.cs
210
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Cli.TemplateResolution; using Microsoft.TemplateEngine.Edge.Template; using Microsoft.TemplateEngine.Utils; namespace Microsoft.TemplateEngine.Cli.UnitTests.TemplateResolutionTests { internal static class ResolutionTestHelper { public static ICacheTag CreateTestCacheTag(string choice, string choiceDescription = null, string defaultValue = null, string defaultIfOptionWithoutValue = null) { return new CacheTag(null, new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { choice, choiceDescription } }, defaultValue, defaultIfOptionWithoutValue); } public static ICacheTag CreateTestCacheTag(IReadOnlyList<string> choiceList, string tagDescription = null, string defaultValue = null, string defaultIfOptionWithoutValue = null) { Dictionary<string, string> choicesDict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (string choice in choiceList) { choicesDict.Add(choice, null); }; return new CacheTag(tagDescription, choicesDict, defaultValue, defaultIfOptionWithoutValue); } public static string DebugOutputForResolutionResult(TemplateResolutionResult matchResult, Func<ITemplateMatchInfo, bool> filter) { if (!matchResult.TryGetCoreMatchedTemplatesWithDisposition(filter, out IReadOnlyList<ITemplateMatchInfo> matchingTemplates)) { return "No templates matched the filter"; } StringBuilder builder = new StringBuilder(512); foreach (ITemplateMatchInfo templateMatchInfo in matchingTemplates) { builder.AppendLine($"Identity: {templateMatchInfo.Info.Identity}"); foreach (MatchInfo disposition in templateMatchInfo.MatchDisposition) { builder.AppendLine($"\t{disposition.Location.ToString()} = {disposition.Kind.ToString()}"); } builder.AppendLine(); } return builder.ToString(); } } }
41.758621
186
0.642444
[ "MIT" ]
Hammerstad/templating
test/Microsoft.TemplateEngine.Cli.UnitTests/TemplateResolutionTests/ResolutionTestHelper.cs
2,365
C#
using System; namespace Homework { class ExcellentOrNot { static void Main(string[] args) { var num = double.Parse(Console.ReadLine()); if(num %2 == 0){ Console.WriteLine("Even"); }else{ Console.WriteLine("Odd"); } } } }
17.352941
55
0.518644
[ "Apache-2.0" ]
DPlamenov/Homework-tasks
ProgrammingBasics/EvenorOdd.cs
297
C#
using Discount.Grpc.Entities; using System.Threading.Tasks; namespace Discount.Grpc.Repositories { public interface IDiscountRepository { Task<Coupon> GetDiscount(string productName); Task<bool> CreateDiscount(Coupon coupon); Task<bool> UpdateDiscount(Coupon coupon); Task<bool> DeleteDiscount(string productName); } }
20.5
54
0.710027
[ "MIT" ]
MichaelFelipeCabrera/AspnetMicroservices
src/Services/Discount/Discount.Grpc/Repositories/IDiscountRepository.cs
371
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; /// <summary> /// Tests that the System.Linq.Expressions.Interpreter.CallInstruction.GetHelperType /// method works as expected when used in a trimmed application. /// </summary> internal class Program { static int Main(string[] args) { for (int rank = 1; rank < 6; rank++) { Array arrayObj = Array.CreateInstance(typeof(string), Enumerable.Repeat(1, rank).ToArray()); arrayObj.SetValue("solitary value", Enumerable.Repeat(0, rank).ToArray()); ConstantExpression array = Expression.Constant(arrayObj); IEnumerable<DefaultExpression> indices = Enumerable.Repeat(Expression.Default(typeof(int)), rank); // This code path for the Compile call excercises the method being tested. Func<string> func = Expression.Lambda<Func<string>>( Expression.ArrayAccess(array, indices)).Compile(preferInterpretation: true); if (func() != "solitary value") { return -1; } } return 100; } }
35.944444
110
0.650696
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Linq.Expressions/tests/TrimmingTests/GetHelperTypeTests.cs
1,294
C#
using Biohazrd.Metadata; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Biohazrd.Transformation.Common { /// <summary>Strips any declarations marked with <see cref="LazilyGenerated"/> which are not referenced.</summary> public sealed class StripUnreferencedLazyDeclarationsTransformation : TransformationBase { private readonly HashSet<TranslatedDeclaration> ReferencedLazyDeclarations = new(ReferenceEqualityComparer.Instance); private readonly ReferenceWalker Walker = new(); private sealed class ReferenceWalker : __TypeReferenceVisitor { // We're really using this more like HashSet<(TranslatedDeclaration, VisitorContext)>, but we want to use reference equality on the declaration and tuples don't make that easy. private Dictionary<TranslatedDeclaration, VisitorContext> FoundLazyDeclarations = new(ReferenceEqualityComparer.Instance); public int Count => FoundLazyDeclarations.Count; public void Clear() => FoundLazyDeclarations.Clear(); public Dictionary<TranslatedDeclaration, VisitorContext> GetFoundLazyDeclarationsAndClear() { Dictionary<TranslatedDeclaration, VisitorContext> result = FoundLazyDeclarations; FoundLazyDeclarations = new Dictionary<TranslatedDeclaration, VisitorContext>(ReferenceEqualityComparer.Instance); return result; } protected override void VisitRecord(VisitorContext context, TranslatedRecord declaration) => VisitRecord(context, declaration, isDirectVisit: false); public void VisitDirect(VisitorContext context, TranslatedDeclaration declaration) { if (declaration is TranslatedRecord record) { Debug.Assert(declaration.Metadata.Has<LazilyGenerated>()); VisitRecord(context, record, isDirectVisit: true); } else { base.Visit(context, declaration); } } private void VisitRecord(VisitorContext context, TranslatedRecord declaration, bool isDirectVisit) { // If this isn't a direct visit and the declaration is lazy, skip it to avoid counting a lazy declaration as referenced when it is referenced by // its self or another lazy declaration (If this is a direct visit, we know this lazy declaration has already been referenced.) if (!isDirectVisit && declaration.Metadata.Has<LazilyGenerated>()) { return; } base.VisitRecord(context, declaration); } protected override void VisitTypeReference(VisitorContext context, ImmutableArray<TypeReference> parentTypeReferences, TypeReference typeReference) { if (typeReference is not TranslatedTypeReference translatedTypeReference) { goto baseCall; } VisitorContext resolvedContext; TranslatedDeclaration? resolvedDeclaration = translatedTypeReference.TryResolve(context.Library, out resolvedContext); if (resolvedDeclaration is null) { goto baseCall; } // Check if the resolved declaration or any of its parental lineage are lazily generated and mark them as found while (true) { if (resolvedDeclaration.Metadata.Has<LazilyGenerated>()) { FoundLazyDeclarations.TryAdd(resolvedDeclaration, resolvedContext); } resolvedDeclaration = resolvedContext.ParentDeclaration; if (resolvedDeclaration is null) { break; } resolvedContext = resolvedContext.MakePrevious(); } baseCall: base.VisitTypeReference(context, parentTypeReferences, typeReference); } } protected override TranslatedLibrary PreTransformLibrary(TranslatedLibrary library) { Debug.Assert(ReferencedLazyDeclarations.Count == 0); ReferencedLazyDeclarations.Clear(); Debug.Assert(Walker.Count == 0); Walker.Clear(); // Enumerate all lazy declarations referenced by non-lazy declarations in the library Walker.Visit(library); // Loop so we keep adding new lazy declarations found to be referenced by lazy declarations processed by the previous iteration while (Walker.Count > 0) { // Reset the walker and process its results foreach ((TranslatedDeclaration lazyDeclaration, VisitorContext lazyContext) in Walker.GetFoundLazyDeclarationsAndClear()) { // Try to record the referenced lazy declaration. If it was already seen before, there's nothing more to do if (!ReferencedLazyDeclarations.Add(lazyDeclaration)) { continue; } // If this is the first time we've seen this lazy declaration, walk it to find any lazy declarations which it references Walker.VisitDirect(lazyContext, lazyDeclaration); } } return library; } protected override TransformationResult TransformRecord(TransformationContext context, TranslatedRecord declaration) { if (!declaration.Metadata.Has<LazilyGenerated>()) { return declaration; } if (ReferencedLazyDeclarations.Contains(declaration)) { return declaration; } // This lazily-generated declaration was not referenced, remove it return null; } protected override TranslatedLibrary PostTransformLibrary(TranslatedLibrary library) { ReferencedLazyDeclarations.Clear(); return library; } } }
46.068702
188
0.643745
[ "MIT" ]
InfectedLibraries/Biohazrd
Biohazrd.Transformation/Common/StripUnreferencedLazyDeclarationsTransformation.cs
6,037
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. #nullable enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class FunctionPointerTypeSymbol : TypeSymbol { public static FunctionPointerTypeSymbol CreateFromSource(FunctionPointerTypeSyntax syntax, Binder typeBinder, DiagnosticBag diagnostics, ConsList<TypeSymbol> basesBeingResolved, bool suppressUseSiteDiagnostics) => new FunctionPointerTypeSymbol( FunctionPointerMethodSymbol.CreateFromSource( syntax, typeBinder, diagnostics, basesBeingResolved, suppressUseSiteDiagnostics)); /// <summary> /// Creates a function pointer from individual parts. This method should only be used when diagnostics are not needed. This is /// intended for use in test code. /// </summary> public static FunctionPointerTypeSymbol CreateFromPartsForTests( CallingConvention callingConvention, TypeWithAnnotations returnType, ImmutableArray<CustomModifier> refCustomModifiers, RefKind returnRefKind, ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<ImmutableArray<CustomModifier>> parameterRefCustomModifiers, ImmutableArray<RefKind> parameterRefKinds, CSharpCompilation compilation) => new FunctionPointerTypeSymbol(FunctionPointerMethodSymbol.CreateFromPartsForTest(callingConvention, returnType, refCustomModifiers, returnRefKind, parameterTypes, parameterRefCustomModifiers, parameterRefKinds, compilation)); /// <summary> /// Creates a function pointer from individual parts. This method should only be used when diagnostics are not needed. /// </summary> public static FunctionPointerTypeSymbol CreateFromParts( CallingConvention callingConvention, ImmutableArray<CustomModifier> callingConventionModifiers, TypeWithAnnotations returnType, RefKind returnRefKind, ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, CSharpCompilation compilation) => new FunctionPointerTypeSymbol(FunctionPointerMethodSymbol.CreateFromParts(callingConvention, callingConventionModifiers, returnType, returnRefKind, parameterTypes, parameterRefKinds, compilation)); public static FunctionPointerTypeSymbol CreateFromMetadata(Cci.CallingConvention callingConvention, ImmutableArray<ParamInfo<TypeSymbol>> retAndParamTypes) => new FunctionPointerTypeSymbol( FunctionPointerMethodSymbol.CreateFromMetadata(callingConvention, retAndParamTypes)); public FunctionPointerTypeSymbol SubstituteTypeSymbol( TypeWithAnnotations substitutedReturnType, ImmutableArray<TypeWithAnnotations> substitutedParameterTypes, ImmutableArray<CustomModifier> refCustomModifiers, ImmutableArray<ImmutableArray<CustomModifier>> paramRefCustomModifiers) => new FunctionPointerTypeSymbol(Signature.SubstituteParameterSymbols(substitutedReturnType, substitutedParameterTypes, refCustomModifiers, paramRefCustomModifiers)); private FunctionPointerTypeSymbol(FunctionPointerMethodSymbol signature) { Signature = signature; } public FunctionPointerMethodSymbol Signature { get; } public override bool IsReferenceType => false; public override bool IsValueType => true; public override TypeKind TypeKind => TypeKind.FunctionPointer; public override bool IsRefLikeType => false; public override bool IsReadOnly => false; public override SymbolKind Kind => SymbolKind.FunctionPointerType; public override Symbol? ContainingSymbol => null; public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override Accessibility DeclaredAccessibility => Accessibility.NotApplicable; public override bool IsStatic => false; public override bool IsAbstract => false; public override bool IsSealed => false; // Pointers do not support boxing, so they really have no base type. internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null; internal override ManagedKind GetManagedKind(ref HashSet<DiagnosticInfo>? useSiteDiagnostics) => ManagedKind.Unmanaged; internal override ObsoleteAttributeData? ObsoleteAttributeData => null; public override void Accept(CSharpSymbolVisitor visitor) => visitor.VisitFunctionPointerType(this); public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) => visitor.VisitFunctionPointerType(this); public override ImmutableArray<Symbol> GetMembers() => ImmutableArray<Symbol>.Empty; public override ImmutableArray<Symbol> GetMembers(string name) => ImmutableArray<Symbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument a) => visitor.VisitFunctionPointerType(this, a); internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol>? basesBeingResolved = null) => ImmutableArray<NamedTypeSymbol>.Empty; internal override bool Equals(TypeSymbol t2, TypeCompareKind compareKind, IReadOnlyDictionary<TypeParameterSymbol, bool>? isValueTypeOverrideOpt = null) { if (ReferenceEquals(this, t2)) { return true; } if (!(t2 is FunctionPointerTypeSymbol other)) { return false; } return Signature.Equals(other.Signature, compareKind, isValueTypeOverrideOpt); } public override int GetHashCode() { return Hash.Combine(1, Signature.GetHashCode()); } protected override ISymbol CreateISymbol() { return new PublicModel.FunctionPointerTypeSymbol(this, DefaultNullableAnnotation); } protected override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { Debug.Assert(nullableAnnotation != DefaultNullableAnnotation); return new PublicModel.FunctionPointerTypeSymbol(this, nullableAnnotation); } internal override void AddNullableTransforms(ArrayBuilder<byte> transforms) { Signature.AddNullableTransforms(transforms); } internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result) { var newSignature = Signature.ApplyNullableTransforms(defaultTransformFlag, transforms, ref position); bool madeChanges = (object)Signature != newSignature; result = madeChanges ? new FunctionPointerTypeSymbol(newSignature) : this; return madeChanges; } internal override DiagnosticInfo? GetUseSiteDiagnostic() { DiagnosticInfo? fromSignature = Signature.GetUseSiteDiagnostic(); if (fromSignature?.Code == (int)ErrorCode.ERR_BindToBogus && fromSignature.Arguments.AsSingleton() == (object)Signature) { return new CSDiagnosticInfo(ErrorCode.ERR_BogusType, this); } return fromSignature; } internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo? result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { return Signature.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes); } internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance) { Debug.Assert(this.Equals(other, TypeCompareKind.AllIgnoreOptions)); var mergedSignature = Signature.MergeEquivalentTypes(((FunctionPointerTypeSymbol)other).Signature, variance); if ((object)mergedSignature != Signature) { return new FunctionPointerTypeSymbol(mergedSignature); } return this; } internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform) { var substitutedSignature = Signature.SetNullabilityForReferenceTypes(transform); if ((object)Signature != substitutedSignature) { return new FunctionPointerTypeSymbol(substitutedSignature); } return this; } /// <summary> /// For scenarios such as overriding with differing ref kinds (such as out vs in or ref) /// we need to compare function pointer parameters assuming that Ref matches RefReadonly/In /// and Out. This is done because you cannot overload on ref vs out vs in in regular method /// signatures, and we are disallowing similar overloads in source with function pointers. /// </summary> internal static bool RefKindEquals(TypeCompareKind compareKind, RefKind refKind1, RefKind refKind2) => (compareKind & TypeCompareKind.FunctionPointerRefMatchesOutInRefReadonly) != 0 ? (refKind1 == RefKind.None) == (refKind2 == RefKind.None) : refKind1 == refKind2; /// <summary> /// For scenarios such as overriding with differing ref kinds (such as out vs in or ref) /// we need to compare function pointer parameters assuming that Ref matches RefReadonly/In /// and Out. For that reason, we must also ensure that GetHashCode returns equal hashcodes /// for types that only differ by the type of ref they have. /// </summary> internal static RefKind GetRefKindForHashCode(RefKind refKind) => refKind == RefKind.None ? RefKind.None : RefKind.Ref; /// <summary> /// Return true if the given type is valid as a calling convention modifier type. /// </summary> internal static bool IsCallingConventionModifier(NamedTypeSymbol modifierType) { Debug.Assert(modifierType.ContainingAssembly is not null || modifierType.IsErrorType()); return (object?)modifierType.ContainingAssembly == modifierType.ContainingAssembly?.CorLibrary && modifierType.Arity == 0 && modifierType.Name != "CallConv" && modifierType.Name.StartsWith("CallConv", StringComparison.Ordinal) && modifierType.IsCompilerServicesTopLevelType(); } } }
53.09633
240
0.703413
[ "MIT" ]
IanKemp/roslyn
src/Compilers/CSharp/Portable/Symbols/FunctionPointers/FunctionPointerTypeSymbol.cs
11,577
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver { [SerializeField] TKey[] m_keys; [SerializeField] TValue[] m_values; public SerializableDictionary() { } public SerializableDictionary(IDictionary<TKey, TValue> dict) : base(dict.Count) { foreach (var kvp in dict) { this[kvp.Key] = kvp.Value; } } public void CopyFrom(IDictionary<TKey, TValue> dict) { this.Clear(); foreach (var kvp in dict) { this[kvp.Key] = kvp.Value; } } public void OnAfterDeserialize() { if(m_keys != null && m_values != null && m_keys.Length == m_values.Length) { this.Clear(); int n = m_keys.Length; for(int i = 0; i < n; ++i) { this[m_keys[i]] = m_values[i]; } m_keys = null; m_values = null; } } public void OnBeforeSerialize() { int n = this.Count; m_keys = new TKey[n]; m_values = new TValue[n]; int i = 0; foreach(var kvp in this) { m_keys[i] = kvp.Key; m_values[i] = kvp.Value; ++i; } } }
18.030303
109
0.610084
[ "MIT" ]
pdyxs/UnityProjectStarter
Assets/Plugins/Externals/SerializableDictionary/SerializableDictionary.cs
1,192
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("TibiaMapTester")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TibiaMapTester")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("339a29e0-e9e7-4f5a-bbea-3b941e9bbd28")] // 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.837838
85
0.727209
[ "MIT" ]
Sixish/Odyssey-Generator
TibiaMapTester/TibiaMapTester/Properties/AssemblyInfo.cs
1,440
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Управление общими сведениями о сборке осуществляется с помощью // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("Crypt")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Crypt")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми // для COM-компонентов. Если требуется обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("f1884e9b-0030-4243-92b2-5465c1cb9871")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер построения // Редакция // // Можно задать все значения или принять номер построения и номер редакции по умолчанию, // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.162162
99
0.756374
[ "Unlicense" ]
JonMagon/PWLuaOOG
Crypt/Properties/AssemblyInfo.cs
1,984
C#
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Context { public interface ConsumeRetryContext { /// <summary> /// The retry attempt in progress, or zero if this is the first time through /// </summary> int RetryAttempt { get; } /// <summary> /// The number of retries that have already been attempted, note that this is zero /// on the first retry attempt /// </summary> int RetryCount { get; } } }
40.178571
91
0.656889
[ "ECL-2.0", "Apache-2.0" ]
AOrlov/MassTransit
src/MassTransit/Context/ConsumeRetryContext.cs
1,127
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.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServerClient.Razor { /// <summary> /// The purpose of the <see cref="FileUriProvider"/> is to take something that's not always addressable (an <see cref="ITextBuffer"/>) and make it addressable. /// This is required in LSP scenarios because everything operates off of the assumption that a document can be addressable via a <see cref="Uri"/>. /// </summary> internal abstract class FileUriProvider { /// <summary> /// Gets or creates an addressable <see cref="Uri"/> for the provided <paramref name="textBuffer"/>. /// /// In the case that the <paramref name="textBuffer"/> is not currently addressable via a <see cref="Uri"/>, we create one. /// </summary> /// <param name="textBuffer">A text buffer</param> /// <returns>A <see cref="Uri"/> that can be used to locate the provided <paramref name="textBuffer"/>.</returns> public abstract Uri GetOrCreate(ITextBuffer textBuffer); /// <summary> /// Attempts to retrieve the Razor addressable <see cref="Uri"/> for the provided <paramref name="textBuffer"/>. /// </summary> /// <param name="textBuffer">A text buffer</param> /// <param name="uri">A <see cref="Uri"/> that can be used to locate the provided <paramref name="textBuffer"/>.</param> /// <returns><c>true</c> if a Razor based <see cref="Uri"/> existed on the buffer, other wise <c>false</c>.</returns> public abstract bool TryGet(ITextBuffer textBuffer, out Uri uri); /// <summary> /// Adds or updates the provided <paramref name="uri"/> for the given <paramref name="textBuffer"/> under a Razor property name. /// </summary> /// <param name="textBuffer">A text buffer</param> /// <param name="uri">A <see cref="Uri"/> that can be used to locate the provided <paramref name="textBuffer"/>.</param> public abstract void AddOrUpdate(ITextBuffer textBuffer, Uri uri); } }
55.925
163
0.657577
[ "Apache-2.0" ]
tmat/razor-tooling
src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/FileUriProvider.cs
2,239
C#
using System; using System.Linq; using Microsoft.AnalysisServices.Tabular; using TabularModel = Microsoft.AnalysisServices.Tabular.Model; using Column = Dax.Template.Model.Column; using Dax.Template.Exceptions; using Dax.Template.Interfaces; using Dax.Template.Constants; namespace Dax.Template.Tables.Dates { public class CustomDateTemplateDefinition : CustomTemplateDefinition { /// <summary> /// Define the calendar type for time intelligence calculations /// </summary> public string? CalendarType { get; set; } public string[]? CalendarTypes { get; set; } } public class CustomDateTable : BaseDateTemplate<IDateTemplateConfig> { // TODO: this could be localized (as other column names) const string DATE_COLUMN_NAME = "Date"; public CustomDateTable(IDateTemplateConfig config, CustomDateTemplateDefinition template, TabularModel? model, string? referenceTable = null) : base(config, template, model) { HiddenTable = referenceTable; Annotations.Add(Attributes.SQLBI_TEMPLATE_ATTRIBUTE, Attributes.SQLBI_TEMPLATE_DATES); Annotations.Add( Attributes.SQLBI_TEMPLATETABLE_ATTRIBUTE, (referenceTable == null) ? Attributes.SQLBI_TEMPLATETABLE_DATEAUTOTEMPLATE : Attributes.SQLBI_TEMPLATETABLE_DATE ); if (!string.IsNullOrWhiteSpace(template.CalendarType)) { CalendarType = new string[] { template.CalendarType }; } else { CalendarType = template.CalendarTypes; } } protected override void InitTemplate(IDateTemplateConfig config, CustomTemplateDefinition template, Predicate<CustomTemplateDefinition.Column> skipColumn, TabularModel? model) { bool hasHolidays = HolidaysConfig.HasHolidays(config.HolidaysReference); if (hasHolidays) { if (model?.Tables.FirstOrDefault(t => t.Name == config.HolidaysReference?.TableName) == null) { throw new TemplateException($"Holidays table '{config.HolidaysReference?.TableName}' not found."); } } base.InitTemplate( config, template, // Skip columns related to holidays if no holidays configuration available ((columnDefinition) => columnDefinition.RequiresHolidays && !hasHolidays), model); } protected override Column CreateColumn(string name, DataType dataType) { if (name == DATE_COLUMN_NAME) { return new Model.DateColumn() { Name = name, DataType = dataType }; } else return base.CreateColumn(name, dataType); } } }
40.680556
183
0.617958
[ "MIT" ]
sql-bi/DaxTemplate
src/Dax.Template/Tables/Dates/CustomDateTable.cs
2,931
C#
/* * Original author: Nicholas Shulman <nicksh .at. u.washington.edu>, * MacCoss Lab, Department of Genome Sciences, UW * * Copyright 2011 University of Washington - Seattle, WA * * 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 pwiz.Skyline.Model.Results; using pwiz.Skyline.Properties; namespace pwiz.Skyline.Model.Find { /// <summary> /// Finds all transitions that were manually integrated. /// </summary> public class ManuallyIntegratedPeakFinder : AbstractTransitionResultFinder { public override string Name { get { return @"manually_integrated_peaks"; } } public override string DisplayName { get { return Resources.ManuallyIntegratedPeakFinder_DisplayName_Manually_integrated_peaks; } } protected override FindMatch MatchTransition(TransitionChromInfo transitionChromInfo) { return transitionChromInfo.IsUserSetManual ? new FindMatch(Resources.ManuallyIntegratedPeakFinder_MatchTransition_Manually_integrated_peak) : null; } protected override FindMatch MatchTransitionGroup(TransitionGroupChromInfo transitionGroupChromInfo) { return transitionGroupChromInfo.IsUserSetManual ? new FindMatch(Resources.ManuallyIntegratedPeakFinder_DisplayName_Manually_integrated_peaks) : null; } } }
37.321429
120
0.658373
[ "Apache-2.0" ]
CSi-Studio/pwiz
pwiz_tools/Skyline/Model/Find/ManuallyIntegratedPeakFinder.cs
2,092
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Plugins { public interface IMarkdownService { string Name { get; } MarkupResult Markup(string src, string path); MarkupResult Markup(string src, string path, bool enableValidation); } }
28.066667
102
0.686461
[ "MIT" ]
Algorithman/docfx
src/Microsoft.DocAsCode.Plugins/IMarkdownService.cs
409
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using PJanssen.ParsecSharp.IO; namespace PJanssen.ParsecSharp { [TestClass] public class CharsTests { #region Any [TestMethod] public void Any_EmptyStream_ReturnsError() { var parser = Chars.Any(); var result = parser.Parse(""); ParseAssert.IsError(result); } [TestMethod] public void Any_NonEmptyStream_ReturnsChar() { var parser = Chars.Any(); var result = parser.Parse("a"); ParseAssert.ValueEquals('a', result); } #endregion #region Satisfy [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Satisfy_PredicateNull_ThrowsException() { Chars.Satisfy(null); } [TestMethod] public void Satisfy_PassingPredicate_ReturnsChar() { var parser = Chars.Satisfy(c => true); var result = parser.Parse("xyz"); ParseAssert.ValueEquals('x', result); } [TestMethod] public void Satisfy_FailingPredicate_ReturnsError() { var parser = Chars.Satisfy(c => false); var result = parser.Parse("xyz"); ParseAssert.IsError(result); } #endregion #region Char [TestMethod] public void Char_MatchingChar_ReturnsChar() { var parser = Chars.Char('x'); var result = parser.Parse("xyz"); ParseAssert.ValueEquals('x', result); } [TestMethod] public void Char_NonMatchingChar_ReturnsError() { var parser = Chars.Char('x'); var result = parser.Parse("abc"); ParseAssert.IsError(result); } #endregion #region OneOf [TestMethod] public void OneOf_MatchingChar_ReturnsChar() { var parser = Chars.OneOf("abc"); var result = parser.Parse("b"); ParseAssert.ValueEquals('b', result); } [TestMethod] public void OneOf_NonMatchingChar_ReturnsError() { var parser = Chars.OneOf("xyz"); var result = parser.Parse("a"); ParseAssert.IsError(result); } #endregion #region NoneOf [TestMethod] public void NoneOf_MatchingChar_ReturnsError() { var parser = Chars.NoneOf("abc"); var result = parser.Parse("b"); ParseAssert.IsError(result); } [TestMethod] public void OneOf_NonMatchingChar_ReturnsChar() { var parser = Chars.NoneOf("xyz"); var result = parser.Parse("b"); ParseAssert.ValueEquals('b', result); } #endregion #region Not [TestMethod] public void Not_MatchingChar_ReturnsError() { var parser = Chars.Not('x'); var result = parser.Parse("x"); ParseAssert.IsError(result); } [TestMethod] public void Not_NonMatchingChar_ReturnsParsedChar() { var parser = Chars.Not('x'); var result = parser.Parse("y"); ParseAssert.ValueEquals('y', result); } #endregion #region EndOfLine [TestMethod] public void EndOfLine_NoMatch_ReturnsError() { var parser = Chars.EndOfLine(); var result = parser.Parse("abc"); ParseAssert.IsError(result); } [TestMethod] public void EndOfLine_LF_ReturnsLF() { var parser = Chars.EndOfLine(); var result = parser.Parse("\n"); ParseAssert.ValueEquals('\n', result); } [TestMethod] public void EndOfLine_CRLF_ReturnsLF() { var parser = Chars.EndOfLine(); var result = parser.Parse("\r\n"); ParseAssert.ValueEquals('\n', result); } #endregion #region String [TestMethod] public void String_EndOfInput_ReturnsError() { var parser = Chars.String("xyz"); var result = parser.Parse("xy"); ParseAssert.IsError(result); } [TestMethod] public void String_NoMatch_ReturnsError() { var parser = Chars.String("xyz"); var result = parser.Parse("abc"); ParseAssert.IsError(result); } [TestMethod] public void String_NoMatch_ConsumesNoInput() { var parser = Chars.String("xyz"); var input = new StringInputReader("---"); var result = parser.Parse(input); Position position = input.GetPosition(); Assert.AreEqual(0, position.Offset); } [TestMethod] public void String_PartialMatch_SetsCorrectPosition() { var parser = Chars.String("xyz"); var input = new StringInputReader("xy-"); var result = parser.Parse(input); Position position = input.GetPosition(); Assert.AreEqual(2, position.Offset, "Offset"); Assert.AreEqual(1, position.Line, "Line"); Assert.AreEqual(3, position.Column, "Column"); } [TestMethod] public void String_Match_ReturnsValue() { var parser = Chars.String("abc"); var result = parser.Parse("abc"); ParseAssert.ValueEquals("abc", result); } #endregion } }
22.491525
59
0.573662
[ "MIT" ]
dantincu/turmerik-obsolete-2021-05-11
dotnet/src-ext/_src/ParsecSharp/ParsecSharp.Tests/CharsTests.cs
5,310
C#
// These sources have been forked from https://github.com/dotnet/corefx/releases/tag/v1.1.8 // then customized by Ole Consignado in order to meet it needs. // Original sources should be found at: https://github.com/dotnet/corefx/tree/v1.1.8/src/System.ComponentModel.Annotations // Thanks to Microsoft for making it open source! // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Otc.ComponentModel.DataAnnotations { /// <summary> /// Enumeration of logical data types that may appear in <see cref="DataTypeAttribute" /> /// </summary> public enum DataType { /// <summary> /// Custom data type, not one of the static data types we know /// </summary> Custom = 0, /// <summary> /// DateTime data type /// </summary> DateTime = 1, /// <summary> /// Date data type /// </summary> Date = 2, /// <summary> /// Time data type /// </summary> Time = 3, /// <summary> /// Duration data type /// </summary> Duration = 4, /// <summary> /// Phone number data type /// </summary> PhoneNumber = 5, /// <summary> /// Currency data type /// </summary> Currency = 6, /// <summary> /// Plain text data type /// </summary> Text = 7, /// <summary> /// Html data type /// </summary> Html = 8, /// <summary> /// Multiline text data type /// </summary> MultilineText = 9, /// <summary> /// Email address data type /// </summary> EmailAddress = 10, /// <summary> /// Password data type -- do not echo in UI /// </summary> Password = 11, /// <summary> /// URL data type /// </summary> Url = 12, /// <summary> /// URL to an Image -- to be displayed as an image instead of text /// </summary> ImageUrl = 13, /// <summary> /// Credit card data type /// </summary> CreditCard = 14, /// <summary> /// Postal code data type /// </summary> PostalCode = 15, /// <summary> /// File upload data type /// </summary> Upload = 16 } }
25.288462
122
0.494677
[ "MIT" ]
OleConsignado/otc-annotations
src/Otc.ComponentModel.Annotations/src/Otc/ComponentModel/DataAnnotations/DataType.cs
2,630
C#
using NodeCanvas.Framework; using ParadoxNotion.Design; using System; using UnityEngine; namespace NodeCanvas.Tasks.Actions { [Category("Movement")] public class MoveAway : ActionTask<Transform> { [RequiredField] public BBParameter<GameObject> target; public BBParameter<float> speed = 2f; public BBParameter<float> stopDistance = 3f; public bool repeat; protected override void OnExecute() { this.Move(); } protected override void OnUpdate() { this.Move(); } private void Move() { if ((base.agent.position - this.target.value.transform.position).magnitude < this.stopDistance.value) { base.agent.position = Vector3.MoveTowards(base.agent.position, this.target.value.transform.position, -this.speed.value * Time.deltaTime); } else if (!this.repeat) { base.EndAction(); } } } }
19.72093
141
0.705189
[ "MIT" ]
moto2002/kaituo_src
src/NodeCanvas.Tasks.Actions/MoveAway.cs
848
C#
//------------------------------------------------------------------------------ // <自動產生的> // 這段程式碼是由工具產生的。 // // 變更這個檔案可能會導致不正確的行為,而且如果已重新產生 // 程式碼,則會遺失變更。 // </自動產生的> //------------------------------------------------------------------------------ namespace WebPages.SystemAdmin { public partial class Admin { /// <summary> /// head 控制項。 /// </summary> /// <remarks> /// 自動產生的欄位。 /// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。 /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder head; /// <summary> /// form1 控制項。 /// </summary> /// <remarks> /// 自動產生的欄位。 /// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。 /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// ContentPlaceHolder1 控制項。 /// </summary> /// <remarks> /// 自動產生的欄位。 /// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。 /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder1; } }
24.977778
91
0.455516
[ "MIT" ]
zxz13561/UbayWeek4TeamHomework
AccountingNoteSystem/WebPages/SystemAdmin/Admin.Master.designer.cs
1,488
C#
//! \file ImageFC.cs //! \date 2018 Nov 17 //! \brief Mink compressed bitmap format. // // Copyright (C) 2018-2019 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.ComponentModel.Composition; using System.IO; using System.Windows.Media; using GameRes.Utility; namespace GameRes.Formats.Mink { internal class FcMetaData : ImageMetaData { public byte Flag; } [Export(typeof(ImageFormat))] public class FcFormat : ImageFormat { public override string Tag { get { return "BMP/FC"; } } public override string Description { get { return "Mink compressed bitmap format"; } } public override uint Signature { get { return 0; } } public FcFormat () { Signatures = new uint[] { 0x01184346, 0x00184346, 0x00204346, 0 }; } public override ImageMetaData ReadMetaData (IBinaryStream file) { var header = file.ReadHeader (8); if (!header.AsciiEqual ("FC")) return null; int bpp = header[2]; if (bpp != 24 && bpp != 32) return null; byte flag = header[3]; if (flag != 0 && flag != 1) return null; return new FcMetaData { Width = header.ToUInt16 (4), Height = header.ToUInt16 (6), BPP = bpp, Flag = flag, }; } public override ImageData Read (IBinaryStream file, ImageMetaData info) { var reader = new FcReader (file, (FcMetaData)info); return reader.Unpack(); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("FcFormat.Write not implemented"); } } internal class FcReader { IBinaryStream m_input; FcMetaData m_info; public FcReader (IBinaryStream input, FcMetaData info) { m_input = input; m_info = info; } public ImageData Unpack () { m_input.Position = 8; var output = new uint[m_info.iWidth * m_info.iHeight]; UnpackRgb (output); if (32 == m_info.BPP) UnpackAlpha (output); if (m_info.Flag != 0) RestoreRgb (output); PixelFormat format = 32 == m_info.BPP ? PixelFormats.Bgra32 : PixelFormats.Bgr32; return ImageData.CreateFlipped (m_info, format, null, output, m_info.iWidth * 4); } void UnpackRgb (uint[] output) { int dst = 0; m_bits = 0x80000000; uint ref_pixel = m_info.Flag != 0 ? 0x808080u : 0u; uint pixel = ref_pixel; while (dst < output.Length) { if (GetNextBit() == 0) { if (GetNextBit() != 0) { int offset = m_info.iWidth + GetNextBit(); pixel = output[dst - offset + 1]; } else { pixel = output[dst - 1]; } uint v = GetVarInt(); v = (v >> 1) ^ (uint)-(v & 1); pixel = Binary.RotR (pixel, 8) + (v << 24); v = GetVarInt(); v = (v >> 1) ^ (uint)-(v & 1); pixel = Binary.RotR (pixel, 8) + (v << 24); v = GetVarInt(); v = (v >> 1) ^ (uint)-(v & 1); pixel = Binary.RotR (pixel, 8) + (v << 24); pixel >>= 8; output[dst++] = pixel; } else if (GetNextBit() == 0) { if (GetNextBit() == 0) { pixel = output[dst - m_info.iWidth - 1]; uint v = GetVarInt(); v = (v >> 1) ^ (uint)-(v & 1); pixel = Binary.RotR (pixel, 8) + (v << 24); v = GetVarInt(); v = (v >> 1) ^ (uint)-(v & 1); pixel = Binary.RotR (pixel, 8) + (v << 24); v = GetVarInt(); v = (v >> 1) ^ (uint)-(v & 1); pixel = Binary.RotR (pixel, 8) + (v << 24); pixel >>= 8; output[dst++] = pixel; } else { pixel = ref_pixel; uint v = GetVarInt(); v = (v >> 1) ^ (uint)-(v & 1); pixel ^= v & 0xFF; v = GetVarInt(); v = (v >> 1) ^ (uint)-(v & 1); pixel ^= (v & 0xFF) << 8; v = GetVarInt(); v = (v >> 1) ^ (uint)-(v & 1); pixel ^= (v & 0xFF) << 16; output[dst++] = pixel; } } else if (GetNextBit() != 0) { int offset = m_info.iWidth; if (GetNextBit() != 0) { offset += GetNextBit(); } else { offset -= 1; } pixel = output[dst - offset]; output[dst++] = pixel; } else if (GetNextBit() == 0) { pixel = GetBits (24); output[dst++] = pixel; } else { int count = Math.Min ((int)GetVarInt(), output.Length - dst); while (count --> 0) { output[dst++] = pixel; } } } } void UnpackAlpha (uint[] output) { int dst = 0; while (dst < output.Length) { uint val = GetBits (8) << 24; uint count = GetVarInt() + 1; while (count != 0) { output[dst++] |= val; --count; } } } void RestoreRgb (uint[] output) { int stride = m_info.iWidth; int dst = stride; while (dst < output.Length) { uint prev = output[dst-stride]; uint pixel = output[dst]; output[dst] = ((pixel + prev - 0x80) & 0xFF) | (((pixel >> 8) + (prev >> 8) - 0x80) & 0xFF) << 8 | (((pixel >> 16) + (prev >> 16) - 0x80) & 0xFF) << 16 | pixel & 0xFF000000; ++dst; } } uint GetBits (int count) { uint val = m_bits >> (32 - count); m_bits <<= count; if (0 == m_bits) { m_bits = ReadUInt32(); int shift = BitScanForward (val); uint ebx = m_bits ^ 0x80000000; m_bits = (m_bits << 1 | 1) << shift; val ^= ebx >> (shift ^ 0x1F); } return val; } uint m_bits; int GetNextBit () { uint bit = m_bits >> 31; m_bits <<= 1; if (0 == m_bits) { m_bits = ReadUInt32(); bit = m_bits >> 31; m_bits = m_bits << 1 | 1; } return (int)bit; } uint GetVarInt () { int count = 0; do { ++count; } while (GetNextBit() != 0); uint num = 1; while (count --> 0) { num = num << 1 | (uint)GetNextBit(); } return num - 2; } byte[] m_dword_buffer = new byte[4]; uint ReadUInt32 () { int last = m_input.Read (m_dword_buffer, 0, 4); while (last < m_dword_buffer.Length) m_dword_buffer[last++] = 0; return BigEndian.ToUInt32 (m_dword_buffer, 0); } static int BitScanForward (uint val) { int count = 0; for (uint mask = 1; mask != 0; mask <<= 1) { if ((val & mask) != 0) break; ++count; } return count; } } }
32.080645
94
0.412569
[ "MIT" ]
1127815807/GARbro
Legacy/Mink/ImageFC.cs
9,945
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Linq; namespace PoE.BuffWatcher.Scanner { public class ImageScanner : IDisposable { private const int BuffHeight = 84; private const int BuffWidth = 87; private const int BuffStartY = 9; private const int DebuffStartY = 122; // Number of pixels in the corners that arc private const int ArcPixels = 6; private const int SkipPixels = 10; private byte ScanColorA = 0xFF; private byte ScanColorR = 0x57; private byte ScanColorG = 0x41; private byte ScanColorB = 0x33; private readonly Bitmap _bitmap; public ImageScanner(Image image) { _bitmap = new Bitmap(image); } public Image FindBuffs() { var yPos = BuffStartY + ArcPixels + SkipPixels; var rowData = GetRowData(yPos); var rightBorders = FindRightBorders(rowData); if (rightBorders.Count == 0) { return null; } var rects = CalculateRectangles(BuffStartY, rightBorders); return BarCreator.CreateBuffImage(_bitmap, rects); } public Image FindDebuffs() { var yPos = DebuffStartY + ArcPixels + SkipPixels; var rowData = GetRowData(yPos); var rightBorders = FindRightBorders(rowData); if (rightBorders.Count == 0) { return null; } var rects = CalculateRectangles(DebuffStartY, rightBorders); return BarCreator.CreateBuffImage(_bitmap, rects); } private unsafe Span<uint> GetRowData(int yPos) { var time = Stopwatch.StartNew(); var data = _bitmap.LockBits(new Rectangle(0, yPos, _bitmap.Width, 1), ImageLockMode.ReadOnly, _bitmap.PixelFormat); var rowData = new Span<uint>(data.Scan0.ToPointer(), data.Width); _bitmap.UnlockBits(data); time.Stop(); System.Console.WriteLine($"GetRowData took {time.ElapsedMilliseconds}"); return rowData; } private List<int> FindRightBorders(in Span<uint> rowData) { var time = Stopwatch.StartNew(); int lastPosFound = BuffWidth; int abortThreshHold = BuffWidth * 2; List<int> rightBorders = new List<int>(); for (int i = BuffWidth; i - lastPosFound < abortThreshHold && i < _bitmap.Width; i++) { if (ColorCheck(rowData[i])) { rightBorders.Add(i); i += BuffWidth; lastPosFound = i; } } time.Stop(); System.Console.WriteLine($"FindRightBorders took {time.ElapsedMilliseconds}"); return rightBorders; } private bool ColorCheck(uint color) { var bytes = BitConverter.GetBytes(color); var diff = Math.Abs(bytes[3] - ScanColorA) + Math.Abs(bytes[2] - ScanColorR) + Math.Abs(bytes[1] - ScanColorG) + Math.Abs(bytes[0] - ScanColorB); return diff < 5; } private List<Rectangle> CalculateRectangles(int buffStartY, List<int> rightBorders) { return rightBorders.Select(rb => new Rectangle( rb - BuffWidth + 1, buffStartY, BuffWidth, BuffHeight) ).ToList(); } public void Dispose() { _bitmap?.Dispose(); } } }
30.022727
128
0.520565
[ "MIT" ]
Tobbe1974/PoE-Buff-Watcher
PoE.BuffWatcher.Scanner/ImageScanner.cs
3,965
C#
using System; using RosMessageTypes.Std; using Unity.Robotics.Visualizations; using UnityEngine; public class UInt8MultiArrayDefaultVisualizer : GuiVisualizer<UInt8MultiArrayMsg> { [SerializeField] bool m_Tabulate = true; public override Action CreateGUI(UInt8MultiArrayMsg message, MessageMetadata meta) { return () => { message.layout.GUIMultiArray(message.data, ref m_Tabulate); }; } }
23.526316
86
0.709172
[ "Apache-2.0" ]
DLu/ROS-TCP-Connector
com.unity.robotics.visualizations/Runtime/DefaultVisualizers/Std/UInt8MultiArrayDefaultVisualizer.cs
447
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using HairSalon.Models; namespace HairSalon { public class Startup { public Startup(IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; set; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFrameworkMySql() .AddDbContext<HairSalonContext>(options => options .UseMySql(Configuration["ConnectionStrings:DefaultConnection"], ServerVersion.AutoDetect(Configuration["ConnectionStrings:DefaultConnection"]))); } public void Configure(IApplicationBuilder app) { app.UseDeveloperExceptionPage(); app.UseRouting(); app.UseEndpoints(routes => { routes.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); app.UseStaticFiles(); app.Run(async (context) => { await context.Response.WriteAsync("Check routes"); }); } } }
27.38
153
0.695398
[ "MIT" ]
beads89/Hair-Salon
HairSalon/Startup.cs
1,369
C#
namespace IRunes.Models { using System; public class User : BaseModel<string> { public User() { this.Id = Guid.NewGuid().ToString(); } public string Username { get; set; } public string Password { get; set; } public string Email { get; set; } } }
17.263158
48
0.52439
[ "MIT" ]
MiroslavKisov/Software-University
CSharp Web/SIS/IRunes.Models/User.cs
330
C#
using Roc.CMS.Auditing; using Shouldly; using Xunit; namespace Roc.CMS.Tests.Auditing { public class NamespaceStripper_Tests: AppTestBase { private readonly INamespaceStripper _namespaceStripper; public NamespaceStripper_Tests() { _namespaceStripper = Resolve<INamespaceStripper>(); } [Fact] public void Should_Stripe_Namespace() { var controllerName = _namespaceStripper.StripNameSpace("Roc.CMS.Web.Controllers.HomeController"); controllerName.ShouldBe("HomeController"); } [Theory] [InlineData("Roc.CMS.Auditing.GenericEntityService`1[[Roc.CMS.Storage.BinaryObject, Roc.CMS.Core, Version=1.10.1.0, Culture=neutral, PublicKeyToken=null]]", "GenericEntityService<BinaryObject>")] [InlineData("CompanyName.ProductName.Services.Base.EntityService`6[[CompanyName.ProductName.Entity.Book, CompanyName.ProductName.Core, Version=1.10.1.0, Culture=neutral, PublicKeyToken=null],[CompanyName.ProductName.Services.Dto.Book.CreateInput, N...", "EntityService<Book, CreateInput>")] [InlineData("Roc.CMS.Auditing.XEntityService`1[Roc.CMS.Auditing.AService`5[[Roc.CMS.Storage.BinaryObject, Roc.CMS.Core, Version=1.10.1.0, Culture=neutral, PublicKeyToken=null],[Roc.CMS.Storage.TestObject, Roc.CMS.Core, Version=1.10.1.0, Culture=neutral, PublicKeyToken=null],]]", "XEntityService<AService<BinaryObject, TestObject>>")] public void Should_Stripe_Generic_Namespace(string serviceName, string result) { var genericServiceName = _namespaceStripper.StripNameSpace(serviceName); genericServiceName.ShouldBe(result); } } }
50
342
0.718235
[ "MIT" ]
RocChing/Roc.CMS
test/Roc.CMS.Tests/Auditing/NamespaceStripper_Tests.cs
1,702
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BiggerWebFormsSample { public partial class ViewSwitcher { } }
28.125
80
0.42
[ "MIT" ]
CNinnovation/DotnetIntroSep2017
ASPNET/BiggerWebFormsSample/BiggerWebFormsSample/ViewSwitcher.ascx.designer.cs
450
C#
using System; using Girvs.AutoMapper.Mapper; using Girvs.BusinessBasis.Dto; using ZhuoFan.Wb.BasicService.Domain.Enumerations; using ZhuoFan.Wb.BasicService.Domain.Queries; namespace ZhuoFan.Wb.BasicService.Application.ViewModels.User { [AutoMapFrom(typeof(UserQuery))] [AutoMapTo(typeof(UserQuery))] public class UserQueryViewModel : QueryDtoBase<UserQueryListViewModel> { /// <summary> /// 用户名称 /// </summary> public string UserName { get; set; } /// <summary> /// 用户登陆名称 /// </summary> public string UserAccount { get; set; } /// <summary> /// 用户状态 /// </summary> public DataState? DataState { get; set; } } [AutoMapFrom(typeof(Domain.Models.User))] public class UserQueryListViewModel : IDto { public Guid Id { get; set; } /// <summary> /// 用户登陆名称 /// </summary> public string UserAccount { get; set; } /// <summary> /// 用户名称 /// </summary> public string UserName { get; set; } /// <summary> /// 联系电话 /// </summary> public string ContactNumber { get; set; } /// <summary> /// 用户状态 /// </summary> public DataState State { get; set; } /// <summary> /// 用户类型 /// </summary> public UserType UserType { get; set; } } }
24.186441
74
0.543097
[ "Apache-2.0" ]
shenxiangxiong/Girvs
Examples/BasicManagement/ZhuoFan.Wb.BasicService.Application/ViewModels/User/UserQueryViewModel.cs
1,501
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.Reflection; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Xunit; // ReSharper disable ArrangeAccessorOwnerBody // ReSharper disable MemberCanBePrivate.Local // ReSharper disable UnusedMember.Local // ReSharper disable PossibleInvalidOperationException // ReSharper disable ParameterOnlyUsedForPreconditionCheck.Local // ReSharper disable InconsistentNaming // ReSharper disable ConvertToAutoProperty namespace Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal { public class BackingFieldConventionTest { [Fact] public void Auto_property_name_matching_field_is_used_as_first_preference() => FieldMatchTest<TheDarkSideOfTheMoon>("ComfortablyNumb", "<ComfortablyNumb>k__BackingField"); [Fact] public void Property_name_matching_field_is_used_as_next_preference() => FieldMatchTest<TheDarkSideOfTheMoon>("IsThereAnybodyOutThere", "IsThereAnybodyOutThere"); [Fact] public void Camel_case_matching_field_is_used_as_next_preference() => FieldMatchTest<TheDarkSideOfTheMoon>("Breathe", "breathe"); [Fact] public void Camel_case_matching_field_is_not_used_if_type_is_not_compatible() => FieldMatchTest<TheDarkSideOfTheMoon>("OnTheRun", "_onTheRun"); [Fact] public void Underscore_camel_case_matching_field_is_used_as_next_preference() => FieldMatchTest<TheDarkSideOfTheMoon>("Time", "_time"); [Fact] public void Underscpre_camel_case_matching_field_is_not_used_if_type_is_not_compatible() => FieldMatchTest<TheDarkSideOfTheMoon>("TheGreatGigInTheSky", "_TheGreatGigInTheSky"); [Fact] public void Underscpre_matching_field_is_used_as_next_preference() => FieldMatchTest<TheDarkSideOfTheMoon>("Money", "_Money"); [Fact] public void Underscore_matching_field_is_not_used_if_type_is_not_compatible() => FieldMatchTest<TheDarkSideOfTheMoon>("UsAndThem", "m_usAndThem"); [Fact] public void M_underscpre_camel_case_matching_field_is_used_as_next_preference() => FieldMatchTest<TheDarkSideOfTheMoon>("AnyColourYouLike", "m_anyColourYouLike"); [Fact] public void M_underscore_camel_case_matching_field_is_not_used_if_type_is_not_compatible() => FieldMatchTest<TheDarkSideOfTheMoon>("BrainDamage", "m_BrainDamage"); [Fact] public void M_underscore_matching_field_is_used_as_next_preference() => FieldMatchTest<TheDarkSideOfTheMoon>("Eclipse", "m_Eclipse"); [Fact] public void M_underscore_matching_field_is_not_used_if_type_is_not_compatible() { var entityType = new Model().AddEntityType(typeof(TheDarkSideOfTheMoon)); var property = entityType.AddProperty("SpeakToMe", typeof(int)); new BackingFieldConvention().Apply(property.Builder); Assert.Null(property.GetFieldName()); } [Fact] public void Property_name_matching_field_is_used_as_first_preference_for_field_only() => FieldMatchTest<TheDarkerSideOfTheMoon>("IsThereAnybodyOutThere", "IsThereAnybodyOutThere"); [Fact] public void Camel_case_matching_field_is_used_as_next_preference_for_field_only() => FieldMatchTest<TheDarkerSideOfTheMoon>("Breathe", "breathe"); [Fact] public void Camel_case_matching_field_is_not_used_if_type_is_not_compatible_for_field_only() => FieldMatchTest<TheDarkerSideOfTheMoon>("OnTheRun", "_onTheRun"); [Fact] public void Underscore_camel_case_matching_field_is_used_as_next_preference_for_field_only() => FieldMatchTest<TheDarkerSideOfTheMoon>("Time", "_time"); [Fact] public void Underscpre_camel_case_matching_field_is_not_used_if_type_is_not_compatible_for_field_only() => FieldMatchTest<TheDarkerSideOfTheMoon>("TheGreatGigInTheSky", "_TheGreatGigInTheSky"); [Fact] public void Underscpre_matching_field_is_used_as_next_preference_for_field_only() => FieldMatchTest<TheDarkerSideOfTheMoon>("Money", "_Money"); [Fact] public void Underscore_matching_field_is_not_used_if_type_is_not_compatible_for_field_only() => FieldMatchTest<TheDarkerSideOfTheMoon>("UsAndThem", "m_usAndThem"); [Fact] public void M_underscpre_camel_case_matching_field_is_used_as_next_preference_for_field_only() => FieldMatchTest<TheDarkerSideOfTheMoon>("AnyColourYouLike", "m_anyColourYouLike"); [Fact] public void M_underscore_camel_case_matching_field_is_not_used_if_type_is_not_compatible_for_field_only() => FieldMatchTest<TheDarkerSideOfTheMoon>("BrainDamage", "m_BrainDamage"); [Fact] public void M_underscore_matching_field_is_used_as_next_preference_for_field_only() => FieldMatchTest<TheDarkerSideOfTheMoon>("Eclipse", "m_Eclipse"); [Fact] public void M_underscore_matching_field_is_not_used_if_type_is_not_compatible_for_field_only() { var entityType = new Model().AddEntityType(typeof(TheDarkerSideOfTheMoon)); var property = entityType.AddProperty("SpeakToMe", typeof(int)); new BackingFieldConvention().Apply(property.Builder); Assert.Null(property.GetFieldName()); } private static void FieldMatchTest<TEntity>(string propertyName, string fieldName) { var entityType = new Model().AddEntityType(typeof(TEntity)); var property = entityType.AddProperty(propertyName, typeof(int)); new BackingFieldConvention().Apply(property.Builder); Assert.Equal(fieldName, property.GetFieldName()); } [Fact] public void Field_in_base_type_is_matched() { var entityType = new Model().AddEntityType(typeof(TheDarkSide)); var property = entityType.AddProperty(OfTheMoon.TheGreatGigInTheSkyProperty); new BackingFieldConvention().Apply(property.Builder); Assert.Equal("_theGreatGigInTheSky", property.GetFieldName()); } [Fact] public void Matched_field_on_base_class_is_found() { var entityType = new Model().AddEntityType(typeof(TheDarkSide)); var property = entityType.AddProperty(TheDarkSide.OnBaseProperty); new BackingFieldConvention().Apply(property.Builder); Assert.Equal("_onBase", property.GetFieldName()); } [Fact] public void Explicitly_set_FieldInfo_is_used() { var entityType = new Model().AddEntityType(typeof(TheDarkSideOfTheMoon)); var property = entityType.AddProperty("OnTheRun", typeof(int)); property.SetField("m_onTheRun"); new BackingFieldConvention().Apply(property.Builder); Assert.Equal("m_onTheRun", property.GetFieldName()); } [Fact] public void FieldInfo_set_by_annotation_is_used() { var entityType = new Model().AddEntityType(typeof(TheDarkSideOfTheMoon)); var property = entityType.AddProperty("OnTheRun", typeof(int)); property.SetField("m_onTheRun", ConfigurationSource.DataAnnotation); new BackingFieldConvention().Apply(property.Builder); Assert.Equal("m_onTheRun", property.GetFieldName()); } #pragma warning disable 649 #pragma warning disable 169 #pragma warning disable IDE0027 // Use expression body for accessors #pragma warning disable IDE1006 // Naming Styles #pragma warning disable IDE0044 // Add readonly modifier private class TheDarkSideOfTheMoon { private readonly string m_SpeakToMe; private int _notSpeakToMe; public int SpeakToMe { get { return _notSpeakToMe; } set { _notSpeakToMe = value; } } private int? comfortablyNumb; private int? _comfortablyNumb; private int? _ComfortablyNumb; private int? m_comfortablyNumb; private int? m_ComfortablyNumb; public int ComfortablyNumb { get; set; } private readonly int IsThereAnybodyOutThere; private readonly int isThereAnybodyOutThere; private readonly int _isThereAnybodyOutThere; private readonly int _IsThereAnybodyOutThere; private readonly int m_isThereAnybodyOutThere; private readonly int m_IsThereAnybodyOutThere; private int? breathe; private int? _breathe; private int? _Breathe; private int? m_breathe; private int? m_Breathe; public int Breathe { get { return (int)breathe; } set { breathe = value; } } private readonly string onTheRun; private int? _onTheRun; private int? _OnTheRun; private int? m_onTheRun; private int? m_OnTheRun; public int OnTheRun { get { return (int)_onTheRun; } set { _onTheRun = value; } } private int? _time; private int? _Time; private int? m_time; private int? m_Time; public int Time { get { return (int)_time; } set { _time = value; } } private readonly string _theGreatGigInTheSky; private int? _TheGreatGigInTheSky; private int? m_theGreatGigInTheSky; private int? m_TheGreatGigInTheSky; public int TheGreatGigInTheSky { get { return (int)_TheGreatGigInTheSky; } set { _TheGreatGigInTheSky = value; } } private int? _Money; private int? m_money; private int? m_Money; public int Money { get { return (int)_Money; } set { _Money = value; } } private readonly string _UsAndThem; private int? m_usAndThem; private int? m_UsAndThem; public int UsAndThem { get { return (int)m_usAndThem; } set { m_usAndThem = value; } } private int? m_anyColourYouLike; private int? m_AnyColourYouLike; public int AnyColourYouLike { get { return (int)m_anyColourYouLike; } set { m_anyColourYouLike = value; } } private readonly string m_brainDamage; private int? m_BrainDamage; public int BrainDamage { get { return (int)m_BrainDamage; } set { m_BrainDamage = value; } } private int? m_Eclipse; public int Eclipse { get { return (int)m_Eclipse; } set { m_Eclipse = value; } } } private class TheDarkerSideOfTheMoon { private readonly string m_SpeakToMe; private readonly int IsThereAnybodyOutThere; private readonly int isThereAnybodyOutThere; private readonly int _isThereAnybodyOutThere; private readonly int _IsThereAnybodyOutThere; private readonly int m_isThereAnybodyOutThere; private readonly int m_IsThereAnybodyOutThere; private int? breathe; private int? _breathe; private int? _Breathe; private int? m_breathe; private int? m_Breathe; private readonly string onTheRun; private int? _onTheRun; private int? _OnTheRun; private int? m_onTheRun; private int? m_OnTheRun; private int? _time; private int? _Time; private int? m_time; private int? m_Time; private readonly string _theGreatGigInTheSky; private int? _TheGreatGigInTheSky; private int? m_theGreatGigInTheSky; private int? m_TheGreatGigInTheSky; private int? _Money; private int? m_money; private int? m_Money; private readonly string _UsAndThem; private int? m_usAndThem; private int? m_UsAndThem; private int? m_anyColourYouLike; private int? m_AnyColourYouLike; private readonly string m_brainDamage; private int? m_BrainDamage; private int? m_Eclipse; } private class TheDarkSide : OfTheMoon { public static readonly PropertyInfo OnBaseProperty = typeof(TheDarkSide).GetProperty(nameof(OnBase)); public int OnBase { get { return _onBase; } set { _onBase = value; } } public new int Unrelated = 1; } private class OfTheMoon { public static readonly PropertyInfo TheGreatGigInTheSkyProperty = typeof(OfTheMoon).GetProperty(nameof(TheGreatGigInTheSky)); private int? _theGreatGigInTheSky; public int TheGreatGigInTheSky { get { return (int)_theGreatGigInTheSky; } set { _theGreatGigInTheSky = value; } } protected int _onBase; public int Unrelated = 2; } #pragma warning restore 649 #pragma warning restore 169 #pragma warning restore IDE0027 // Use expression body for accessors #pragma warning restore IDE1006 // Naming Styles #pragma warning restore IDE0044 // Add readonly modifier } }
36.181586
113
0.635965
[ "Apache-2.0" ]
AzureMentor/EntityFrameworkCore
test/EFCore.Tests/Metadata/Conventions/Internal/BackingFieldConventionTest.cs
14,147
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 glue-2017-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Glue.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Glue.Model.Internal.MarshallTransformations { /// <summary> /// GetClassifier Request Marshaller /// </summary> public class GetClassifierRequestMarshaller : IMarshaller<IRequest, GetClassifierRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetClassifierRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetClassifierRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Glue"); string target = "AWSGlue.GetClassifier"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-03-31"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetName()) { context.Writer.WritePropertyName("Name"); context.Writer.Write(publicRequest.Name); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static GetClassifierRequestMarshaller _instance = new GetClassifierRequestMarshaller(); internal static GetClassifierRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetClassifierRequestMarshaller Instance { get { return _instance; } } } }
34.495238
141
0.623136
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/Glue/Generated/Model/Internal/MarshallTransformations/GetClassifierRequestMarshaller.cs
3,622
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenOverridingAndHidingTests : CSharpTestBase { [Fact] public void TestOverridingSimple() { // Tests: // Override virtual member // Override abstract member // Change parameter names in overridden member var source = @" abstract class Base { public abstract void Method(int a, ref string[] b); public virtual void Method(int a, System.Exception b) { System.Console.WriteLine(""Base.Method({0})"", a); } public virtual int Property { get { System.Console.WriteLine(""Base.Property.get()""); return 0; } set { System.Console.WriteLine(""Base.Property.set({0})"", value); } } } class Derived : Base { public override void Method(int i, ref string[] j) { System.Console.WriteLine(""Derived.Method({0}, {1})"", i, j[0]); } public override int Property { get { System.Console.WriteLine(""Derived.Property.get()""); return 1; } set { System.Console.WriteLine(""Derived.Property.set({0})"", value); } } } class Derived2 : Derived { public override void Method(int b, System.Exception c) { System.Console.WriteLine(""Derived2.Method({0})"", b); } } class Test { public static void Main() { Derived d = new Derived(); Base b = d; Derived2 d2 = new Derived2(); Base b2 = d2; Derived db = d2; string[] s1 = new string[] {""a""}; string[] s2 = new string[] {""b""}; string[] s3 = new string[] {""c""}; d2.Method(1, ref s1); b2.Method(2, ref s1); d.Method(3, ref s2); b.Method(4, ref s3); d2.Method(3, new System.Exception()); b2.Method(4, new System.ArgumentException()); d.Method(5, new System.Exception()); b.Method(6, new System.ArgumentException()); db.Method(7, new System.Exception()); int x = d2.Property; x = b2.Property; d.Property = 8; b.Property = 9; db.Property = 10; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived.Method(1, a) Derived.Method(2, a) Derived.Method(3, b) Derived.Method(4, c) Derived2.Method(3) Derived2.Method(4) Base.Method(5) Base.Method(6) Derived2.Method(7) Derived.Property.get() Derived.Property.get() Derived.Property.set(8) Derived.Property.set(9) Derived.Property.set(10)", expectedSignatures: new[] { Signature("Base", "Method", ".method public hidebysig newslot abstract virtual instance System.Void Method(System.Int32 a, System.String[]& b) cil managed"), Signature("Base", "Method", ".method public hidebysig newslot virtual instance System.Void Method(System.Int32 a, System.Exception b) cil managed"), Signature("Base", "Property", ".property readwrite instance System.Int32 Property"), Signature("Base", "get_Property", ".method public hidebysig newslot specialname virtual instance System.Int32 get_Property() cil managed"), Signature("Base", "set_Property", ".method public hidebysig newslot specialname virtual instance System.Void set_Property(System.Int32 value) cil managed"), Signature("Derived", "Method", ".method public hidebysig virtual instance System.Void Method(System.Int32 i, System.String[]& j) cil managed"), Signature("Derived", "Property", ".property readwrite instance System.Int32 Property"), Signature("Derived", "get_Property", ".method public hidebysig specialname virtual instance System.Int32 get_Property() cil managed"), Signature("Derived", "set_Property", ".method public hidebysig specialname virtual instance System.Void set_Property(System.Int32 value) cil managed"), Signature("Derived2", "Method", ".method public hidebysig virtual instance System.Void Method(System.Int32 b, System.Exception c) cil managed") }); } [WorkItem(6470, "DevDiv_Projects/Roslyn")] [Fact()] public void TestHidingObjectMembers() { // Tests: // Hide / overload virtual methods declared on object (ToString, GetHashcode etc.) var source = @" using System; class BaseClass<TInt, TLong> { public override string ToString() { Console.WriteLine(""BaseClass.ToString()""); return base.ToString(); } public virtual string ToString<T>() { Console.WriteLine(""BaseClass.ToString<T>()""); return ToString(); } public new virtual int GetHashCode() { Console.WriteLine(""BaseClass.GetHashCode()""); return base.GetHashCode(); } public virtual long GetHashCode(TInt x) { Console.WriteLine(""BaseClass.GetHashCode({0})"", x.ToString()); return GetHashCode(); } public static new void Equals(object x, object y) { Console.WriteLine(""BaseClass.Equals({0}, {1})"", x.ToString(), y.ToString()); } } class DerivedClass : BaseClass<int, long> { public new string ToString() { Console.WriteLine(""DerivedClass.ToString()""); return base.ToString(); } public new string ToString<T>() { Console.WriteLine(""DerivedClass.ToString<T>()""); return base.ToString<T>(); } public new virtual int GetHashCode() { Console.WriteLine(""DerivedClass.GetHashCode()""); return base.GetHashCode(); } public override long GetHashCode(int y) { Console.WriteLine(""DerivedClass.GetHashCode({0})"", y.ToString()); return base.GetHashCode(); } public override bool Equals(object obj) { Console.WriteLine(""DerivedClass.GetHashCode({0})"", obj.ToString()); return base.Equals(obj); } public static new void Equals(object x, object y) { Console.WriteLine(""DerivedClass.Equals({0}, {1})"", x.ToString(), y.ToString()); } } class Test { public static void Main() { BaseClass<int, long> b = new DerivedClass(); DerivedClass d = new DerivedClass(); b.ToString(); b.ToString<int>(); b.GetHashCode(); b.GetHashCode(0); b.Equals(1); BaseClass<int, long>.Equals(1, 2); d.ToString(); d.ToString<int>(); d.GetHashCode(); d.GetHashCode(3); d.Equals(4); DerivedClass.Equals(5, 6); } }"; var comp = CompileAndVerify(source, expectedOutput: @" BaseClass.ToString() BaseClass.ToString<T>() BaseClass.ToString() BaseClass.GetHashCode() DerivedClass.GetHashCode(0) BaseClass.GetHashCode() DerivedClass.GetHashCode(1) BaseClass.Equals(1, 2) DerivedClass.ToString() BaseClass.ToString() DerivedClass.ToString<T>() BaseClass.ToString<T>() BaseClass.ToString() DerivedClass.GetHashCode() BaseClass.GetHashCode() DerivedClass.GetHashCode(3) BaseClass.GetHashCode() DerivedClass.GetHashCode(4) DerivedClass.Equals(5, 6)", expectedSignatures: new[] { Signature("BaseClass`2", "ToString", ".method public hidebysig virtual instance System.String ToString() cil managed"), Signature("BaseClass`2", "ToString", ".method public hidebysig newslot virtual instance System.String ToString<T>() cil managed"), Signature("DerivedClass", "ToString", ".method public hidebysig instance System.String ToString() cil managed"), Signature("DerivedClass", "ToString", ".method public hidebysig instance System.String ToString<T>() cil managed"), Signature("BaseClass`2", "GetHashCode", ".method public hidebysig newslot virtual instance System.Int32 GetHashCode() cil managed"), Signature("BaseClass`2", "GetHashCode", ".method public hidebysig newslot virtual instance System.Int64 GetHashCode(TInt x) cil managed"), Signature("DerivedClass", "GetHashCode", ".method public hidebysig newslot virtual instance System.Int32 GetHashCode() cil managed"), Signature("DerivedClass", "GetHashCode", ".method public hidebysig virtual instance System.Int64 GetHashCode(System.Int32 y) cil managed") }); comp.VerifyDiagnostics( // (12,7): warning CS0659: 'DerivedClass' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class DerivedClass : BaseClass<int, long> Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "DerivedClass").WithArguments("DerivedClass")); } [Fact] public void TestHidingDifferentMemberKinds() { // Tests: // Sanity check - hiding / overloading of one type of construct with another // (e.g. method with field / field with property etc.) should work var source = @"using System; public class Class1 { public virtual float Member1 { set { Console.WriteLine(""Class1.Member1""); } } // virtual property public virtual void Member2() { Console.WriteLine(""Class1.Member2""); } // virtual method } public class Class2 : Class1 { new protected enum Member1 { First } // enum new interface Member2 { void Member1(); } // interface public static void Test() { Member1 x = Member1.First; Member2 y = null; Member1 z = x; x = z; Member2 w = y; y = w; } public class Class3 : Class2 { new protected virtual void Member1() { Console.WriteLine(""Class3.Member1""); } // virtual method new public static int Member2 = 10; // static field public new static void Test() { Class3 a = new Class3(); a.Member1(); Class4.Member1(); Class4 x = new Class4(); x.Member2(); // Does not bind to delegate? Class5 y = new Class5(); Member2 = Class5.Member2 + y.Member1; } class Class4 : Class3 { public new static void Member1() { Console.WriteLine(""Class4.Member1""); } // static method public new delegate void Member2(); // delegate } class Class5 : Class3 { public new readonly int Member1 = 2; // readonly new public const int Member2 = 2; // const } } } public class Class5 : Class1 { protected new virtual float Member1 { get { Console.WriteLine(""Class5.get_Member1""); return 0; } set { Console.WriteLine(""Class5.set_Member1""); } } // virtual property public new virtual void Member2() { Console.WriteLine(""Class5.Member2""); } // virtual method public static void Test() { Class5 a = new Class5(); a.Member2(); Class6 y = new Class6(); y.Member2(); a.Member1 = y.Member1; y.Member1 = a.Member1; Class7 z = new Class7(); z.Member1 = z.Member1; z.Member2(); } class Class6 : Class5 { protected sealed override float Member1 { get { Console.WriteLine(""Class6.get_Member1""); return base.Member1; } } // overriding sealed property new private double[] Member2 = new double[] { }; // private field } class Class7 : Class6 { protected new virtual double Member1 { get { Console.WriteLine(""Class7.get_Member1""); return base.Member1; } } // new virtual property public override void Member2() { Console.WriteLine(""Class7.Member2""); base.Member2(); } //overriding method } } class Test { public static void Main() { Class2.Test(); Class2.Class3.Test(); Class5.Test(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Class3.Member1 Class4.Member1 Class1.Member2 Class5.Member2 Class5.Member2 Class6.get_Member1 Class5.get_Member1 Class5.set_Member1 Class5.get_Member1 Class5.set_Member1 Class6.get_Member1 Class5.get_Member1 Class5.set_Member1 Class7.Member2 Class5.Member2", expectedSignatures: new[] { Signature("Class2+Class3", "Member1", ".method family hidebysig newslot virtual instance System.Void Member1() cil managed"), Signature("Class2+Class3", "Member2", ".field public static System.Int32 Member2"), Signature("Class2+Class3+Class4", "Member1", ".method public hidebysig static System.Void Member1() cil managed"), Signature("Class2+Class3+Class5", "Member1", ".field public initonly instance System.Int32 Member1"), Signature("Class2+Class3+Class5", "Member2", ".field public literal static System.Int32 Member2 = 2"), Signature("Class5", "Member2", ".method public hidebysig newslot virtual instance System.Void Member2() cil managed"), Signature("Class5+Class6", "Member2", ".field private instance System.Double[] Member2"), Signature("Class5+Class7", "Member2", ".method public hidebysig virtual instance System.Void Member2() cil managed") }); } [Fact] public void TestOverridingChangeGenericParameterNames() { // Tests: // Change names of method-level type parameters in overridden method – test that we emit the type parameters correctly var source = @" using System; using System.Collections.Generic; abstract class Base<T, U, V> { public virtual List<T> @virtual<T, U>(ref T x, U y, V z) { Console.WriteLine(""Base.virtual1""); return null; } public virtual List<T> @virtual<A, B>(T x, U y, V z, A a, B b) { Console.WriteLine(""Base.virtual2""); return null; } } class Derived<T, U> : Base<T, U, int> { public override List<T> @virtual<T, U>(ref T x, U y, int z) { Console.WriteLine(""Derived.virtual1""); return null; } public override List<T> @virtual<A, B>(T x, U y, int z, A a, B b) { Console.WriteLine(""Derived.virtual2""); return null; } } class Derived2<X, Y> : Base<X, Y, int> { public override List<A> @virtual<A, B>(ref A a, B b, int c) { Console.WriteLine(""Derived2.virtual1""); return null; } public override List<X> @virtual<T, U>(X a, Y b, int c, T d, U e) { Console.WriteLine(""Derived2.virtual2""); return null; } } class Test { public static void Main() { Derived<int, long> d = new Derived<int, long>(); Derived2<int, long> d2 = new Derived2<int, long>(); Base<int, long, int> b = d; string s = """"; int i = 1; long l = 1; b.@virtual(ref s, i, i); b.@virtual(i, l, i, s, s); b = d2; b.@virtual(ref i, s, i); b.@virtual(i, l, i, i, l); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived.virtual1 Derived.virtual2 Derived2.virtual1 Derived2.virtual2", expectedSignatures: new[] { Signature("Base`3", "virtual", ".method public hidebysig newslot virtual instance System.Collections.Generic.List`1[T] virtual<A, B>(T x, U y, V z, A a, B b) cil managed"), Signature("Base`3", "virtual", ".method public hidebysig newslot virtual instance System.Collections.Generic.List`1[T] virtual<T, U>(T& x, U y, V z) cil managed"), Signature("Derived`2", "virtual", ".method public hidebysig virtual instance System.Collections.Generic.List`1[T] virtual<A, B>(T x, U y, System.Int32 z, A a, B b) cil managed"), Signature("Derived`2", "virtual", ".method public hidebysig virtual instance System.Collections.Generic.List`1[T] virtual<T, U>(T& x, U y, System.Int32 z) cil managed"), Signature("Derived2`2", "virtual", ".method public hidebysig virtual instance System.Collections.Generic.List`1[A] virtual<A, B>(A& a, B b, System.Int32 c) cil managed"), Signature("Derived2`2", "virtual", ".method public hidebysig virtual instance System.Collections.Generic.List`1[X] virtual<T, U>(X a, Y b, System.Int32 c, T d, U e) cil managed") }); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void TestOverridingWithParamsAndAliasedNames() { // Tests: // Replace params with non-params in signature of overridden member (and vice-versa) // Use aliased name for type of parameter / return type in overridden member var source = @" using System; using TypeB = System.Int32; using TypeC = NS.Derived; using NSAlias2 = NS; using NSAlias = NS; abstract class Base { internal abstract TypeB Method(System.Exception a, TypeB b, params NS.Derived[] c); public virtual void Method2(TypeC c1, NSAlias2.Derived c2, NS.Derived[] c3) { Console.WriteLine(""Base.Method2( , , [{0}])"", c3.Length); } public abstract void Method3(int[] b1, params int[] b2); } namespace NS { using TypeA = System.Exception; abstract class Base2 : Base { // Adding additional 'params' public override void Method2(Derived c1, NS.Derived c2, params NSAlias.Derived[] C3) { Console.WriteLine(""Base2.Method2( , , [{0}])"", C3.Length); } } class Derived : Base2 { // Omitting 'params' internal override TypeB Method(TypeA A, int B, TypeC[] C) { Console.WriteLine(""Derived.Method( , {0}, [{1}])"", B, C.Length); return 0; } // Preserving 'params' public override void Method3(int[] B1, params int[] b2) { Console.WriteLine(""Derived.Method3([{0}], [{1}])"", B1.Length, b2.Length); } } } class Test { public static void Main() { TypeC d = new TypeC(); Base b = d; d.Method(new System.Exception(), 1, new TypeC[]{d}); b.Method(new System.Exception(), 2, d, d); // d.Method2(d, d, d, d, d); Should report error - No overload for Method2 takes 5 arguments b.Method2(d, d, new TypeC[]{d, d, d}); d.Method3(new int[4]{1, 2, 3, 4}, new int[5] {6, 7, 8, 9, 10}); b.Method3(new int[6]{1, 2, 3, 4, 5, 6}, 8, 9, 10, 11, 12, 13, 14); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived.Method( , 1, [1]) Derived.Method( , 2, [2]) Base2.Method2( , , [3]) Derived.Method3([4], [5]) Derived.Method3([6], [7])", expectedSignatures: new[] { Signature("Base", "Method", ".method assembly hidebysig newslot strict abstract virtual instance System.Int32 Method(System.Exception a, System.Int32 b, [System.ParamArrayAttribute()] NS.Derived[] c) cil managed"), Signature("NS.Derived", "Method", ".method assembly hidebysig strict virtual instance System.Int32 Method(System.Exception A, System.Int32 B, [System.ParamArrayAttribute()] NS.Derived[] C) cil managed"), Signature("Base", "Method2", ".method public hidebysig newslot virtual instance System.Void Method2(NS.Derived c1, NS.Derived c2, NS.Derived[] c3) cil managed"), Signature("NS.Base2", "Method2", ".method public hidebysig virtual instance System.Void Method2(NS.Derived c1, NS.Derived c2, NS.Derived[] C3) cil managed"), Signature("Base", "Method3", ".method public hidebysig newslot abstract virtual instance System.Void Method3(System.Int32[] b1, [System.ParamArrayAttribute()] System.Int32[] b2) cil managed"), Signature("NS.Derived", "Method3", ".method public hidebysig virtual instance System.Void Method3(System.Int32[] B1, [System.ParamArrayAttribute()] System.Int32[] b2) cil managed") }); } [Fact] public void TestOverridingVirtualWithAbstract() { // Tests: // Override virtual member with abstract member – override this abstract member in further derived class var source = @" using System; abstract class Base<T, U> { T f; public abstract void Method(T i, U j); public virtual T Property { get { Console.WriteLine(""Base.get_Property""); return f; } set { Console.WriteLine(""Base.set_Property = {0}"", value.ToString()); } } } class Base2<A, B> : Base<A, B> { public override void Method(A a, B b) { // base.Method(a, b); Error - Cannot call abstract base member Console.WriteLine(""Base2.Method({0}, {1})"", a.ToString(), b.ToString()); } public override A Property { set { Console.WriteLine(""Base2.set_Property = {0}""); value.ToString(); } } } abstract class Base3<T, U> : Base2<T, U> { public override abstract void Method(T x, U y); public override abstract T Property { set; } } class Base4<U, V> : Base3<U, V> { U f; public override void Method(U x, V y) { // base.Method(x, y); Error - Cannot call abstract base member Console.WriteLine(""Base4.Method({0}, {1})"", x.ToString(), y.ToString()); } public override U Property { set { // base.Property = f; Error - Cannot call abstract base member Console.WriteLine(""Base2.set_Property""); } } } class Derived : Base4<string, string> { } class Test { public static void Main() { Derived d = new Derived(); Base<string, string> b = d; Base2<string, string> b2 = d; Base3<string, string> b3 = d; d.Method(""a"", ""b""); b.Method(""a"", ""b""); b2.Method(""a"", ""b""); b3.Method(""a"", ""b""); d.Property = ""a""; string x = d.Property; b.Property = ""b""; x = b.Property; b2.Property = ""c""; x = b2.Property; b3.Property = ""d""; x = b3.Property; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base4.Method(a, b) Base4.Method(a, b) Base4.Method(a, b) Base4.Method(a, b) Base2.set_Property Base.get_Property Base2.set_Property Base.get_Property Base2.set_Property Base.get_Property Base2.set_Property Base.get_Property", expectedSignatures: new[] { Signature("Base`2", "Method", ".method public hidebysig newslot abstract virtual instance System.Void Method(T i, U j) cil managed"), Signature("Base`2", "Property", ".property readwrite instance T Property"), Signature("Base`2", "get_Property", ".method public hidebysig newslot specialname virtual instance T get_Property() cil managed"), Signature("Base`2", "set_Property", ".method public hidebysig newslot specialname virtual instance System.Void set_Property(T value) cil managed"), Signature("Base2`2", "Method", ".method public hidebysig virtual instance System.Void Method(A a, B b) cil managed"), Signature("Base2`2", "Property", ".property writeonly instance A Property"), Signature("Base2`2", "set_Property", ".method public hidebysig specialname virtual instance System.Void set_Property(A value) cil managed"), Signature("Base3`2", "Method", ".method public hidebysig abstract virtual instance System.Void Method(T x, U y) cil managed"), Signature("Base3`2", "Property", ".property writeonly instance T Property"), Signature("Base3`2", "set_Property", ".method public hidebysig specialname abstract virtual instance System.Void set_Property(T value) cil managed"), Signature("Base4`2", "Method", ".method public hidebysig virtual instance System.Void Method(U x, V y) cil managed"), Signature("Base4`2", "Property", ".property writeonly instance U Property"), Signature("Base4`2", "set_Property", ".method public hidebysig specialname virtual instance System.Void set_Property(U value) cil managed") }); } [Fact] private void TestBaseAccessForMembersHiddenInImmediateBaseClass() { // Tests: // Invoke base virtual member from within overridden member using base.VirtualMember // in case where an implementation for the member is hidden by accessibility // in immediate base type but available in a further base type var source = @" using System; abstract class Base<T, U> { T f; public virtual void Method(T i, U j) { Console.WriteLine(""Base.Method({0}, {1})"", i, j); } public virtual T Property { get { Console.WriteLine(""Base.get_Property()""); return f; } set { Console.WriteLine(""Base.set_Property({0})"", value); } } } class Base2<A, B> : Base<A, B> { private new void Method(A a, B b) { Console.WriteLine(""Base2.Method({0}, {1})"", a, b); } private new A Property { set { Console.WriteLine(""Base2.set_Property({0})"", value); } } } class Derived<U, V> : Base2<U, V> { U f; public override void Method(U x, V y) { base.Method(x, y); } public override U Property { set { f = base.Property; base.Property = f; } } } class Test { public static void Main() { Derived<string, string> d = new Derived<string, string>(); d.Method(""a"", ""b""); d.Property = ""c""; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base.Method(a, b) Base.get_Property() Base.set_Property()"); comp.VerifyIL("Derived<U, V>.Method", @" { // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""void Base<U, V>.Method(U, V)"" IL_0008: ret }"); comp.VerifyIL("Derived<U, V>.Property.set", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: call ""U Base<U, V>.Property.get"" IL_0007: stfld ""U Derived<U, V>.f"" IL_000c: ldarg.0 IL_000d: ldarg.0 IL_000e: ldfld ""U Derived<U, V>.f"" IL_0013: call ""void Base<U, V>.Property.set"" IL_0018: ret }"); } [Fact] private void TestBaseAccessForMembersMissingInImmediateBaseClass() { // Tests: // Invoke base virtual member from within overridden member using base.VirtualMember // in case where an implementation for the member is missing // in immediate base type but available in a further base type var source = @" using System; abstract class Base<T, U> { T f; public virtual void Method(T i, U j) { Console.WriteLine(""Base.Method({0}, {1})"", i, j); } public virtual T Property { get { Console.WriteLine(""Base.get_Property()""); return f; } set { Console.WriteLine(""Base.set_Property({0})"", value); } } } class Base2<A, B> : Base<A, B> { } class Derived<U, V> : Base2<U, V> { U f; public override void Method(U x, V y) { base.Method(x, y); } public override U Property { get { f = base.Property; base.Property = f; return f; } } } class Test { public static void Main() { Derived<string, string> d = new Derived<string, string>(); d.Method(""a"", ""b""); string x = d.Property; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base.Method(a, b) Base.get_Property() Base.set_Property()"); comp.VerifyIL("Test.Main", @" { // Code size 28 (0x1c) .maxstack 4 IL_0000: newobj ""Derived<string, string>..ctor()"" IL_0005: dup IL_0006: ldstr ""a"" IL_000b: ldstr ""b"" IL_0010: callvirt ""void Base<string, string>.Method(string, string)"" IL_0015: callvirt ""string Base<string, string>.Property.get"" IL_001a: pop IL_001b: ret }"); comp.VerifyIL("Derived<U, V>.Method", @" { // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""void Base<U, V>.Method(U, V)"" IL_0008: ret }"); comp.VerifyIL("Derived<U, V>.Property.get", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: call ""U Base<U, V>.Property.get"" IL_0007: stfld ""U Derived<U, V>.f"" IL_000c: ldarg.0 IL_000d: ldarg.0 IL_000e: ldfld ""U Derived<U, V>.f"" IL_0013: call ""void Base<U, V>.Property.set"" IL_0018: ldarg.0 IL_0019: ldfld ""U Derived<U, V>.f"" IL_001e: ret }"); } [Fact] private void TestBaseAccessForObjectMembers() { // Tests: // Override virtual methods declared on object (ToString, GetHashCode etc.) // Sanity check – it should be possible to invoke virtual methods declared on object // from within derived type using base.ToString() etc. var source = @" class BaseClass<TInt, TLong> { public override string ToString() { return base.ToString(); } public override int GetHashCode() { return base.GetHashCode(); } } abstract class DerivedClass : BaseClass<int, long> { public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object obj) { return base.Equals(obj); } } "; var comp = CompileAndVerify(source); comp.VerifyIL("BaseClass<TInt, TLong>.ToString", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string object.ToString()"" IL_0006: ret }"); comp.VerifyIL("BaseClass<TInt, TLong>.GetHashCode", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int object.GetHashCode()"" IL_0006: ret }"); comp.VerifyIL("DerivedClass.GetHashCode", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int BaseClass<int, long>.GetHashCode()"" IL_0006: ret }"); comp.VerifyIL("DerivedClass.Equals", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool object.Equals(object)"" IL_0007: ret }"); } [Fact] private void TestOverridingFinalizeImpersonator() { // Tests: // Override overloaded member from base type named Finalize having same / different signature // than object.Finalize() var source = @"using System; abstract class Base<TInt, TLong> { protected virtual void Finalize() { Console.WriteLine(""Base.Finalize()""); } protected abstract void Finalize(TInt x); protected abstract void Finalize(TLong y); } class Derived : Base<int, long> { protected override void Finalize() { Console.WriteLine(""Derived.Finalize()""); base.Finalize(); } protected override void Finalize(int x) { Console.WriteLine(""Derived.Finalize({0})"", x); } protected override void Finalize(long y) { Console.WriteLine(""Derived.Finalize({0}L)"", y); } public void Test() { this.Finalize(); this.Finalize(1); this.Finalize(2L); base.Finalize(); } } abstract class Base2 { protected abstract void Finalize(); public void Test() { Base2 b = new Derived2(); b.Finalize(); } } class Derived2 : Base2 { protected override void Finalize() { Console.WriteLine(""Derived2.Finalize()""); } } class Test { static void Main() { Derived d = new Derived(); d.Test(); Derived2 d2 = new Derived2(); d2.Test(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived.Finalize() Base.Finalize() Derived.Finalize(1) Derived.Finalize(2L) Base.Finalize() Derived2.Finalize() ", expectedSignatures: new[] { Signature("Base`2", "Finalize", ".method family hidebysig newslot virtual instance System.Void Finalize() cil managed"), Signature("Base`2", "Finalize", ".method family hidebysig newslot abstract virtual instance System.Void Finalize(TInt x) cil managed"), Signature("Base`2", "Finalize", ".method family hidebysig newslot abstract virtual instance System.Void Finalize(TLong y) cil managed"), Signature("Base2", "Finalize", ".method family hidebysig newslot abstract virtual instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize(System.Int32 x) cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize(System.Int64 y) cil managed"), Signature("Derived2", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); comp.VerifyIL("Derived.Test", @" { // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: callvirt ""void Base<int, long>.Finalize()"" IL_0006: ldarg.0 IL_0007: ldc.i4.1 IL_0008: callvirt ""void Base<int, long>.Finalize(int)"" IL_000d: ldarg.0 IL_000e: ldc.i4.2 IL_000f: conv.i8 IL_0010: callvirt ""void Base<int, long>.Finalize(long)"" IL_0015: ldarg.0 IL_0016: call ""void Base<int, long>.Finalize()"" IL_001b: ret }"); comp.VerifyIL("Base2.Test", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Derived2..ctor()"" IL_0005: callvirt ""void Base2.Finalize()"" IL_000a: ret }"); } [Fact] private void TestOverrideResolution2() { // Tests: // Override overloaded base virtual / abstract member – overloads differ by generic type parameter count // Override overloaded base virtual / abstract member – overloads spread across multiple base types var source = @" using System; abstract class Base<T, U> { public abstract T Method(); public abstract long Method<T>(); public abstract long Method<T, U>(); } abstract class Base2<A, B> : Base<A, B> { A f; public override A Method() { Console.WriteLine(""Base2.Method()""); return f; } public override abstract long Method<A>(); public override abstract long Method<A, B>(); } class Derived : Base2<long, double> { public override long Method() { base.Method(); Console.WriteLine(""Derived.Method()""); return 0; } public override long Method<X>() { Console.WriteLine(""Derived.Method<>""); return 0; } public override long Method<X, Y>() { Console.WriteLine(""Derived.Method<,>)""); return 0; } } class Test { public static void Main() { Base<long, double> b = new Derived(); b.Method(); b.Method<int>(); b.Method<int, int>(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base2.Method() Derived.Method() Derived.Method<> Derived.Method<,>)"); } [Fact] private void TestOverrideResolution1() { // Tests: // Override overloaded base virtual / abstract member – overloads differ by parameter types and count // Override overloaded base virtual / abstract member – overloads spread across multiple base types var source = @" using System; using System.Collections.Generic; abstract class Base<T, U> { public abstract T Method(int x); public abstract T Method(List<T> x); public abstract long Method<T>(List<int> x); public abstract T Method(int x, string y); public abstract T Method(List<T> x, List<U> y); public abstract T Method<V>(T x, U y); public abstract T Method<V>(int x, string y); public abstract T Method<V>(List<T> x, List<V> y); public abstract T Method<V>(List<int> x, List<string> y); } abstract class Base2<A, B> : Base<A, B> { A f; public override A Method(int x) { return f; } public abstract A Method(A x); public abstract A Method(List<int> x); public abstract long Method<A>(List<A> x); public abstract A Method(A x, B y); public abstract A Method(List<int> x, List<string> y); public abstract A Method<V>(A x, V y); public abstract A Method<V>(List<A> x, List<B> y); public abstract A Method<V>(List<int> x, List<long> y); } class Derived : Base2<long, double> { public override long Method(int x) { return 1; } public override long Method(long x) { return 2; } public override long Method(List<long> x) { return 3; } public override long Method(List<int> x) { return 4; } public override long Method<X>(List<X> x) { return 5; } public override long Method<X>(List<int> x) { return 6; } public override long Method(long x, double y) { return 7; } public override long Method(int x, string y) { return 8; } public override long Method(List<long> x, List<double> y) { return 9; } public override long Method(List<int> x, List<string> y) { return 10; } public override long Method<V>(long x, V y) { return 11; } public override long Method<V>(long x, double y) { return 12; } public override long Method<V>(int x, string y) { return 13; } public override long Method<V>(List<long> x, List<V> y) { return 14; } public override long Method<V>(List<long> x, List<double> y) { return 15; } public override long Method<V>(List<int> x, List<string> y) { return 16; } public override long Method<V>(List<int> x, List<long> y) { return 17; } } class Test { public static void Main() { Base2<long, double> b = new Derived(); int i = 1; long l = 1L; double d = 1D; Console.Write(b.Method(i)); Console.Write(b.Method(new List<long>())); Console.Write(b.Method(new List<int>())); Console.Write(b.Method(new List<string>())); Console.Write(b.Method<int>(new List<int>())); Console.Write(b.Method(l, d)); Console.Write(b.Method(i, """")); Console.Write(b.Method(new List<long>(), new List<double>())); Console.Write(b.Method(new List<int>(), new List<string>())); Console.Write(b.Method(l, """")); Console.Write(b.Method<double>(1L, d)); Console.Write(b.Method<string>(1, """")); Console.Write(b.Method(new List<long>(), new List<int>())); Console.Write(b.Method<int>(new List<long>(), new List<double>())); Console.Write(b.Method<int>(new List<int>(), new List<string>())); Console.Write(b.Method<int>(new List<int>(), new List<long>())); } }"; var comp = CompileAndVerify(source, expectedOutput: @"2545571191011111114151617"); } [ConditionalFact(typeof(ClrOnly), Reason = "Test of execution of explicitly ambiguous IL")] private void TestAmbiguousOverridesWarningCase() { // Tests: // Test that we continue to report errors / warnings even when ambiguous base methods that we are trying to // override only differ by ref / out - test that only a warning (for runtime ambiguity) is reported // in the case where ambiguous signatures differ by just ref / out var source = @" using System; using System.Collections.Generic; abstract class Base<T, U> { public virtual void Method(ref List<T> x, out List<U> y) { Console.WriteLine(""Base.Method(ref, out)""); y = null; } public virtual void Method(out List<U> y, ref List<T> x) { Console.WriteLine(""Base.Method(out, ref)""); y = null; } public virtual void Method(ref List<U> x) { Console.WriteLine(""Base.Method(ref)""); } } class Base2<A, B> : Base<A, B> { public virtual void Method(out List<A> x) { Console.WriteLine(""Base2.Method(out)""); x = null; } } class Derived : Base2<int, int> { public override void Method(ref List<int> a, out List<int> b) { Console.WriteLine(""Derived.Method(ref, out)""); b = null; } // Reports warning about runtime ambiguity public override void Method(ref List<int> a) { Console.WriteLine(""Derived.Method(ref)""); } // No warning when ambiguous signatures are spread across multiple base types } class Test { public static void Main() { Base<int, int> b = new Derived(); List<int> arg = new List<int>(); b.Method(out arg, ref arg); b.Method(ref arg, out arg); b.Method(ref arg); } } "; // Note: This test is exercising a case that is 'Runtime Ambiguous'. In the generated IL, it is ambiguous which // method is being overridden. As far as I can tell, the output won't change from build to build / machine to machine // although it may change from one version of the CLR to another (not sure). If it turns out that this makes // the test flaky, we can delete this test. var comp = CompileAndVerify(source, expectedOutput: @" Derived.Method(ref, out) Base.Method(ref, out) Base.Method(ref)"); } [WorkItem(540214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540214")] [Fact] private void TestEmitSynthesizedSealedSetter() { var source = @" class Base { public virtual int P { get { System.Console.WriteLine(""Base.P.Get=1""); return 1; } set { System.Console.WriteLine(""Base.P.Set({0})"", value); } } } class Derived : Base { public sealed override int P { get { System.Console.WriteLine(""Derived.P.Get=1""); return 1; } } } class Program { static void Main() { Derived d = new Derived(); Base bd = d; d.P++; bd.P++; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived.P.Get=1 Base.P.Set(2) Derived.P.Get=1 Base.P.Set(2)", expectedSignatures: new[] { Signature("Derived", "set_P", ".method public hidebysig specialname virtual final instance System.Void set_P(System.Int32 value) cil managed") }); } [WorkItem(540214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540214")] [Fact] private void TestEmitSynthesizedSealedGetter() { var source = @" class Base { public virtual int P { get { System.Console.WriteLine(""Base.P.Get=1""); return 1; } set { System.Console.WriteLine(""Base.P.Set({0})"", value); } } } class Derived : Base { public sealed override int P { set { System.Console.WriteLine(""Derived.P.Set({0})"", value); } } } class Program { static void Main() { Derived d = new Derived(); Base bd = d; d.P++; bd.P++; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base.P.Get=1 Derived.P.Set(2) Base.P.Get=1 Derived.P.Set(2)", expectedSignatures: new[] { Signature("Derived", "get_P", ".method public hidebysig specialname virtual final instance System.Int32 get_P() cil managed") }); } [WorkItem(540327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540327")] [Fact] private void TestOverrideWithSealedProperty() { var source = @"using System; abstract public class Base { public virtual float Property1 { set { Console.WriteLine(""Base.set_Property1""); } } public virtual float Property2 { get { Console.WriteLine(""Base.get_Property2""); return 0; } } public abstract float Property3 { get; set; } public class Derived : Base { public sealed override float Property1 { set { Console.WriteLine(""Derived.set_Property1""); } } public sealed override float Property2 { get { Console.WriteLine(""Derived.get_Property2""); return 1; } } public sealed override float Property3 { get { Console.WriteLine(""Derived.get_Property3""); return 2; } set { Console.WriteLine(""Derived.set_Property3"");} } } } class Test { public static void Main() { Base b = new Base.Derived(); b.Property1 = b.Property2; b.Property3 = b.Property3; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived.get_Property2 Derived.set_Property1 Derived.get_Property3 Derived.set_Property3", expectedSignatures: new[] { Signature("Base+Derived", "Property1", ".property writeonly instance System.Single Property1"), Signature("Base+Derived", "set_Property1", ".method public hidebysig specialname virtual final instance System.Void set_Property1(System.Single value) cil managed"), Signature("Base+Derived", "Property2", ".property readonly instance System.Single Property2"), Signature("Base+Derived", "get_Property2", ".method public hidebysig specialname virtual final instance System.Single get_Property2() cil managed"), Signature("Base+Derived", "Property3", ".property readwrite instance System.Single Property3"), Signature("Base+Derived", "get_Property3", ".method public hidebysig specialname virtual final instance System.Single get_Property3() cil managed"), Signature("Base+Derived", "set_Property3", ".method public hidebysig specialname virtual final instance System.Void set_Property3(System.Single value) cil managed") }); } [Fact] private void TestOverrideWithAbstractProperty() { var source = @"using System; public class Base1 { public virtual long Property1 { get { Console.WriteLine(""Base1.get_Property1""); return 0; } set { Console.WriteLine(""Base1.set_Property1""); } } public virtual long Property2 { get { Console.WriteLine(""Base1.get_Property2""); return 0; } set { Console.WriteLine(""Base1.set_Property2""); } } } abstract public class Base2 : Base1 { public abstract override long Property1 { get; } public abstract override long Property2 { set; } } public class Derived : Base2 { public override long Property1 { get { Console.WriteLine(""Derived.get_Property1""); return 1; } } public override long Property2 { get { Console.WriteLine(""Derived.get_Property2""); return 1; } set { Console.WriteLine(""Derived.set_Property2""); } } } class Test { public static void Main() { Base1 b = new Derived(); Base2 b2 = new Derived(); b.Property1++; ++b.Property2; b2.Property1 -= 1; b2.Property2 *= 1; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived.get_Property1 Base1.set_Property1 Derived.get_Property2 Derived.set_Property2 Derived.get_Property1 Base1.set_Property1 Derived.get_Property2 Derived.set_Property2", expectedSignatures: new[] { Signature("Base2", "Property1", ".property readonly instance System.Int64 Property1"), Signature("Base2", "get_Property1", ".method public hidebysig specialname abstract virtual instance System.Int64 get_Property1() cil managed"), Signature("Base2", "Property2", ".property writeonly instance System.Int64 Property2"), Signature("Base2", "set_Property2", ".method public hidebysig specialname abstract virtual instance System.Void set_Property2(System.Int64 value) cil managed"), Signature("Derived", "Property1", ".property readonly instance System.Int64 Property1"), Signature("Derived", "get_Property1", ".method public hidebysig specialname virtual instance System.Int64 get_Property1() cil managed"), Signature("Derived", "Property2", ".property readwrite instance System.Int64 Property2"), Signature("Derived", "get_Property2", ".method public hidebysig specialname virtual instance System.Int64 get_Property2() cil managed"), Signature("Derived", "set_Property2", ".method public hidebysig specialname virtual instance System.Void set_Property2(System.Int64 value) cil managed") }); } [Fact] private void TestOverrideWithAbstractProperty2() { var source = @"using System; public class Base1 { public virtual long Property1 { get { Console.WriteLine(""Base1.get_Property1""); return 0; } } public virtual long Property2 { set { Console.WriteLine(""Base1.set_Property2""); } } public virtual long Property3 { get { Console.WriteLine(""Base1.get_Property3""); return 0; } set { Console.WriteLine(""Base1.set_Property3""); } } } abstract public class Base2 : Base1 { public abstract override long Property1 { get; } public abstract override long Property2 { set; } public abstract override long Property3 { get; set; } } public class Derived : Base2 { public override long Property1 { get { Console.WriteLine(""Derived.get_Property1""); return 1; } } public override long Property2 { set { Console.WriteLine(""Derived.set_Property2""); } } public override long Property3 { get { Console.WriteLine(""Derived.get_Property3""); return 1; } set { Console.WriteLine(""Derived.set_Property3""); } } } class Test { public static void Main() { Base1 b = new Derived(); Base2 b2 = new Derived(); long x = b.Property1; b.Property2 = x; --b.Property3; x = b2.Property1; b2.Property2 = x; b2.Property3--; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived.get_Property1 Derived.set_Property2 Derived.get_Property3 Derived.set_Property3 Derived.get_Property1 Derived.set_Property2 Derived.get_Property3 Derived.set_Property3", expectedSignatures: new[] { Signature("Base2", "Property1", ".property readonly instance System.Int64 Property1"), Signature("Base2", "get_Property1", ".method public hidebysig specialname abstract virtual instance System.Int64 get_Property1() cil managed"), Signature("Base2", "Property2", ".property writeonly instance System.Int64 Property2"), Signature("Base2", "set_Property2", ".method public hidebysig specialname abstract virtual instance System.Void set_Property2(System.Int64 value) cil managed"), Signature("Base2", "Property3", ".property readwrite instance System.Int64 Property3"), Signature("Base2", "get_Property3", ".method public hidebysig specialname abstract virtual instance System.Int64 get_Property3() cil managed"), Signature("Base2", "set_Property3", ".method public hidebysig specialname abstract virtual instance System.Void set_Property3(System.Int64 value) cil managed"), Signature("Derived", "Property1", ".property readonly instance System.Int64 Property1"), Signature("Derived", "get_Property1", ".method public hidebysig specialname virtual instance System.Int64 get_Property1() cil managed"), Signature("Derived", "Property2", ".property writeonly instance System.Int64 Property2"), Signature("Derived", "set_Property2", ".method public hidebysig specialname virtual instance System.Void set_Property2(System.Int64 value) cil managed"), Signature("Derived", "Property3", ".property readwrite instance System.Int64 Property3"), Signature("Derived", "get_Property3", ".method public hidebysig specialname virtual instance System.Int64 get_Property3() cil managed"), Signature("Derived", "set_Property3", ".method public hidebysig specialname virtual instance System.Void set_Property3(System.Int64 value) cil managed") }); } [Fact] public void TestHidingStaticMembers() { // Tests: // Hide static base members using new // Overload static base member with member that has different signature // Hide private base members var source = @" using System; class Base { static void Method() { Console.WriteLine(""Base.Method()""); } static void Method<T>() { Console.WriteLine(""Base.Method<T>()""); } static void Method<T>(T x, int y) { Console.WriteLine(""Base.Method<T>(T, int)""); } static long Property { get { Console.WriteLine(""Base.get_Property()""); return 0; } set { Console.WriteLine(""Base.set_Property()""); } } static public class Type { public static void Method() { Console.WriteLine(""Base.Type.Method()""); } } public class Derived : Base { static void Method() { Console.WriteLine(""Derived.Method()""); } new long Property { set { Console.WriteLine(""Derived.set_Property()""); } } static void Method<T>(T x) { Console.WriteLine(""Derived.Method<T>(T)""); } public static void Method<T, U>(T x, int y) { Console.WriteLine(""Derived.Method<T, U>(T, int)""); } new public class Type { public static void Method() { Console.WriteLine(""Derived.Type.Method()""); } } public new static void Test() { Derived.Method(); Derived x = new Derived(); x.Property = 2; Method<int>(1); Type.Method(); } } public static void Test() { Derived.Method(); Derived.Method<int>(); Derived.Method<int>(1, 2); Derived.Method<int, int>(1, 2); Derived.Property = 2; Derived.Type.Method(); } } class Base2 { int Field = 2; protected const int Field2 = 2; public readonly long Field3 = 3; private long Field4 = 3; public class Type<T> { public static void Method() { Console.WriteLine(""Base2.Type<T>.Method()""); } } public class Type2<T> { public static void Method() { Console.WriteLine(""Base2.Type2<T>.Method()""); } } public void Test() { int x = Field; long y = Field4; Type<int>.Method(); Type2<int>.Method(); Derived2.Type<int>.Method(); Derived2.Type<int, long>.Method(); Derived2.Type<int, long>.Type2<int>.Method(); Derived2.Type2<int>.Method(); } public class Derived2 : Base2 { int Field = 2; public int Field2 = 3; new public long Field4 = 4; new public static void Field3() { Console.WriteLine(""Derived2.Field3""); } public abstract class Type<T, U> { public static void Method() { Console.WriteLine(""Derived2.Type<T, U>.Method()""); } public class Type2<X> { public static void Method() { Console.WriteLine(""Derived2.Type2<T>.Method()""); } } } public class Type2<T> { public static void Method() { Console.WriteLine(""Derived2.Type<T, U>.Method()""); } } public new void Test() { Field4 = base.Field4; int x = Field; x = Field2; Field3(); x = Base2.Field2; long y = base.Field3; y = Field4 = base.Field4; } } } class Base3 { int Field = 1; class Type { } public static int Field2 = 1; void Method() { } } abstract class Derived3 : Base3 { new int Field = 2; public class Type { } protected static int Field2 = 1; public abstract void Method(); } class Test { public static void Main() { Base.Test(); Base.Derived.Test(); Base2 b = new Base2(); b.Test(); Base2.Derived2 d = new Base2.Derived2(); d.Test(); Base2.Derived2.Field3(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base.Method() Base.Method<T>() Base.Method<T>(T, int) Derived.Method<T, U>(T, int) Base.set_Property() Derived.Type.Method() Derived.Method() Derived.set_Property() Derived.Method<T>(T) Derived.Type.Method() Base2.Type<T>.Method() Base2.Type2<T>.Method() Base2.Type<T>.Method() Derived2.Type<T, U>.Method() Derived2.Type2<T>.Method() Derived2.Type<T, U>.Method() Derived2.Field3 Derived2.Field3"); comp.VerifyDiagnostics( // (12,21): warning CS0108: 'Base.Derived.Method()' hides inherited member 'Base.Method()'. Use the new keyword if hiding was intended. // static void Method() { Console.WriteLine("Derived.Method()"); } Diagnostic(ErrorCode.WRN_NewRequired, "Method").WithArguments("Base.Derived.Method()", "Base.Method()").WithLocation(12, 21), // (62,13): warning CS0108: 'Base2.Derived2.Field' hides inherited member 'Base2.Field'. Use the new keyword if hiding was intended. // int Field = 2; Diagnostic(ErrorCode.WRN_NewRequired, "Field").WithArguments("Base2.Derived2.Field", "Base2.Field").WithLocation(62, 13), // (63,20): warning CS0108: 'Base2.Derived2.Field2' hides inherited member 'Base2.Field2'. Use the new keyword if hiding was intended. // public int Field2 = 3; Diagnostic(ErrorCode.WRN_NewRequired, "Field2").WithArguments("Base2.Derived2.Field2", "Base2.Field2").WithLocation(63, 20), // (74,22): warning CS0108: 'Base2.Derived2.Type2<T>' hides inherited member 'Base2.Type2<T>'. Use the new keyword if hiding was intended. // public class Type2<T> Diagnostic(ErrorCode.WRN_NewRequired, "Type2").WithArguments("Base2.Derived2.Type2<T>", "Base2.Type2<T>").WithLocation(74, 22), // (99,13): warning CS0109: The member 'Derived3.Field' does not hide an accessible member. The new keyword is not required. // new int Field = 2; Diagnostic(ErrorCode.WRN_NewNotRequired, "Field").WithArguments("Derived3.Field").WithLocation(99, 13), // (101,26): warning CS0108: 'Derived3.Field2' hides inherited member 'Base3.Field2'. Use the new keyword if hiding was intended. // protected static int Field2 = 1; Diagnostic(ErrorCode.WRN_NewRequired, "Field2").WithArguments("Derived3.Field2", "Base3.Field2").WithLocation(101, 26), // (92,9): warning CS0414: The field 'Base3.Field' is assigned but its value is never used // int Field = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Field").WithArguments("Base3.Field").WithLocation(92, 9), // (99,13): warning CS0414: The field 'Derived3.Field' is assigned but its value is never used // new int Field = 2; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "Field").WithArguments("Derived3.Field").WithLocation(99, 13)); } [Fact] public void TestHidingWarnings() { // Tests: // Hide base virtual member using new // By default members should be hidden by signature if new is not specified // new should hide by signature var source = @" using System; using System.Collections.Generic; class Base<T> { public virtual void Method() { Console.WriteLine(""Base<T>.Method()""); } public virtual void Method(T x) { Console.WriteLine(""Base<T>.Method(T)""); } public virtual void Method(T x, T y, List<T> a, Dictionary<T, T> b) { Console.WriteLine(""Base<T>.Method(T, T, List<T>, Dictionary<T, T>)""); } public virtual void Method<U>(T x, T y) { Console.WriteLine(""Base<T>.Method<U>(T, T)""); } public virtual void Method<U>(U x, T y, List<U> a, Dictionary<T, U> b) { Console.WriteLine(""Base<T>.Method<U>(U, T, List<U>, Dictionary<T, U>)""); } public virtual int Property1 { get { Console.WriteLine(""Base<T>.Property""); return 0; } } public virtual int Property2 { get { Console.WriteLine(""Base<T>.Property""); return 0; } set { } } public virtual void Method2() { Console.WriteLine(""Base<T>.Method2()""); } public virtual void Method3() { Console.WriteLine(""Base<T>.Method3()""); } } class Derived<U> : Base<U> { public new void Method(U x, U y) { Console.WriteLine(""Derived<U>.Method(U, U)""); } public void Method(U x, U y, List<U> a, Dictionary<U, U> b) { Console.WriteLine(""Derived<U>.Method(U, U, List<U>, Dictionary<U, U>)""); } public void Method<V>(V x, U y, List<V> a, Dictionary<U, V> b) { Console.WriteLine(""Derived<U>.Method(U, U)""); } public new void Method<V>(V x, U y, List<V> a, Dictionary<V, U> b) { Console.WriteLine(""Derived<U>.Method(U, U)""); } public virtual int Property1 { set { Console.WriteLine(""Derived<U>.Property1""); } } public static int Property2 { get; set; } public static void Method(U i) { Console.WriteLine(""Derived<U>.Method(U)""); } public int Method2 = 0; public void Method<A, B>(U x, U y) { Console.WriteLine(""Derived<U>.Method<A, B>(U, U)""); } public new int Method3 { get; set; } } class Derived2 : Derived<int> { public override void Method() { Console.WriteLine(""Derived2.Method()""); } public override void Method<U>(int x, int y) { Console.WriteLine(""Derived2.Method<U>(int x, int y)""); } public override int Property1 { set { Console.WriteLine(""Derived2.Property1""); } } } class Test { public static void Main() { Derived2 d2 = new Derived2(); Derived<int> d = d2; Base<int> b = d2; b.Method(); b.Method(1); b.Method<int>(1, 1); b.Method<int>(1, 1, new List<int>(), new Dictionary<int, int>()); b.Method(1, 1, new List<int>(), new Dictionary<int, int>()); b.Method2(); int x = b.Property1; b.Property2 -= 1; b.Method3(); d.Method(); Derived<int>.Method(1); d.Method<int>(1, 1); d.Method<long>(1, 1, new List<long>(), new Dictionary<int, long>()); d.Method<long>(1, 1, new List<long>(), new Dictionary<long, int>()); d.Method(1, 1, new List<int>(), new Dictionary<int, int>()); d.Method2(); d.Method2 = 2; // Both Method2's are visible? d.Method<int, int>(1, 1); d.Property1 = 1; Derived<int>.Property2 = Derived<int>.Property2; d.Method3(); x = d.Method3; } }"; var comp = CompileAndVerify(source, expectedOutput: @"Derived2.Method() Base<T>.Method(T) Derived2.Method<U>(int x, int y) Base<T>.Method<U>(U, T, List<U>, Dictionary<T, U>) Base<T>.Method(T, T, List<T>, Dictionary<T, T>) Base<T>.Method2() Base<T>.Property Base<T>.Property Base<T>.Method3() Derived2.Method() Derived<U>.Method(U) Derived2.Method<U>(int x, int y) Derived<U>.Method(U, U) Derived<U>.Method(U, U) Derived<U>.Method(U, U, List<U>, Dictionary<U, U>) Base<T>.Method2() Derived<U>.Method<A, B>(U, U) Derived2.Property1 Base<T>.Method3()"); comp.VerifyDiagnostics( // (43,21): warning CS0109: The member 'Derived<U>.Method(U, U)' does not hide an accessible member. The new keyword is not required. Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("Derived<U>.Method(U, U)"), // (47,17): warning CS0114: 'Derived<U>.Method(U, U, System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<U, U>)' hides inherited member 'Base<U>.Method(U, U, System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<U, U>)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method").WithArguments("Derived<U>.Method(U, U, System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<U, U>)", "Base<U>.Method(U, U, System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<U, U>)"), // (51,17): warning CS0114: 'Derived<U>.Method<V>(V, U, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<U, V>)' hides inherited member 'Base<U>.Method<U>(U, U, System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<U, U>)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method").WithArguments("Derived<U>.Method<V>(V, U, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<U, V>)", "Base<U>.Method<U>(U, U, System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<U, U>)"), // (55,21): warning CS0109: The member 'Derived<U>.Method<V>(V, U, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<V, U>)' does not hide an accessible member. The new keyword is not required. Diagnostic(ErrorCode.WRN_NewNotRequired, "Method").WithArguments("Derived<U>.Method<V>(V, U, System.Collections.Generic.List<V>, System.Collections.Generic.Dictionary<V, U>)"), // (64,24): warning CS0114: 'Derived<U>.Method(U)' hides inherited member 'Base<U>.Method(U)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Method").WithArguments("Derived<U>.Method(U)", "Base<U>.Method(U)"), // (59,24): warning CS0114: 'Derived<U>.Property1' hides inherited member 'Base<U>.Property1'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Property1").WithArguments("Derived<U>.Property1", "Base<U>.Property1"), // (63,23): warning CS0114: 'Derived<U>.Property2' hides inherited member 'Base<U>.Property2'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "Property2").WithArguments("Derived<U>.Property2", "Base<U>.Property2"), // (68,16): warning CS0108: 'Derived<U>.Method2' hides inherited member 'Base<U>.Method2()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "Method2").WithArguments("Derived<U>.Method2", "Base<U>.Method2()")); } [Fact] public void TestOverloadingByRefOutDifferences() { var text = @" using System; abstract class Base { public abstract void Method(ref int x); public abstract void Method(Exception x); public abstract void Method(out long x); public abstract void Method(ArgumentException x); } abstract class Base2 : Base { public abstract void Method(int x); public abstract void Method(out Exception x); public abstract void Method(long x); public abstract void Method(ref ArgumentException x); } class Derived2 : Base2 { public override void Method(ref int x) { } public override void Method(int x) { } public override void Method(Exception x) { } public override void Method(out Exception x) { x = null; } public override void Method(out long x) { x = 0; } public override void Method(ArgumentException x) { } public override void Method(long x) { } public override void Method(ref ArgumentException x) { } }"; var comp = CompileAndVerify(text, expectedSignatures: new[] { Signature("Derived2", "Method", ".method public hidebysig virtual instance System.Void Method(System.ArgumentException x) cil managed"), Signature("Derived2", "Method", ".method public hidebysig virtual instance System.Void Method(System.ArgumentException& x) cil managed"), Signature("Derived2", "Method", ".method public hidebysig virtual instance System.Void Method(System.Exception x) cil managed"), Signature("Derived2", "Method", ".method public hidebysig virtual instance System.Void Method([out] System.Exception& x) cil managed"), Signature("Derived2", "Method", ".method public hidebysig virtual instance System.Void Method(System.Int32 x) cil managed"), Signature("Derived2", "Method", ".method public hidebysig virtual instance System.Void Method(System.Int32& x) cil managed"), Signature("Derived2", "Method", ".method public hidebysig virtual instance System.Void Method(System.Int64 x) cil managed"), Signature("Derived2", "Method", ".method public hidebysig virtual instance System.Void Method([out] System.Int64& x) cil managed") }); comp.VerifyDiagnostics(); } [WorkItem(540341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540341")] [Fact] private void TestInternalMethods() { // Tests: // internal virtual / abstract methods should be marked with strict modifier var source = @" using System.Collections.Generic; abstract class Base<T> { internal virtual List<T> Method1() { return null; } } abstract class Base2<T> : Base<T> { internal abstract List<T> Method2(); } class Derived : Base2<int> { internal sealed override List<int> Method1(){ return null; } internal sealed override List<int> Method2(){ return null; } }"; var comp = CompileAndVerify(source, expectedSignatures: new[] { Signature("Base`1", "Method1", ".method assembly hidebysig newslot strict virtual instance System.Collections.Generic.List`1[T] Method1() cil managed"), Signature("Base2`1", "Method2", ".method assembly hidebysig newslot strict abstract virtual instance System.Collections.Generic.List`1[T] Method2() cil managed"), Signature("Derived", "Method1", ".method assembly hidebysig virtual final instance System.Collections.Generic.List`1[System.Int32] Method1() cil managed"), Signature("Derived", "Method2", ".method assembly hidebysig virtual final instance System.Collections.Generic.List`1[System.Int32] Method2() cil managed"), }); comp.VerifyDiagnostics(); // No errors } [Fact] private void TestProtectedInternalMethods() { // Tests: // protected internal virtual / abstract methods should not be marked with strict modifier var source = @" using System.Collections.Generic; abstract class Base<T> { protected internal virtual List<T> Method1() { return null; } } abstract class Base2<T> : Base<T> { protected internal abstract List<T> Method2(); } class Derived : Base2<int> { protected internal sealed override List<int> Method1(){ return null; } protected internal sealed override List<int> Method2(){ return null; } }"; var comp = CompileAndVerify(source, expectedSignatures: new[] { Signature("Base`1", "Method1", ".method famorassem hidebysig newslot virtual instance System.Collections.Generic.List`1[T] Method1() cil managed"), Signature("Base2`1", "Method2", ".method famorassem hidebysig newslot abstract virtual instance System.Collections.Generic.List`1[T] Method2() cil managed"), Signature("Derived", "Method1", ".method famorassem hidebysig virtual final instance System.Collections.Generic.List`1[System.Int32] Method1() cil managed"), Signature("Derived", "Method2", ".method famorassem hidebysig virtual final instance System.Collections.Generic.List`1[System.Int32] Method2() cil managed") }); comp.VerifyDiagnostics(); // No errors } [Fact] private void TestProtectedMethods() { // Tests: // protected virtual / abstract methods should not be marked with strict modifier var source = @" using System; using System.Collections.Generic; abstract class Base<T> { protected virtual List<T> Method1() { return null; } } abstract class Base2<T> : Base<T> { protected abstract List<T> Method2(); } class Derived : Base2<int> { protected sealed override List<int> Method1(){ return null; } protected sealed override List<int> Method2(){ return null; } }"; var comp = CompileAndVerify(source, expectedSignatures: new[] { Signature("Base`1", "Method1", ".method family hidebysig newslot virtual instance System.Collections.Generic.List`1[T] Method1() cil managed"), Signature("Base2`1", "Method2", ".method family hidebysig newslot abstract virtual instance System.Collections.Generic.List`1[T] Method2() cil managed"), Signature("Derived", "Method1", ".method family hidebysig virtual final instance System.Collections.Generic.List`1[System.Int32] Method1() cil managed"), Signature("Derived", "Method2", ".method family hidebysig virtual final instance System.Collections.Generic.List`1[System.Int32] Method2() cil managed") }); } [Fact] private void TestPublicMethods() { // Tests: // public virtual / abstract methods should not be marked with strict modifier var source = @" using System.Collections.Generic; abstract class Base<T> { public virtual List<T> Method1() { return null; } } abstract class Base2<T> : Base<T> { public abstract List<T> Method2(); } class Derived : Base2<int> { public sealed override List<int> Method1(){ return null; } public sealed override List<int> Method2(){ return null; } }"; var comp = CompileAndVerify(source, expectedSignatures: new[] { Signature("Base`1", "Method1", ".method public hidebysig newslot virtual instance System.Collections.Generic.List`1[T] Method1() cil managed"), Signature("Base2`1", "Method2", ".method public hidebysig newslot abstract virtual instance System.Collections.Generic.List`1[T] Method2() cil managed"), Signature("Derived", "Method1", ".method public hidebysig virtual final instance System.Collections.Generic.List`1[System.Int32] Method1() cil managed"), Signature("Derived", "Method2", ".method public hidebysig virtual final instance System.Collections.Generic.List`1[System.Int32] Method2() cil managed"), }); comp.VerifyDiagnostics(); // No errors } [WorkItem(540341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540341")] [Fact] private void TestInternalAccessors() { // Tests: // internal virtual / abstract accessors should be marked with strict modifier var source = @" using System.Collections.Generic; abstract class Base<T> { public virtual List<T> Property1 { get { return null; } internal set { } } public virtual List<T> Property2 { set { } internal get { return null; } } internal abstract List<T> Property5 { get; set; } } abstract class Base2<T> : Base<T> { public abstract List<T> Property3 { get; internal set; } public abstract List<T> Property4 { set; internal get; } internal virtual List<T> Property6 { get; set; } } class Derived : Base2<int> { public sealed override List<int> Property1 { get { return null; } internal set { } } public sealed override List<int> Property2 { internal get { return null; } set { } } public sealed override List<int> Property3 { get { return null; } internal set { } } public sealed override List<int> Property4 { internal get { return null; } set { } } internal sealed override List<int> Property5 { get; set; } internal sealed override List<int> Property6 { get; set; } }"; var comp = CompileAndVerify(source, expectedSignatures: new[] { Signature("Base`1", "get_Property1", ".method public hidebysig newslot specialname virtual instance System.Collections.Generic.List`1[T] get_Property1() cil managed"), Signature("Base`1", "set_Property1", ".method assembly hidebysig newslot strict specialname virtual instance System.Void set_Property1(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Base`1", "get_Property2", ".method assembly hidebysig newslot strict specialname virtual instance System.Collections.Generic.List`1[T] get_Property2() cil managed"), Signature("Base`1", "set_Property2", ".method public hidebysig newslot specialname virtual instance System.Void set_Property2(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Base`1", "get_Property5", ".method assembly hidebysig newslot strict specialname abstract virtual instance System.Collections.Generic.List`1[T] get_Property5() cil managed"), Signature("Base`1", "set_Property5", ".method assembly hidebysig newslot strict specialname abstract virtual instance System.Void set_Property5(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Base2`1", "get_Property3", ".method public hidebysig newslot specialname abstract virtual instance System.Collections.Generic.List`1[T] get_Property3() cil managed"), Signature("Base2`1", "set_Property3", ".method assembly hidebysig newslot strict specialname abstract virtual instance System.Void set_Property3(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Base2`1", "get_Property4", ".method assembly hidebysig newslot strict specialname abstract virtual instance System.Collections.Generic.List`1[T] get_Property4() cil managed"), Signature("Base2`1", "set_Property4", ".method public hidebysig newslot specialname abstract virtual instance System.Void set_Property4(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Base2`1", "get_Property6", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] assembly hidebysig newslot strict specialname virtual instance System.Collections.Generic.List`1[T] get_Property6() cil managed"), Signature("Base2`1", "set_Property6", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] assembly hidebysig newslot strict specialname virtual instance System.Void set_Property6(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Derived", "get_Property1", ".method public hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property1() cil managed"), Signature("Derived", "set_Property1", ".method assembly hidebysig specialname virtual final instance System.Void set_Property1(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived", "get_Property2", ".method assembly hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property2() cil managed"), Signature("Derived", "set_Property2", ".method public hidebysig specialname virtual final instance System.Void set_Property2(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived", "get_Property3", ".method public hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property3() cil managed"), Signature("Derived", "set_Property3", ".method assembly hidebysig specialname virtual final instance System.Void set_Property3(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived", "get_Property4", ".method assembly hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property4() cil managed"), Signature("Derived", "set_Property4", ".method public hidebysig specialname virtual final instance System.Void set_Property4(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived", "get_Property5", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] assembly hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property5() cil managed"), Signature("Derived", "set_Property5", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] assembly hidebysig specialname virtual final instance System.Void set_Property5(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived", "get_Property6", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] assembly hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property6() cil managed"), Signature("Derived", "set_Property6", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] assembly hidebysig specialname virtual final instance System.Void set_Property6(System.Collections.Generic.List`1[System.Int32] value) cil managed") }); comp.VerifyDiagnostics(); // No errors } [Fact] public void TestProtectedInternalAccessors() { // Tests: // protected internal virtual / abstract accessors should not be marked with strict modifier var source = @" using System.Collections.Generic; abstract class Base<T> { public virtual List<T> Property1 { get { return null; } protected internal set { } } public virtual List<T> Property2 { set { } protected internal get { return null; } } protected internal virtual List<T> Property5 { get; set; } } class Derived : Base<int> { public sealed override List<int> Property1 { get { return null; } protected internal set { } } public sealed override List<int> Property2 { protected internal get { return null; } set { } } protected internal sealed override List<int> Property5 { get; set; } }"; var comp = CompileAndVerify(source, expectedSignatures: new[] { Signature("Base`1", "get_Property1", ".method public hidebysig newslot specialname virtual instance System.Collections.Generic.List`1[T] get_Property1() cil managed"), Signature("Base`1", "set_Property1", ".method famorassem hidebysig newslot specialname virtual instance System.Void set_Property1(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Base`1", "get_Property2", ".method famorassem hidebysig newslot specialname virtual instance System.Collections.Generic.List`1[T] get_Property2() cil managed"), Signature("Base`1", "set_Property2", ".method public hidebysig newslot specialname virtual instance System.Void set_Property2(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Base`1", "get_Property5", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] famorassem hidebysig newslot specialname virtual instance System.Collections.Generic.List`1[T] get_Property5() cil managed"), Signature("Base`1", "set_Property5", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] famorassem hidebysig newslot specialname virtual instance System.Void set_Property5(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Derived", "get_Property1", ".method public hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property1() cil managed"), Signature("Derived", "set_Property1", ".method famorassem hidebysig specialname virtual final instance System.Void set_Property1(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived", "get_Property2", ".method famorassem hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property2() cil managed"), Signature("Derived", "set_Property2", ".method public hidebysig specialname virtual final instance System.Void set_Property2(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived", "get_Property5", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] famorassem hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property5() cil managed"), Signature("Derived", "set_Property5", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] famorassem hidebysig specialname virtual final instance System.Void set_Property5(System.Collections.Generic.List`1[System.Int32] value) cil managed") }); comp.VerifyDiagnostics(); // No errors } [Fact] private void TestProtectedInternalAccessorsInDifferentAssembly() { var source1 = @" using System.Collections.Generic; public class Base<T> { public virtual List<T> Property1 { get { return null; } protected internal set { } } public virtual List<T> Property2 { protected internal get { return null; } set { } } }"; var compilation1 = CreateCompilation(source1); var source2 = @" using System.Collections.Generic; public class Derived : Base<int> { public sealed override List<int> Property1 { get { return null; } protected set { } } public sealed override List<int> Property2 { protected get { return null; } set { } } } // Omitted Accessors public class Derived2 : Base<int> { public sealed override List<int> Property1 { protected set { } } public sealed override List<int> Property2 { protected get { return null; } } }"; var comp = CompileAndVerify(source2, new[] { new CSharpCompilationReference(compilation1) }, expectedSignatures: new[] { Signature("Derived", "get_Property1", ".method public hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property1() cil managed"), Signature("Derived", "set_Property1", ".method family hidebysig specialname virtual final instance System.Void set_Property1(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived", "get_Property2", ".method family hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property2() cil managed"), Signature("Derived", "set_Property2", ".method public hidebysig specialname virtual final instance System.Void set_Property2(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived2", "get_Property1", ".method public hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property1() cil managed"), Signature("Derived2", "set_Property1", ".method family hidebysig specialname virtual final instance System.Void set_Property1(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived2", "get_Property2", ".method family hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property2() cil managed"), Signature("Derived2", "set_Property2", ".method public hidebysig specialname virtual final instance System.Void set_Property2(System.Collections.Generic.List`1[System.Int32] value) cil managed") }); comp.VerifyDiagnostics(); // No errors } [Fact] public void TestProtectedAccessors() { // Tests: // protected virtual / abstract accessors should not be marked with strict modifier var source = @" using System.Collections.Generic; abstract class Base<T> { public virtual List<T> Property1 { get { return null; } protected set { } } public virtual List<T> Property2 { set { } protected get { return null; } } protected abstract List<T> Property5 { get; set; } } class Derived : Base<int> { public sealed override List<int> Property1 { get { return null; } protected set { } } public sealed override List<int> Property2 { protected get { return null; } set { } } protected sealed override List<int> Property5 { get; set; } }"; var comp = CompileAndVerify(source, expectedSignatures: new[] { Signature("Base`1", "get_Property1", ".method public hidebysig newslot specialname virtual instance System.Collections.Generic.List`1[T] get_Property1() cil managed"), Signature("Base`1", "set_Property1", ".method family hidebysig newslot specialname virtual instance System.Void set_Property1(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Base`1", "get_Property2", ".method family hidebysig newslot specialname virtual instance System.Collections.Generic.List`1[T] get_Property2() cil managed"), Signature("Base`1", "set_Property2", ".method public hidebysig newslot specialname virtual instance System.Void set_Property2(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Base`1", "get_Property5", ".method family hidebysig newslot specialname abstract virtual instance System.Collections.Generic.List`1[T] get_Property5() cil managed"), Signature("Base`1", "set_Property5", ".method family hidebysig newslot specialname abstract virtual instance System.Void set_Property5(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Derived", "get_Property1", ".method public hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property1() cil managed"), Signature("Derived", "set_Property1", ".method family hidebysig specialname virtual final instance System.Void set_Property1(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived", "get_Property2", ".method family hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property2() cil managed"), Signature("Derived", "set_Property2", ".method public hidebysig specialname virtual final instance System.Void set_Property2(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived", "get_Property5", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] family hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property5() cil managed"), Signature("Derived", "set_Property5", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] family hidebysig specialname virtual final instance System.Void set_Property5(System.Collections.Generic.List`1[System.Int32] value) cil managed") }); comp.VerifyDiagnostics(); // No errors } [Fact] private void TestPublicAccessors() { // Tests: // public virtual / abstract accessors should not be marked with strict modifier var source = @" using System.Collections.Generic; abstract class Base<T> { public virtual List<T> Property1 { get { return null; } set { } } public abstract List<T> Property5 { get; set; } } class Derived : Base<int> { public sealed override List<int> Property1 { get { return null; } set { } } public sealed override List<int> Property5 { get; set; } }"; var comp = CompileAndVerify(source, expectedSignatures: new[] { Signature("Base`1", "get_Property1", ".method public hidebysig newslot specialname virtual instance System.Collections.Generic.List`1[T] get_Property1() cil managed"), Signature("Base`1", "set_Property1", ".method public hidebysig newslot specialname virtual instance System.Void set_Property1(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Base`1", "get_Property5", ".method public hidebysig newslot specialname abstract virtual instance System.Collections.Generic.List`1[T] get_Property5() cil managed"), Signature("Base`1", "set_Property5", ".method public hidebysig newslot specialname abstract virtual instance System.Void set_Property5(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Derived", "get_Property1", ".method public hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property1() cil managed"), Signature("Derived", "set_Property1", ".method public hidebysig specialname virtual final instance System.Void set_Property1(System.Collections.Generic.List`1[System.Int32] value) cil managed"), Signature("Derived", "get_Property5", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public hidebysig specialname virtual final instance System.Collections.Generic.List`1[System.Int32] get_Property5() cil managed"), Signature("Derived", "set_Property5", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public hidebysig specialname virtual final instance System.Void set_Property5(System.Collections.Generic.List`1[System.Int32] value) cil managed") }); comp.VerifyDiagnostics(); // No errors } [Fact] private void TestOverrideOverloadedMethod() { var source = @" using System.Collections.Generic; public abstract class Base<T> { public abstract void Method(T x); public virtual void Method(List<T> x, int y) { } } abstract class Base2<T> : Base<T> { public abstract void Method<U>(T x); public abstract int Method(List<T> x, long y); } class Derived : Base2<int> { public override void Method(int x) { } public override void Method<T>(int x) { } public override void Method(List<int> x, int y) { } public override int Method(List<int> x, long y) { return 0; } }"; var comp = CompileAndVerify(source, expectedSignatures: new[] { Signature("Derived", "Method", ".method public hidebysig virtual instance System.Int32 Method(System.Collections.Generic.List`1[System.Int32] x, System.Int64 y) cil managed"), Signature("Derived", "Method", ".method public hidebysig virtual instance System.Void Method(System.Collections.Generic.List`1[System.Int32] x, System.Int32 y) cil managed"), Signature("Derived", "Method", ".method public hidebysig virtual instance System.Void Method(System.Int32 x) cil managed"), Signature("Derived", "Method", ".method public hidebysig virtual instance System.Void Method<T>(System.Int32 x) cil managed") }); comp.VerifyDiagnostics(); // No errors } [Fact] private void TestOverrideHidingMember() { // Tests: // Hide base virtual member with a virtual new / abstract new member // Test that we don't override the hidden base member on further derived classes var source = @" using System; using System.Collections.Generic; public abstract class Base<T> { public virtual void Method<K>(T x) { Console.WriteLine(""Base<T>.Method<K>(T x)""); } public virtual void Method(List<T> x, int y) { Console.WriteLine(""Base<T>.Method(List<T> x, int y)""); } public virtual List<T> Property { set { Console.WriteLine(""Base<T>.set_Property""); } } } abstract class Base2<T> : Base<T> { public new virtual void Method<U>(T x) { Console.WriteLine(""Base2<T>.Method<U>(T x)""); } public new virtual void Method(List<T> x, int y) { Console.WriteLine(""Base2<T>.Method(List<T> x, int y)""); } public new virtual List<T> Property { get { Console.WriteLine(""Base2<T>.get_Property""); return null; } set { Console.WriteLine(""Base2<T>.set_Property""); } } } class Derived : Base2<int> { public override void Method<T>(int x) { Console.WriteLine(""Derived.Method<T>(int x)""); } public override void Method(List<int> x, int y) { Console.WriteLine(""Derived.Method(List<int> x, int y)""); } public override List<int> Property { set { Console.WriteLine(""Derived.set_Property""); } } } class Test { public static void Main() { Base<int> b = new Derived(); Base2<int> b2 = new Derived(); b.Method<long>(1); b.Method(new List<int>(), 1); List<int> x = null; b.Property = x; b2.Method<long>(1); b2.Method(new List<int>(), 1); x = b2.Property; b2.Property = x; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base<T>.Method<K>(T x) Base<T>.Method(List<T> x, int y) Base<T>.set_Property Derived.Method<T>(int x) Derived.Method(List<int> x, int y) Base2<T>.get_Property Derived.set_Property", expectedSignatures: new[] { Signature("Base2`1", "Method", ".method public hidebysig newslot virtual instance System.Void Method(System.Collections.Generic.List`1[T] x, System.Int32 y) cil managed"), Signature("Base2`1", "Method", ".method public hidebysig newslot virtual instance System.Void Method<U>(T x) cil managed"), Signature("Base2`1", "get_Property", ".method public hidebysig newslot specialname virtual instance System.Collections.Generic.List`1[T] get_Property() cil managed"), Signature("Base2`1", "set_Property", ".method public hidebysig newslot specialname virtual instance System.Void set_Property(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Derived", "Method", ".method public hidebysig virtual instance System.Void Method(System.Collections.Generic.List`1[System.Int32] x, System.Int32 y) cil managed"), Signature("Derived", "Method", ".method public hidebysig virtual instance System.Void Method<T>(System.Int32 x) cil managed"), Signature("Derived", "set_Property", ".method public hidebysig specialname virtual instance System.Void set_Property(System.Collections.Generic.List`1[System.Int32] value) cil managed") }); comp.VerifyDiagnostics(); // No errors } [WorkItem(528172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528172")] [Fact] public void TestHideWithInaccessibleVirtualMember() { // Tests: // Hide public base member with inaccessible internal virtual derived member // On further derived try to override public base member – this should result in PEVerify failure var source = @" using System; using System.Collections.Generic; public abstract class Base<T> { public virtual void Method<K>(T x) { Console.WriteLine(""Base<T>.Method<K>(T x)""); } public virtual void Method(List<T> x, int y) { Console.WriteLine(""Base<T>.Method(List<T> x, int y)""); } public virtual List<T> Property { set { Console.WriteLine(""Base<T>.set_Property""); } } } public abstract class Base2<T> : Base<T> { internal new virtual void Method<U>(T x) { Console.WriteLine(""Base2<T>.Method<U>(T x)""); } internal new virtual void Method(List<T> x, int y) { Console.WriteLine(""Base2<T>.Method(List<T> x, int y)""); } internal new virtual List<T> Property { get { Console.WriteLine(""Base2<T>.get_Property""); return null; } set { Console.WriteLine(""Base2<T>.set_Property""); } } } class DerivedTest : Base2<int> { internal override void Method<U>(int x) { Console.WriteLine(""DerivedTest.Method<U>(T x)""); } internal override void Method(List<int> x, int y) { Console.WriteLine(""DerivedTest.Method(List<int> x, int y)""); } internal override List<int> Property { get { Console.WriteLine(""DerivedTest.get_Property""); return null; } set { Console.WriteLine(""DerivedTest.set_Property""); } } }"; var source2 = @" using System; using System.Collections.Generic; public class Derived : Base2<int> { public override void Method<T>(int x) { Console.WriteLine(""Derived.Method<T>(int x)""); } public override void Method(List<int> x, int y) { Console.WriteLine(""Derived.Method(List<int> x, int y)""); } public override List<int> Property { set { Console.WriteLine(""Derived.set_Property""); } } } public class Test { public static void Main() { Base<int> b = new Derived(); Base2<int> b2 = new Derived(); b.Method<long>(1); b.Method(new List<int>(), 1); List<int> x = null; b.Property = x; b2.Method<long>(1); b2.Method(new List<int>(), 1); b2.Property = x; } }"; var referencedCompilation = CreateCompilation(source, options: TestOptions.ReleaseDll, assemblyName: "OHI_CodeGen_TestHideWithInaccessibleVirtualMember1"); var outerCompilation = CreateCompilation(source2, new[] { new CSharpCompilationReference(referencedCompilation) }, options: TestOptions.ReleaseExe, assemblyName: "OHI_CodeGen_TestHideWithInaccessibleVirtualMember2"); outerCompilation.VerifyDiagnostics(); // No errors // Verify that PEVerify will fail despite the fact that compiler produces no errors // This is consistent with Dev10 behavior // // Dev10 PEVerify failure: // [token 0x02000002] Type load failed. // [IL]: Error: [Dev10.exe : Test::Main][offset 0x00000001] Unable to resolve token. // // Dev10 Runtime Exception: // Unhandled Exception: System.TypeLoadException: Method 'Method' on type 'Derived' // from assembly 'Dev10, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // is overriding a method that is not visible from that assembly. CompileAndVerify(outerCompilation, verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 65 (0x41) .maxstack 4 .locals init (Base2<int> V_0, //b2 System.Collections.Generic.List<int> V_1) //x IL_0000: newobj ""Derived..ctor()"" IL_0005: newobj ""Derived..ctor()"" IL_000a: stloc.0 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: callvirt ""void Base<int>.Method<long>(int)"" IL_0012: dup IL_0013: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0018: ldc.i4.1 IL_0019: callvirt ""void Base<int>.Method(System.Collections.Generic.List<int>, int)"" IL_001e: ldnull IL_001f: stloc.1 IL_0020: ldloc.1 IL_0021: callvirt ""void Base<int>.Property.set"" IL_0026: ldloc.0 IL_0027: ldc.i4.1 IL_0028: callvirt ""void Base<int>.Method<long>(int)"" IL_002d: ldloc.0 IL_002e: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0033: ldc.i4.1 IL_0034: callvirt ""void Base<int>.Method(System.Collections.Generic.List<int>, int)"" IL_0039: ldloc.0 IL_003a: ldloc.1 IL_003b: callvirt ""void Base<int>.Property.set"" IL_0040: ret } "); } [Fact] public void TestHideWithInaccessibleMember() { // Tests: // Hide public base member with inaccessible (internal) derived member // In further derived class override / invoke public base member – try hiding with static and instance members var source = @" using System; using System.Collections.Generic; public abstract class Base<T> { public virtual void Method<K>(T x) { Console.WriteLine(""Base<T>.Method<K>(T x)""); } public virtual void Method(List<T> x, int y) { Console.WriteLine(""Base<T>.Method(List<T> x, int y)""); } public virtual List<T> Property { set { Console.WriteLine(""Base<T>.set_Property""); } } } public class Base1<T> : Base<T> { } public abstract class Base2<T> : Base1<T> { private new void Method<U>(T x) { base.Method<U>(x); Console.WriteLine(""Base2<T>.Method<U>(T x)""); } internal new static void Method(List<T> x, int y) { Console.WriteLine(""Base2<T>.Method(List<T> x, int y)""); } internal new List<T> Property { get { Console.WriteLine(""Base2<T>.get_Property""); return null; } set { base.Property = value; Console.WriteLine(""Base2<T>.set_Property""); } } }"; var source2 = @" using System; using System.Collections.Generic; public class Derived : Base2<int> { public override void Method<T>(int x) { base.Method<T>(x); Console.WriteLine(""Derived.Method<T>(int x)""); } public override void Method(List<int> x, int y) { base.Method(x, y); Console.WriteLine(""Derived.Method(List<int> x, int y)""); } public override List<int> Property { set { base.Property = value; Console.WriteLine(""Derived.set_Property""); } } } public class Test { public static void Main() { Base<int> b = new Derived(); Base2<int> b2 = new Derived(); b.Method<long>(1); b.Method(new List<int>(), 1); List<int> x = null; b.Property = x; b2.Method<long>(1); b2.Method(new List<int>(), 1); b2.Property = x; } }"; var referencedCompilation = CreateCompilation(source, assemblyName: "OHI_CodeGen_TestHideWithInaccessibleMember"); var comp = CompileAndVerify( source2, new[] { referencedCompilation.EmitToImageReference() }, expectedOutput: @" Base<T>.Method<K>(T x) Derived.Method<T>(int x) Base<T>.Method(List<T> x, int y) Derived.Method(List<int> x, int y) Base<T>.set_Property Derived.set_Property Base<T>.Method<K>(T x) Derived.Method<T>(int x) Base<T>.Method(List<T> x, int y) Derived.Method(List<int> x, int y) Base<T>.set_Property Derived.set_Property", expectedSignatures: new[] { Signature("Base2`1", "Method", ".method assembly hidebysig static System.Void Method(System.Collections.Generic.List`1[T] x, System.Int32 y) cil managed"), Signature("Base2`1", "Method", ".method private hidebysig instance System.Void Method<U>(T x) cil managed"), Signature("Base2`1", "set_Property", ".method assembly hidebysig specialname instance System.Void set_Property(System.Collections.Generic.List`1[T] value) cil managed"), Signature("Derived", "Method", ".method public hidebysig virtual instance System.Void Method(System.Collections.Generic.List`1[System.Int32] x, System.Int32 y) cil managed"), Signature("Derived", "Method", ".method public hidebysig virtual instance System.Void Method<T>(System.Int32 x) cil managed"), Signature("Derived", "set_Property", ".method public hidebysig specialname virtual instance System.Void set_Property(System.Collections.Generic.List`1[System.Int32] value) cil managed") }); comp.VerifyDiagnostics(); // No errors } [Fact] public void TestHideSealedMember() { // Tests: // Hide sealed member with virtual / abstract member – override this member in further derived class var source = @" using System; using System.Collections.Generic; public abstract class Base<T> { protected virtual void Method<K>(T x) { Console.WriteLine(""Base<T>.Method<K>(T x)""); } protected virtual void Method(List<T> x, int y) { Console.WriteLine(""Base<T>.Method(List<T> x, int y)""); } protected virtual List<T> Property { get { Console.WriteLine(""Base<T>.get_Property""); return null;} set { Console.WriteLine(""Base<T>.set_Property""); } } public void Test(Base<int> d) { Base<int> b = d; Base2<int> b2 = (Base2<int>)d; b.Method<long>(1); b.Method(new List<int>(), 1); List<int> x = null; b.Property = x; x = b.Property; b2.Method<long>(1); b2.Method(new List<int>(), 1); b2.Property = x; x = b2.Property; } } public class Base1<T> : Base<T> { protected sealed override void Method<U>(T x) { Console.WriteLine(""Base1<T>.Method<U>(T x)""); } protected sealed override void Method(List<T> x, int y) { Console.WriteLine(""Base1<T>.Method(List<T> x, int y)""); } protected sealed override List<T> Property { set { Console.WriteLine(""Base1<T>.set_Property""); } } } public abstract class Base2<T> : Base1<T> { protected internal new virtual void Method<U>(T x) { Console.WriteLine(""Base2<T>.Method<U>(T x)""); } protected internal new abstract void Method(List<T> x, int y); protected internal new virtual List<T> Property { set { Console.WriteLine(""Base2<T>.set_Property""); } get { Console.WriteLine(""Base2<T>.get_Property""); return null; } } }"; var source2 = @" using System; using System.Collections.Generic; public class Derived : Base2<int> { protected override void Method<T>(int x) { Console.WriteLine(""Derived.Method<T>(int x)""); } protected override void Method(List<int> x, int y) { Console.WriteLine(""Derived.Method(List<int> x, int y)""); } protected override List<int> Property { get { Console.WriteLine(""Derived.get_Property""); return null; } } } public class Test { public static void Main() { Base<int> b = new Derived(); b.Test(b); } }"; var referencedCompilation = CreateCompilation(source, assemblyName: "OHI_CodeGen_TestHideSealedMember"); var comp = CompileAndVerify( source2, new[] { referencedCompilation.EmitToImageReference() }, expectedOutput: @" Base1<T>.Method<U>(T x) Base1<T>.Method(List<T> x, int y) Base1<T>.set_Property Base<T>.get_Property Derived.Method<T>(int x) Derived.Method(List<int> x, int y) Base2<T>.set_Property Derived.get_Property"); comp.VerifyDiagnostics(); // No errors } [WorkItem(540431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540431")] [Fact] public void TestOverrideNewToVBVirtualOverloadsMetadata() { #region "Impl" var text1 = @"using System; public class CSIMeth02Derived : VBIMeth02Impl // VB Impl { public override void Sub01(params byte[] ary) // base:virtual { Console.Write(""CSS1_OV ""); } public new void Sub011(sbyte p1, params byte[] ary) // base:overloads { Console.Write(""CSS11_New ""); } public new string Func01(params string[] ary) // base:virtual { Console.Write(""CSF1_New ""); return ary[0]; } public string Func011(object p1, params string[] ary) // base:overloads- warning CS108 { Console.Write(""CSF11_Warn ""); return p1.ToString(); } } "; #endregion var text2 = @" class Test { static void Main() { CSIMeth02Derived obj = new CSIMeth02Derived(); obj.Sub01(1, 2, 3); ((VBIMeth02Impl)obj).Sub01(1, 2, 3); ((IMeth02)obj).Sub01(1, 2, 3); ((IMeth01)obj).Sub01(1, 2, 3); obj.Func01(""1"", ""2"", ""3""); ((VBIMeth02Impl)obj).Func01(""1"", ""2"", ""3""); ((IMeth02)obj).Func01(""1"", ""2"", ""3""); ((IMeth01)obj).Func01(""1"", ""2"", ""3""); } } "; var asm01 = TestReferences.MetadataTests.InterfaceAndClass.VBInterfaces01; var asm02 = TestReferences.MetadataTests.InterfaceAndClass.VBClasses01; var refs = new System.Collections.Generic.List<MetadataReference>() { asm01, asm02 }; var comp1 = CreateCompilation(text1, references: refs, assemblyName: "OHI_DeriveOverrideNewVirtualOverload001", options: TestOptions.ReleaseDll); refs.Add(new CSharpCompilationReference(comp1)); var comp = CreateCompilation(text2, references: refs, assemblyName: "OHI_DeriveOverrideNewVirtualOverload002", options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"CSS1_OV CSS1_OV VBS11_OL CSS1_OV CSF1_New VBF1_V VBF11 VBF1_V"); } [WorkItem(540431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540431")] [Fact] public void TestOverrideNewToVBVirtualPropMetadata() { #region "Impl" var text1 = @"using System; public class CSIPropImplDerived : VBIPropImpl { private string _str; private uint _uint; //public string ReadOnlyProp //{ // get { return _str; } //} public new string WriteOnlyProp { set { _str = value; } } public override string NormalProp // base:virtual { // get { return _str; } set { _str = value; } } public override uint get_ReadOnlyPropWithParams(ushort x) // base:virtual { return _uint; } public override void set_WriteOnlyPropWithParams(uint x, ulong y) // base:virtual { _uint = x; } public new long get_NormalPropWithParams(long x, short y) // base:virtual { return (long)_uint; } public new void set_NormalPropWithParams(long x, short y, long z) // base:virtual { _uint = (uint)x; } } "; #endregion var text2 = @"using System; class Test { static void Main() { CSIPropImplDerived obj = new CSIPropImplDerived(); obj.NormalProp = ""CSNormProp ""; ((VBIPropImpl)obj).NormalProp = ""VBNormProp ""; Console.Write(obj.NormalProp); Console.Write(((VBIPropImpl)obj).NormalProp); obj.WriteOnlyProp = ""CSWriteReadOnly ""; ((VBIPropImpl)obj).WriteOnlyProp = ""VBWriteReadOnly ""; Console.Write(obj.ReadOnlyProp); Console.Write(((VBIPropImpl)obj).ReadOnlyProp); obj.set_NormalPropWithParams(100, 2, 3); ((VBIPropImpl)obj).set_NormalPropWithParams(200, 200, 5); Console.Write(obj.get_NormalPropWithParams(300, 6)); Console.Write(((VBIPropImpl)obj).get_NormalPropWithParams(400, 7)); ((VBIPropImpl)obj).set_WriteOnlyPropWithParams(800, 0); obj.set_WriteOnlyPropWithParams(900, 0); Console.Write(obj.get_ReadOnlyPropWithParams(0)); Console.Write(((VBIPropImpl)obj).get_ReadOnlyPropWithParams(1)); } } "; var asm01 = TestReferences.MetadataTests.InterfaceAndClass.VBInterfaces01; var asm02 = TestReferences.MetadataTests.InterfaceAndClass.VBClasses01; var refs = new System.Collections.Generic.List<MetadataReference>() { asm01, asm02 }; var comp1 = CreateCompilation(text1, references: refs, assemblyName: "OHI_DeriveOverrideVirtualProp001", options: TestOptions.ReleaseDll); refs.Add(new CSharpCompilationReference(comp1)); var comp = CreateCompilation(text2, references: refs, assemblyName: "OHI_DeriveOverrideVirtualProp002", options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"VBDefault VBDefault VBWriteReadOnly VBWriteReadOnly 100200900900"); } [Fact] public void TestDerivedImplPropWithBaseInMetadata() { var text1 = @"using System; using Metadata; public class ICSPropDerived : ICSPropImpl, ICSProp { // no impl of ReadOnlyProp public new EFoo WriteOnlyProp { set { efoo = (EFoo)(value + 1); } } // override get only public override EFoo ReadWriteProp { get { return (EFoo)(efoo + 1); } // set { efoo = value; } } } "; var text2 = @"using System; using Metadata; class Test { static void Main() { ICSPropDerived pobj = new ICSPropDerived(); ICSPropImpl pbaseobj = pobj; pobj.WriteOnlyProp = EFoo.One; // new in derived Console.Write(pobj.ReadOnlyProp); // call base pbaseobj.WriteOnlyProp = EFoo.Two; // call base Console.Write(pbaseobj.ReadWriteProp); // call derived pobj.ReadWriteProp = EFoo.Zero; // call base Console.Write(pobj.ReadWriteProp); // call derived pbaseobj.ReadWriteProp = EFoo.Zero; // call base Console.Write(pobj.ReadOnlyProp); // call base } } "; var asm01 = TestReferences.MetadataTests.InterfaceAndClass.CSInterfaces01; var asm02 = TestReferences.MetadataTests.InterfaceAndClass.CSClasses01; var comp1 = CreateCompilation( text1, references: new[] { asm01, asm02 }, assemblyName: "OHI_DeriveBaseInMetadataProp001"); var comp2 = CreateCompilation( text2, references: new MetadataReference[] { asm01, asm02, new CSharpCompilationReference(comp1) }, options: TestOptions.ReleaseExe, assemblyName: "OHI_DeriveBaseInMetadataProp002"); CompileAndVerify(comp2, expectedOutput: @"TwoThreeOneZero"); } [WorkItem(540452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540452")] [WorkItem(540453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540453")] [Fact] public void TestGenericDDerivedImplWithBaseInMetadata() { #region "Text1" var text1 = @"using System; namespace Metadata { // base class ICSGenImpl<T, string> does NOT impl interface directly abstract public class ICSGenDerived<T> : ICSGenImpl<T, string>, ICSGen<T, string> { // base: virtual public override sealed void M01(T p1, T p2) { Console.Write(""DOvSe_TT ""); } // base: abstract public override void M01(T p1, ref T p2, out DFoo<T> p3) { p3 = null; Console.Write(""DOv_RefOutT ""); } // base: no virtual public new virtual string M01(string p1, string p2) { Console.Write(""DNewv_VV ""); return p1.ToString(); } // base: virtual public override string M01(string p1, object p2) { Console.Write(""DOv_VObj ""); return p1; } // base: virtual public abstract override string M01(string p1, params object[] p2); } } "; #endregion #region "Text2" var text2 = @"using System; namespace Metadata { public class ICSGenDerivedDerived<T> : ICSGenDerived<T>, ICSGen<T, string> { public new void M01(T p1, params T[] ary) { Console.Write(""DDNew_TParams ""); } public override void M01(params T[] ary) { Console.Write(""DDOv_ParamsT ""); } public new void M01(T p1, ref T p2, out DFoo<T> p3) { p3 = null; Console.Write(""DDNew_RefOutT ""); } public override string M01(string p1, string p2) { Console.Write(""DDOv_VV ""); return p1.ToString(); } public override sealed string M01(string p1, object p2) { Console.Write(""DDOvSe_VObj ""); return p1; } public override sealed string M01(string p1, params object[] p2) { Console.Write(""DDOvSe_VParams ""); return p1; } } } "; #endregion #region "Text3" var text3 = @"using System; using Metadata; class Test { static void Main() { ICSGenDerivedDerived<short> ddobj = new ICSGenDerivedDerived<short>(); ICSGenDerived<short> dobj = ddobj; ICSGenImpl<short, string> obj = dobj; ICSGen<short, string> iobj = dobj; sbyte sb = -128; short sh = 12345; DFoo<short> dfoo = null; // (base)virtual (D)override seal (DD) - obj.M01(sb, sh); iobj.M01(sb, sh); Console.WriteLine(); // (base)virtual (D)_ (DD) new iobj.M01(3, sb, sh); // DD ddobj.M01(sh, sb, 1); // DD dobj.M01(sh, sb, 1); // b obj.M01(sb, 2, sh); // b Console.WriteLine(); // (base)virtual (D)_ (DD) override short[] ary = new short[] { 1, 2, 3 }; // all DD iobj.M01(new short[] { 1, 2 }); ddobj.M01(ary); dobj.M01(new short[] { 1 }); obj.M01(ary); Console.WriteLine(); // (base)abstract (D) override (DD) new iobj.M01(-128, ref sh, out dfoo); ddobj.M01(sb, ref sh, out dfoo); dobj.M01(sh, ref sh, out dfoo); // Roslyn (40,38): error CS1620: Argument 3 must be passed with the 'ref' keyword obj.M01(127, ref sh, out dfoo); Console.WriteLine(); // (base)None (D) new virtual (DD) override string str = ""Hi""; iobj.M01(str, ""Hey""); ddobj.M01(""Hey"", str); dobj.M01(str, str); obj.M01(str, ""Hey""); Console.WriteLine(); // (base)virtual (D)override (DD) override_seal object oo = null; iobj.M01(str, oo); ddobj.M01(str, oo); dobj.M01(str, new object()); obj.M01(str, oo); Console.WriteLine(); // (base)virtual (D) abstract override (DD) override seal iobj.M01(str, str, null); ddobj.M01(null, str, null); // Roslyn (62,23): error CS1503: Argument 1: cannot convert from '<null>' to 'short etc. dobj.M01(str, null, str, null); // Roslyn (63,13): error CS1501: No overload for method 'M01' takes 4 arguments obj.M01(null, null, str, str); } } "; #endregion var asm01 = TestReferences.MetadataTests.InterfaceAndClass.CSInterfaces01; var asm02 = TestReferences.MetadataTests.InterfaceAndClass.CSClasses01; var refs = new System.Collections.Generic.List<MetadataReference>() { asm01, asm02 }; var comp1 = CreateCompilation(text1, references: refs, assemblyName: "OHI_GenericDDeriveBaseInMetadata001", options: TestOptions.ReleaseDll); // better output with error info if any comp1.VerifyDiagnostics(); // No Errors refs.Add(new CSharpCompilationReference(comp1)); var comp2 = CreateCompilation(text2, references: refs, assemblyName: "OHI_GenericDDeriveBaseInMetadata002", options: TestOptions.ReleaseDll); Assert.Equal(0, comp2.GetDiagnostics().Count()); refs.Add(new CSharpCompilationReference(comp2)); var comp = CreateCompilation(text3, references: refs, assemblyName: "OHI_GenericDDeriveBaseInMetadata003", options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); // No Errors CompileAndVerify(comp, expectedOutput: @"DOvSe_TT DOvSe_TT DDNew_TParams DDNew_TParams Base_TParamsT Base_TParamsT DDOv_ParamsT DDOv_ParamsT DDOv_ParamsT DDOv_ParamsT DDNew_RefOutT DDNew_RefOutT DOv_RefOutT DOv_RefOutT DDOv_VV DDOv_VV DDOv_VV BaseNV_VV DDOvSe_VObj DDOvSe_VObj DDOvSe_VObj DDOvSe_VObj DDOvSe_VParams DDOvSe_VParams DDOvSe_VParams DDOvSe_VParams "); } [Fact] public void TestBridgeMethodFromBaseVBMetadata() { var text1 = @"using System; using Metadata; //partial class Test //{ public class D : VBBase, IMeth03.INested { public override sealed void NestedSub(ushort p) { Console.Write(""Derived (OVSealed) ""); } } //} "; var text2 = @" using System; partial class Test { static void Main() { new D().NestedSub(1); object o = new Test(); Console.Write(new D().NestedFunc(ref o)); } } "; var asm01 = TestReferences.MetadataTests.InterfaceAndClass.VBInterfaces01; var asm02 = TestReferences.MetadataTests.InterfaceAndClass.VBClasses02; var comp = CreateCompilation( new string[] { text1, text2 }, references: new[] { asm01, asm02 }, options: TestOptions.ReleaseExe, assemblyName: "OHI_BridgeMethodFromBaseVB007"); var verifier = CompileAndVerify( comp, expectedOutput: @"Derived (OVSealed) VBaseFunc (Non-Virtual)", expectedSignatures: new[] { Signature("D", "NestedSub", ".method public hidebysig virtual final instance System.Void NestedSub(System.UInt16 p) cil managed"), Signature("D", "IMeth03.INested.NestedFunc", ".method private hidebysig newslot virtual final instance System.String IMeth03.INested.NestedFunc(System.Object& p) cil managed") }); } [Fact] public void TestOverridingGenericNestedClasses() { // Tests: // Sanity check – use open (T) and closed (C<String>) generic types in the signature of overriding methods // Override members of generic base class nested inside other generic classes var source = @" using System; using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal abstract class Base<V, W> { protected internal abstract T Property { set; } internal abstract void Method<Z>(T A, U[] B, List<V> C, Dictionary<W, Z> D); } } } internal class Derived1<T, U> : Outer<T>.Inner<int>.Base<long, U> { protected internal override T Property { set { Console.WriteLine(""Derived1.set_Property""); } } internal override void Method<K>(T a, int[] b, List<long> c, Dictionary<U, K> d) { Console.WriteLine(""Derived1.Method""); } internal class Derived2 : Outer<string>.Inner<int>.Base<long, string> { protected internal override string Property { set { Console.WriteLine(""Derived2.set_Property""); } } internal override void Method<K>(string a, int[] b, List<long> c, Dictionary<string, K> d) { Console.WriteLine(""Derived2.Method""); } } } public class Test { public static void Main() { Outer<string>.Inner<int>.Base<long, string> b = new Derived1<string, string>(); b.Property = """"; b.Method<string>("""", new int[] { }, new List<long>(), new Dictionary<string, string>()); b = new Derived1<string, string>.Derived2(); b.Property = """"; b.Method<string>("""", new int[] { }, new List<long>(), new Dictionary<string, string>()); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived1.set_Property Derived1.Method Derived2.set_Property Derived2.Method", expectedSignatures: new[] { Signature("Derived1`2", "set_Property", ".method famorassem hidebysig specialname virtual instance System.Void set_Property(T value) cil managed"), Signature("Derived1`2", "Method", ".method assembly hidebysig strict virtual instance System.Void Method<K>(T a, System.Int32[] b, System.Collections.Generic.List`1[System.Int64] c, System.Collections.Generic.Dictionary`2[U,K] d) cil managed"), Signature("Derived1`2+Derived2", "set_Property", ".method famorassem hidebysig specialname virtual instance System.Void set_Property(System.String value) cil managed"), Signature("Derived1`2+Derived2", "Method", ".method assembly hidebysig strict virtual instance System.Void Method<K>(System.String a, System.Int32[] b, System.Collections.Generic.List`1[System.Int64] c, System.Collections.Generic.Dictionary`2[System.String,K] d) cil managed") }); comp.VerifyDiagnostics(); // No Errors } [Fact] public void TestOverloadGetSetMethodWithPropMetadata() { #region "src" var text1 = @"using System; public class CSPropBase : VBIPropImpl { protected string _str; public virtual string get_ReadOnlyProp() { return _str; } public void set_WriteOnlyProp(string val) { _str = val + ""M |""; } } "; var text2 = @"using System; public class CSPropDerived : CSPropBase { public override string get_ReadOnlyProp() { return _str; } public new void set_WriteOnlyProp(string val) { _str = val + ""D |""; } } "; var text3 = @"using System; class Test { static void Main() { CSPropDerived obj = new CSPropDerived(); CSPropBase bobj = obj; // call derived methods obj.set_WriteOnlyProp(""Derived ""); Console.Write(obj.get_ReadOnlyProp()); bobj.set_WriteOnlyProp(""Base ""); Console.Write(bobj.get_ReadOnlyProp()); // call interface prop impl obj.WriteOnlyProp = ""PropImpl""; Console.Write(obj.ReadOnlyProp); } } "; #endregion var asm01 = TestReferences.MetadataTests.InterfaceAndClass.VBInterfaces01; var asm02 = TestReferences.MetadataTests.InterfaceAndClass.VBClasses01; var comp1 = CreateCompilation( text1, references: new MetadataReference[] { asm01, asm02 }, assemblyName: "OHI_OverloadGetSetMethodWithProp001"); var comp2 = CreateCompilation( text2, references: new MetadataReference[] { asm01, asm02, new CSharpCompilationReference(comp1) }, assemblyName: "OHI_OverloadGetSetMethodWithProp002"); var comp = CreateCompilation( text3, references: new MetadataReference[] { asm01, asm02, new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }, options: TestOptions.ReleaseExe, assemblyName: "OHI_OverloadGetSetMethodWithProp003"); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "Derived D |Base M |PropImpl"); } [Fact] public void TestVBNestedClassesOverrideNewMetadata() { #region "Text1" var text1 = @" public class CNested : IMeth03.Nested { sbyte _sbyte = 1; public override sbyte ReadOnlySByte { get { return _sbyte; } } public new virtual sbyte WriteOnlySByte { set { _sbyte = value; } } public override sbyte PropSByte { get { return _sbyte; } set { _sbyte = value; } } } "; #endregion #region "Text2" var text2 = @"using System; public class CNestedDerived : CNested { sbyte _sbyte = 2; public new sbyte ReadOnlySByte { get { return _sbyte; } } public override sbyte WriteOnlySByte { set { _sbyte = value; } } public override sealed sbyte PropSByte { get { return _sbyte; } set { _sbyte = value; } } } "; #endregion #region "Text" var text = @"using System; class Test { static void Main() { CNestedDerived obj = new CNestedDerived(); CNested bobj = obj; IMeth03.Nested vbobj = obj; obj.PropSByte = 123; Console.WriteLine(obj.ReadOnlySByte); obj.WriteOnlySByte = 124; Console.WriteLine(obj.PropSByte); bobj.PropSByte = 125; Console.WriteLine(bobj.ReadOnlySByte); bobj.WriteOnlySByte = 126; Console.WriteLine(bobj.PropSByte); vbobj.PropSByte = 127; Console.WriteLine(vbobj.ReadOnlySByte); vbobj.WriteOnlySByte = -128; Console.WriteLine(vbobj.PropSByte); } } "; #endregion var asmfile = TestReferences.MetadataTests.InterfaceAndClass.VBInterfaces01; var comp1 = CreateCompilation( text1, references: new[] { asmfile }, assemblyName: "OHI_ClassOverrideNewVBNested001"); var comp2 = CreateCompilation( text2, references: new[] { asmfile, comp1.EmitToImageReference() }, assemblyName: "OHI_ClassOverrideNewVBNested002"); var comp = CreateCompilation( text, references: new MetadataReference[] { asmfile, new CSharpCompilationReference(comp1), new CSharpCompilationReference(comp2) }, options: TestOptions.ReleaseExe, assemblyName: "OHI_ClassOverrideNewVBNested003"); CompileAndVerify(comp, expectedOutput: @"123 124 1 126 1 127 "); } /// <summary> /// Override generic method with different type parameter letter /// - public virtual void Method&lt;TMethod&gt;(TOuter modopt(IsConst)[] modopt(IsConst) x, /// TInner modopt(IsConst)[] modopt(IsConst) y, /// TMethod modopt(IsConst)[] modopt(IsConst) z); /// </summary> [Fact] public void TestOverrideGenericMethodWithTypeParamDiffNameWithCustomModifiers() { var text = @" namespace Metadata { using System; public class GD : Outer<string>.Inner<ulong> { public override void Method<X>(string[] x, ulong[] y, X[] z) { Console.Write(""Hello {0}"", z.Length); } static void Main() { new GD().Method<byte>(null, null, new byte[] { 0, 127, 255 }); } } } "; var verifier = CompileAndVerify( text, new[] { TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll }, expectedOutput: @"Hello 3", expectedSignatures: new[] { // The ILDASM output is following,and Roslyn handles it correctly. // Verifier tool gives different output due to the limitation of Reflection // @".method public hidebysig virtual instance System.Void Method<X>(" + // @"System.String modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x," + // @"UInt64 modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) y," + // @"!!X modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) z) cil managed") Signature("Metadata.GD", "Method", @".method public hidebysig virtual instance System.Void Method<X>(" + @"modopt(System.Runtime.CompilerServices.IsConst) System.String[] x, " + @"modopt(System.Runtime.CompilerServices.IsConst) System.UInt64[] y, modopt(System.Runtime.CompilerServices.IsConst) X[] z) cil managed"), }); } [WorkItem(540516, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540516")] [Fact] public void TestCallMethodsWithLeastCustomModifiers() { var text = @"using Metadata; public class Program { public static void Main() { LeastModoptsWin obj = new LeastModoptsWin(); // ok - 51 System.Console.Write(obj.M(obj.GetByte(), obj.GetByte())); } } "; var verifier = CompileAndVerify(text, references: new[] { TestReferences.SymbolsTests.CustomModifiers.ModoptTests }, expectedOutput: "51"); } [WorkItem(540517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540517")] [Fact] public void TestOverrideMethodsWithCustomModifiers() { var text = @"using System; using Metadata; public class Derived : LeastModoptsWin { public override sealed byte M(byte t, byte v) { return 88; } // W CS1957 } public class Test { static void Main() { LeastModoptsWin d = new Derived(); Console.WriteLine(d.M(33, 44)); Console.WriteLine(d.M(d.GetByte(), d.GetByte())); } } "; var verifier = CompileAndVerify(text, references: new[] { TestReferences.SymbolsTests.CustomModifiers.ModoptTests }, expectedOutput: @"88 88 ", expectedSignatures: new[] { Signature("Derived", "M", ".method public hidebysig virtual final instance modopt(System.Runtime.CompilerServices.IsConst) System.Byte M(System.Byte t, System.Byte v) cil managed") }); var comp = (CSharpCompilation)verifier.Compilation; comp.VerifyDiagnostics(); var baseType = comp.GlobalNamespace.GetMember<NamespaceSymbol>("Metadata").GetMember<NamedTypeSymbol>("LeastModoptsWin"); var derivedType = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Derived"); var overridingMethod = derivedType.GetMember<MethodSymbol>("M"); var overriddenMethod = overridingMethod.OverriddenMethod; Assert.Equal("System.Byte modopt(System.Runtime.CompilerServices.IsConst) Metadata.LeastModoptsWin.M(System.Byte t, System.Byte v)", overriddenMethod.ToTestDisplayString()); } [Fact] public void TestOverridingGenericClasses_HideTypeParameter() { // Tests: // Override generic methods on generic classes – test case where type parameter // on method hides the type parameter on class (both in base type and in overriding type) var source = @" using System; using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal abstract class Base<V, W> { public virtual void Method<Z>(T a, U[] b, List<V> c, Dictionary<W, Z> d) { Console.WriteLine(""Base.Method`1""); } internal abstract void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); } internal class Derived1<X, Y> : Outer<long>.Inner<int>.Base<long, Y> { public sealed override void Method<X>(long A, int[] b, List<long> C, Dictionary<Y, X> d) { Console.WriteLine(""Derived1.Method`1""); } internal sealed override void Method<X, Y>(long A, int[] b, List<X> C, Dictionary<Y, Y> d) { Console.WriteLine(""Derived1.Method`2""); } } } } class Test { public static void Main() { Outer<long>.Inner<int>.Base<long, string> b = new Outer<long>.Inner<int>.Derived1<string, string>(); b.Method<string>(1, new int[]{}, new List<long>(), new Dictionary<string, string>()); b.Method<string, int>(1, new int[]{}, new List<string>(), new Dictionary<int, int>()); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived1.Method`1 Derived1.Method`2", expectedSignatures: new[] { Signature("Outer`1+Inner`1+Derived1`2", "Method", ".method public hidebysig virtual final instance System.Void Method<X>(System.Int64 A, System.Int32[] b, System.Collections.Generic.List`1[System.Int64] C, System.Collections.Generic.Dictionary`2[Y,X] d) cil managed"), Signature("Outer`1+Inner`1+Derived1`2", "Method", ".method assembly hidebysig virtual final instance System.Void Method<X, Y>(System.Int64 A, System.Int32[] b, System.Collections.Generic.List`1[X] C, System.Collections.Generic.Dictionary`2[Y,Y] d) cil managed") }); comp.VerifyDiagnostics( // (11,43): warning CS0693: Type parameter 'V' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Base<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "V").WithArguments("V", "Outer<T>.Inner<U>.Base<V, W>"), // (11,46): warning CS0693: Type parameter 'W' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Base<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "W").WithArguments("W", "Outer<T>.Inner<U>.Base<V, W>"), // (15,41): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (19,43): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (19,46): warning CS0693: Type parameter 'Y' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "Y").WithArguments("Y", "Outer<T>.Inner<U>.Derived1<X, Y>")); } [Fact] private void TestHideMethodWithModreqCustomModifiers() { var text = @"using System; using Metadata; internal class D1 : Modreq { public void M(uint x) { Console.Write(x + 1); } // silently hide base class member } internal class D2 : Modreq { public new void M(uint x) { Console.Write(x + 2); } // Dev10 Warning CS0109 } class Test { static void Main() { new D1().M(10); new D2().M(20); } } "; //var errs = comp.GetDiagnostics(); //Assert.Equal(1, errs.Count()); //Assert.Equal(109, errs.First().Code); var verifier = CompileAndVerify(text, references: new[] { TestReferences.SymbolsTests.CustomModifiers.ModoptTests }, expectedOutput: "1122", expectedSignatures: new[] { Signature("D1", "M", @".method public hidebysig instance System.Void M(System.UInt32 x) cil managed"), Signature("D2", "M", @".method public hidebysig instance System.Void M(System.UInt32 x) cil managed") }); } [WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")] [Fact] public void AccessorMethodAccessorOverridingExecution() { var text = @" public class A { protected string _p; virtual public string P { get { return _p; } set { _p = ""A"" + value; } } } public class B : A { virtual public void set_P(string value) { _p = ""B"" + value; } } public class C : B { public override string P { get { return _p; } set { _p = ""C"" + value; } } } class Program { static void Main(string[] args) { C c = new C(); c.P = ""1""; System.Console.WriteLine(c.P); } } "; CompileAndVerify(text, expectedOutput: "C1"); } [WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")] [Fact] public void AccessorMethodAccessorOverridingRoundTrip() { var text = @" public class A { public virtual int P { get; set; } } public class B : A { public virtual int get_P() { return 0; } } public class C : B { public override int P { get; set; } } "; Action<ModuleSymbol> validator = module => { var globalNamespace = module.GlobalNamespace; var classA = globalNamespace.GetMember<NamedTypeSymbol>("A"); var classB = globalNamespace.GetMember<NamedTypeSymbol>("B"); var classC = globalNamespace.GetMember<NamedTypeSymbol>("C"); var methodA = classA.GetMember<PropertySymbol>("P").GetMethod; var methodB = classB.GetMember<MethodSymbol>("get_P"); var methodC = classC.GetMember<PropertySymbol>("P").GetMethod; Assert.True(methodA.IsVirtual); Assert.True(methodB.IsVirtual); Assert.True(methodC.IsOverride); Assert.Null(methodA.OverriddenMethod); Assert.Null(methodB.OverriddenMethod); Assert.Equal(methodA, methodC.OverriddenMethod); }; CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator); } [WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")] [Fact] public void MethodAccessorMethodOverridingRoundTrip() { var text = @" public class A { public virtual int get_P() { return 0; } } public class B : A { public virtual int P { get; set; } } public class C : B { public override int get_P() { return 0; } } "; Action<ModuleSymbol> validator = module => { var globalNamespace = module.GlobalNamespace; var classA = globalNamespace.GetMember<NamedTypeSymbol>("A"); var classB = globalNamespace.GetMember<NamedTypeSymbol>("B"); var classC = globalNamespace.GetMember<NamedTypeSymbol>("C"); var methodA = classA.GetMember<MethodSymbol>("get_P"); var methodB = classB.GetMember<PropertySymbol>("P").GetMethod; var methodC = classC.GetMember<MethodSymbol>("get_P"); Assert.True(methodA.IsVirtual); Assert.True(methodB.IsVirtual); Assert.True(methodC.IsOverride); Assert.Null(methodA.OverriddenMethod); Assert.Null(methodB.OverriddenMethod); Assert.Equal(methodA, methodC.OverriddenMethod); }; CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator); } /// <summary> /// If a PEMethodSymbol is metadata virtual and explicitly /// overrides another method, then it will return true for /// IsOverride, even if the method is not considered to be /// overridden by C# semantics. In such cases, IsOverride /// will be true, but OverriddenMethod will return null. /// This test just checks that nothing blows up in such cases. /// </summary> [WorkItem(541834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541834")] [Fact] public void ExplicitOverrideWithoutCSharpOverride() { var ilSource = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig newslot virtual instance void Foo() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Base .class public auto ansi beforefieldinit Derived extends Base { .method public hidebysig newslot virtual instance void Bar() cil managed { .override Base::Foo //different name ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var cSharpSource = @" public class Override : Derived { public override void Bar() { } } public class Invoke { public void Test(Derived d) { d.Foo(); d.Bar(); } } "; CompileWithCustomILSource(cSharpSource, ilSource, compilation => { compilation.VerifyDiagnostics(); var globalNamespace = compilation.GlobalNamespace; var baseClass = globalNamespace.GetMember<NamedTypeSymbol>("Base"); var derivedClass = globalNamespace.GetMember<NamedTypeSymbol>("Derived"); var overrideClass = globalNamespace.GetMember<NamedTypeSymbol>("Override"); var invokeClass = globalNamespace.GetMember<NamedTypeSymbol>("Invoke"); var baseMethod = baseClass.GetMember<MethodSymbol>("Foo"); var derivedMethod = derivedClass.GetMember<MethodSymbol>("Bar"); var overrideMethod = overrideClass.GetMember<MethodSymbol>("Bar"); Assert.True(derivedMethod.IsOverride); Assert.Null(derivedMethod.OverriddenMethod); Assert.True(overrideMethod.IsOverride); Assert.Equal(derivedMethod, overrideMethod.OverriddenMethod); }); } [WorkItem(542828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542828")] [Fact] public void MetadataOverrideVirtualHiddenByNonVirtual() { var source = @" using A = BaseVirtual; using B = DerivedNonVirtual; using C = Derived2Override; class Program { static void Main() { A a = new A(); B b = new B(); C c = new C(); A ab = b; A ac = c; B bc = c; a.M(); b.M(); c.M(); ab.M(); ac.M(); bc.M(); } } "; Action<ModuleSymbol> validator = module => { var globalNamespace = module.GetReferencedAssemblySymbols().Last().GlobalNamespace; var classA = globalNamespace.GetMember<NamedTypeSymbol>("BaseVirtual"); var classB = globalNamespace.GetMember<NamedTypeSymbol>("DerivedNonVirtual"); var classC = globalNamespace.GetMember<NamedTypeSymbol>("Derived2Override"); Assert.Equal(classA, classB.BaseType()); Assert.Equal(classB, classC.BaseType()); var methodA = classA.GetMember<MethodSymbol>("M"); var methodB = classB.GetMember<MethodSymbol>("M"); var methodC = classC.GetMember<MethodSymbol>("M"); Assert.True(methodA.IsVirtual); Assert.False(methodB.IsVirtual); Assert.False(methodB.IsOverride); Assert.True(methodC.IsOverride); // Even though the runtime regards C.M as an override of A.M, // the language (i.e. C#) does not. Assert.Null(methodC.OverriddenMethod); }; var references = new MetadataReference[] { TestReferences.SymbolsTests.Methods.ILMethods }; var verifier = CompileAndVerify( source, references: references, sourceSymbolValidator: validator, expectedOutput: @"BaseVirtual DerivedNonVirtual Derived2Override BaseVirtual Derived2Override DerivedNonVirtual "); // The emitted calls tell us about the overriding behavior that Dev10 expects // (since it always emits a call to the least overridden method). This is how // we can confirm that Roslyn ignores the runtime overriding behavior (i.e. C.M // overriding A.M) in the same way as Dev10. // From Dev10, calls should be A, B, C, A, A, B verifier.VerifyIL("Program.Main", @" { // Code size 61 (0x3d) .maxstack 2 .locals init (BaseVirtual V_0, //a Derived2Override V_1, //c BaseVirtual V_2, //ab BaseVirtual V_3, //ac DerivedNonVirtual V_4) //bc IL_0000: newobj ""BaseVirtual..ctor()"" IL_0005: stloc.0 IL_0006: newobj ""DerivedNonVirtual..ctor()"" IL_000b: newobj ""Derived2Override..ctor()"" IL_0010: stloc.1 IL_0011: dup IL_0012: stloc.2 IL_0013: ldloc.1 IL_0014: stloc.3 IL_0015: ldloc.1 IL_0016: stloc.s V_4 IL_0018: ldloc.0 IL_0019: callvirt ""void BaseVirtual.M()"" IL_001e: callvirt ""void DerivedNonVirtual.M()"" IL_0023: ldloc.1 IL_0024: callvirt ""void Derived2Override.M()"" IL_0029: ldloc.2 IL_002a: callvirt ""void BaseVirtual.M()"" IL_002f: ldloc.3 IL_0030: callvirt ""void BaseVirtual.M()"" IL_0035: ldloc.s V_4 IL_0037: callvirt ""void DerivedNonVirtual.M()"" IL_003c: ret } "); } [WorkItem(543158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543158")] [Fact()] public void NoDefaultForParams_Dev10781558() { var source = @" using System; abstract class A { public abstract void Foo(params int[] x); } class B : A { public override void Foo(int[] x = null) { Console.Write(x); } static void Main() { new B().Foo(); } } "; Func<bool, Action<ModuleSymbol>> validator = isFromMetadata => module => { var globalNamespace = module.GlobalNamespace; var classA = globalNamespace.GetMember<NamedTypeSymbol>("A"); var classB = globalNamespace.GetMember<NamedTypeSymbol>("B"); Assert.Equal(classA, classB.BaseType()); var fooA = classA.GetMember<MethodSymbol>("Foo"); var fooB = classB.GetMember<MethodSymbol>("Foo"); Assert.Equal(fooA, fooB.GetConstructedLeastOverriddenMethod(classB)); Assert.Equal(1, fooA.ParameterCount); var parameterA = fooA.Parameters[0]; Assert.True(parameterA.IsParams, "Parameter is not ParameterArray"); Assert.False(parameterA.HasExplicitDefaultValue, "ParameterArray param has default value"); Assert.False(parameterA.IsOptional, "ParameterArray param cannot be optional"); Assert.Equal(1, fooB.ParameterCount); var parameterB = fooB.Parameters[0]; Assert.True(parameterB.IsParams, "Parameter is not ParameterArray"); Assert.False(parameterB.HasExplicitDefaultValue, "ParameterArray param has default value"); Assert.Equal(ConstantValue.Null, parameterB.ExplicitDefaultConstantValue); Assert.False(parameterB.IsOptional, "ParameterArray param cannot be optional"); if (isFromMetadata) { WellKnownAttributesTestBase.VerifyParamArrayAttribute(parameterB); }; }; var verifier = CompileAndVerify(source, symbolValidator: validator(true), sourceSymbolValidator: validator(false), expectedOutput: @"System.Int32[]"); } [WorkItem(543158, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543158")] [Fact] public void XNoDefaultForParams_Dev10781558() { var source = @" public class Base { public virtual void M() {} }"; var source2 = @" using System; public class Derived : Base { public override void M() { Console.WriteLine(""M""); } } public class Test { public static void Main() { var obj = new Derived(); obj.M(); } }"; var compref = CreateCompilation(source, assemblyName: "XNoDefaultForParams_Dev10781558_Library"); var comp = CompileAndVerify(source2, references: new[] { new CSharpCompilationReference(compref) }, expectedOutput: "M"); } [Fact] public void CrossLanguageCase1() { var vb1Compilation = CreateVisualBasicCompilation("VB1", @"Public MustInherit Class C1 MustOverride Sub foo() End Class", compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); vb1Compilation.VerifyDiagnostics(); var cs1Compilation = CreateCSharpCompilation("CS1", @"using System; public abstract class C2 : C1 { new internal virtual void foo() { Console.WriteLine(""C2""); } }", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new[] { vb1Compilation }); var cs1Verifier = CompileAndVerify(cs1Compilation); cs1Verifier.VerifyDiagnostics(); var vb2Compilation = CreateVisualBasicCompilation("VB2", @"Imports System Public Class C3 : Inherits C2 Public Overrides Sub foo Console.WriteLine(""C3"") End Sub End Class", compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations: new Compilation[] { vb1Compilation, cs1Compilation }); vb2Compilation.VerifyDiagnostics(); var cs2Compilation = CreateCSharpCompilation("CS2", @" public class C4 : C3 { } // Below commented code results in PEVerify failures // for both Roslyn and Dev11. //public class C5 : C2 //{ // public override void foo() // { // Console.WriteLine(""C5""); // } //} public class Program { public static void Main() { C1 x = new C4(); x.foo(); //C2 y = new C5(); //y.foo(); } }", compilationOptions: TestOptions.ReleaseExe, referencedCompilations: new Compilation[] { vb1Compilation, cs1Compilation, vb2Compilation }); var cs2Verifier = CompileAndVerify(cs2Compilation, expectedOutput: @"C3"); cs2Verifier.VerifyDiagnostics(); } [Fact] public void CrossLanguageCase2() { var vb1Compilation = CreateVisualBasicCompilation("VB1", @"Public MustInherit Class C1 MustOverride Sub foo() End Class", compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); vb1Compilation.VerifyDiagnostics(); var cs1Compilation = CreateCSharpCompilation("CS1", @"using System; [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS2"")] public abstract class C2 : C1 { new internal virtual void foo() { Console.WriteLine(""C2""); } }", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new[] { vb1Compilation }); var cs1Verifier = CompileAndVerify(cs1Compilation); cs1Verifier.VerifyDiagnostics(); var vb2Compilation = CreateVisualBasicCompilation("VB2", @"Imports System Public Class C3 : Inherits C2 Public Overrides Sub foo Console.WriteLine(""C3"") End Sub End Class", compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations: new Compilation[] { vb1Compilation, cs1Compilation }); vb2Compilation.VerifyDiagnostics(); var cs2Compilation = CreateCSharpCompilation("CS2", @"using System; public class C4 : C3 { public override void foo() { Console.WriteLine(""C4""); } } abstract public class C5 : C2 { internal override void foo() { Console.WriteLine(""C5""); } } public class Program { public static void Main() { C1 x = new C4(); x.foo(); C2 y = new C4(); y.foo(); } }", compilationOptions: TestOptions.ReleaseExe, referencedCompilations: new Compilation[] { vb1Compilation, cs1Compilation, vb2Compilation }); var cs2Verifier = CompileAndVerify(cs2Compilation, expectedOutput: @"C4 C2"); cs2Verifier.VerifyDiagnostics(); } [Fact] public void HidingAndNamedParameters() { var source = @"using System; class Base { public void M(int x) { Console.WriteLine(""Base.M(x:"" + x + "")""); } } class Derived : Base { public new void M(int y) { Console.WriteLine(""Derived.M(y:"" + y + "")""); } } public class Test { public static void Main() { Derived d = new Derived(); d.M(x: 1); d.M(y: 2); } }"; var comp = CompileAndVerify(source, expectedOutput: @"Base.M(x:1) Derived.M(y:2)"); } [WorkItem(531095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531095")] [Fact] public void MissingAssemblyReference01() { var A = CreateCSharpCompilation("A", @"public class A {}", compilationOptions: TestOptions.ReleaseDll); CompileAndVerify(A).VerifyDiagnostics(); var B = CreateCSharpCompilation("B", @"public interface B { void M(A a); }", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new[] { A }); CompileAndVerify(B).VerifyDiagnostics(); var C = CreateCSharpCompilation("C", @"public class C { public void M(int a) { } }", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new[] { A }); CompileAndVerify(B).VerifyDiagnostics(); var D = CreateCSharpCompilation("D", @"public class D : C, B { }", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new[] { B, C }).VerifyDiagnostics( // (1,21): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class D : C, B { } Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 21) ); } [WorkItem(531095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531095")] [Fact] public void MissingAssemblyReference02() { var A = CreateCompilation(@"public class A {}", assemblyName: "A"); var B = CreateCompilation(@"public interface B { void M(A a); }", references: new[] { new CSharpCompilationReference(A) }, assemblyName: "B"); var C = CreateCompilation(@"public class C { public void M(A a) { } }", references: new[] { new CSharpCompilationReference(A) }, assemblyName: "C"); var D = CreateCompilation(@"public class D : C, B { }", references: new[] { new CSharpCompilationReference(B), new CSharpCompilationReference(C) }, assemblyName: "D"); A.VerifyDiagnostics(); B.VerifyDiagnostics(); C.VerifyDiagnostics(); D.VerifyDiagnostics( // (1,14): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // public class D : C, B { } Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("A", "A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } #region "Diagnostics" [Fact] public void CrossLanguageCase3() { var vb1Compilation = CreateVisualBasicCompilation("VB1", @"Public MustInherit Class C1 MustOverride Sub foo() End Class", compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); vb1Compilation.VerifyDiagnostics(); var cs1Compilation = CreateCSharpCompilation("CS1", @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS2"")] public abstract class C2 : C1 { new internal virtual void foo() { } }", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new[] { vb1Compilation }); var cs1Verifier = CompileAndVerify(cs1Compilation); cs1Verifier.VerifyDiagnostics(); var vb2Compilation = CreateVisualBasicCompilation("VB2", @"Public Class C3 : Inherits C2 Public Overrides Sub foo End Sub End Class", compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedCompilations: new Compilation[] { vb1Compilation, cs1Compilation }); vb2Compilation.VerifyDiagnostics(); var cs2Compilation = CreateCSharpCompilation("CS2", @"abstract public class C4 : C3 { public override void foo() { } } public class C5 : C2 { public override void foo() { } } public class C6 : C2 { internal override void foo() { } }", compilationOptions: TestOptions.ReleaseDll, referencedCompilations: new Compilation[] { vb1Compilation, cs1Compilation, vb2Compilation }); cs2Compilation.VerifyDiagnostics( // (10,26): error CS0507: 'C5.foo()': cannot change access modifiers when overriding 'internal' inherited member 'C2.foo()' // public override void foo() Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "foo").WithArguments("C5.foo()", "internal", "C2.foo()"), // (8,14): error CS0534: 'C5' does not implement inherited abstract member 'C1.foo()' // public class C5 : C2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C5").WithArguments("C5", "C1.foo()"), // (15,14): error CS0534: 'C6' does not implement inherited abstract member 'C1.foo()' // public class C6 : C2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C6").WithArguments("C6", "C1.foo()")); } #endregion } }
39.060079
398
0.620448
[ "Apache-2.0" ]
Ashera138/roslyn
src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenOverridingAndHiding.cs
168,414
C#
using MediatR; using System; namespace PresenceLight.Core.LifxServices { public class InitializeCommand : IRequest { public AppState AppState { get; set; } } }
16.545455
46
0.686813
[ "MIT" ]
JMilthaler/presencelight
src/PresenceLight.Core/Lights/LifxServices/Initialize/InitializeCommand.cs
184
C#
using System.IO; using System.Linq; using System.Threading.Tasks; using Fluid; using OrchardCore.Html.Model; using OrchardCore.Html.Settings; using OrchardCore.Html.ViewModels; using OrchardCore.ContentManagement.Display.ContentDisplay; using OrchardCore.ContentManagement.Metadata; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Views; using OrchardCore.Liquid; namespace OrchardCore.Html.Drivers { public class HtmlBodyPartDisplay : ContentPartDisplayDriver<HtmlBodyPart> { private readonly IContentDefinitionManager _contentDefinitionManager; private readonly ILiquidTemplateManager _liquidTemplatemanager; public HtmlBodyPartDisplay( IContentDefinitionManager contentDefinitionManager, ILiquidTemplateManager liquidTemplatemanager) { _contentDefinitionManager = contentDefinitionManager; _liquidTemplatemanager = liquidTemplatemanager; } public override IDisplayResult Display(HtmlBodyPart HtmlBodyPart) { return Initialize<HtmlBodyPartViewModel>("HtmlBodyPart", m => BuildViewModelAsync(m, HtmlBodyPart)) .Location("Detail", "Content:5") .Location("Summary", "Content:10"); } public override IDisplayResult Edit(HtmlBodyPart HtmlBodyPart) { return Initialize<HtmlBodyPartViewModel>("HtmlBodyPart_Edit", m => BuildViewModelAsync(m, HtmlBodyPart)); } public override async Task<IDisplayResult> UpdateAsync(HtmlBodyPart model, IUpdateModel updater) { var viewModel = new HtmlBodyPartViewModel(); await updater.TryUpdateModelAsync(viewModel, Prefix, t => t.Source); model.Html = viewModel.Source; return Edit(model); } private async Task BuildViewModelAsync(HtmlBodyPartViewModel model, HtmlBodyPart HtmlBodyPart) { var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(HtmlBodyPart.ContentItem.ContentType); var contentTypePartDefinition = contentTypeDefinition.Parts.FirstOrDefault(p => p.Name == nameof(HtmlBodyPart)); var settings = contentTypePartDefinition.GetSettings<HtmlBodyPartSettings>(); var templateContext = new TemplateContext(); templateContext.SetValue("ContentItem", HtmlBodyPart.ContentItem); templateContext.MemberAccessStrategy.Register<HtmlBodyPartViewModel>(); using (var writer = new StringWriter()) { await _liquidTemplatemanager.RenderAsync(HtmlBodyPart.Html, writer, NullEncoder.Default, templateContext); model.Html = writer.ToString(); } model.ContentItem = HtmlBodyPart.ContentItem; model.Source = HtmlBodyPart.Html; model.HtmlBodyPart = HtmlBodyPart; model.TypePartSettings = settings; } } }
39.746667
124
0.700772
[ "BSD-3-Clause" ]
CMSCollection/OrchardCore
src/OrchardCore.Modules/OrchardCore.Html/Drivers/HtmlBodyPartDisplay.cs
2,981
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MarketIO.gRPC.Client { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26
70
0.646724
[ "Apache-2.0" ]
Bdaya-Dev/gRPC-Learning
src/Client/MarketIO.gRPC.Client/MarketIO.gRPC.Client/Program.cs
702
C#
using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Rendering; /// <summary> /// 剔除需要的数据包 /// </summary> public class FullCullBuffers { /// <summary> /// 本地到世界的坐标矩阵集合 /// </summary> private ComputeBuffer LocalToWorldMatrixBufferCulled; /// <summary> /// 需要剔除的数据集合 /// </summary> private ComputeBuffer DrawDataBuffer; /// <summary> /// Draw数据 /// </summary> private ComputeBuffer ArgsBuffer; private uint[] args = new uint[5] { 0, 0, 0, 0, 0 }; private MaterialPropertyBlock materialBlock; private int DrawCount; private Mesh m_Mesh; private Material m_Material; private Bounds m_DrawBounds = new Bounds(Vector3.zero, Vector3.one * 100); public FullCullBuffers(Mesh p_Mesh, Material p_Mat) { Init(p_Mesh, p_Mat); } private void Init(Mesh p_Mesh, Material p_Mat) { InitDrawData(p_Mesh, p_Mat); InitBuffer(); InitArgsBuffer(); } private void InitBuffer() { if (this.ArgsBuffer != null || this.DrawDataBuffer != null) { Dispose(); } this.ArgsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments); } private void InitDrawData(Mesh p_Mesh, Material p_Mat) { m_Mesh = p_Mesh; m_Material = p_Mat; } /// <summary> /// 绘制总量发生改变时调用 更新总量 /// </summary> private void InitArgsBuffer() { materialBlock = new MaterialPropertyBlock(); int subMeshIndex = 0; // Indirect args if (m_Mesh != null) { args[0] = (uint)m_Mesh.GetIndexCount(subMeshIndex); args[1] = (uint)DrawCount; args[2] = (uint)m_Mesh.GetIndexStart(subMeshIndex); args[3] = (uint)m_Mesh.GetBaseVertex(subMeshIndex); } else { args[0] = args[1] = args[2] = args[3] = 0; } ArgsBuffer.SetData(args); } /// <summary> /// 刷新剔除数据 (每当数据总量发生修改时调用) /// </summary> /// <param name="p_DrawData"></param> public void UpdateBuffer(List<FullCameraCulling.CellData> p_DrawData) { DrawCount = p_DrawData.Count; if (DrawDataBuffer != null) { DrawDataBuffer.Release(); } DrawDataBuffer = new ComputeBuffer(p_DrawData.Count, Marshal.SizeOf(typeof(FullCameraCulling.CellData))); DrawDataBuffer.SetData(p_DrawData.ToArray()); } public void Cull(ComputeShader cs, bool p_ActiveFrustumCulling, bool p_ActiveOcclusionCulling, RenderTexture hzRT, Vector4 hzRTSize, Matrix4x4 p_VP, Vector3 p_CamPos, Vector4[] p_CameraPanels ) { if (LocalToWorldMatrixBufferCulled != null) { LocalToWorldMatrixBufferCulled.SetCounterValue(0); } else { LocalToWorldMatrixBufferCulled = new ComputeBuffer(DrawCount, Marshal.SizeOf<Matrix4x4>(), ComputeBufferType.Append); } var k = cs.FindKernel("CSMain"); cs.SetBuffer(k, "LocalToWorldCulled", LocalToWorldMatrixBufferCulled); cs.SetTexture(k, "_HiZMap", hzRT); cs.SetVector("_HiZTextureSize", hzRTSize); cs.SetMatrix("_UNITY_MATRIX_VP", p_VP); cs.SetVector("_CamPosition", p_CamPos); cs.SetBuffer(k, "bounds", DrawDataBuffer); cs.SetBool("_ActiveFrustumCulling", p_ActiveFrustumCulling); cs.SetBool("_ActiveOcclusionCulling", p_ActiveOcclusionCulling); cs.SetVectorArray("_CameraPanels", p_CameraPanels); cs.SetInt("_Count", DrawCount); int threadSizeX = 64; int dispatchXLength = DrawCount / threadSizeX + (DrawCount % (int)threadSizeX > 0 ? 1 : 0); cs.Dispatch(k, (int)dispatchXLength, 1, 1); ComputeBuffer.CopyCount(LocalToWorldMatrixBufferCulled, ArgsBuffer, sizeof(uint) * 1); this.materialBlock.SetBuffer("localToWorldBuffer", LocalToWorldMatrixBufferCulled); } public void Draw(Vector3 drawCenter, ShadowCastingMode p_ShadowCastingMode, bool isReceiveShadow) { m_DrawBounds.center = drawCenter; Graphics.DrawMeshInstancedIndirect(m_Mesh, 0, m_Material, m_DrawBounds, ArgsBuffer, 0, materialBlock, p_ShadowCastingMode, isReceiveShadow); } public void Dispose() { LocalToWorldMatrixBufferCulled.Dispose(); DrawDataBuffer.Dispose(); ArgsBuffer.Dispose(); } }
30.14
113
0.632825
[ "MIT" ]
Yogioo/UnityTools
Assets/Hiz-Occlusion/FullCullBuffers.cs
4,651
C#
using System; using FluentAssertions; using NUnit.Framework; using SFA.DAS.Apim.Developer.Domain.Extensions; using SFA.DAS.Apim.Developer.Domain.Models; namespace SFA.DAS.Apim.Developer.Domain.UnitTests.Extensions { public class WhenGettingApimUserTypeFromId { [Test] public void Then_If_Numeric_Then_Provider() { //Act var actual = 123456.ToString().ApimUserType(); //Assert actual.Should().Be(ApimUserType.Provider); } [Test] public void Then_If_Guid_Then_External() { //Act var actual = Guid.NewGuid().ToString().ApimUserType(); //Assert actual.Should().Be(ApimUserType.External); } [Test] public void Then_If_AlphaNumeric_Then_Employer() { //Act var actual = "ABC123".ApimUserType(); //Assert actual.Should().Be(ApimUserType.Employer); } } }
25.731707
66
0.551659
[ "MIT" ]
SkillsFundingAgency/das-apim-developer-api
src/SFA.DAS.Apim.Developer.Domain.UnitTests/Extensions/WhenGettingApimUserTypeFromId.cs
1,055
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 amplifybackend-2020-08-11.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.AmplifyBackend.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AmplifyBackend.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for GatewayTimeoutException Object /// </summary> public class GatewayTimeoutExceptionUnmarshaller : IErrorResponseUnmarshaller<GatewayTimeoutException, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public GatewayTimeoutException Unmarshall(JsonUnmarshallerContext context) { return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse()); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public GatewayTimeoutException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse) { context.Read(); GatewayTimeoutException unmarshalledObject = new GatewayTimeoutException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { } return unmarshalledObject; } private static GatewayTimeoutExceptionUnmarshaller _instance = new GatewayTimeoutExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static GatewayTimeoutExceptionUnmarshaller Instance { get { return _instance; } } } }
35.470588
137
0.674627
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/AmplifyBackend/Generated/Model/Internal/MarshallTransformations/GatewayTimeoutExceptionUnmarshaller.cs
3,015
C#
// See https://aka.ms/new-console-template for more information var image = new int[3, 3] { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } }; WriteImage(image); RotateImageClockwise90(image); WriteImage(image); static void RotateImageClockwise90(int[,] image) { var length = image.GetLength(0); for (int row = 0; row < length / 2; row++) { for (int column = row; column < length - row - 1; column++) { int top = image[row, column]; image[row, column] = image[length - 1 - column, row]; image[length - 1 - column, row] = image[length - 1 - row, length - 1 - column]; image[length - 1 - row, length - 1 - column] = image[column, length - 1 - row]; image[column, length - 1 - row] = top; } } } static void WriteImage(int[,] image) { for (var i = 0; i < image.GetLength(0); i++) { for (var j = 0; j < image.GetLength(1); j++) { Console.Write(image[i, j]); Console.Write('\t'); } Console.Write('\n'); } Console.Write('\n'); }
22.961538
67
0.475712
[ "MIT" ]
colotiline/cracking-the-coding-interview
chapter-1/1-6/Program.cs
1,196
C#
namespace Exercicio1_CSharp.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class CreatePersonTables : DbMigration { public override void Up() { CreateTable( "dbo.LegalPersons", c => new { Id = c.Int(nullable: false, identity: true), CNPJ = c.String(), IE = c.String(), Name = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.NaturalPersons", c => new { Id = c.Int(nullable: false, identity: true), LastName = c.String(), Age = c.Byte(nullable: false), CPF = c.String(), RG = c.String(), Name = c.String(), }) .PrimaryKey(t => t.Id); } public override void Down() { DropTable("dbo.NaturalPersons"); DropTable("dbo.LegalPersons"); } } }
29.139535
68
0.3751
[ "MIT" ]
Jhonegao/Csharp_Certification-Microsoft
Exercicio1_CSharp/Exercicio1_CSharp/Exercicio1_CSharp.Data/Migrations/202002222028162_CreatePersonTables.cs
1,255
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DisplayManager : MonoBehaviour { void Start() { Debug.Log("displays connected: " + Display.displays.Length); // Display.displays[0] is the primary, default display and is always ON, so start at index 1. // Check if additional displays are available and activate each. for (int i = 1; i < Display.displays.Length; i++) { Display.displays[i].Activate(); } } }
27.631579
101
0.641905
[ "MIT" ]
Loner291999/some-projects-at-THH
DM-Satellite-v2/Assets/Scripts/DisplayManager.cs
527
C#
using System.Threading.Tasks; using Abp.Application.Services; using MT.Sessions.Dto; namespace MT.Sessions { public interface ISessionAppService : IApplicationService { Task<GetCurrentLoginInformationsOutput> GetCurrentLoginInformations(); } }
22.166667
78
0.770677
[ "MIT" ]
zhang-jun-yi/ABPZero
MT.Application/Sessions/ISessionAppService.cs
268
C#
using AOT; using System; using System.Runtime.InteropServices; using UnityEngine.Scripting; using UnityEngine.XR.ARSubsystems; namespace UnityEngine.XR.ARCore { /// <summary> /// ARCore implementation of the <c>XRSessionSubsystem</c>. Do not create this directly. Use the <c>SubsystemManager</c> instead. /// </summary> [Preserve] public sealed class ARCoreSessionSubsystem : XRSessionSubsystem { /// <summary> /// Creates the provider interface. /// </summary> /// <returns>The provider interface for ARCore</returns> protected override IProvider CreateProvider() { return new Provider(); } class Provider : IProvider { public Provider() { NativeApi.UnityARCore_session_construct(CameraPermissionRequestProvider); } public override void Resume() { NativeApi.UnityARCore_session_resume(); } public override void Pause() { NativeApi.UnityARCore_session_pause(); } public override void Update(XRSessionUpdateParams updateParams) { NativeApi.UnityARCore_session_update( updateParams.screenOrientation, updateParams.screenDimensions); } public override void Destroy() { NativeApi.UnityARCore_session_destroy(); } public override void Reset() { NativeApi.UnityARCore_session_reset(); } public override void OnApplicationPause() { NativeApi.UnityARCore_session_onApplicationPause(); } public override void OnApplicationResume() { NativeApi.UnityARCore_session_onApplicationResume(); } public override Promise<SessionAvailability> GetAvailabilityAsync() { return ExecuteAsync<SessionAvailability>((context) => { NativeApi.ArPresto_checkApkAvailability(OnCheckApkAvailability, context); }); } public override Promise<SessionInstallationStatus> InstallAsync() { return ExecuteAsync<SessionInstallationStatus>((context) => { NativeApi.ArPresto_requestApkInstallation(true, OnApkInstallation, context); }); } public override IntPtr nativePtr { get { return NativeApi.UnityARCore_session_getNativePtr(); } } public override TrackingState trackingState { get { return NativeApi.UnityARCore_session_getTrackingState(); } } static Promise<T> ExecuteAsync<T>(Action<IntPtr> apiMethod) { var promise = new ARCorePromise<T>(); GCHandle gch = GCHandle.Alloc(promise); apiMethod(GCHandle.ToIntPtr(gch)); return promise; } [MonoPInvokeCallback(typeof(Action<NativeApi.ArPrestoApkInstallStatus, IntPtr>))] static void OnApkInstallation(NativeApi.ArPrestoApkInstallStatus status, IntPtr context) { var sessionInstallation = SessionInstallationStatus.None; switch (status) { case NativeApi.ArPrestoApkInstallStatus.ErrorDeviceNotCompatible: sessionInstallation = SessionInstallationStatus.ErrorDeviceNotCompatible; break; case NativeApi.ArPrestoApkInstallStatus.ErrorUserDeclined: sessionInstallation = SessionInstallationStatus.ErrorUserDeclined; break; case NativeApi.ArPrestoApkInstallStatus.Requested: // This shouldn't happen sessionInstallation = SessionInstallationStatus.Error; break; case NativeApi.ArPrestoApkInstallStatus.Success: sessionInstallation = SessionInstallationStatus.Success; break; case NativeApi.ArPrestoApkInstallStatus.Error: default: sessionInstallation = SessionInstallationStatus.Error; break; } ResolvePromise(context, sessionInstallation); } [MonoPInvokeCallback(typeof(Action<NativeApi.ArAvailability, IntPtr>))] static void OnCheckApkAvailability(NativeApi.ArAvailability availability, IntPtr context) { var sessionAvailability = SessionAvailability.None; switch (availability) { case NativeApi.ArAvailability.SupportedNotInstalled: case NativeApi.ArAvailability.SupportedApkTooOld: sessionAvailability = SessionAvailability.Supported; break; case NativeApi.ArAvailability.SupportedInstalled: sessionAvailability = SessionAvailability.Supported | SessionAvailability.Installed; break; default: sessionAvailability = SessionAvailability.None; break; } ResolvePromise(context, sessionAvailability); } [MonoPInvokeCallback(typeof(NativeApi.CameraPermissionRequestProviderDelegate))] static void CameraPermissionRequestProvider(NativeApi.CameraPermissionsResultCallbackDelegate callback, IntPtr context) { ARCorePermissionManager.RequestPermission(k_CameraPermissionName, (permissinName, granted) => { callback(granted, context); }); } static void ResolvePromise<T>(IntPtr context, T arg) where T : struct { GCHandle gch = GCHandle.FromIntPtr(context); var promise = (ARCorePromise<T>)gch.Target; if (promise != null) promise.Resolve(arg); gch.Free(); } const string k_CameraPermissionName = "android.permission.CAMERA"; } [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] static void RegisterDescriptor() { XRSessionSubsystemDescriptor.RegisterDescriptor(new XRSessionSubsystemDescriptor.Cinfo { id = "ARCore-Session", subsystemImplementationType = typeof(ARCoreSessionSubsystem), supportsInstall = false }); } static class NativeApi { public enum ArPrestoApkInstallStatus { Uninitialized = 0, Requested = 1, Success = 100, Error = 200, ErrorDeviceNotCompatible = 201, ErrorUserDeclined = 203, } public enum ArAvailability { UnknownError = 0, UnknownChecking = 1, UnknownTimedOut = 2, UnsupportedDeviceNotCapable = 100, SupportedNotInstalled = 201, SupportedApkTooOld = 202, SupportedInstalled = 203 } public delegate void CameraPermissionRequestProviderDelegate( CameraPermissionsResultCallbackDelegate resultCallback, IntPtr context); public delegate void CameraPermissionsResultCallbackDelegate( bool granted, IntPtr context); #if UNITY_ANDROID && !UNITY_EDITOR [DllImport("UnityARCore")] public static extern IntPtr UnityARCore_session_getNativePtr(); [DllImport("UnityARCore")] public static extern void ArPresto_checkApkAvailability( Action<ArAvailability, IntPtr> onResult, IntPtr context); [DllImport("UnityARCore")] public static extern void ArPresto_requestApkInstallation( bool userRequested, Action<ArPrestoApkInstallStatus, IntPtr> onResult, IntPtr context); [DllImport("UnityARCore")] public static extern void UnityARCore_session_update( ScreenOrientation orientation, Vector2Int screenDimensions); [DllImport("UnityARCore")] public static extern void UnityARCore_session_construct( CameraPermissionRequestProviderDelegate cameraPermissionRequestProvider); [DllImport("UnityARCore")] public static extern void UnityARCore_session_destroy(); [DllImport("UnityARCore")] public static extern void UnityARCore_session_resume(); [DllImport("UnityARCore")] public static extern void UnityARCore_session_pause(); [DllImport("UnityARCore")] public static extern void UnityARCore_session_onApplicationResume(); [DllImport("UnityARCore")] public static extern void UnityARCore_session_onApplicationPause(); [DllImport("UnityARCore")] public static extern void UnityARCore_session_reset(); [DllImport("UnityARCore")] public static extern TrackingState UnityARCore_session_getTrackingState(); #else public static IntPtr UnityARCore_session_getNativePtr() { return IntPtr.Zero; } public static void ArPresto_checkApkAvailability( Action<ArAvailability, IntPtr> onResult, IntPtr context) { onResult(ArAvailability.UnsupportedDeviceNotCapable, context); } public static void ArPresto_requestApkInstallation( bool userRequested, Action<ArPrestoApkInstallStatus, IntPtr> onResult, IntPtr context) { onResult(ArPrestoApkInstallStatus.ErrorDeviceNotCompatible, context); } public static void UnityARCore_session_update( ScreenOrientation orientation, Vector2Int screenDimensions) { } public static void UnityARCore_session_construct( CameraPermissionRequestProviderDelegate cameraPermissionRequestProvider) { } public static void UnityARCore_session_destroy() { } public static void UnityARCore_session_resume() { } public static void UnityARCore_session_pause() { } public static void UnityARCore_session_onApplicationResume() { } public static void UnityARCore_session_onApplicationPause() { } public static void UnityARCore_session_reset() { } public static TrackingState UnityARCore_session_getTrackingState() { return TrackingState.None; } #endif } } }
35.940625
133
0.572385
[ "MIT" ]
Jimmy5467/Entity-Lens
Library/PackageCache/com.unity.xr.arcore@2.0.2/Runtime/ARCoreSessionSubsystem.cs
11,501
C#
using System; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using Flurl.Http.Testing; using Netatmo.Models; using NodaTime; using NodaTime.Testing; using Xunit; namespace Netatmo.Tests { public class CredentialManager : IDisposable { public CredentialManager() { httpTest = new HttpTest(); } public void Dispose() { httpTest.Dispose(); } private readonly HttpTest httpTest; [Fact] public async Task GenerateToken_Should_Acquire_Excepted_CredentialToken() { var expectedToken = new { access_token = "2YotnFZFEjr1zCsicMWpAA", expires_in = 10800, refresh_token = "tGzv3JOkF0XG5Qx2TlKWIA" }; httpTest.RespondWithJson(expectedToken); var sut = new Netatmo.CredentialManager("https://api.netatmo.com/", "clientId", "clientSecret", SystemClock.Instance); await sut.GenerateToken("username@email.com", "p@$$W0rd", new[] { Scope.CameraAccess, Scope.CameraRead, Scope.CameraWrite, Scope.HomecoachRead, Scope.PresenceAccess, Scope.PresenceRead, Scope.StationRead, Scope.StationWrite, Scope.ThermostatRead }); var token = sut.CredentialToken; httpTest .ShouldHaveCalled("https://api.netatmo.com/oauth2/token") .WithVerb(HttpMethod.Post) .WithContentType("application/x-www-form-urlencoded") .WithRequestBody( "grant_type=password&client_id=clientId&client_secret=clientSecret&username=username%40email.com&password=p%40%24%24W0rd&scope=access_camera+read_camera+write_camera+read_homecoach+access_presence+read_presence+read_station+write_thermostat+read_thermostat") .Times(1); token.Should().BeOfType<CredentialToken>(); token.AccessToken.Should().Be(expectedToken.access_token); token.RefreshToken.Should().Be(expectedToken.refresh_token); token.ExpiresAt.Should().Be(token.ReceivedAt.Plus(Duration.FromSeconds(expectedToken.expires_in))); } [Fact] public void ProvideOAuth2Token_Should_Provide_Token_From_Existing() { var expectedToken = new { access_token = "2YotnFZFEjr1zCsicMWpAA", expires_in = 20 }; httpTest.RespondWithJson(expectedToken); var sut = new Netatmo.CredentialManager("https://api.netatmo.com/", "clientId", "clientSecret", SystemClock.Instance); sut.ProvideOAuth2Token(expectedToken.access_token); var token = sut.CredentialToken; token.Should().BeOfType<CredentialToken>(); token.AccessToken.Should().Be(expectedToken.access_token); token.RefreshToken.Should().BeNull(); token.ExpiresAt.Should().Be(token.ReceivedAt.Plus(Duration.FromSeconds(expectedToken.expires_in))); } [Fact] public async Task RefreshToken_Should_Refresh_Token() { var token = new { access_token = "2YotnFZFEjr1zCsicMWpAA", expires_in = 10800, refresh_token = "tGzv3JOkF0XG5Qx2TlKWIA" }; var expectedToken = new { access_token = "dGVzdGNsaWVudDpzZWNyZXQ", expires_in = 10800, refresh_token = "fdb8fdbecf1d03ce5e6125c067733c0d51de209c" }; httpTest.RespondWithJson(token); httpTest.RespondWithJson(expectedToken); var fakeClock = new FakeClock(SystemClock.Instance.GetCurrentInstant(), Duration.FromMinutes(-2)); var sut = new Netatmo.CredentialManager("https://api.netatmo.com/", "clientId", "clientSecret", fakeClock); await sut.GenerateToken("username@email.com", "p@$$W0rd"); var oldToken = sut.CredentialToken; await sut.RefreshToken(); var refreshedToken = sut.CredentialToken; httpTest .ShouldHaveCalled("https://api.netatmo.com/oauth2/token") .WithVerb(HttpMethod.Post) .WithContentType("application/x-www-form-urlencoded") .WithRequestBody( $"grant_type=refresh_token&client_id=clientId&client_secret=clientSecret&refresh_token={oldToken.RefreshToken}") .Times(1); refreshedToken.Should().BeOfType<CredentialToken>(); refreshedToken.AccessToken.Should().Be(expectedToken.access_token); refreshedToken.RefreshToken.Should().Be(expectedToken.refresh_token); refreshedToken.ExpiresAt.Should().Be(refreshedToken.ReceivedAt.Plus(Duration.FromSeconds(expectedToken.expires_in))); refreshedToken.Should().NotBe(oldToken); } } }
38.227273
278
0.616924
[ "MIT" ]
CristianT/Netatmo
src/Netatmo.Tests/CredentialManager.cs
5,046
C#
using System; namespace Encrypt__Sort_and_Print_Array { class Program { static void Main() { var n = int.Parse(Console.ReadLine()); var arr = new int[n]; var res = 0; for (int i = 0; i < n; i++) { var vowel = 0; var consonant = 0; var input = Console.ReadLine(); for (int j = 0; j < input.Length; j++) { if (input[j] == 'A' || input[j] == 'E' || input[j] == 'I' || input[j] == 'O' || input[j] == 'U' || input[j] == 'a' || input[j] == 'e' || input[j] == 'i' || input[j] == 'o' || input[j] == 'u') { vowel += (int)input[j] * input.Length; } else consonant += (int)input[j] / input.Length; } res = vowel + consonant; arr[i] = res; } Array.Sort(arr); foreach (var item in arr) { Console.WriteLine(item); } } } }
30.473684
115
0.348877
[ "MIT" ]
markodjunev/Softuni
C#/Tech Module 4.0/Arrays - More Exercise/Encrypt, Sort and Print Array/Encrypt, Sort and Print Array.cs
1,160
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace PodioAPI.Models { public class ItemCalculate { [JsonProperty("total")] public double? Total { get; set; } [JsonProperty("groups")] private List<CalculationGroup> CalculationGroups { get; set; } } public class CalculationGroup { [JsonProperty("groups")] public List<ValueGroup> ValueGroups { get; set; } [JsonProperty("count")] public double? Count { get; set; } } public class ValueGroup { [JsonProperty("value")] public string Value { get; set; } [JsonProperty("label")] public string Label { get; set; } } }
22.34375
70
0.595804
[ "MIT" ]
mads4990/podio-dotnet
Source/Podio .NET/Models/ItemCalculate.cs
717
C#
/* CSVReader - a simple open source C# class library to read CSV data * by Andrew Stellman - http://www.stellman-greene.com/CSVReader * * CSVReader.cs - Class to read CSV data from a string, file or stream * * download the latest version: http://svn.stellman-greene.com/CSVReader * * (c) 2008, Stellman & Greene Consulting * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Stellman & Greene Consulting nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY STELLMAN & GREENE CONSULTING ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL STELLMAN & GREENE CONSULTING BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ using System; using System.Collections.Generic; using System.IO; using System.Data; using System.Text; namespace Com.StellmanGreene.CSVReader { /// <summary> /// Read CSV-formatted data from a file or TextReader /// </summary> public class CSVReader : IDisposable { // public const string NEWLINE = "\n"; //public const string NEWLINE = "\r\n"; /// <summary> /// This reader will read all of the CSV data /// </summary> private BinaryReader reader; /// <summary> /// The number of rows to scan for types when building a DataTable (0 to scan the whole file) /// </summary> public int ScanRows = 0; #region Constructors /// <summary> /// Read CSV-formatted data from a file /// </summary> /// <param name="filename">Name of the CSV file</param> public CSVReader(FileInfo csvFileInfo) { if (csvFileInfo == null) throw new ArgumentNullException("Null FileInfo passed to CSVReader"); this.reader = new BinaryReader(File.OpenRead(csvFileInfo.FullName)); } /// <summary> /// Read CSV-formatted data from a string /// </summary> /// <param name="csvData">String containing CSV data</param> public CSVReader(string csvData) { if (csvData == null) throw new ArgumentNullException("Null string passed to CSVReader"); this.reader = new BinaryReader(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(csvData))); } /// <summary> /// Read CSV-formatted data from a TextReader /// </summary> /// <param name="reader">TextReader that's reading CSV-formatted data</param> public CSVReader(TextReader reader) { if (reader == null) throw new ArgumentNullException("Null TextReader passed to CSVReader"); this.reader = new BinaryReader(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(reader.ReadToEnd()))); } #endregion string currentLine = ""; /// <summary> /// Read the next row from the CSV data /// </summary> /// <returns>A list of objects read from the row, or null if there is no next row</returns> public List<object> ReadRow() { // ReadLine() will return null if there's no next line if (reader.BaseStream.Position >= reader.BaseStream.Length) return null; StringBuilder builder = new StringBuilder(); // Read the next line while ((reader.BaseStream.Position < reader.BaseStream.Length) && (!builder.ToString().EndsWith(NEWLINE) && !builder.ToString().EndsWith("\r"))) { char c = reader.ReadChar(); builder.Append(c); } currentLine = builder.ToString(); if (currentLine.EndsWith(NEWLINE)) currentLine = currentLine.Remove(currentLine.IndexOf(NEWLINE), NEWLINE.Length); // Modifying to handle \r if (currentLine.EndsWith("\r")) currentLine = currentLine.Remove(currentLine.IndexOf("\r"), "\r".Length); // Build the list of objects in the line List<object> objects = new List<object>(); while (currentLine != "" && currentLine.Length > 0) objects.Add(ReadNextObject()); return objects; } /// <summary> /// Read the next object from the currentLine string /// </summary> /// <returns>The next object in the currentLine string</returns> private object ReadNextObject() { if (currentLine == null) return null; // Check to see if the next value is quoted bool quoted = false; if (currentLine.StartsWith("\"")) quoted = true; // Find the end of the next value string nextObjectString = ""; int i = 0; int len = currentLine.Length; bool foundEnd = false; while (!foundEnd && i <= len) { // Check if we've hit the end of the string if ((!quoted && i == len) // non-quoted strings end with a comma or end of line || (!quoted && currentLine.Substring(i, 1) == ",") // quoted strings end with a quote followed by a comma or end of line || (quoted && i == len - 1 && currentLine.EndsWith("\"")) || (quoted && currentLine.Substring(i, 2) == "\",")) foundEnd = true; else i++; } if (quoted) { if (i > len || !currentLine.Substring(i, 1).StartsWith("\"")) throw new FormatException("Invalid CSV format: " + currentLine.Substring(0, i)); i++; } nextObjectString = currentLine.Substring(0, i).Replace("\"\"", "\""); if (i < len) currentLine = currentLine.Substring(i + 1); else currentLine = ""; if (quoted) { if (nextObjectString.StartsWith("\"")) nextObjectString = nextObjectString.Substring(1); if (nextObjectString.EndsWith("\"")) nextObjectString = nextObjectString.Substring(0, nextObjectString.Length - 1); return nextObjectString; } else { object convertedValue; StringConverter.ConvertString(nextObjectString, out convertedValue); return convertedValue; } } /// <summary> /// Read the row data read using repeated ReadRow() calls and build a DataColumnCollection with types and column names /// </summary> /// <param name="headerRow">True if the first row contains headers</param> /// <returns>System.Data.DataTable object populated with the row data</returns> public DataTable CreateDataTable(bool headerRow) { // Read the CSV data into rows List<List<object>> rows = new List<List<object>>(); List<object> readRow = null; while ((readRow = ReadRow()) != null) rows.Add(readRow); // The types and names (if headerRow is true) will be stored in these lists List<Type> columnTypes = new List<Type>(); List<string> columnNames = new List<string>(); // Read the column names from the header row (if there is one) if (headerRow) foreach (object name in rows[0]) columnNames.Add(name.ToString()); // Read the column types from each row in the list of rows bool headerRead = false; foreach (List<object> row in rows) if (headerRead || !headerRow) for (int i = 0; i < row.Count; i++) // If we're adding a new column to the columnTypes list, use its type. // Otherwise, find the common type between the one that's there and the new row. if (columnTypes.Count < i + 1) columnTypes.Add(row[i].GetType()); else columnTypes[i] = StringConverter.FindCommonType(columnTypes[i], row[i].GetType()); else headerRead = true; // Create the table and add the columns DataTable table = new DataTable(); for (int i = 0; i < columnTypes.Count; i++) { table.Columns.Add(); table.Columns[i].DataType = columnTypes[i]; if (i < columnNames.Count) table.Columns[i].ColumnName = columnNames[i]; } // Add the data from the rows headerRead = false; foreach (List<object> row in rows) if (headerRead || !headerRow) { DataRow dataRow = table.NewRow(); for (int i = 0; i < row.Count; i++) dataRow[i] = row[i]; table.Rows.Add(dataRow); } else headerRead = true; return table; } /// <summary> /// Read a CSV file into a table /// </summary> /// <param name="filename">Filename of CSV file</param> /// <param name="headerRow">True if the first row contains column names</param> /// <param name="scanRows">The number of rows to scan for types when building a DataTable (0 to scan the whole file)</param> /// <returns>System.Data.DataTable object that contains the CSV data</returns> public static DataTable ReadCSVFile(string filename, bool headerRow, int scanRows) { using (CSVReader reader = new CSVReader(new FileInfo(filename))) { reader.ScanRows = scanRows; return reader.CreateDataTable(headerRow); } } /// <summary> /// Read a CSV file into a table /// </summary> /// <param name="filename">Filename of CSV file</param> /// <param name="headerRow">True if the first row contains column names</param> /// <returns>System.Data.DataTable object that contains the CSV data</returns> public static DataTable ReadCSVFile(string filename, bool headerRow) { using (CSVReader reader = new CSVReader(new FileInfo(filename))) return reader.CreateDataTable(headerRow); } public static DataTable ReadCSVData(string csvData, bool headerRow) { using (CSVReader reader = new CSVReader(csvData: csvData)) return reader.CreateDataTable(headerRow); } #region IDisposable Members public void Dispose() { if (reader != null) { try { // Can't call BinaryReader.Dispose due to its protection level reader.Close(); } catch { } } } #endregion } }
39.379747
156
0.56019
[ "MIT" ]
shwetams/xmlcsvtojson
adf.transformations/adf.filetransformation/adf.filetransformation/CSVReader.cs
12,446
C#
using System; using Tracker.Core.Definitions; // ReSharper disable once CheckNamespace namespace Tracker.Core.Domain.Models { public class EntityCreateModel : IHaveIdentifier, ITrackCreated, ITrackUpdated { public Guid Id { get; set; } public DateTimeOffset Created { get; set; } public string? CreatedBy { get; set; } public DateTimeOffset Updated { get; set; } public string? UpdatedBy { get; set; } } }
23.15
82
0.671706
[ "MIT" ]
RubenDelange/EntityFrameworkCore.Generator
sample/Tracker/Tracker.Core/Domain/EntityCreateModel.cs
463
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Data.Common; using System.Globalization; namespace System.Data.ProviderBase { internal class BasicFieldNameLookup { // Dictionary stores the index into the _fieldNames, match via case-sensitive private Dictionary<string, int> _fieldNameLookup; // original names for linear searches when exact matches fail private readonly string[] _fieldNames; // By default _compareInfo is set to InvariantCulture CompareInfo private CompareInfo _compareInfo; public BasicFieldNameLookup(string[] fieldNames) { if (null == fieldNames) { throw ADP.ArgumentNull(nameof(fieldNames)); } _fieldNames = fieldNames; } public BasicFieldNameLookup(System.Collections.ObjectModel.ReadOnlyCollection<string> columnNames) { int length = columnNames.Count; string[] fieldNames = new string[length]; for (int i = 0; i < length; ++i) { fieldNames[i] = columnNames[i]; } _fieldNames = fieldNames; GenerateLookup(); } public BasicFieldNameLookup(DbDataReader reader) { int length = reader.FieldCount; string[] fieldNames = new string[length]; for (int i = 0; i < length; ++i) { fieldNames[i] = reader.GetName(i); } _fieldNames = fieldNames; } public int GetOrdinal(string fieldName) { if (null == fieldName) { throw ADP.ArgumentNull(nameof(fieldName)); } int index = IndexOf(fieldName); if (-1 == index) { throw ADP.IndexOutOfRange(fieldName); } return index; } public int IndexOfName(string fieldName) { if (null == _fieldNameLookup) { GenerateLookup(); } int value; // via case sensitive search, first match with lowest ordinal matches return _fieldNameLookup.TryGetValue(fieldName, out value) ? value : -1; } public int IndexOf(string fieldName) { if (null == _fieldNameLookup) { GenerateLookup(); } int index; // via case sensitive search, first match with lowest ordinal matches if (!_fieldNameLookup.TryGetValue(fieldName, out index)) { // via case insensitive search, first match with lowest ordinal matches index = LinearIndexOf(fieldName, CompareOptions.IgnoreCase); if (-1 == index) { // do the slow search now (kana, width insensitive comparison) index = LinearIndexOf(fieldName, ADP.compareOptions); } } return index; } protected virtual CompareInfo GetCompareInfo() { return CultureInfo.InvariantCulture.CompareInfo; } private int LinearIndexOf(string fieldName, CompareOptions compareOptions) { if (null == _compareInfo) { _compareInfo = GetCompareInfo(); } int length = _fieldNames.Length; for (int i = 0; i < length; ++i) { if (0 == _compareInfo.Compare(fieldName, _fieldNames[i], compareOptions)) { _fieldNameLookup[fieldName] = i; // add an exact match for the future return i; } } return -1; } // RTM common code for generating Dictionary from array of column names private void GenerateLookup() { int length = _fieldNames.Length; Dictionary<string, int> hash = new Dictionary<string, int>(length); // via case sensitive search, first match with lowest ordinal matches for (int i = length - 1; 0 <= i; --i) { string fieldName = _fieldNames[i]; hash[fieldName] = i; } _fieldNameLookup = hash; } } }
32.020979
106
0.538109
[ "MIT" ]
Priya91/corefx-1
src/Common/src/System/Data/Common/BasicFieldNameLookup.cs
4,581
C#
// PostgreSQL IDatabase, IConnection, ICommand, IReader Wrapper // using System; using System.Collections.Generic; using Npgsql; namespace Business.Core.PostgreSQL { public class Database : IDatabase { public Profile.Profile Profile { get; set; } public Database(Profile.Profile profile) { Profile = profile; } public string Type => "PostgreSQL"; NpgsqlConnection PostgreSQLConnection { get; set; } public IConnection Connection { get; set; } public ICommand Command { get; set; } void IDatabase.Connect() { PostgreSQLConnection = new NpgsqlConnection( $"Host={Profile?.PostgreSQLProfile.Host};Username={Profile?.PostgreSQLProfile.User};Database={Profile?.PostgreSQLProfile.Database}" ); Connection = new Connection() { PostgreSQLConnection = PostgreSQLConnection }; Command = new Command { PostgreSQLConnection = PostgreSQLConnection }; } public Version SchemaVersion() { return Core.SchemaVersion.Get(this); } // Server-side functions public UInt32? Book(string Name, float Amount) { return Core.Function.Book(this, Name, Amount); } public List<Balance> BookBalance(string Name, float Amount) { return Core.Function.BookBalance(this, Name, Amount); } } }
26.76087
136
0.730301
[ "MIT" ]
jazd/Business
CSharp/Core.PostreSQL/Database.cs
1,233
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace ParallelForEach { class Program { static void Main() { // 2 million var limit = 2_000_000; var numbers = Enumerable.Range(0, limit).ToList(); var watch = Stopwatch.StartNew(); var primeNumbersFromForeach = GetPrimeList(numbers); watch.Stop(); var watchForParallel = Stopwatch.StartNew(); var primeNumbersFromParallelForeach = GetPrimeListWithParallel(numbers); watchForParallel.Stop(); Console.WriteLine($"Classical foreach loop | Total prime numbers : {primeNumbersFromForeach.Count} | Time Taken : {watch.ElapsedMilliseconds} ms."); Console.WriteLine($"Parallel.ForEach loop | Total prime numbers : {primeNumbersFromParallelForeach.Count} | Time Taken : {watchForParallel.ElapsedMilliseconds} ms."); Console.WriteLine("Press any key to exit."); Console.ReadLine(); } /// <summary> /// GetPrimeList returns Prime numbers by using sequential ForEach /// </summary> /// <param name="inputs"></param> /// <returns></returns> private static IList<int> GetPrimeList(IList<int> numbers) => numbers.Where(IsPrime).ToList(); /// <summary> /// GetPrimeListWithParallel returns Prime numbers by using Parallel.ForEach /// </summary> /// <param name="numbers"></param> /// <returns></returns> private static IList<int> GetPrimeListWithParallel(IList<int> numbers) { var primeNumbers = new ConcurrentBag<int>(); Parallel.ForEach(numbers, number => { if (IsPrime(number)) { primeNumbers.Add(number); } }); return primeNumbers.ToList(); } /// <summary> /// IsPrime returns true if number is Prime, else false.(https://en.wikipedia.org/wiki/Prime_number) /// </summary> /// <param name="number"></param> /// <returns></returns> private static bool IsPrime(int number) { if (number < 2) { return false; } for (var divisor = 2; divisor <= Math.Sqrt(number); divisor++) { if (number % divisor == 0) { return false; } } return true; } } }
32.144578
179
0.552099
[ "MIT" ]
nrawat207/ParallelProgramming-CSharp
src/ParallelProgramming-CSharp/ParallelForEach/Program.cs
2,670
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. // Template Source: Templates\CSharp\Model\ComplexType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type SharepointIds. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof(DerivedTypeConverter))] public partial class SharepointIds { /// <summary> /// Gets or sets listId. /// The unique identifier (guid) for the item's list in SharePoint. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "listId", Required = Newtonsoft.Json.Required.Default)] public string ListId { get; set; } /// <summary> /// Gets or sets listItemId. /// An integer identifier for the item within the containing list. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "listItemId", Required = Newtonsoft.Json.Required.Default)] public string ListItemId { get; set; } /// <summary> /// Gets or sets listItemUniqueId. /// The unique identifier (guid) for the item within OneDrive for Busienss or a SharePoint site. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "listItemUniqueId", Required = Newtonsoft.Json.Required.Default)] public string ListItemUniqueId { get; set; } /// <summary> /// Gets or sets siteId. /// The unique identifier (guid) for the item's site collection (SPSite). /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "siteId", Required = Newtonsoft.Json.Required.Default)] public string SiteId { get; set; } /// <summary> /// Gets or sets siteUrl. /// The SharePoint URL for the site that contains the item. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "siteUrl", Required = Newtonsoft.Json.Required.Default)] public string SiteUrl { get; set; } /// <summary> /// Gets or sets webId. /// The unique identifier (guid) for the item's site (SPWeb). /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "webId", Required = Newtonsoft.Json.Required.Default)] public string WebId { get; set; } /// <summary> /// Gets or sets additional data. /// </summary> [JsonExtensionData(ReadData = true)] public IDictionary<string, object> AdditionalData { get; set; } } }
42.64
153
0.611632
[ "MIT" ]
PaoloPia/msgraph-sdk-dotnet
src/Microsoft.Graph/Models/Generated/SharepointIds.cs
3,198
C#
using Parsec.Extensions; using Parsec.Readers; using Parsec.Shaiya.SData; namespace Parsec.Shaiya.Skill; public class DBSkillDataRecord : IBinarySDataRecord { public long Id { get; set; } public long SkillLevel { get; set; } public long Image { get; set; } public long Ani { get; set; } public long Effect { get; set; } public long ToggleType { get; set; } public long Sound { get; set; } public long Level { get; set; } public long Country { get; set; } public long AttackFighter { get; set; } public long DefenseFighter { get; set; } public long PatrolRogue { get; set; } public long ShootRogue { get; set; } public long AttackMage { get; set; } public long DefenseMage { get; set; } public long Grow { get; set; } public long Point { get; set; } public long Typeshow { get; set; } public long TypeAttack { get; set; } public long Typeeffect { get; set; } public long Type { get; set; } public long NeedWeapon1 { get; set; } public long NeedWeapon2 { get; set; } public long NeedWeapon3 { get; set; } public long NeedWeapon4 { get; set; } public long NeedWeapon5 { get; set; } public long NeedWeapon6 { get; set; } public long NeedWeapon7 { get; set; } public long NeedWeapon8 { get; set; } public long NeedWeapon9 { get; set; } public long NeedWeapon10 { get; set; } public long NeedWeapon11 { get; set; } public long NeedWeapon12 { get; set; } public long NeedWeapon13 { get; set; } public long NeedWeapon14 { get; set; } public long NeedWeapon15 { get; set; } public long Shield { get; set; } public long Sp { get; set; } public long Mp { get; set; } public long ReadyTime { get; set; } public long ResetTime { get; set; } public long AttackRange { get; set; } public long StateType { get; set; } public long AttribType { get; set; } public long Disable { get; set; } public long PrevSkill { get; set; } public long SuccessType { get; set; } public long SuccessValue { get; set; } public long TargetType { get; set; } public long ApplyRange { get; set; } public long MultiAttack { get; set; } public long KeepTime { get; set; } public long Weapon1 { get; set; } public long Weapon2 { get; set; } public long WeaponValue { get; set; } public long Bag { get; set; } public long Arrow { get; set; } public long DaMageType { get; set; } public long DaMage1 { get; set; } public long DaMage2 { get; set; } public long DaMage3 { get; set; } public long TimeDaMageType { get; set; } public long TimeDaMage1 { get; set; } public long TimeDaMage2 { get; set; } public long TimeDaMage3 { get; set; } public long AddDaMage1 { get; set; } public long AddDaMage2 { get; set; } public long AddDaMage3 { get; set; } public long AbilityType1 { get; set; } public long AbilityValue1 { get; set; } public long AbilityType2 { get; set; } public long AbilityValue2 { get; set; } public long AbilityType3 { get; set; } public long AbilityValue3 { get; set; } public long AbilityType4 { get; set; } public long AbilityValue4 { get; set; } public long AbilityType5 { get; set; } public long AbilityValue5 { get; set; } public long AbilityType6 { get; set; } public long AbilityValue6 { get; set; } public long AbilityType7 { get; set; } public long AbilityValue7 { get; set; } public long AbilityType8 { get; set; } public long AbilityValue8 { get; set; } public long AbilityType9 { get; set; } public long AbilityValue9 { get; set; } public long AbilityType10 { get; set; } public long AbilityValue10 { get; set; } public long Heal1 { get; set; } public long Heal2 { get; set; } public long Heal3 { get; set; } public long TimeHeal1 { get; set; } public long TimeHeal2 { get; set; } public long TimeHeal3 { get; set; } public long DefenceType { get; set; } public long DefenceValue { get; set; } public long LimitHp { get; set; } public long FixRange { get; set; } public long ChangeType { get; set; } public long ChangeLevel { get; set; } public long TacticZoneBound { get; set; } public void Read(SBinaryReader binaryReader, params object[] options) { Id = binaryReader.Read<long>(); SkillLevel = binaryReader.Read<long>(); Image = binaryReader.Read<long>(); Ani = binaryReader.Read<long>(); Effect = binaryReader.Read<long>(); ToggleType = binaryReader.Read<long>(); Sound = binaryReader.Read<long>(); Level = binaryReader.Read<long>(); Country = binaryReader.Read<long>(); AttackFighter = binaryReader.Read<long>(); DefenseFighter = binaryReader.Read<long>(); PatrolRogue = binaryReader.Read<long>(); ShootRogue = binaryReader.Read<long>(); AttackMage = binaryReader.Read<long>(); DefenseMage = binaryReader.Read<long>(); Grow = binaryReader.Read<long>(); Point = binaryReader.Read<long>(); Typeshow = binaryReader.Read<long>(); TypeAttack = binaryReader.Read<long>(); Typeeffect = binaryReader.Read<long>(); Type = binaryReader.Read<long>(); NeedWeapon1 = binaryReader.Read<long>(); NeedWeapon2 = binaryReader.Read<long>(); NeedWeapon3 = binaryReader.Read<long>(); NeedWeapon4 = binaryReader.Read<long>(); NeedWeapon5 = binaryReader.Read<long>(); NeedWeapon6 = binaryReader.Read<long>(); NeedWeapon7 = binaryReader.Read<long>(); NeedWeapon8 = binaryReader.Read<long>(); NeedWeapon9 = binaryReader.Read<long>(); NeedWeapon10 = binaryReader.Read<long>(); NeedWeapon11 = binaryReader.Read<long>(); NeedWeapon12 = binaryReader.Read<long>(); NeedWeapon13 = binaryReader.Read<long>(); NeedWeapon14 = binaryReader.Read<long>(); NeedWeapon15 = binaryReader.Read<long>(); Shield = binaryReader.Read<long>(); Sp = binaryReader.Read<long>(); Mp = binaryReader.Read<long>(); ReadyTime = binaryReader.Read<long>(); ResetTime = binaryReader.Read<long>(); AttackRange = binaryReader.Read<long>(); StateType = binaryReader.Read<long>(); AttribType = binaryReader.Read<long>(); Disable = binaryReader.Read<long>(); PrevSkill = binaryReader.Read<long>(); SuccessType = binaryReader.Read<long>(); SuccessValue = binaryReader.Read<long>(); TargetType = binaryReader.Read<long>(); ApplyRange = binaryReader.Read<long>(); MultiAttack = binaryReader.Read<long>(); KeepTime = binaryReader.Read<long>(); Weapon1 = binaryReader.Read<long>(); Weapon2 = binaryReader.Read<long>(); WeaponValue = binaryReader.Read<long>(); Bag = binaryReader.Read<long>(); Arrow = binaryReader.Read<long>(); DaMageType = binaryReader.Read<long>(); DaMage1 = binaryReader.Read<long>(); DaMage2 = binaryReader.Read<long>(); DaMage3 = binaryReader.Read<long>(); TimeDaMageType = binaryReader.Read<long>(); TimeDaMage1 = binaryReader.Read<long>(); TimeDaMage2 = binaryReader.Read<long>(); TimeDaMage3 = binaryReader.Read<long>(); AddDaMage1 = binaryReader.Read<long>(); AddDaMage2 = binaryReader.Read<long>(); AddDaMage3 = binaryReader.Read<long>(); AbilityType1 = binaryReader.Read<long>(); AbilityValue1 = binaryReader.Read<long>(); AbilityType2 = binaryReader.Read<long>(); AbilityValue2 = binaryReader.Read<long>(); AbilityType3 = binaryReader.Read<long>(); AbilityValue3 = binaryReader.Read<long>(); AbilityType4 = binaryReader.Read<long>(); AbilityValue4 = binaryReader.Read<long>(); AbilityType5 = binaryReader.Read<long>(); AbilityValue5 = binaryReader.Read<long>(); AbilityType6 = binaryReader.Read<long>(); AbilityValue6 = binaryReader.Read<long>(); AbilityType7 = binaryReader.Read<long>(); AbilityValue7 = binaryReader.Read<long>(); AbilityType8 = binaryReader.Read<long>(); AbilityValue8 = binaryReader.Read<long>(); AbilityType9 = binaryReader.Read<long>(); AbilityValue9 = binaryReader.Read<long>(); AbilityType10 = binaryReader.Read<long>(); AbilityValue10 = binaryReader.Read<long>(); Heal1 = binaryReader.Read<long>(); Heal2 = binaryReader.Read<long>(); Heal3 = binaryReader.Read<long>(); TimeHeal1 = binaryReader.Read<long>(); TimeHeal2 = binaryReader.Read<long>(); TimeHeal3 = binaryReader.Read<long>(); DefenceType = binaryReader.Read<long>(); DefenceValue = binaryReader.Read<long>(); LimitHp = binaryReader.Read<long>(); FixRange = binaryReader.Read<long>(); ChangeType = binaryReader.Read<long>(); ChangeLevel = binaryReader.Read<long>(); TacticZoneBound = binaryReader.Read<long>(); } public IEnumerable<byte> GetBytes(params object[] options) { var buffer = new List<byte>(); buffer.AddRange(Id.GetBytes()); buffer.AddRange(SkillLevel.GetBytes()); buffer.AddRange(Image.GetBytes()); buffer.AddRange(Ani.GetBytes()); buffer.AddRange(Effect.GetBytes()); buffer.AddRange(ToggleType.GetBytes()); buffer.AddRange(Sound.GetBytes()); buffer.AddRange(Level.GetBytes()); buffer.AddRange(Country.GetBytes()); buffer.AddRange(AttackFighter.GetBytes()); buffer.AddRange(DefenseFighter.GetBytes()); buffer.AddRange(PatrolRogue.GetBytes()); buffer.AddRange(ShootRogue.GetBytes()); buffer.AddRange(AttackMage.GetBytes()); buffer.AddRange(DefenseMage.GetBytes()); buffer.AddRange(Grow.GetBytes()); buffer.AddRange(Point.GetBytes()); buffer.AddRange(Typeshow.GetBytes()); buffer.AddRange(TypeAttack.GetBytes()); buffer.AddRange(Typeeffect.GetBytes()); buffer.AddRange(Type.GetBytes()); buffer.AddRange(NeedWeapon1.GetBytes()); buffer.AddRange(NeedWeapon2.GetBytes()); buffer.AddRange(NeedWeapon3.GetBytes()); buffer.AddRange(NeedWeapon4.GetBytes()); buffer.AddRange(NeedWeapon5.GetBytes()); buffer.AddRange(NeedWeapon6.GetBytes()); buffer.AddRange(NeedWeapon7.GetBytes()); buffer.AddRange(NeedWeapon8.GetBytes()); buffer.AddRange(NeedWeapon9.GetBytes()); buffer.AddRange(NeedWeapon10.GetBytes()); buffer.AddRange(NeedWeapon11.GetBytes()); buffer.AddRange(NeedWeapon12.GetBytes()); buffer.AddRange(NeedWeapon13.GetBytes()); buffer.AddRange(NeedWeapon14.GetBytes()); buffer.AddRange(NeedWeapon15.GetBytes()); buffer.AddRange(Shield.GetBytes()); buffer.AddRange(Sp.GetBytes()); buffer.AddRange(Mp.GetBytes()); buffer.AddRange(ReadyTime.GetBytes()); buffer.AddRange(ResetTime.GetBytes()); buffer.AddRange(AttackRange.GetBytes()); buffer.AddRange(StateType.GetBytes()); buffer.AddRange(AttribType.GetBytes()); buffer.AddRange(Disable.GetBytes()); buffer.AddRange(PrevSkill.GetBytes()); buffer.AddRange(SuccessType.GetBytes()); buffer.AddRange(SuccessValue.GetBytes()); buffer.AddRange(TargetType.GetBytes()); buffer.AddRange(ApplyRange.GetBytes()); buffer.AddRange(MultiAttack.GetBytes()); buffer.AddRange(KeepTime.GetBytes()); buffer.AddRange(Weapon1.GetBytes()); buffer.AddRange(Weapon2.GetBytes()); buffer.AddRange(WeaponValue.GetBytes()); buffer.AddRange(Bag.GetBytes()); buffer.AddRange(Arrow.GetBytes()); buffer.AddRange(DaMageType.GetBytes()); buffer.AddRange(DaMage1.GetBytes()); buffer.AddRange(DaMage2.GetBytes()); buffer.AddRange(DaMage3.GetBytes()); buffer.AddRange(TimeDaMageType.GetBytes()); buffer.AddRange(TimeDaMage1.GetBytes()); buffer.AddRange(TimeDaMage2.GetBytes()); buffer.AddRange(TimeDaMage3.GetBytes()); buffer.AddRange(AddDaMage1.GetBytes()); buffer.AddRange(AddDaMage2.GetBytes()); buffer.AddRange(AddDaMage3.GetBytes()); buffer.AddRange(AbilityType1.GetBytes()); buffer.AddRange(AbilityValue1.GetBytes()); buffer.AddRange(AbilityType2.GetBytes()); buffer.AddRange(AbilityValue2.GetBytes()); buffer.AddRange(AbilityType3.GetBytes()); buffer.AddRange(AbilityValue3.GetBytes()); buffer.AddRange(AbilityType4.GetBytes()); buffer.AddRange(AbilityValue4.GetBytes()); buffer.AddRange(AbilityType5.GetBytes()); buffer.AddRange(AbilityValue5.GetBytes()); buffer.AddRange(AbilityType6.GetBytes()); buffer.AddRange(AbilityValue6.GetBytes()); buffer.AddRange(AbilityType7.GetBytes()); buffer.AddRange(AbilityValue7.GetBytes()); buffer.AddRange(AbilityType8.GetBytes()); buffer.AddRange(AbilityValue8.GetBytes()); buffer.AddRange(AbilityType9.GetBytes()); buffer.AddRange(AbilityValue9.GetBytes()); buffer.AddRange(AbilityType10.GetBytes()); buffer.AddRange(AbilityValue10.GetBytes()); buffer.AddRange(Heal1.GetBytes()); buffer.AddRange(Heal2.GetBytes()); buffer.AddRange(Heal3.GetBytes()); buffer.AddRange(TimeHeal1.GetBytes()); buffer.AddRange(TimeHeal2.GetBytes()); buffer.AddRange(TimeHeal3.GetBytes()); buffer.AddRange(DefenceType.GetBytes()); buffer.AddRange(DefenceValue.GetBytes()); buffer.AddRange(LimitHp.GetBytes()); buffer.AddRange(FixRange.GetBytes()); buffer.AddRange(ChangeType.GetBytes()); buffer.AddRange(ChangeLevel.GetBytes()); buffer.AddRange(TacticZoneBound.GetBytes()); return buffer; } }
43.755418
73
0.641477
[ "MIT" ]
matigramirez/Parsec
src/Parsec/Shaiya/Skill/DBSkillDataRecord.cs
14,135
C#