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
// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Xunit; namespace Steeltoe.Discovery.Eureka.Test { public class DiscoveryManagerTest : AbstractBaseTest { [Fact] public void DiscoveryManager_IsSingleton() { Assert.Equal(ApplicationInfoManager.Instance, ApplicationInfoManager.Instance); } [Fact] public void DiscoveryManager_Uninitialized() { Assert.Null(DiscoveryManager.Instance.Client); Assert.Null(DiscoveryManager.Instance.ClientConfig); Assert.Null(DiscoveryManager.Instance.InstanceConfig); } [Fact] public void Initialize_Throws_IfInstanceConfigNull() { var ex = Assert.Throws<ArgumentNullException>(() => DiscoveryManager.Instance.Initialize(new EurekaClientConfig(), (EurekaInstanceConfig)null, null)); Assert.Contains("instanceConfig", ex.Message); } [Fact] public void Initialize_Throws_IfClientConfigNull() { var ex = Assert.Throws<ArgumentNullException>(() => DiscoveryManager.Instance.Initialize(null, new EurekaInstanceConfig(), null)); Assert.Contains("clientConfig", ex.Message); } [Fact] public void Initialize_WithBothConfigs_InitializesAll() { EurekaInstanceConfig instanceConfig = new EurekaInstanceConfig(); EurekaClientConfig clientConfig = new EurekaClientConfig() { ShouldRegisterWithEureka = false, ShouldFetchRegistry = false }; DiscoveryManager.Instance.Initialize(clientConfig, instanceConfig); Assert.NotNull(DiscoveryManager.Instance.InstanceConfig); Assert.Equal(instanceConfig, DiscoveryManager.Instance.InstanceConfig); Assert.NotNull(DiscoveryManager.Instance.ClientConfig); Assert.Equal(clientConfig, DiscoveryManager.Instance.ClientConfig); Assert.NotNull(DiscoveryManager.Instance.Client); Assert.Equal(instanceConfig, ApplicationInfoManager.Instance.InstanceConfig); } [Fact] public void Initialize_WithClientConfig_InitializesAll() { EurekaClientConfig clientConfig = new EurekaClientConfig() { ShouldRegisterWithEureka = false, ShouldFetchRegistry = false }; DiscoveryManager.Instance.Initialize(clientConfig); Assert.Null(DiscoveryManager.Instance.InstanceConfig); Assert.NotNull(DiscoveryManager.Instance.ClientConfig); Assert.Equal(clientConfig, DiscoveryManager.Instance.ClientConfig); Assert.NotNull(DiscoveryManager.Instance.Client); Assert.Null(ApplicationInfoManager.Instance.InstanceConfig); } } }
38.640449
162
0.673742
[ "ECL-2.0", "Apache-2.0" ]
DrDao/Discovery
test/Steeltoe.Discovery.EurekaBase.Test/DiscoveryManagerTest.cs
3,441
C#
using Tweetinvi.Models; namespace Tweetinvi.Parameters { /// <summary> /// For more information read : https://developer.twitter.com/en/docs/geo/places-near-location/api-reference/get-geo-reverse_geocode /// </summary> public interface IGeoSearchReverseParameters : ICustomRequestParameters { /// <summary> /// Coordinates of the geo location. /// </summary> ICoordinates Coordinates { get; set; } /// <summary> /// This is the minimal granularity of place types to return. /// </summary> Granularity Granularity { get; set; } /// <summary> /// A hint on the “region” in which to search. If a number, then this is a radius in meters, /// but it can also take a string that is suffixed with ft to specify feet. /// </summary> int? Accuracy { get; set; } /// <summary> /// Maximum number of places to return. /// </summary> int? MaximumNumberOfResults { get; set; } /// <summary> /// If supplied, the response will use the JSONP format with a callback of the given name. /// </summary> string Callback { get; set; } } /// <summary> /// https://dev.twitter.com/rest/reference/get/geo/reverse_geocode /// </summary> public class GeoSearchReverseParameters : CustomRequestParameters, IGeoSearchReverseParameters { public GeoSearchReverseParameters(ICoordinates coordinates) { Coordinates = coordinates; } public ICoordinates Coordinates { get; set; } public Granularity Granularity { get; set; } public int? Accuracy { get; set; } public int? MaximumNumberOfResults { get; set; } public string Callback { get; set; } } }
34.245283
136
0.609917
[ "MIT" ]
IEvangelist/tweetinvi
src/Tweetinvi.Core/Public/Parameters/HelpClient/GeoSearchReverseParameters.cs
1,821
C#
// ----------------------------------------------------------------------- // <copyright file="ServiceBase.cs" company="OSharp开源团队"> // Copyright (c) 2014 OSharp. All rights reserved. // </copyright> // <last-editor>郭明锋</last-editor> // <last-date>2014-07-17 3:42</last-date> // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using OSharp.Core.Data; namespace OSharp.Core { /// <summary> /// 业务实现基类 /// </summary> public abstract class ServiceBase { protected ServiceBase(IUnitOfWork unitOfWork) { UnitOfWork = unitOfWork; } /// <summary> /// 获取或设置 单元操作对象 /// </summary> protected IUnitOfWork UnitOfWork { get; private set; } } }
26.194444
76
0.505832
[ "Apache-2.0" ]
J-W-Chan/osharp
src/OSharp.Core/ServiceBase.cs
993
C#
using System; using System.IO; using System.Linq; using McMaster.Extensions.CommandLineUtils; using static Bullseye.Targets; using static SimpleExec.Command; namespace build { class Program { private const string Prefix = "AspNetIdentity"; private const bool RequireTests = false; private const string ArtifactsDir = "artifacts"; private const string Build = "build"; private const string Test = "test"; private const string Pack = "pack"; static void Main(string[] args) { var app = new CommandLineApplication(throwOnUnexpectedArg: false); var sign = app.Option<(bool hasValue, int theValue)>("--sign", "Sign binaries and nuget package", CommandOptionType.SingleOrNoValue); CleanArtifacts(); app.OnExecute(() => { Target(Build, () => { Run("dotnet", $"build -c Release", echoPrefix: Prefix); if (sign.HasValue()) { Sign("*.dll", "./src/bin/release"); } }); Target(Test, DependsOn(Build), () => { Run("dotnet", $"test -c Release --no-build", echoPrefix: Prefix); }); Target(Pack, DependsOn(Build), () => { var project = Directory.GetFiles("./src", "*.csproj", SearchOption.TopDirectoryOnly).First(); Run("dotnet", $"pack {project} -c Release -o ./{ArtifactsDir} --no-build", echoPrefix: Prefix); if (sign.HasValue()) { Sign("*.nupkg", $"./{ArtifactsDir}"); } CopyArtifacts(); }); Target("default", DependsOn(Test, Pack)); RunTargetsAndExit(app.RemainingArguments, logPrefix: Prefix); }); app.Execute(args); } private static void Sign(string extension, string directory) { var signClientConfig = Environment.GetEnvironmentVariable("SignClientConfig"); var signClientSecret = Environment.GetEnvironmentVariable("SignClientSecret"); if (string.IsNullOrWhiteSpace(signClientConfig)) { throw new Exception("SignClientConfig environment variable is missing. Aborting."); } if (string.IsNullOrWhiteSpace(signClientSecret)) { throw new Exception("SignClientSecret environment variable is missing. Aborting."); } var files = Directory.GetFiles(directory, extension, SearchOption.AllDirectories); if (files.Count() == 0) { throw new Exception($"File to sign not found: {extension}"); } foreach (var file in files) { Console.WriteLine(" Signing " + file); Run("dotnet", $"SignClient sign -c {signClientConfig} -i {file} -r sc-ids@dotnetfoundation.org -s \"{signClientSecret}\" -n 'IdentityServer4'", noEcho: true); } } private static void CopyArtifacts() { var files = Directory.GetFiles($"./{ArtifactsDir}"); foreach (string s in files) { var fileName = Path.GetFileName(s); var destFile = Path.Combine("../../nuget", fileName); File.Copy(s, destFile, true); } } private static void CleanArtifacts() { Directory.CreateDirectory($"./{ArtifactsDir}"); foreach (var file in Directory.GetFiles($"./{ArtifactsDir}")) { File.Delete(file); } } } }
33.598291
174
0.509285
[ "Apache-2.0" ]
cboyce428/IdentityServer4
src/AspNetIdentity/build/Program.cs
3,933
C#
using Game.Controllers; using Game.Signals.Base; namespace Game.Signals { public enum EUnitSignalType { Moved, Dragged, StartDragged } public class UnitSignal : SignalBase<UnitSignalData, UnitController> { public UnitSignal(UnitSignalData value, UnitController owner) : base(value, owner) { } } public readonly struct UnitSignalData { public readonly EUnitSignalType type; public readonly UnitController unitRef; public UnitSignalData(EUnitSignalType type, UnitController unitRef) { this.type = type; this.unitRef = unitRef; } } }
21.34375
90
0.626647
[ "MIT" ]
redmoon-games/SimpleMergeSource
Assets/Scripts/Game/Signals/UnitSignal.cs
683
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace WebPoll { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Poll", action = "Welcome", id = UrlParameter.Optional } ); } } }
25.043478
101
0.586806
[ "MIT" ]
redarrowlabs/pubnub-c-sharp
demos/ePoll/WebPoll/App_Start/RouteConfig.cs
578
C#
using System; using System.Linq; using BattleSystem.Core.Moves; using BattleSystem.Core.Random; using Moq; using NUnit.Framework; namespace BattleSystem.Core.Tests.Moves { /// <summary> /// Unit tests for <see cref="MoveSet"/>. /// </summary> [TestFixture] public class MoveSetTests { [Test] public void AddMove_AddsMove() { // Arrange var moveSet = TestHelpers.CreateMoveSet(); // Act moveSet.AddMove(TestHelpers.CreateMove()); // Assert Assert.That(moveSet.Moves.Count, Is.EqualTo(1)); } [Test] public void AddMove_NullMove_Throws() { // Arrange var moveSet = TestHelpers.CreateMoveSet(); // Act and Assert Assert.Throws<ArgumentNullException>(() => moveSet.AddMove(null)); } [Test] public void ChooseRandom_DoesNotReturnNull() { // Arrange var moveSet = TestHelpers.CreateMoveSet( TestHelpers.CreateMove(), TestHelpers.CreateMove() ); // Act var move = moveSet.ChooseRandom(new Mock<IRandom>().Object); // Assert Assert.That(move, Is.Not.Null); } [Test] public void Summarise_ContainsCorrectSummaries() { // Arrange var moveSet = TestHelpers.CreateMoveSet( TestHelpers.CreateMove(name: "move1"), TestHelpers.CreateMove(name: "move3") ); // Act var choices = moveSet.Summarise(); // Assert Assert.Multiple(() => { Assert.That(choices, Contains.Substring("move1")); Assert.That(choices, Contains.Substring("move3")); }); } [Test] public void Summarise_WithIndexes_ContainsCorrectSummaries() { // Arrange var moveSet = TestHelpers.CreateMoveSet( TestHelpers.CreateMove(name: "move1"), TestHelpers.CreateMove(name: "move3") ); // Act var choices = moveSet.Summarise(true); // Assert Assert.Multiple(() => { Assert.That(choices, Contains.Substring("1: move1")); Assert.That(choices, Contains.Substring("2: move3")); }); } [Test] public void GetIndexes_ReturnsCorrectIndexes() { // Arrange var moveSet = TestHelpers.CreateMoveSet( TestHelpers.CreateMove(name: "move1"), TestHelpers.CreateMove(name: "move2"), TestHelpers.CreateMove(name: "move4") ); // Act var indexes = moveSet.GetIndexes().ToList(); // Assert Assert.Multiple(() => { Assert.That(indexes.Count, Is.EqualTo(3)); Assert.That(indexes, Contains.Item(1)); Assert.That(indexes, Contains.Item(2)); Assert.That(indexes, Contains.Item(3)); }); } [TestCase(0, "move1")] [TestCase(1, "move2")] [TestCase(2, "move3")] [TestCase(3, "move4")] public void GetMove_ValidIndex_ReturnsCorrectMove(int index, string expectedName) { // Arrange var moveSet = TestHelpers.CreateMoveSet( TestHelpers.CreateMove(name: "move1"), TestHelpers.CreateMove(name: "move2"), TestHelpers.CreateMove(name: "move3"), TestHelpers.CreateMove(name: "move4") ); // Act var move = moveSet.GetMove(index); // Assert Assert.That(move.Name, Is.EqualTo(expectedName)); } [TestCase(-1)] [TestCase(5)] public void GetMove_InvalidIndex_Throws(int index) { // Arrange var moveSet = TestHelpers.CreateMoveSet( TestHelpers.CreateMove() ); // Act and Assert Assert.Throws<ArgumentException>(() => _ = moveSet.GetMove(index)); } } }
28.163399
89
0.507774
[ "MIT" ]
phrasmotica/BattleSystem
BattleSystem.Core.Tests/Moves/MoveSetTests.cs
4,311
C#
using System; using Shiny; using Shiny.BluetoothLE; using Shiny.Logging; using Shiny.Locations; using Shiny.Notifications; using Shiny.Sensors; using Shiny.SpeechRecognition; using Shiny.Net.Http; using Microsoft.Extensions.DependencyInjection; using Samples.Settings; using Samples.Loggers; namespace Samples.ShinySetup { public class SampleStartup : Startup { public override void ConfigureServices(IServiceCollection builder) { Log.UseConsole(); Log.UseDebug(); Log.AddLogger(new AppCenterLogger(), true, false); Log.AddLogger(new DbLogger(), true, false); // create your infrastructures // jobs, connectivity, power, filesystem, are installed automatically builder.AddSingleton<SampleSqliteConnection>(); // startup tasks builder.RegisterStartupTask<StartupTask1>(); builder.RegisterStartupTask<StartupTask2>(); // configuration builder.RegisterSettings<AppSettings>(); // register all of the acr stuff you want to use builder.UseHttpTransfers<SampleAllDelegate>(); //builder.UseBeacons<SampleAllDelegate>(); builder.UseBleCentral<SampleAllDelegate>(); builder.UseBlePeripherals(); builder.UseGeofencing<SampleAllDelegate>(); builder.UseGpsBackground<SampleAllDelegate>(); builder.UseNotifications(); builder.UseSpeechRecognition(); builder.UseAccelerometer(); builder.UseAmbientLightSensor(); builder.UseBarometer(); builder.UseCompass(); builder.UseDeviceOrientationSensor(); builder.UseMagnetometer(); builder.UsePedometer(); builder.UseProximitySensor(); } } }
32.631579
81
0.643548
[ "MIT" ]
DanielCauser/shiny
Samples/Samples/ShinySetup/SampleStartup.cs
1,862
C#
using Guu.Utils; using VikDisk.Core; namespace VikDisk.Game { internal class Chapter1 : Injector { internal override void SetupMod() { //+------------------------------- //+ GENERATE LARGO IDs //+------------------------------- //SlimeUtils.GenerateLargoIDs(Enums.Identifiables.REAL_GLITCH_SLIME); SlimeUtils.GenerateLargoIDs(Enums.Identifiables.ALBINO_SLIME); } internal override void PopulateMod() { //+------------------------------- //+ INJECT DIETS //+------------------------------- // Spicy Diets SlimeDietHandler.AddSpicyDiet(Identifiable.Id.CRYSTAL_SLIME, Identifiable.Id.STRANGE_DIAMOND_CRAFT); SlimeDietHandler.AddSpicyDiet(Identifiable.Id.ROCK_SLIME, Identifiable.Id.SLIME_FOSSIL_CRAFT); SlimeDietHandler.AddSpicyDiet(Identifiable.Id.HONEY_SLIME, Identifiable.Id.HEXACOMB_CRAFT); // Favorites SlimeDietHandler.AddFavoriteExtra(Identifiable.Id.PINK_SLIME, false, Identifiable.Id.CARROT_VEGGIE, Identifiable.Id.HEN, Identifiable.Id.POGO_FRUIT); SlimeDietHandler.AddFavoriteExtra(Identifiable.Id.SABER_SLIME, false, Identifiable.Id.ELDER_HEN, Identifiable.Id.ELDER_ROOSTER); // Super Foods //. SPECIFIC LARGOS // Synergies SlimeDietHandler.AddSpecificLargo(Identifiable.Id.QUANTUM_SLIME, Enums.Identifiables.REAL_GLITCH_SLIME, Enums.Identifiables.ELECTRIC_LARGO_SYNERGY); //+------------------------------- //+ INJECT SPAWNS //+------------------------------- // Mutations SlimeSpawnHandler.AddMutationToSpawn(Identifiable.Id.PINK_SLIME, Enums.Identifiables.ALBINO_SLIME, ZoneDirector.Zone.REEF); } } }
43.34
116
0.504384
[ "MIT" ]
RicardoTheCoder/ViktorsDiskoveries
Project/VikDisk/Game/Chapters/Chapter1.cs
2,169
C#
using System; namespace Day_of_the_Programmer { class Program { static string dayOfProgrammer(int year) { DateTime date = new DateTime(year, 8, 31); do { date = date.AddDays(1); } while (date.DayOfYear != 256); if (year < 1918 && year % 4 == 0 && !DateTime.IsLeapYear(date.Year)) { date = date.AddDays(-1); } else if (year == 1918) { date = date.AddDays(13); } return date.ToString("dd.MM.yyyy"); } static void Main(string[] args) { int year = Convert.ToInt32(Console.ReadLine().Trim()); string result = dayOfProgrammer(year); Console.WriteLine(result); } } }
21.35
80
0.454333
[ "MIT" ]
ggriffo/HackerRank
Day of the Programmer/Program.cs
856
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using TMSA.SistemaEducacional.Domain.Pessoas; using TMSA.SistemaEducacional.Infra.Data.Extensions; namespace TMSA.SistemaEducacional.Infra.Data.Mappings { public class PessoaJuridicaMapping : EntityTypeConfiguration<PessoaJuridica> { public override void Map(EntityTypeBuilder<PessoaJuridica> builder) { builder.Ignore(p => p.CascadeMode); builder.Ignore(p => p.ValidationResult); builder.Property(p => p.CNPJ) .IsRequired() .HasMaxLength(14) .HasColumnType("varchar(13)"); builder.Property(p => p.InscricaoEstadutal) .IsRequired(); builder.Property(p => p.NomeFantasia) .IsRequired(); builder.Property(p => p.RazaoSocial) .IsRequired(); builder.HasOne(p => p.Pessoa) .WithOne(pj => pj.PessoaJuridica) .HasForeignKey<PessoaJuridica>(pj => pj.PessoaId); builder.ToTable("PessoasJuridicas"); } } }
30.447368
80
0.609334
[ "MIT" ]
ThiagoMSArrais/Sistema-Educacional
SistemaEducacional/src/TMSA.SistemaEducacional.Infra.Data/Mappings/PessoaJuridicaMapping.cs
1,159
C#
using FluentValidation; using System; using System.Text.RegularExpressions; namespace LyncNinja.Domain.Extensions { public static class RuleBuilderExtensions { #region Fields private const string URL_REGEX = @"^[a-zA-Z0-9].*(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:\/?#[\]@!\$&'\(\)\*\+,;=.]+[\/]?$"; private const string HTTP_SCHEME = "http://"; private const string HTTPS_SCHEME = "https://"; #endregion public static IRuleBuilder<T, string> IsUrl<T>(this IRuleBuilder<T, string> ruleBuilder) => ruleBuilder .NotEmpty() .WithMessage("Please enter a URL") .Must(BeAValidUrl) .WithMessage("The URL provided is invalid. Please provide a valid URL."); #region Private Methods /// <summary> /// Validates a URL is of a valid format /// </summary> /// <param name="url"></param> /// <returns></returns> private static bool BeAValidUrl(string url) { if (!Regex.IsMatch(url, URL_REGEX, RegexOptions.IgnoreCase)) return false; if (!url.StartsWith(HTTP_SCHEME, StringComparison.OrdinalIgnoreCase) || !url.StartsWith(HTTPS_SCHEME, StringComparison.OrdinalIgnoreCase)) url = HTTP_SCHEME + url; if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri)) return (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps); return false; } #endregion } }
35.622222
150
0.559576
[ "MIT" ]
lukecusolito/LyncNinja
LyncNinja.Domain/Extensions/RuleBuilderExtensions.cs
1,605
C#
namespace Team.Blogging.Settings { public static class BloggingSettings { private const string Prefix = "Blogging"; //Add your own setting names here. Example: //public const string MySetting1 = Prefix + ".MySetting1"; } }
26
66
0.653846
[ "MIT" ]
lwqwag/Team.Bloging
src/Team.Bloging.Domain/Settings/BloggingSettings.cs
262
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Rulesets.Objects.Types { /// <summary> /// A HitObject that has a starting X-position. /// </summary> public interface IHasXPosition { /// <summary> /// The starting X-position of this HitObject. /// </summary> float X { get; } } }
27.941176
93
0.595789
[ "MIT" ]
AtomCrafty/osu
osu.Game/Rulesets/Objects/Types/IHasXPosition.cs
461
C#
namespace DotNetBungieAPI.Models.Forum; [Flags] [JsonConverter(typeof(JsonStringEnumConverter))] public enum ForumTopicsCategoryFiltersEnum { None = 0, Links = 1, Questions = 2, AnsweredQuestions = 4, Media = 8, TextOnly = 16, Announcement = 32, BungieOfficial = 64, Polls = 128 }
19.875
48
0.676101
[ "MIT" ]
EndGameGl/.NetBungieAPI
DotNetBungieAPI/Models/Forum/ForumTopicsCategoryFiltersEnum.cs
320
C#
#pragma checksum "..\..\..\..\Views\SearchResultView.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "54247AB02E48135C7F3C82B4EC7BDD56D132D0EE" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Caliburn.Micro; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Controls.Ribbon; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; using WpfUiCore.Views; namespace WpfUiCore.Views { /// <summary> /// SearchResultView /// </summary> public partial class SearchResultView : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector { #line 64 "..\..\..\..\Views\SearchResultView.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox SearchString; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "5.0.3.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/WpfUiCore;V1.0.0.0;component/views/searchresultview.xaml", System.UriKind.Relative); #line 1 "..\..\..\..\Views\SearchResultView.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "5.0.3.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.SearchString = ((System.Windows.Controls.TextBox)(target)); return; } this._contentLoaded = true; } } }
39.097826
143
0.658882
[ "Apache-2.0" ]
dashwort/MarketWatch
WpfUiCore/obj/Debug/netcoreapp3.0/Views/SearchResultView.g.i.cs
3,599
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.Data.Sqlite; using FDK; namespace DTXMania2.old.RecordDBRecord { class v006_RecordDBRecord { public const int VERSION = 6; /// <summary> /// ユーザを一意に識別するID。 /// </summary> public string UserId { get; set; } /// <summary> /// 曲譜面ファイルのハッシュ値。 /// </summary> public string SongHashId { get; set; } /// <summary> /// スコア。 /// </summary> public int Score { get; set; } /// <summary> /// カウントマップラインのデータ。 /// 1ブロックを1文字('0':0~'C':12)で表し、<see cref="DTXMania.ステージ.演奏.カウントマップライン.カウントマップの最大要素数"/> 個の文字が並ぶ。 /// もし不足分があれば、'0' とみなされる。 /// </summary> public string CountMap { get; set; } /// <summary> /// 曲別SKILL。 /// </summary> public double Skill { get; set; } /// <summary> /// 達成率。 /// </summary> public double Achievement { get; set; } // 生成と終了 public v006_RecordDBRecord() { this.UserId = "Anonymous"; this.SongHashId = ""; this.Score = 0; this.CountMap = ""; this.Skill = 0.0; this.Achievement = 0.0; } public v006_RecordDBRecord( SqliteDataReader reader ) : this() { this.UpdateFrom( reader ); } /// <summary> /// SqliteDataReader からレコードを読み込んでフィールドを更新する。 /// </summary> /// <param name="record">Read() 済みの SqliteDataReader。</param> public void UpdateFrom( SqliteDataReader record ) { for( int i = 0; i < record.FieldCount; i++ ) { switch( record.GetName( i ) ) { case "UserId": this.UserId = record.GetString( i ); break; case "SongHashId": this.SongHashId = record.GetString( i ); break; case "Score": this.Score = record.GetInt32( i ); break; case "CountMap": this.CountMap = record.GetString( i ); break; case "Skill": this.Skill = record.GetDouble( i ); break; case "Achievement": this.Achievement = record.GetDouble( i ); break; } } } /// <summary> /// DBにレコードを挿入または更新する。 /// </summary> public void InsertTo( SQLiteDB db ) { using var cmd = new SqliteCommand( "REPLACE INTO Records VALUES(" + $"'{this.UserId}'," + $"'{this.SongHashId}'" + $"{this.Score}," + $"'{this.CountMap}'," + $"{this.Skill}," + $"{this.Achievement}" + ")", db.Connection ); cmd.ExecuteNonQuery(); } } }
28.5
104
0.475709
[ "MIT" ]
DTXMania/DTXMania2
DTXMania2/保存データ/RecordDB/old/v006_RecordDBRecord.cs
3,306
C#
using System; using System.Collections.Generic; using System.Text; using System.Runtime.Serialization; namespace Nohros.Toolkit.DnsLookup { public class NoResponseException : SystemException { public NoResponseException() { } public NoResponseException(Exception inner_exception) : base(null, inner_exception) { } public NoResponseException(string message, Exception inner_exception) : base (message, inner_exception) { } protected NoResponseException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
36.25
110
0.748276
[ "MIT" ]
nohros/must
src/platform/toolkit/dnslookup/noresponseexception.cs
580
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.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ReferenceManagerTests : CSharpTestBase { private static readonly CSharpCompilationOptions s_signedDll = TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2); [Fact] public void WinRtCompilationReferences() { var ifaceDef = CreateStandardCompilation( @" public interface ITest { }", options: TestOptions.DebugWinMD, assemblyName: "ITest"); ifaceDef.VerifyDiagnostics(); var ifaceImageRef = ifaceDef.EmitToImageReference(); var wimpl = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WImpl).GetReference(display: "WImpl"); var implDef2 = CreateStandardCompilation( @" public class C { public static void Main() { ITest test = new WImpl(); } }", references: new MetadataReference[] { ifaceDef.ToMetadataReference(), wimpl }, options: TestOptions.DebugExe); implDef2.VerifyDiagnostics(); } [Fact] public void VersionUnification_SymbolUsed() { // Identity: C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9 var v1 = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(display: "C, V1"); // Identity: C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9 var v2 = AssemblyMetadata.CreateFromImage(TestResources.General.C2).GetReference(display: "C, V2"); var refV1 = CreateStandardCompilation("public class D : C { }", new[] { v1 }, assemblyName: "refV1"); var refV2 = CreateStandardCompilation("public class D : C { }", new[] { v2 }, assemblyName: "refV2"); // reference asks for a lower version than available: var testRefV1 = CreateStandardCompilation("public class E : D { }", new MetadataReference[] { new CSharpCompilationReference(refV1), v2 }, assemblyName: "testRefV1"); // reference asks for a higher version than available: var testRefV2 = CreateStandardCompilation("public class E : D { }", new MetadataReference[] { new CSharpCompilationReference(refV2), v1 }, assemblyName: "testRefV2"); // TODO (tomat): we should display paths rather than names "refV1" and "C" testRefV1.VerifyDiagnostics( // warning CS1701: // Assuming assembly reference 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' // used by 'refV1' matches identity 'C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' of 'C', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "D").WithArguments( "C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "refV1", "C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "C")); // TODO (tomat): we should display paths rather than names "refV2" and "C" testRefV2.VerifyDiagnostics( // error CS1705: Assembly 'refV2' with identity 'refV2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // uses 'C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' which has a higher version than referenced assembly // 'C' with identity 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion, "D").WithArguments( "refV2", "refV2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "C", "C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9")); } [Fact] [WorkItem(546080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546080")] public void VersionUnification_SymbolNotUsed() { var v1 = MetadataReference.CreateFromImage(TestResources.General.C1); var v2 = MetadataReference.CreateFromImage(TestResources.General.C2); var refV1 = CreateStandardCompilation("public class D : C { }", new[] { v1 }); var refV2 = CreateStandardCompilation("public class D : C { }", new[] { v2 }); // reference asks for a lower version than available: var testRefV1 = CreateStandardCompilation("public class E { }", new MetadataReference[] { new CSharpCompilationReference(refV1), v2 }); // reference asks for a higher version than available: var testRefV2 = CreateStandardCompilation("public class E { }", new MetadataReference[] { new CSharpCompilationReference(refV2), v1 }); testRefV1.VerifyDiagnostics(); testRefV2.VerifyDiagnostics(); } [Fact] public void VersionUnification_MultipleVersions() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {} "; var libV1 = CreateStandardCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {} "; var libV2 = CreateStandardCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceLibV3 = @" [assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public class C {} "; var libV3 = CreateStandardCompilation( sourceLibV3, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV2 = @" using System.Collections.Generic; [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class R { public C Field; } "; var refLibV2 = CreateStandardCompilation( sourceRefLibV2, assemblyName: "RefLibV2", references: new[] { new CSharpCompilationReference(libV2) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { var x = new R(); System.Console.WriteLine(x.Field); } } "; // higher version should be preferred over lower version regardless of the order of the references var main13 = CreateStandardCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(libV1), new CSharpCompilationReference(libV3), new CSharpCompilationReference(refLibV2) }); // TODO (tomat): we should display paths rather than names "RefLibV2" and "Lib" main13.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV2' matches identity 'Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV2", "Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib")); var main31 = CreateStandardCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(libV3), new CSharpCompilationReference(libV1), new CSharpCompilationReference(refLibV2) }); // TODO (tomat): we should display paths rather than names "RefLibV2" and "Lib" main31.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV2' matches identity 'Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV2", "Lib, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib")); } [Fact] [WorkItem(529808, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529808"), WorkItem(530246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530246")] public void VersionUnification_UseSiteWarnings() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {} public delegate void D(); public interface I {} "; var libV1 = CreateStandardCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {} public delegate void D(); public interface I {} "; var libV2 = CreateStandardCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV1 = @" using System.Collections.Generic; [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class R { public R(C c) {} public C Field; public C Property { get; set; } public int this[C arg] { get { return 0; } set {} } public event D Event; public List<C> Method1() { return null; } public void Method2(List<List<C>> c) { } public void GenericMethod<T>() where T : I { } } public class S1 : List<C> { public class Inner {} } public class S2 : I {} public class GenericClass<T> where T : I { public class S {} } "; var refLibV1 = CreateStandardCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new[] { new CSharpCompilationReference(libV1) }, options: s_signedDll); string sourceX = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class P : Q {} public class Q : S2 {} "; var x = CreateStandardCompilation( sourceX, assemblyName: "X", references: new[] { new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV1) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { var c = new C(); // ok var r = new R(null); // error: C in parameter var f = r.Field; // error: C in type var a = r.Property; // error: C in return type var b = r[c]; // error: C in parameter r.Event += () => {}; // error: C in type var m = r.Method1(); // error: ~> C in return type r.Method2(null); // error: ~> C in parameter r.GenericMethod<OKImpl>(); // error: ~> I in constraint var g = new GenericClass<OKImpl>.S(); // error: ~> I in constraint -- should report only once, for GenericClass<OKImpl>, not again for S. var s1 = new S1(); // error: ~> C in base var s2 = new S2(); // error: ~> I in implements var s3 = new S1.Inner(); // error: ~> C in base -- should only report once, for S1, not again for Inner. var e = new P(); // error: P -> Q -> S2 ~> I in implements } } public class Z : S2 // error: S2 ~> I in implements { } public class OKImpl : I { } "; var main = CreateStandardCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2), new CSharpCompilationReference(x) }); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" main.VerifyDiagnostics( // (23,18): warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy // public class Z : S2 // error: S2 ~> I in implements Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "S2").WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // (7,21): warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy // var r = new R(null); // error: C in parameter Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "R").WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // (10,17): warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy // var b = r[c]; // error: C in parameter Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "r[c]").WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // (12,17): warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy // var m = r.Method1(); // error: ~> C in return type Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "r.Method1").WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // (13,9): warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy // r.Method2(null); // error: ~> C in parameter Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "r.Method2").WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // (14,9): warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy // r.GenericMethod<OKImpl>(); // error: ~> I in constraint Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "r.GenericMethod<OKImpl>").WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'X' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "X", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib")); CompileAndVerify(main, validator: (assembly) => { var reader = assembly.GetMetadataReader(); // Dev11 adds "Lib 1.0" to the references, we don't (see DevDiv #15580) AssertEx.SetEqual(new[] { $"{RuntimeCorLibName.Name} {RuntimeCorLibName.Version.ToString(2)}", "RefLibV1 1.0", "Lib 2.0", "X 2.0" }, reader.DumpAssemblyReferences()); }, // PE verification fails on some platforms. Would need .config file with Lib v1 -> Lib v2 binding redirect verify: Verification.Skipped); } [Fact] [WorkItem(546080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546080")] public void VersionUnification_UseSiteDiagnostics_Multiple() { string sourceA1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A {} "; var a1 = CreateStandardCompilation( sourceA1, assemblyName: "A", options: s_signedDll); string sourceA2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class A {} "; var a2 = CreateStandardCompilation( sourceA2, assemblyName: "A", options: s_signedDll); string sourceB1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class B {} "; var b1 = CreateStandardCompilation( sourceB1, assemblyName: "B", options: s_signedDll); string sourceB2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class B {} "; var b2 = CreateStandardCompilation( sourceB2, assemblyName: "B", options: s_signedDll); string sourceRefA1B2 = @" using System.Collections.Generic; [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class R { public Dictionary<A, B> Dict = new Dictionary<A, B>(); public void Goo(A a, B b) {} } "; var refA1B2 = CreateStandardCompilation( sourceRefA1B2, assemblyName: "RefA1B2", references: new[] { new CSharpCompilationReference(a1), new CSharpCompilationReference(b2) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { var r = new R(); System.Console.WriteLine(r.Dict); // warning & error r.Goo(null, null); // warning & error } } "; var main = CreateStandardCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(refA1B2), new CSharpCompilationReference(a2), new CSharpCompilationReference(b1) }); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" // TODO (tomat): this should include 2 warnings: main.VerifyDiagnostics( // error CS1705: Assembly 'RefA1B2' with identity 'RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly 'B' // with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion).WithArguments( "RefA1B2", "RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"), // (8,9): error CS1705: Assembly 'RefA1B2' with identity 'RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly 'B' // with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion, "r.Goo").WithArguments( "RefA1B2", "RefA1B2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2")); } [Fact] public void VersionUnification_UseSiteDiagnostics_OptionalAttributes() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyVersionAttribute : Attribute { public AssemblyVersionAttribute(string version) {} public string Version { get; set; } } } public class CGAttribute : System.Attribute { } "; var libV1 = CreateCompilation( sourceLibV1, assemblyName: "Lib", references: new[] { MinCorlibRef }, options: s_signedDll); libV1.VerifyDiagnostics(); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyVersionAttribute : Attribute { public AssemblyVersionAttribute(string version) {} public string Version { get; set; } } } public class CGAttribute : System.Attribute { } "; var libV2 = CreateCompilation( sourceLibV2, assemblyName: "Lib", references: new[] { MinCorlibRef }, options: s_signedDll); libV2.VerifyDiagnostics(); string sourceRefLibV1 = @" namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All, Inherited = true)] public sealed class CompilerGeneratedAttribute : CGAttribute { } } "; var refLibV1 = CreateCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new MetadataReference[] { MinCorlibRef, new CSharpCompilationReference(libV1) }, options: s_signedDll); refLibV1.VerifyDiagnostics(); string sourceMain = @" public class C { public int P { get; set; } // error: backing field is marked by CompilerGeneratedAttribute, whose base type is in the unified assembly } "; var main = CreateCompilation( sourceMain, assemblyName: "Main", references: new MetadataReference[] { MinCorlibRef, new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2) }); // Dev11 reports warning since the base type of CompilerGeneratedAttribute is in unified assembly. // Roslyn doesn't report any use-site diagnostics for optional attributes, it just ignores them main.VerifyDiagnostics(); } [Fact] public void VersionUnification_SymbolEquality() { string sourceLibV1 = @" using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] public interface I {} "; var libV1 = CreateStandardCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" using System.Reflection; [assembly: AssemblyVersion(""2.0.0.0"")] public interface I {} "; var libV2 = CreateStandardCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV1 = @" using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] public class C : I { } "; var refLibV1 = CreateStandardCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new[] { new CSharpCompilationReference(libV1) }, options: s_signedDll); string sourceMain = @" public class M { public void F() { I x = new C(); } } "; var main = CreateStandardCompilation( sourceMain, assemblyName: "Main", references: new[] { new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2) }); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" main.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' // used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments( "Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib")); } [Fact] [WorkItem(546752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546752")] public void VersionUnification_NoPiaMissingCanonicalTypeSymbol() { string sourceLibV1 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A {} "; var libV1 = CreateStandardCompilation( sourceLibV1, assemblyName: "Lib", options: s_signedDll); string sourceLibV2 = @" [assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class A {} "; var libV2 = CreateStandardCompilation( sourceLibV2, assemblyName: "Lib", options: s_signedDll); string sourceRefLibV1 = @" using System.Runtime.InteropServices; public class B : A { public void M(IB i) { } } [ComImport] [Guid(""F79F0037-0874-4EE3-BC45-158EDBA3ABA3"")] [TypeIdentifier] public interface IB { } "; var refLibV1 = CreateStandardCompilation( sourceRefLibV1, assemblyName: "RefLibV1", references: new[] { new CSharpCompilationReference(libV1) }, options: TestOptions.ReleaseDll); string sourceMain = @" public class Test { static void Main() { B b = new B(); b.M(null); } } "; // NOTE: We won't get a nopia type unless we use a PE reference (i.e. source won't work). var main = CreateStandardCompilation( sourceMain, assemblyName: "Main", references: new MetadataReference[] { MetadataReference.CreateFromImage(refLibV1.EmitToArray()), new CSharpCompilationReference(libV2) }, options: TestOptions.ReleaseExe); // TODO (tomat): we should display paths rather than names "RefLibV1" and "Lib" main.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // warning CS1701: Assuming assembly reference 'Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'RefLibV1' matches identity 'Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'Lib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("Lib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "RefLibV1", "Lib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "Lib"), // (7,9): error CS1748: Cannot find the interop type that matches the embedded interop type 'IB'. Are you missing an assembly reference? // b.M(null); Diagnostic(ErrorCode.ERR_NoCanonicalView, "b.M").WithArguments("IB")); } [WorkItem(546525, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546525")] [Fact] public void AssemblyReferencesWithAliases() { var source = @"extern alias SysCore; using System.Linq; namespace Microsoft.TeamFoundation.WebAccess.Common { public class CachedRegistry { public static void Main(string[] args) { System.Console.Write('k'); } } }"; var tree = Parse(source); var r1 = AssemblyMetadata.CreateFromImage(TestResources.NetFX.v4_0_30319.System_Core).GetReference(filePath: @"c:\temp\aa.dll", display: "System.Core.v4_0_30319.dll"); var r2 = AssemblyMetadata.CreateFromImage(TestResources.NetFX.v4_0_30319.System_Core).GetReference(filePath: @"c:\temp\aa.dll", display: "System.Core.v4_0_30319.dll"); var r2_SysCore = r2.WithAliases(new[] { "SysCore" }); var compilation = CreateCompilation(new List<SyntaxTree> { tree }, new[] { MscorlibRef, r1, r2_SysCore }, new CSharpCompilationOptions(OutputKind.ConsoleApplication), "Test"); CompileAndVerify(compilation, expectedOutput: "k"); } [WorkItem(545062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545062")] [Fact] public void DuplicateReferences() { CSharpCompilation c; string source; var r1 = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(filePath: @"c:\temp\a.dll", display: "R1"); var r2 = AssemblyMetadata.CreateFromImage(TestResources.General.C1).GetReference(filePath: @"c:\temp\a.dll", display: "R2"); var rGoo = r2.WithAliases(new[] { "goo" }); var rBar = r2.WithAliases(new[] { "bar" }); var rEmbed = r1.WithEmbedInteropTypes(true); source = @" class D { } "; c = CreateStandardCompilation(source, new[] { r1, r2 }); Assert.Null(c.GetReferencedAssemblySymbol(r1)); Assert.NotNull(c.GetReferencedAssemblySymbol(r2)); c.VerifyDiagnostics(); source = @" class D : C { } "; c = CreateStandardCompilation(source, new[] { r1, r2 }); Assert.Null(c.GetReferencedAssemblySymbol(r1)); Assert.NotNull(c.GetReferencedAssemblySymbol(r2)); c.VerifyDiagnostics(); c = CreateStandardCompilation(source, new[] { rGoo, r2 }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(r2)); AssertEx.SetEqual(new[] { "goo", "global" }, c.ExternAliases); c.VerifyDiagnostics(); // 2 aliases for the same path, aliases not used to qualify name c = CreateStandardCompilation(source, new[] { rGoo, rBar }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(rBar)); AssertEx.SetEqual(new[] { "goo", "bar" }, c.ExternAliases); c.VerifyDiagnostics( // (2,11): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C")); source = @" class D : C { } "; // /l and /r with the same path c = CreateStandardCompilation(source, new[] { rGoo, rEmbed }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(rEmbed)); c.VerifyDiagnostics( // error CS1760: Assemblies 'R1' and 'R2' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references. Diagnostic(ErrorCode.ERR_AssemblySpecifiedForLinkAndRef).WithArguments("R1", "R2"), // error CS1747: Cannot embed interop types from assembly 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttribute).WithArguments("C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "System.Runtime.InteropServices.GuidAttribute"), // error CS1759: Cannot embed interop types from assembly 'C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttributes).WithArguments("C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "System.Runtime.InteropServices.ImportedFromTypeLibAttribute", "System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute"), // (2,11): error CS1752: Interop type 'C' cannot be embedded. Use the applicable interface instead. // class D : C { } Diagnostic(ErrorCode.ERR_NewCoClassOnLink, "C").WithArguments("C")); source = @" extern alias goo; extern alias bar; public class D : goo::C { } public class E : bar::C { } "; // 2 aliases for the same path, aliases used c = CreateStandardCompilation(source, new[] { rGoo, rBar }); Assert.Null(c.GetReferencedAssemblySymbol(rGoo)); Assert.NotNull(c.GetReferencedAssemblySymbol(rBar)); c.VerifyDiagnostics(); } // "<path>\x\y.dll" -> "<path>\x\..\x\y.dll" private static string MakeEquivalentPath(string path) { string[] parts = path.Split(Path.DirectorySeparatorChar); Debug.Assert(parts.Length >= 3); int dir = parts.Length - 2; List<string> newParts = new List<string>(parts); newParts.Insert(dir, ".."); newParts.Insert(dir, parts[dir]); return newParts.Join(Path.DirectorySeparatorChar.ToString()); } [Fact] public void DuplicateAssemblyReferences_EquivalentPath() { string p1 = Temp.CreateFile().WriteAllBytes(TestResources.General.MDTestLib1).Path; string p2 = MakeEquivalentPath(p1); string p3 = MakeEquivalentPath(p2); var r1 = MetadataReference.CreateFromFile(p1); var r2 = MetadataReference.CreateFromFile(p2); var r3 = MetadataReference.CreateFromFile(p3); SyntaxTree t1, t2, t3; var compilation = CSharpCompilation.Create("goo", syntaxTrees: new[] { t1 = Parse($"#r \"{p2}\"", options: TestOptions.Script), t2 = Parse($"#r \"{p3}\"", options: TestOptions.Script), t3 = Parse("#r \"Lib\"", options: TestOptions.Script), }, references: new MetadataReference[] { MscorlibRef_v4_0_30316_17626, r1, r2 }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver( assemblyNames: new Dictionary<string, PortableExecutableReference> { { "Lib", r3 } }, files: new Dictionary<string, PortableExecutableReference> { { p2, r2 }, { p3, r3 } })) ); // no diagnostics expected, all duplicate references should be ignored as they all refer to the same file: compilation.VerifyDiagnostics(); var refs = compilation.ExternalReferences; Assert.Equal(3, refs.Length); Assert.Equal(MscorlibRef_v4_0_30316_17626, refs[0]); Assert.Equal(r1, refs[1]); Assert.Equal(r2, refs[2]); // All #r's resolved are represented in directive references. var dirRefs = compilation.DirectiveReferences; Assert.Equal(1, dirRefs.Length); var as1 = compilation.GetReferencedAssemblySymbol(r2); Assert.Equal("MDTestLib1", as1.Identity.Name); // r1 is a dup of r2: Assert.Null(compilation.GetReferencedAssemblySymbol(r1)); var rd1 = t1.GetCompilationUnitRoot().GetReferenceDirectives().Single(); var rd2 = t2.GetCompilationUnitRoot().GetReferenceDirectives().Single(); var rd3 = t3.GetCompilationUnitRoot().GetReferenceDirectives().Single(); var dr1 = compilation.GetDirectiveReference(rd1) as PortableExecutableReference; var dr2 = compilation.GetDirectiveReference(rd2) as PortableExecutableReference; var dr3 = compilation.GetDirectiveReference(rd3) as PortableExecutableReference; Assert.Equal(MetadataImageKind.Assembly, dr1.Properties.Kind); Assert.Equal(MetadataImageKind.Assembly, dr2.Properties.Kind); Assert.Equal(MetadataImageKind.Assembly, dr3.Properties.Kind); Assert.True(dr1.Properties.Aliases.IsEmpty); Assert.True(dr2.Properties.Aliases.IsEmpty); Assert.True(dr3.Properties.Aliases.IsEmpty); Assert.False(dr1.Properties.EmbedInteropTypes); Assert.False(dr2.Properties.EmbedInteropTypes); Assert.False(dr3.Properties.EmbedInteropTypes); // the paths come from the resolver: Assert.Equal(p2, dr1.FilePath); Assert.Equal(p3, dr2.FilePath); Assert.Equal(p3, dr3.FilePath); } [Fact] public void DuplicateModuleReferences_EquivalentPath() { var dir = Temp.CreateDirectory(); string p1 = dir.CreateFile("netModule1.netmodule").WriteAllBytes(TestResources.SymbolsTests.netModule.netModule1).Path; string p2 = MakeEquivalentPath(p1); var m1 = MetadataReference.CreateFromFile(p1, new MetadataReferenceProperties(MetadataImageKind.Module)); var m2 = MetadataReference.CreateFromFile(p2, new MetadataReferenceProperties(MetadataImageKind.Module)); var compilation = CSharpCompilation.Create("goo", options: TestOptions.ReleaseDll, references: new MetadataReference[] { m1, m2 }); // We don't deduplicate references based on file path on the compilation level. // The host (command line compiler and msbuild workspace) is responsible for such de-duplication, if needed. compilation.VerifyDiagnostics( // error CS8015: Module 'netModule1.netmodule' is already defined in this assembly. Each module must have a unique filename. Diagnostic(ErrorCode.ERR_NetModuleNameMustBeUnique).WithArguments("netModule1.netmodule"), // netModule1.netmodule: error CS0101: The namespace '<global namespace>' already contains a definition for 'Class1' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Class1", "<global namespace>"), // netModule1.netmodule: error CS0101: The namespace 'NS1' already contains a definition for 'Class4' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Class4", "NS1"), // netModule1.netmodule: error CS0101: The namespace 'NS1' already contains a definition for 'Class8' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Class8", "NS1")); var mods = compilation.Assembly.Modules.ToArray(); Assert.Equal(3, mods.Length); Assert.NotNull(compilation.GetReferencedModuleSymbol(m1)); Assert.NotNull(compilation.GetReferencedModuleSymbol(m2)); } /// <summary> /// Two metadata files with the same strong identity referenced twice, with embedInteropTypes=true and embedInteropTypes=false. /// </summary> [Fact] public void DuplicateAssemblyReferences_EquivalentStrongNames_Metadata() { var ref1 = AssemblyMetadata.CreateFromImage(TestResources.General.C2).GetReference(embedInteropTypes: true, filePath: @"R:\A\MTTestLib1.dll"); var ref2 = AssemblyMetadata.CreateFromImage(TestResources.General.C2).GetReference(embedInteropTypes: false, filePath: @"R:\B\MTTestLib1.dll"); var c = CreateStandardCompilation("class C {}", new[] { ref1, ref2 }); c.VerifyDiagnostics( // error CS1760: Assemblies 'R:\B\MTTestLib1.dll' and 'R:\A\MTTestLib1.dll' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references. Diagnostic(ErrorCode.ERR_AssemblySpecifiedForLinkAndRef).WithArguments(@"R:\B\MTTestLib1.dll", @"R:\A\MTTestLib1.dll")); } /// <summary> /// Two compilations with the same strong identity referenced twice, with embedInteropTypes=true and embedInteropTypes=false. /// </summary> [Fact] public void DuplicateAssemblyReferences_EquivalentStrongNames_Compilations() { var sourceLib = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface I {}"; var lib1 = CreateStandardCompilation(sourceLib, options: s_signedDll, assemblyName: "Lib"); var lib2 = CreateStandardCompilation(sourceLib, options: s_signedDll, assemblyName: "Lib"); var ref1 = lib1.ToMetadataReference(embedInteropTypes: true); var ref2 = lib2.ToMetadataReference(embedInteropTypes: false); var c = CreateStandardCompilation("class C {}", new[] { ref1, ref2 }); c.VerifyDiagnostics( // error CS1760: Assemblies 'Lib' and 'Lib' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references. Diagnostic(ErrorCode.ERR_AssemblySpecifiedForLinkAndRef).WithArguments("Lib", "Lib")); } [Fact] public void DuplicateAssemblyReferences_EquivalentName() { string p1 = Temp.CreateFile().WriteAllBytes(TestResources.NetFX.v4_0_30319.System_Core).Path; string p2 = Temp.CreateFile().CopyContentFrom(p1).Path; var r1 = MetadataReference.CreateFromFile(p1); var r2 = MetadataReference.CreateFromFile(p2); var compilation = CSharpCompilation.Create("goo", references: new[] { r1, r2 }); var refs = compilation.Assembly.Modules.Select(module => module.GetReferencedAssemblies()).ToArray(); Assert.Equal(1, refs.Length); Assert.Equal(1, refs[0].Length); } /// <summary> /// Two Framework identities with unified versions. /// </summary> [Fact] [WorkItem(546026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546026"), WorkItem(546169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546169")] public void CS1703ERR_DuplicateImport() { var p1 = Temp.CreateFile().WriteAllBytes(TestResources.NetFX.v4_0_30319.System).Path; var p2 = Temp.CreateFile().WriteAllBytes(TestResources.NetFX.v2_0_50727.System).Path; var text = @"namespace N {}"; var comp = CSharpCompilation.Create( "DupSignedRefs", new[] { SyntaxFactory.ParseSyntaxTree(text) }, new[] { MetadataReference.CreateFromFile(p1), MetadataReference.CreateFromFile(p2) }, TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); comp.VerifyDiagnostics( // error CS1703: Multiple assemblies with equivalent identity have been imported: '...\v4.0.30319\System.dll' and '...\v2.0.50727\System.dll'. Remove one of the duplicate references. Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments(p1, p2)); } [Fact] public void CS1704ERR_DuplicateImportSimple() { var libSource = @" using System; public class A { }"; var peImage = CreateStandardCompilation(libSource, options: TestOptions.ReleaseDll, assemblyName: "CS1704").EmitToArray(); var dir1 = Temp.CreateDirectory(); var exe1 = dir1.CreateFile("CS1704.dll").WriteAllBytes(peImage); var dir2 = Temp.CreateDirectory(); var exe2 = dir2.CreateFile("CS1704.dll").WriteAllBytes(peImage); var ref1 = AssemblyMetadata.CreateFromFile(exe1.Path).GetReference(aliases: ImmutableArray.Create("A1")); var ref2 = AssemblyMetadata.CreateFromFile(exe2.Path).GetReference(aliases: ImmutableArray.Create("A2")); var source = @" extern alias A1; extern alias A2; class B : A1::A { } class C : A2::A { } "; // Dev12 reports CS1704. An assembly with the same simple name '...' has already been imported. // We consider the second reference a duplicate and ignore it (merging the aliases). CreateStandardCompilation(source, new[] { ref1, ref2 }).VerifyDiagnostics(); } [Fact] public void WeakIdentitiesWithDifferentVersions() { var sourceLibV1 = @" using System.Reflection; [assembly: AssemblyVersion(""1.0.0.0"")] public class C1 { } "; var sourceLibV2 = @" using System.Reflection; [assembly: AssemblyVersion(""2.0.0.0"")] public class C2 { } "; var sourceRefLibV1 = @" public class P { public C1 x; } "; var sourceMain = @" public class Q { public P x; public C1 y; public C2 z; } "; var libV1 = CreateStandardCompilation(sourceLibV1, assemblyName: "Lib"); var libV2 = CreateStandardCompilation(sourceLibV2, assemblyName: "Lib"); var refLibV1 = CreateStandardCompilation(sourceRefLibV1, new[] { new CSharpCompilationReference(libV1) }, assemblyName: "RefLibV1"); var main = CreateStandardCompilation(sourceMain, new[] { new CSharpCompilationReference(libV1), new CSharpCompilationReference(refLibV1), new CSharpCompilationReference(libV2) }, assemblyName: "Main"); main.VerifyDiagnostics( // error CS1704: An assembly with the same simple name 'Lib' has already been imported. Try removing one of the references (e.g. 'Lib') or sign them to enable side-by-side. Diagnostic(ErrorCode.ERR_DuplicateImportSimple).WithArguments("Lib", "Lib"), // (5,12): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1")); } /// <summary> /// Although the CLR considers all WinRT references equivalent the Dev11 C# and VB compilers still /// compare their identities as if they were regular managed dlls. /// </summary> [Fact] public void WinMd_SameSimpleNames_SameVersions() { var sourceMain = @" public class Q { public C1 y; public C2 z; } "; // W1.dll: (W, Version=255.255.255.255, Culture=null, PKT=null) // W2.dll: (W, Version=255.255.255.255, Culture=null, PKT=null) using (AssemblyMetadata metadataLib1 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1), metadataLib2 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.W2)) { var mdRefLib1 = metadataLib1.GetReference(filePath: @"C:\W1.dll"); var mdRefLib2 = metadataLib2.GetReference(filePath: @"C:\W2.dll"); var main = CreateStandardCompilation(sourceMain, new[] { mdRefLib1, mdRefLib2 }); // Dev12 reports CS1704. An assembly with the same simple name '...' has already been imported. // We consider the second reference a duplicate and ignore it. main.VerifyDiagnostics( // (4,12): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C1").WithArguments("C1")); } } /// <summary> /// Although the CLR considers all WinRT references equivalent the Dev11 C# and VB compilers still /// compare their identities as if they were regular managed dlls. /// </summary> [Fact] public void WinMd_DifferentSimpleNames() { var sourceMain = @" public class Q { public C1 y; public CB z; } "; // W1.dll: (W, Version=255.255.255.255, Culture=null, PKT=null) // WB.dll: (WB, Version=255.255.255.255, Culture=null, PKT=null) using (AssemblyMetadata metadataLib1 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1), metadataLib2 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WB)) { var mdRefLib1 = metadataLib1.GetReference(filePath: @"C:\W1.dll"); var mdRefLib2 = metadataLib2.GetReference(filePath: @"C:\WB.dll"); var main = CreateStandardCompilation(sourceMain, new[] { mdRefLib1, mdRefLib2 }); main.VerifyDiagnostics(); } } /// <summary> /// Although the CLR considers all WinRT references equivalent the Dev11 C# and VB compilers still /// compare their identities as if they were regular managed dlls. /// </summary> [Fact] public void WinMd_SameSimpleNames_DifferentVersions() { var sourceMain = @" public class Q { public CB y; public CB_V1 z; } "; // WB.dll: (WB, Version=255.255.255.255, Culture=null, PKT=null) // WB_Version1.dll: (WB, Version=1.0.0.0, Culture=null, PKT=null) using (AssemblyMetadata metadataLib1 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WB), metadataLib2 = AssemblyMetadata.CreateFromImage(TestResources.WinRt.WB_Version1)) { var mdRefLib1 = metadataLib1.GetReference(filePath: @"C:\WB.dll"); var mdRefLib2 = metadataLib2.GetReference(filePath: @"C:\WB_Version1.dll"); var main = CreateStandardCompilation(sourceMain, new[] { mdRefLib1, mdRefLib2 }); main.VerifyDiagnostics( // error CS1704: An assembly with the same simple name 'WB' has already been imported. Try removing one of the references (e.g. 'C:\WB.dll') or sign them to enable side-by-side. Diagnostic(ErrorCode.ERR_DuplicateImportSimple).WithArguments("WB", @"C:\WB.dll"), // (4,12): error CS0246: The type or namespace name 'CB' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "CB").WithArguments("CB")); } } /// <summary> /// We replicate the Dev11 behavior here but is there any real world scenario for this? /// </summary> [Fact] public void MetadataReferencesDifferInCultureOnly() { var arSA = TestReferences.SymbolsTests.Versioning.AR_SA; var enUS = TestReferences.SymbolsTests.Versioning.EN_US; var source = @" public class A { public arSA a = new arSA(); public enUS b = new enUS(); } "; var compilation = CreateStandardCompilation(source, references: new[] { arSA, enUS }); var arSA_sym = compilation.GetReferencedAssemblySymbol(arSA); var enUS_sym = compilation.GetReferencedAssemblySymbol(enUS); Assert.Equal("ar-SA", arSA_sym.Identity.CultureName); Assert.Equal("en-US", enUS_sym.Identity.CultureName); compilation.VerifyDiagnostics(); } private class ReferenceResolver1 : MetadataReferenceResolver { public readonly string path1, path2; public bool resolved1, resolved2; public ReferenceResolver1(string path1, string path2) { this.path1 = path1; this.path2 = path2; } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { switch (reference) { case "1": resolved1 = true; return ImmutableArray.Create(MetadataReference.CreateFromFile(path1)); case "2.dll": resolved2 = true; return ImmutableArray.Create(MetadataReference.CreateFromFile(path2)); default: return ImmutableArray<PortableExecutableReference>.Empty; } } public override bool Equals(object other) => true; public override int GetHashCode() => 1; } [Fact] public void ReferenceResolution1() { var path1 = Temp.CreateFile().WriteAllBytes(TestResources.General.MDTestLib1).Path; var path2 = Temp.CreateFile().WriteAllBytes(TestResources.General.MDTestLib2).Path; var resolver = new ReferenceResolver1(path1, path2); var c1 = CSharpCompilation.Create("c1", syntaxTrees: new[] { Parse("#r \"1\"", options: TestOptions.Script), Parse("#r \"2.dll\"", options: TestOptions.Script), }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); Assert.NotNull(c1.Assembly); // force creation of SourceAssemblySymbol var dirRefs = c1.DirectiveReferences; var assemblySymbol1 = c1.GetReferencedAssemblySymbol(dirRefs[0]); var assemblySymbol2 = c1.GetReferencedAssemblySymbol(dirRefs[1]); Assert.Equal("MDTestLib1", assemblySymbol1.Name); Assert.Equal("MDTestLib2", assemblySymbol2.Name); Assert.True(resolver.resolved1); Assert.True(resolver.resolved2); } private class TestException : Exception { } private class ErroneousReferenceResolver : TestMetadataReferenceResolver { public ErroneousReferenceResolver() { } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { switch (reference) { case "throw": throw new TestException(); } return base.ResolveReference(reference, baseFilePath, properties); } } [Fact] public void ReferenceResolution_ExceptionsFromResolver() { var options = TestOptions.ReleaseDll.WithMetadataReferenceResolver(new ErroneousReferenceResolver()); foreach (var tree in new[] { Parse("#r \"throw\"", options: TestOptions.Script), }) { var c = CSharpCompilation.Create("c", syntaxTrees: new[] { tree }, options: options); Assert.Throws<TestException>(() => { var a = c.Assembly; }); } } [Fact] public void ResolvedReferencesCaching() { var c1 = CSharpCompilation.Create("goo", syntaxTrees: new[] { Parse("class C {}") }, references: new[] { MscorlibRef, SystemCoreRef, SystemRef }); var a1 = c1.SourceAssembly; var c2 = c1.AddSyntaxTrees(Parse("class D { }")); var a2 = c2.SourceAssembly; } // TODO: make x-plat (https://github.com/dotnet/roslyn/issues/6465) [ConditionalFact(typeof(WindowsOnly))] public void ReferenceResolution_RelativePaths() { var t1 = Parse(@" #r ""lib.dll"" ", filename: @"C:\A\a.csx", options: TestOptions.Script); var rd1 = (ReferenceDirectiveTriviaSyntax)t1.GetRoot().GetDirectives().Single(); var t2 = Parse(@" #r ""lib.dll"" ", filename: @"C:\B\b.csx", options: TestOptions.Script); var rd2 = (ReferenceDirectiveTriviaSyntax)t2.GetRoot().GetDirectives().Single(); var c = CreateCompilationWithMscorlib45(new[] { t1, t2 }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver( pathResolver: new VirtualizedRelativePathResolver(new[] { @"C:\A\lib.dll", @"C:\B\lib.dll" }), files: new Dictionary<string, PortableExecutableReference>() { { @"C:\A\lib.dll", TestReferences.NetFx.v4_0_30319.Microsoft_CSharp }, { @"C:\B\lib.dll", TestReferences.NetFx.v4_0_30319.Microsoft_VisualBasic }, }))); c.VerifyDiagnostics(); Assert.Same(TestReferences.NetFx.v4_0_30319.Microsoft_CSharp, c.GetDirectiveReference(rd1)); Assert.Same(TestReferences.NetFx.v4_0_30319.Microsoft_VisualBasic, c.GetDirectiveReference(rd2)); } [Fact] public void CyclesInReferences() { var sourceA = @" public class A { } "; var a = CreateStandardCompilation(sourceA, assemblyName: "A"); var sourceB = @" public class B : A { } public class Goo {} "; var b = CreateStandardCompilation(sourceB, new[] { new CSharpCompilationReference(a) }, assemblyName: "B"); var refB = MetadataReference.CreateFromImage(b.EmitToArray()); var sourceA2 = @" public class A { public Goo x = new Goo(); } "; // construct A2 that has a reference to assembly identity "B". var a2 = CreateStandardCompilation(sourceA2, new[] { refB }, assemblyName: "A"); var refA2 = MetadataReference.CreateFromImage(a2.EmitToArray()); var symbolB = a2.GetReferencedAssemblySymbol(refB); Assert.True(symbolB is Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol, "PE symbol expected"); // force A assembly symbol to be added to a metadata cache: var c = CreateStandardCompilation("class C : A {}", new[] { refA2, refB }, assemblyName: "C"); var symbolA2 = c.GetReferencedAssemblySymbol(refA2); Assert.True(symbolA2 is Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol, "PE symbol expected"); Assert.Equal(1, ((AssemblyMetadata)refA2.GetMetadataNoCopy()).CachedSymbols.WeakCount); GC.KeepAlive(symbolA2); // Recompile "B" and remove int Goo. The assembly manager should not reuse symbols for A since they are referring to old version of B. var b2 = CreateStandardCompilation(@" public class B : A { public void Bar() { object objX = this.x; } } ", new[] { refA2 }, assemblyName: "B"); // TODO (tomat): Dev11 also reports: // b2.cs(5,28): error CS0570: 'A.x' is not supported by the language b2.VerifyDiagnostics( // (6,28): error CS7068: Reference to type 'Goo' claims it is defined in this assembly, but it is not defined in source or any added modules // object objX = this.x; Diagnostic(ErrorCode.ERR_MissingTypeInSource, "x").WithArguments("Goo")); } [Fact] public void BoundReferenceCaching_CyclesInReferences() { var a = CreateStandardCompilation("public class A { }", assemblyName: "A"); var b = CreateStandardCompilation("public class B : A { } ", new[] { new CSharpCompilationReference(a) }, assemblyName: "B"); var refB = MetadataReference.CreateFromImage(b.EmitToArray()); // construct A2 that has a reference to assembly identity "B". var a2 = CreateStandardCompilation(@"public class A { B B; }", new[] { refB }, assemblyName: "A"); var refA2 = MetadataReference.CreateFromImage(a2.EmitToArray()); var withCircularReference1 = CreateStandardCompilation(@"public class B : A { }", new[] { refA2 }, assemblyName: "B"); var withCircularReference2 = withCircularReference1.WithOptions(TestOptions.ReleaseDll); Assert.NotSame(withCircularReference1, withCircularReference2); // until we try to reuse bound references we share the manager: Assert.True(withCircularReference1.ReferenceManagerEquals(withCircularReference2)); var assembly1 = withCircularReference1.SourceAssembly; Assert.True(withCircularReference1.ReferenceManagerEquals(withCircularReference2)); var assembly2 = withCircularReference2.SourceAssembly; Assert.False(withCircularReference1.ReferenceManagerEquals(withCircularReference2)); var refA2_symbol1 = withCircularReference1.GetReferencedAssemblySymbol(refA2); var refA2_symbol2 = withCircularReference2.GetReferencedAssemblySymbol(refA2); Assert.NotNull(refA2_symbol1); Assert.NotNull(refA2_symbol2); Assert.NotSame(refA2_symbol1, refA2_symbol2); } [WorkItem(546828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546828")] [Fact] public void MetadataDependsOnSource() { // {0} is the body of the ReachFramework assembly reference. var ilTemplate = @" .assembly extern ReachFramework {{ {0} }} .assembly extern mscorlib {{ .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 }} .assembly PresentationFramework {{ .publickey = (00 24 00 00 04 80 00 00 94 00 00 00 06 02 00 00 // .$.............. 00 24 00 00 52 53 41 31 00 04 00 00 01 00 01 00 // .$..RSA1........ B5 FC 90 E7 02 7F 67 87 1E 77 3A 8F DE 89 38 C8 // ......g..w:...8. 1D D4 02 BA 65 B9 20 1D 60 59 3E 96 C4 92 65 1E // ....e. .`Y>...e. 88 9C C1 3F 14 15 EB B5 3F AC 11 31 AE 0B D3 33 // ...?....?..1...3 C5 EE 60 21 67 2D 97 18 EA 31 A8 AE BD 0D A0 07 // ..`!g-...1...... 2F 25 D8 7D BA 6F C9 0F FD 59 8E D4 DA 35 E4 4C // /%.}}.o...Y...5.L 39 8C 45 43 07 E8 E3 3B 84 26 14 3D AE C9 F5 96 // 9.EC...;.&.=.... 83 6F 97 C8 F7 47 50 E5 97 5C 64 E2 18 9F 45 DE // .o...GP..\d...E. F4 6B 2A 2B 12 47 AD C3 65 2B F5 C3 08 05 5D A9 ) // .k*+.G..e+....]. .ver 4:0:0:0 }} .module PresentationFramework.dll // MVID: {{CBA9159C-5BB4-49BC-B41D-AF055BF1C0AB}} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04D00000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi System.Windows.Controls.PrintDialog extends [mscorlib]System.Object {{ .method public hidebysig instance class [ReachFramework]System.Printing.PrintTicket Test() cil managed {{ ret }} .method public hidebysig specialname rtspecialname instance void .ctor() cil managed {{ ret }} }} "; var csharp = @" using System.Windows.Controls; namespace System.Printing { public class PrintTicket { } } class Test { static void Main() { var dialog = new PrintDialog(); var p = dialog.Test(); } } "; // ref only specifies name { var il = string.Format(ilTemplate, ""); var ilRef = CompileIL(il, prependDefaultHeader: false); var comp = CreateStandardCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework"); comp.VerifyDiagnostics(); } // public key specified by ref, but not def { var il = string.Format(ilTemplate, " .publickeytoken = (31 BF 38 56 AD 36 4E 35 ) // 1.8V.6N5"); var ilRef = CompileIL(il, prependDefaultHeader: false); CreateStandardCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework").VerifyDiagnostics(); } // version specified by ref, but not def { var il = string.Format(ilTemplate, " .ver 4:0:0:0"); var ilRef = CompileIL(il, prependDefaultHeader: false); CreateStandardCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework").VerifyDiagnostics(); } // culture specified by ref, but not def { var il = string.Format(ilTemplate, " .locale = (65 00 6E 00 2D 00 63 00 61 00 00 00 ) // e.n.-.c.a..."); var ilRef = CompileIL(il, prependDefaultHeader: false); CreateStandardCompilation(csharp, new[] { ilRef }, assemblyName: "ReachFramework").VerifyDiagnostics(); } } [WorkItem(546828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546828")] [Fact] public void MetadataDependsOnMetadataOrSource() { var il = @" .assembly extern ReachFramework { .ver 4:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly PresentationFramework { .publickey = (00 24 00 00 04 80 00 00 94 00 00 00 06 02 00 00 // .$.............. 00 24 00 00 52 53 41 31 00 04 00 00 01 00 01 00 // .$..RSA1........ B5 FC 90 E7 02 7F 67 87 1E 77 3A 8F DE 89 38 C8 // ......g..w:...8. 1D D4 02 BA 65 B9 20 1D 60 59 3E 96 C4 92 65 1E // ....e. .`Y>...e. 88 9C C1 3F 14 15 EB B5 3F AC 11 31 AE 0B D3 33 // ...?....?..1...3 C5 EE 60 21 67 2D 97 18 EA 31 A8 AE BD 0D A0 07 // ..`!g-...1...... 2F 25 D8 7D BA 6F C9 0F FD 59 8E D4 DA 35 E4 4C // /%.}.o...Y...5.L 39 8C 45 43 07 E8 E3 3B 84 26 14 3D AE C9 F5 96 // 9.EC...;.&.=.... 83 6F 97 C8 F7 47 50 E5 97 5C 64 E2 18 9F 45 DE // .o...GP..\d...E. F4 6B 2A 2B 12 47 AD C3 65 2B F5 C3 08 05 5D A9 ) // .k*+.G..e+....]. .ver 4:0:0:0 } .module PresentationFramework.dll // MVID: {CBA9159C-5BB4-49BC-B41D-AF055BF1C0AB} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x04D00000 // =============== CLASS MEMBERS DECLARATION =================== .class public auto ansi System.Windows.Controls.PrintDialog extends [mscorlib]System.Object { .method public hidebysig instance class [ReachFramework]System.Printing.PrintTicket Test() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } "; var csharp = @" namespace System.Printing { public class PrintTicket { } } "; var oldVersion = @"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")]"; var newVersion = @"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")]"; var ilRef = CompileIL(il, prependDefaultHeader: false); var oldMetadata = AssemblyMetadata.CreateFromImage(CreateStandardCompilation(oldVersion + csharp, assemblyName: "ReachFramework").EmitToArray()); var oldRef = oldMetadata.GetReference(); var comp = CreateStandardCompilation(newVersion + csharp, new[] { ilRef, oldRef }, assemblyName: "ReachFramework"); comp.VerifyDiagnostics(); var method = comp.GlobalNamespace. GetMember<NamespaceSymbol>("System"). GetMember<NamespaceSymbol>("Windows"). GetMember<NamespaceSymbol>("Controls"). GetMember<NamedTypeSymbol>("PrintDialog"). GetMember<MethodSymbol>("Test"); AssemblyIdentity actualIdentity = method.ReturnType.ContainingAssembly.Identity; // Even though the compilation has the correct version number, the referenced binary is preferred. Assert.Equal(oldMetadata.GetAssembly().Identity, actualIdentity); Assert.NotEqual(comp.Assembly.Identity, actualIdentity); } [Fact] [WorkItem(546900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546900")] public void MetadataRefersToSourceAssemblyModule() { var srcA = @" .assembly extern b { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly a { .hash algorithm 0x00008004 .ver 0:0:0:0 } .module a.dll .class public auto ansi beforefieldinit A extends [b]B { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [b]B::.ctor() IL_0006: ret } }"; var aRef = CompileIL(srcA, prependDefaultHeader: false); string srcB = @" public class B { public A A; }"; var b = CreateStandardCompilation(srcB, references: new[] { aRef }, options: TestOptions.ReleaseModule.WithModuleName("mod.netmodule"), assemblyName: "B"); b.VerifyDiagnostics(); } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(530839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530839")] public void EmbedInteropTypesReferences() { var libSource = @" using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion(""1.0.0.0"")] [assembly: Guid(""49a1950e-3e35-4595-8cb9-920c64c44d67"")] [assembly: PrimaryInteropAssembly(1, 0)] [assembly: ImportedFromTypeLib(""Lib"")] [ComImport()] [Guid(""49a1950e-3e35-4595-8cb9-920c64c44d68"")] public interface I { } "; var mainSource = @" public class C : I { } "; var lib = CreateStandardCompilation(libSource, assemblyName: "lib"); var refLib = ((MetadataImageReference)lib.EmitToImageReference()).WithEmbedInteropTypes(true); var main = CreateStandardCompilation(mainSource, new[] { refLib }, assemblyName: "main"); CompileAndVerify(main, validator: (pe) => { var reader = pe.GetMetadataReader(); AssertEx.SetEqual(new[] { "mscorlib 4.0" }, reader.DumpAssemblyReferences()); }, verify: Verification.Passes); } [WorkItem(531537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531537")] [Fact] public void ModuleSymbolReuse() { var text1 = @" class C { TypeFromModule M() { } } "; // Doesn't really matter what this text is - just need a delta. var text2 = @" class D { } "; var assemblyMetadata = AssemblyMetadata.CreateFromImage(CreateStandardCompilation("public class TypeDependedOnByModule { }", assemblyName: "lib1").EmitToArray()); var assemblyRef = assemblyMetadata.GetReference(); var moduleRef = CreateStandardCompilation("public class TypeFromModule : TypeDependedOnByModule { }", new[] { assemblyRef }, options: TestOptions.ReleaseModule, assemblyName: "lib2").EmitToImageReference(); var comp1 = CreateStandardCompilation(text1, new MetadataReference[] { moduleRef, assemblyRef, }); var tree1 = comp1.SyntaxTrees.Single(); var moduleSymbol1 = comp1.GetReferencedModuleSymbol(moduleRef); Assert.Equal(comp1.Assembly, moduleSymbol1.ContainingAssembly); var moduleReferences1 = moduleSymbol1.GetReferencedAssemblies(); Assert.Contains(assemblyMetadata.GetAssembly().Identity, moduleReferences1); var moduleTypeSymbol1 = comp1.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeFromModule"); Assert.Equal(moduleSymbol1, moduleTypeSymbol1.ContainingModule); Assert.Equal(comp1.Assembly, moduleTypeSymbol1.ContainingAssembly); var tree2 = tree1.WithInsertAt(text1.Length, text2); var comp2 = comp1.ReplaceSyntaxTree(tree1, tree2); var moduleSymbol2 = comp2.GetReferencedModuleSymbol(moduleRef); Assert.Equal(comp2.Assembly, moduleSymbol2.ContainingAssembly); var moduleReferences2 = moduleSymbol2.GetReferencedAssemblies(); var moduleTypeSymbol2 = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("TypeFromModule"); Assert.Equal(moduleSymbol2, moduleTypeSymbol2.ContainingModule); Assert.Equal(comp2.Assembly, moduleTypeSymbol2.ContainingAssembly); Assert.NotEqual(moduleSymbol1, moduleSymbol2); Assert.NotEqual(moduleTypeSymbol1, moduleTypeSymbol2); AssertEx.Equal(moduleReferences1, moduleReferences2); } [WorkItem(531537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531537")] [Fact] public void ModuleSymbolReuse_ImplicitType() { var text1 = @" namespace A { void M() { } "; var text2 = @" } "; // Note: we just need *a* module reference for the repro - we're not depending on its contents, name, etc. var moduleRef = CreateStandardCompilation("public class C { }", options: TestOptions.ReleaseModule, assemblyName: "lib").EmitToImageReference(); var comp1 = CreateStandardCompilation(text1, new MetadataReference[] { moduleRef, }); var tree1 = comp1.SyntaxTrees.Single(); var implicitTypeCount1 = comp1.GlobalNamespace.GetMember<NamespaceSymbol>("A").GetMembers(TypeSymbol.ImplicitTypeName).Length; Assert.Equal(1, implicitTypeCount1); var tree2 = tree1.WithInsertAt(text1.Length, text2); var comp2 = comp1.ReplaceSyntaxTree(tree1, tree2); var implicitTypeCount2 = comp2.GlobalNamespace.GetMember<NamespaceSymbol>("A").GetMembers(TypeSymbol.ImplicitTypeName).Length; Assert.Equal(1, implicitTypeCount2); } [Fact] public void CachingAndVisibility() { var cPublic = CreateStandardCompilation("class C { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Public)); var cInternal = CreateStandardCompilation("class D { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var cAll = CreateStandardCompilation("class E { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); var cPublic2 = CreateStandardCompilation("class C { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Public)); var cInternal2 = CreateStandardCompilation("class D { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var cAll2 = CreateStandardCompilation("class E { }", options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); Assert.NotSame(cPublic.Assembly.CorLibrary, cInternal.Assembly.CorLibrary); Assert.NotSame(cAll.Assembly.CorLibrary, cInternal.Assembly.CorLibrary); Assert.NotSame(cAll.Assembly.CorLibrary, cPublic.Assembly.CorLibrary); Assert.Same(cPublic.Assembly.CorLibrary, cPublic2.Assembly.CorLibrary); Assert.Same(cInternal.Assembly.CorLibrary, cInternal2.Assembly.CorLibrary); Assert.Same(cAll.Assembly.CorLibrary, cAll2.Assembly.CorLibrary); } [Fact] public void ImportingPrivateNetModuleMembers() { string moduleSource = @" internal class C { private void m() { } } "; string mainSource = @" "; var module = CreateStandardCompilation(moduleSource, options: TestOptions.ReleaseModule); var moduleRef = module.EmitToImageReference(); // All var mainAll = CreateStandardCompilation(mainSource, new[] { moduleRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); var mAll = mainAll.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers("m"); Assert.Equal(1, mAll.Length); // Internal var mainInternal = CreateStandardCompilation(mainSource, new[] { moduleRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)); var mInternal = mainInternal.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers("m"); Assert.Equal(0, mInternal.Length); // Public var mainPublic = CreateStandardCompilation(mainSource, new[] { moduleRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Public)); var mPublic = mainPublic.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers("m"); Assert.Equal(0, mPublic.Length); } [Fact] [WorkItem(531342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531342"), WorkItem(727122, "DevDiv")] public void PortableLibrary() { var plSource = @"public class C {}"; var pl = CreateCompilation(plSource, new[] { MscorlibPP7Ref, SystemRuntimePP7Ref }); var r1 = new CSharpCompilationReference(pl); var mainSource = @"public class D : C { }"; // w/o facades: var main = CreateCompilation(mainSource, new MetadataReference[] { r1, MscorlibFacadeRef }, options: TestOptions.ReleaseDll); main.VerifyDiagnostics( // (1,18): error CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("System.Object", "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")); // facade specified: main = CreateCompilation(mainSource, new MetadataReference[] { r1, MscorlibFacadeRef, SystemRuntimeFacadeRef }); main.VerifyDiagnostics(); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void OverloadResolutionUseSiteWarning() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] public class B {{ }} "; var libBv1 = CreateStandardCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateStandardCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A { public void M(B b) { } } "; var libAv1 = CreateStandardCompilation( libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); var source = @" public class Source { public void Test() { A a = new A(); a.M(null); } } "; var comp = CreateStandardCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyDiagnostics( // (7,9): warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy // a.M(null); Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "a.M").WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B")); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void MethodGroupConversionUseSiteWarning() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] public class B {{ }} "; var libBv1 = CreateStandardCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateStandardCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A { public void M(B b) { } } "; var libAv1 = CreateStandardCompilation( libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); var source = @" public class Source { public void Test() { A a = new A(); System.Action<B> f = a.M; } } "; var comp = CreateStandardCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyDiagnostics( // (7,30): warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy // System.Action<B> f = a.M; Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "a.M").WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B")); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void IndexerUseSiteWarning() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] public class B {{ }} "; var libBv1 = CreateStandardCompilation(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateStandardCompilation(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A { public int this[B b] { get { return 0; } } } "; var libAv1 = CreateStandardCompilation(libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); var source = @" public class Source { public void Test() { A a = new A(); int x = a[null]; } } "; var comp = CreateStandardCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyDiagnostics( // (7,17): warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy // int x = a[null]; Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "a[null]").WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B")); } [Fact] [WorkItem(762729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762729")] public void Repro762729() { var libBTemplate = @" [assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")] // To be implemented in library A. public interface IGeneric<T> {{ void M(); }} // To be implemented by superclass of class implementing IGeneric<T>. public interface I {{ }} public static class Extensions {{ // To be invoked from the test assembly. public static void Extension<T>(this IGeneric<T> i) {{ i.M(); }} }} "; var libBv1 = CreateCompilationWithMscorlibAndSystemCore(string.Format(libBTemplate, "1"), assemblyName: "B", options: s_signedDll); var libBv2 = CreateCompilationWithMscorlibAndSystemCore(string.Format(libBTemplate, "2"), assemblyName: "B", options: s_signedDll); Assert.Equal("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", libBv1.Assembly.Identity.GetDisplayName()); Assert.Equal("B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", libBv2.Assembly.Identity.GetDisplayName()); libBv1.EmitToImageReference(); libBv2.EmitToImageReference(); var libASource = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class ABase : I { } public class A : ABase, IGeneric<AItem> { void IGeneric<AItem>.M() { } } // Type argument for IGeneric<T>. In the current assembly so there are no versioning issues. public class AItem { } "; var libAv1 = CreateStandardCompilation(libASource, new[] { new CSharpCompilationReference(libBv1) }, assemblyName: "A", options: s_signedDll); libAv1.EmitToImageReference(); var source = @" public class Source { public void Test(A a) { a.Extension(); } } "; var comp = CreateStandardCompilation(source, new[] { new CSharpCompilationReference(libAv1), new CSharpCompilationReference(libBv2) }); comp.VerifyEmitDiagnostics( // warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B"), // (6,11): warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy // a.Extension(); Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "Extension").WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B"), // (6,9): warning CS1701: Assuming assembly reference 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy // a.Extension(); Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "a.Extension").WithArguments("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B")); } [WorkItem(905495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/905495")] [Fact] public void ReferenceWithNoMetadataSection() { var c = CreateStandardCompilation("", new[] { new TestImageReference(TestResources.Basic.NativeApp, "NativeApp.exe") }); c.VerifyDiagnostics( // error CS0009: Metadata file 'NativeApp.exe' could not be opened -- PE image doesn't contain managed metadata. Diagnostic(ErrorCode.FTL_MetadataCantOpenFile).WithArguments(@"NativeApp.exe", CodeAnalysisResources.PEImageDoesntContainManagedMetadata)); } [WorkItem(2988, "https://github.com/dotnet/roslyn/issues/2988")] [Fact] public void EmptyReference1() { var source = "class C { public static void Main() { } }"; var c = CreateStandardCompilation(source, new[] { AssemblyMetadata.CreateFromImage(new byte[0]).GetReference(display: "Empty.dll") }); c.VerifyDiagnostics( Diagnostic(ErrorCode.FTL_MetadataCantOpenFile).WithArguments(@"Empty.dll", CodeAnalysisResources.PEImageDoesntContainManagedMetadata)); } [WorkItem(2992, "https://github.com/dotnet/roslyn/issues/2992")] [Fact] public void MetadataDisposed() { var md = AssemblyMetadata.CreateFromImage(TestResources.NetFX.Minimal.mincorlib); var compilation = CSharpCompilation.Create("test", references: new[] { md.GetReference() }); // Use the Compilation once to force lazy initialization of the underlying MetadataReader compilation.GetTypeByMetadataName("System.Int32").GetMembers(); md.Dispose(); Assert.Throws<ObjectDisposedException>(() => compilation.GetTypeByMetadataName("System.Int64").GetMembers()); } [WorkItem(43, "https://roslyn.codeplex.com/workitem/43")] [Fact] public void ReusingCorLibManager() { var corlib1 = CreateCompilation(""); var assembly1 = corlib1.Assembly; var corlib2 = corlib1.Clone(); var assembly2 = corlib2.Assembly; Assert.Same(assembly1.CorLibrary, assembly1); Assert.Same(assembly2.CorLibrary, assembly2); Assert.True(corlib1.ReferenceManagerEquals(corlib2)); } [WorkItem(5138, "https://github.com/dotnet/roslyn/issues/5138")] [Fact] public void AsymmetricUnification() { var vectors40 = CreateStandardCompilation( @"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")]", options: TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a), assemblyName: "System.Numerics.Vectors"); Assert.Equal("System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", vectors40.Assembly.Identity.GetDisplayName()); var vectors41 = CreateStandardCompilation( @"[assembly: System.Reflection.AssemblyVersion(""4.1.0.0"")]", options: TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a), assemblyName: "System.Numerics.Vectors"); Assert.Equal("System.Numerics.Vectors, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", vectors41.Assembly.Identity.GetDisplayName()); var refVectors40 = vectors40.EmitToImageReference(); var refVectors41 = vectors41.EmitToImageReference(); var c1 = CreateStandardCompilation("", new[] { refVectors40, refVectors41 }, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); c1.VerifyDiagnostics(); var a0 = c1.GetAssemblyOrModuleSymbol(refVectors40); var a1 = c1.GetAssemblyOrModuleSymbol(refVectors41); Assert.Equal("System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((IAssemblySymbol)a0).Identity.GetDisplayName()); Assert.Equal("System.Numerics.Vectors, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((IAssemblySymbol)a1).Identity.GetDisplayName()); var c2 = CreateStandardCompilation("", new[] { refVectors41, refVectors40 }, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); c2.VerifyDiagnostics(); a0 = c2.GetAssemblyOrModuleSymbol(refVectors40); a1 = c2.GetAssemblyOrModuleSymbol(refVectors41); Assert.Equal("System.Numerics.Vectors, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((IAssemblySymbol)a0).Identity.GetDisplayName()); Assert.Equal("System.Numerics.Vectors, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", ((IAssemblySymbol)a1).Identity.GetDisplayName()); } [Fact] public void ReferenceSupersession_FxUnification1() { var c = CreateSubmissionWithExactReferences("System.Diagnostics.Process.GetCurrentProcess()", new[] { TestReferences.NetFx.v2_0_50727.mscorlib, TestReferences.NetFx.v2_0_50727.System, TestReferences.NetFx.v4_0_30319.mscorlib, TestReferences.NetFx.v4_0_30319.System, }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=2.0.0.0: <superseded>", "System, Version=2.0.0.0: <superseded>", "mscorlib, Version=4.0.0.0", "System, Version=4.0.0.0"); } [Fact] public void ReferenceSupersession_StrongNames1() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, TestReferences.SymbolsTests.Versioning.C2, TestReferences.SymbolsTests.Versioning.C1, }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "C, Version=2.0.0.0", "C, Version=1.0.0.0: <superseded>"); } [Fact] public void ReferenceSupersession_WeakNames1() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").EmitToImageReference(), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0"); } [Fact] public void ReferenceSupersession_AliasesErased() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""0.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.1"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(), CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.1.0.0"")] public class C {}", new[] { MscorlibRef }, assemblyName: "C").ToMetadataReference(). WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Z")).WithRecursiveAliases(true)), }); c.VerifyDiagnostics(); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0: global,Z", "C, Version=0.0.0.0: <superseded>", "C, Version=2.0.0.1", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0: <superseded>", "C, Version=1.1.0.0: <superseded>"); } [Fact] public void ReferenceSupersession_NoUnaliasedAssembly() { var c = CreateSubmissionWithExactReferences("new C()", new[] { MscorlibRef_v4_0_30316_17626, CreateStandardCompilation(@"[assembly: System.Reflection.AssemblyVersion(""0.0.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(), CreateStandardCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.1"")] public class C {}", assemblyName: "C").ToMetadataReference(aliases: ImmutableArray.Create("X", "Y")), CreateStandardCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(), CreateStandardCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(), CreateStandardCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.1.0.0"")] public class C {}", assemblyName: "C").ToMetadataReference(). WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Z")).WithRecursiveAliases(true)), }); c.VerifyDiagnostics( // (1,5): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C")); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0: global,Z", "C, Version=0.0.0.0: <superseded>", "C, Version=2.0.0.1: X,Y", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0: <superseded>", "C, Version=1.1.0.0: <superseded>"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithNoAliases() { // c - b (alias X) // - a (via #r) -> b var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" #r ""a"" new B() "; var c = CreateSubmissionWithExactReferences(source, new[] { MscorlibRef_v4_0_30316_17626, bRef.WithAliases(ImmutableArray.Create("X")), aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>() { { "a", (PortableExecutableReference)aRef.WithProperties(MetadataReferenceProperties.Assembly.WithRecursiveAliases(true)) } }))); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "mscorlib", "B: X,global", "A" ); } [Fact] public void ReferenceDirective_NonRecursiveReferenceWithNoAliases() { // c - b (alias X) // - a (via #r) -> b var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" #r ""a"" new B() "; var c = CreateSubmissionWithExactReferences(source, new[] { MscorlibRef_v4_0_30316_17626, bRef.WithAliases(ImmutableArray.Create("X")), aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>() { { "a", (PortableExecutableReference)aRef.WithProperties(MetadataReferenceProperties.Assembly) } }))); c.VerifyDiagnostics( // (3,5): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // new B() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B")); c.VerifyAssemblyAliases( "mscorlib", "B: X", "A"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias1() { // c - b (alias X) // - a // - a (recursive alias Y) -> b var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" extern alias X; extern alias Y; public class P { A a = new Y::A(); X::B b = new Y::B(); } "; var c = CreateCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef, aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y", "A: global,Y", "mscorlib: global,Y"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias2() { // c - b (alias X) // - a (recursive alias Y) -> b // - a var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" extern alias X; extern alias Y; public class P { A a = new Y::A(); X::B b = new Y::B(); } "; var c = CreateCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), aRef, MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y", "A: global,Y", "mscorlib: global,Y"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias3() { // c - b (alias X) // - a (recursive alias Y) -> b // - a var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var source = @" extern alias X; extern alias Y; public class P { A a = new Y::A(); X::B b = new Y::B(); } "; var c = CreateCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef, aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y")).WithRecursiveAliases(true)), aRef, MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y", "A: global,Y", "mscorlib: global,Y"); } [Fact] public void ReferenceDirective_RecursiveReferenceWithAlias4() { // c - b (alias X) // - a (recursive alias Y) -> b // - d (recursive alias Z) -> a var bRef = CreateCompilationWithMscorlib45("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilationWithMscorlib45("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var dRef = CreateCompilationWithMscorlib45("public class D : A { }", new[] { aRef, bRef }, assemblyName: "D").EmitToImageReference(); var source = @" extern alias X; extern alias Y; extern alias Z; public class P { Z::A a = new Y::A(); X::B b = new Y::B(); Z::B d = new X::B(); } "; var c = CreateCompilation(source, new[] { bRef.WithAliases(ImmutableArray.Create("X")), aRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Y", "Y")).WithRecursiveAliases(true)), dRef.WithProperties(MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("Z")).WithRecursiveAliases(true)), MscorlibRef, }, TestOptions.ReleaseDll); c.VerifyDiagnostics(); c.VerifyAssemblyAliases( "B: X,Y,Y,Z", "A: Y,Y,Z", "D: Z", "mscorlib: global,Y,Y,Z"); } [Fact] public void MissingAssemblyResolution1() { // c - a -> b var bRef = CreateStandardCompilation("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateStandardCompilation("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B", bRef } }); var c = CreateStandardCompilation("public class C : A { }", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); Assert.Equal("B", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(bRef)).Name); resolver.VerifyResolutionAttempts( "A -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [NoIOperationValidationFact] public void MissingAssemblyResolution_Aliases() { // c - a -> b with alias X var bRef = CreateStandardCompilation("public class B { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateStandardCompilation("public class A : B { }", new[] { bRef }, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B", bRef.WithAliases(ImmutableArray.Create("X")) } }); var c = CreateStandardCompilation(@" extern alias X; public class C : A { X::B F() => null; } ", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); resolver.VerifyResolutionAttempts( "A -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [NoIOperationValidationFact] public void MissingAssemblyResolution_AliasesMerge() { // c - a -> "b, V1" resolved to "b, V3" with alias X // - d -> "b, V2" resolved to "b, V3" with alias Y var b1Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public class B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilation("public class A : B { }", new[] { MscorlibRef, b1Ref }, assemblyName: "A").EmitToImageReference(); var dRef = CreateCompilation("public class D : B { }", new[] { MscorlibRef, b2Ref }, assemblyName: "D").EmitToImageReference(); var b3RefX = b3Ref.WithAliases(ImmutableArray.Create("X")); var b3RefY = b3Ref.WithAliases(ImmutableArray.Create("Y")); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", b3RefX }, { "B, 2.0.0.0", b3RefY }, }); var c = CreateCompilation(@" extern alias X; extern alias Y; public class C : A { X::B F() => new Y::B(); } ", new[] { MscorlibRef, aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics( // (5,18): warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "A").WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B")); Assert.Equal("B", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(b3RefY)).Name); Assert.Null(c.GetAssemblyOrModuleSymbol(b3RefX)); resolver.VerifyResolutionAttempts( "D -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "D, Version=0.0.0.0", "B, Version=3.0.0.0: Y,X"); } [Fact] public void MissingAssemblyResolution_WeakIdentities1() { // c - a -> "b,v1,PKT=null" // - d -> "b,v2,PKT=null" var b1Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilation(@"public interface A : B { }", new[] { MscorlibRef, b1Ref }, assemblyName: "A").EmitToImageReference(); var dRef = CreateCompilation(@"public interface D : B { }", new[] { MscorlibRef, b2Ref }, assemblyName: "D").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", b1Ref }, { "B, 2.0.0.0", b2Ref }, }); var c = CreateSubmissionWithExactReferences(@"public interface C : A, D { }", new[] { MscorlibRef_v4_0_30316_17626, aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); resolver.VerifyResolutionAttempts( "D -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "D, Version=0.0.0.0", "B, Version=2.0.0.0", "B, Version=1.0.0.0: <superseded>"); } [Fact] public void MissingAssemblyResolution_WeakIdentities2() { // c - a -> "b,v1,PKT=null" // - d -> "b,v2,PKT=null" var b1Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, assemblyName: "B").EmitToImageReference(); var aRef = CreateCompilation(@"public interface A : B { }", new[] { MscorlibRef, b1Ref }, assemblyName: "A").EmitToImageReference(); var dRef = CreateCompilation(@"public interface D : B { }", new[] { MscorlibRef, b2Ref }, assemblyName: "D").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", b3Ref }, { "B, 2.0.0.0", b4Ref }, }); var c = CreateSubmissionWithExactReferences(@"public interface C : A, D { }", new[] { MscorlibRef_v4_0_30316_17626, aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); resolver.VerifyResolutionAttempts( "D -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "D, Version=0.0.0.0", "B, Version=4.0.0.0", "B, Version=3.0.0.0: <superseded>"); } [Fact] public void MissingAssemblyResolution_None() { // c - a -> d // - d var dRef = CreateStandardCompilation("public interface D { }", assemblyName: "D").EmitToImageReference(); var aRef = CreateStandardCompilation("public interface A : D { }", new[] { dRef }, assemblyName: "A").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference>()); var c = CreateStandardCompilation("public interface C : A { }", new[] { aRef, dRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyDiagnostics(); resolver.VerifyResolutionAttempts(); } [Fact] public void MissingAssemblyResolution_ActualMissing() { // c - a -> d var dRef = CreateStandardCompilation("public interface D { }", assemblyName: "D").EmitToImageReference(); var aRef = CreateStandardCompilation("public interface A : D { }", new[] { dRef }, assemblyName: "A").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference>()); var c = CreateStandardCompilation("public interface C : A { }", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyDiagnostics( // (1,18): error CS0012: The type 'D' is defined in an assembly that is not referenced. You must add a reference to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("D", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); resolver.VerifyResolutionAttempts( "A -> D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } /// <summary> /// Ignore assemblies returned by the resolver that don't match the reference identity. /// </summary> [Fact] public void MissingAssemblyResolution_MissingDueToResolutionMismatch() { // c - a -> b var bRef = CreateStandardCompilation("public interface D { }", assemblyName: "B").EmitToImageReference(); var aRef = CreateStandardCompilation("public interface A : D { }", new[] { bRef }, assemblyName: "A").ToMetadataReference(); var eRef = CreateStandardCompilation("public interface E { }", assemblyName: "E").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 1.0.0.0", eRef }, }); var c = CreateStandardCompilation(@"public interface C : A { }", new[] { aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyDiagnostics( // (1,18): error CS0012: The type 'D' is defined in an assembly that is not referenced. You must add a reference to assembly 'B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("D", "B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); resolver.VerifyResolutionAttempts( "A -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [Fact] public void MissingAssemblyResolution_Multiple() { // c - a -> d // - b -> d var dRef = CreateStandardCompilation("public interface D { }", assemblyName: "D").EmitToImageReference(); var aRef = CreateStandardCompilation("public interface A : D { }", new[] { dRef }, assemblyName: "A").ToMetadataReference(); var bRef = CreateStandardCompilation("public interface B : D { }", new[] { dRef }, assemblyName: "B").ToMetadataReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D", dRef } }); var c = CreateStandardCompilation("public interface C : A, B { }", new[] { aRef, bRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); Assert.Equal("D", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(dRef)).Name); resolver.VerifyResolutionAttempts( "B -> D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } [Fact] public void MissingAssemblyResolution_Modules() { // c - a - d // - module(m) - b // - module(n) - d var bRef = CreateStandardCompilation("public interface B { }", assemblyName: "B").EmitToImageReference(); var dRef = CreateStandardCompilation("public interface D { }", assemblyName: "D").EmitToImageReference(); var mRef = CreateStandardCompilation("public interface M : B { }", new[] { bRef }, options: TestOptions.ReleaseModule.WithModuleName("M.netmodule")).EmitToImageReference(); var nRef = CreateStandardCompilation("public interface N : D { }", new[] { dRef }, options: TestOptions.ReleaseModule.WithModuleName("N.netmodule")).EmitToImageReference(); var aRef = CreateStandardCompilation("public interface A : D { }", new[] { dRef }, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B", bRef }, { "D", dRef }, }); var c = CreateStandardCompilation("public interface C : A { }", new[] { aRef, mRef, nRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics(); Assert.Equal("B", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(bRef)).Name); Assert.Equal("D", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(dRef)).Name); // We don't resolve one assembly reference identity twice, even if the requesting definition is different. resolver.VerifyResolutionAttempts( "A -> D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "M.netmodule -> B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); } /// <summary> /// Don't try to resolve AssemblyRefs that already match explicitly specified definition. /// </summary> [Fact] public void MissingAssemblyResolution_BindingToForExplicitReference1() { // c - a -> "b,v1" // - "b,v3" // var b1Ref = CreateStandardCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class B { }", options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateStandardCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class B { }", options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateStandardCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public class B { }", options: s_signedDll, assemblyName: "B").EmitToImageReference(); var aRef = CreateStandardCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class A : B { }", new[] { b1Ref }, options: s_signedDll, assemblyName: "A").EmitToImageReference(); var resolver = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { // the compiler asked for v1, but we have v2 { "B, 1.0.0.0", b2Ref } }); var c = CreateStandardCompilation("public class C : A { }", new[] { aRef, b3Ref }, s_signedDll.WithMetadataReferenceResolver(resolver)); c.VerifyEmitDiagnostics( // (1,18): warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "A").WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B")); Assert.Equal( "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", ((AssemblySymbol)c.GetAssemblyOrModuleSymbol(b3Ref)).Identity.GetDisplayName()); Assert.Null((AssemblySymbol)c.GetAssemblyOrModuleSymbol(b2Ref)); resolver.VerifyResolutionAttempts(); } /// <summary> /// Don't try to resolve AssemblyRefs that already match explicitly specified definition. /// </summary> [NoIOperationValidationFact] public void MissingAssemblyResolution_BindingToExplicitReference_WorseVersion() { // c - a -> d -> "b,v2" // e -> "b,v1" // - "b,v1" var b1Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var resolverA = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 2.0.0.0", b2Ref }, { "B, 1.0.0.0", b1Ref }, }); var aRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef }, s_signedDll.WithMetadataReferenceResolver(resolverA), assemblyName: "A").EmitToImageReference(); Assert.Equal(2, resolverA.ResolutionAttempts.Count); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, }); var c = CreateCompilation("public class C : A { }", new[] { MscorlibRef, aRef, b1Ref }, s_signedDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // (1,14): error CS1705: Assembly // 'A' with identity 'A, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly // 'B' with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion, "C").WithArguments( "A", "A, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"), // (1,14): error CS1705: Assembly // 'D' with identity 'D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' uses // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' which has a higher version than referenced assembly // 'B' with identity 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' Diagnostic(ErrorCode.ERR_AssemblyMatchBadVersion, "C").WithArguments( "D", "D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B", "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2")); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "B, Version=1.0.0.0", "D, Version=1.0.0.0", "E, Version=1.0.0.0"); } /// <summary> /// Don't try to resolve AssemblyRefs that already match explicitly specified definition. /// </summary> [NoIOperationValidationFact] public void MissingAssemblyResolution_BindingToExplicitReference_BetterVersion() { // c - a -> d -> "b,v2" // e -> "b,v1" // - "b,v2" var b1Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", references: new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", references: new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var resolverA = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "B, 2.0.0.0", b2Ref }, { "B, 1.0.0.0", b1Ref }, }); var aRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef }, s_signedDll.WithMetadataReferenceResolver(resolverA), assemblyName: "A").EmitToImageReference(); Assert.Equal(2, resolverA.ResolutionAttempts.Count); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, }); var c = CreateCompilation("public class C : A { }", new[] { MscorlibRef, aRef, b2Ref }, s_signedDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // (1,14): warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by // 'A' matches identity 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "C").WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B"), // (1,14): warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'E' matches identity // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "C").WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "E", "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B")); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "B, Version=2.0.0.0", "D, Version=1.0.0.0", "E, Version=1.0.0.0"); } [Fact] public void MissingAssemblyResolution_BindingToImplicitReference1() { // c - a -> d -> "b,v2" // e -> "b,v1" // "b,v1" // "b,v2" var b1Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var aRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef, b1Ref, b2Ref }, s_signedDll, assemblyName: "A").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, { "B, 1.0.0.0", b1Ref }, { "B, 2.0.0.0", b2Ref }, }); var c = CreateSubmissionWithExactReferences("public class C : A { }", new[] { MscorlibRef_v4_0_30316_17626, aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics(); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "D, Version=1.0.0.0", "B, Version=2.0.0.0", "E, Version=1.0.0.0", "B, Version=1.0.0.0: <superseded>"); } [Fact] public void MissingAssemblyResolution_BindingToImplicitReference2() { // c - a -> d -> "b,v2" // e -> "b,v1" // "b,v1" // "b,v2" var b1Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var aRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef, b1Ref, b2Ref }, s_signedDll, assemblyName: "A").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, { "B, 1.0.0.0", b3Ref }, { "B, 2.0.0.0", b4Ref }, }); var c = CreateCompilation("public class C : A { }", new[] { MscorlibRef, aRef }, s_signedDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // (1,14): warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "C").WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B"), // (1,14): warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'D' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "C").WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "D", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B"), // (1,14): warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'E' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "C").WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "E", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B")); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "D, Version=1.0.0.0", "B, Version=4.0.0.0", "E, Version=1.0.0.0", "B, Version=3.0.0.0"); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); } [Fact] public void MissingAssemblyResolution_BindingToImplicitReference3() { // c - a -> d -> "b,v2" // e -> "b,v1" // "b,v1" // "b,v2" var b1Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b2Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b3Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""3.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var b4Ref = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""4.0.0.0"")] public interface B { }", new[] { MscorlibRef }, options: s_signedDll, assemblyName: "B").EmitToImageReference(); var dRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface D : B { }", new[] { MscorlibRef, b2Ref }, options: s_signedDll, assemblyName: "D").EmitToImageReference(); var eRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface E : B { }", new[] { MscorlibRef, b1Ref }, options: s_signedDll, assemblyName: "E").EmitToImageReference(); var aRef = CreateCompilation(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public interface A : D, E { }", new[] { MscorlibRef, dRef, eRef, b1Ref, b2Ref }, s_signedDll, assemblyName: "A").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "D, 1.0.0.0", dRef }, { "E, 1.0.0.0", eRef }, { "B, 1.0.0.0", b3Ref }, { "B, 2.0.0.0", b4Ref }, }); var c = CreateSubmissionWithExactReferences("public class C : A { }", new[] { MscorlibRef_v4_0_30316_17626, aRef }, TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics( // (1,14): warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'A' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "C").WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B"), // (1,14): warning CS1701: Assuming assembly reference // 'B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'D' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "C").WithArguments( "B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "D", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B"), // (1,14): warning CS1701: Assuming assembly reference // 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' used by 'E' matches identity // 'B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2' of 'B', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin, "C").WithArguments( "B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "E", "B, Version=3.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "B")); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=1.0.0.0", "D, Version=1.0.0.0", "B, Version=4.0.0.0", "E, Version=1.0.0.0", "B, Version=3.0.0.0: <superseded>"); resolverC.VerifyResolutionAttempts( "A -> D, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=2.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> E, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "A -> B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2"); } [Fact] public void MissingAssemblyResolution_Supersession_FxUnification() { var options = TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); // c - "mscorlib, v4" // a -> "mscorlib, v2" // "System, v2" // b -> "mscorlib, v4" // "System, v4" var aRef = CreateCompilation(@"public interface A { System.Diagnostics.Process PA { get; } }", new[] { TestReferences.NetFx.v2_0_50727.mscorlib, TestReferences.NetFx.v2_0_50727.System }, options: options, assemblyName: "A").EmitToImageReference(); var bRef = CreateCompilation(@"public interface B { System.Diagnostics.Process PB { get; } }", new[] { MscorlibRef_v4_0_30316_17626, TestReferences.NetFx.v4_0_30319.System }, options: options, assemblyName: "B").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "System, 2.0.0.0", TestReferences.NetFx.v2_0_50727.System }, { "System, 4.0.0.0", TestReferences.NetFx.v4_0_30319.System }, }); var c = CreateSubmissionWithExactReferences("public interface C : A, B { System.Diagnostics.Process PC { get; } }", new[] { MscorlibRef_v4_0_30316_17626, aRef, bRef }, options.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics(); resolverC.VerifyResolutionAttempts( "B -> System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.dll -> System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.dll -> System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "A -> System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.dll -> System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.dll -> System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "B, Version=0.0.0.0", "System, Version=4.0.0.0", "System, Version=2.0.0.0: <superseded>"); } [Fact] public void MissingAssemblyResolution_Supersession_StrongNames() { var options = TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); // c - a -> "C, v2" // b -> "C, v1" var aRef = CreateCompilation(@"public interface A { C CA { get; } }", new[] { MscorlibRef, TestReferences.SymbolsTests.Versioning.C2 }, options: options, assemblyName: "A").EmitToImageReference(); var bRef = CreateCompilation(@"public interface B { C CB { get; } }", new[] { MscorlibRef, TestReferences.SymbolsTests.Versioning.C1 }, options: options, assemblyName: "B").EmitToImageReference(); var resolverC = new TestMissingMetadataReferenceResolver(new Dictionary<string, MetadataReference> { { "C, 1.0.0.0", TestReferences.SymbolsTests.Versioning.C1 }, { "C, 2.0.0.0", TestReferences.SymbolsTests.Versioning.C2 }, }); var c = CreateSubmissionWithExactReferences("public interface D : A, B { C CC { get; } }", new[] { MscorlibRef_v4_0_30316_17626, aRef, bRef }, options.WithMetadataReferenceResolver(resolverC)); c.VerifyEmitDiagnostics(); resolverC.VerifyResolutionAttempts( "B -> C, Version=1.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9", "A -> C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=374d0c2befcd8cc9"); c.VerifyAssemblyVersionsAndAliases( "mscorlib, Version=4.0.0.0", "A, Version=0.0.0.0", "B, Version=0.0.0.0", "C, Version=1.0.0.0: <superseded>", "C, Version=2.0.0.0"); } } }
48.40751
332
0.617431
[ "Apache-2.0" ]
KlausLoeffelmann/VBPS-pub
src/Compilers/CSharp/Test/Symbol/Compilation/ReferenceManagerTests.cs
157,278
C#
using GrammarNazi.Core.Extensions; using GrammarNazi.Domain.BotCommands; using GrammarNazi.Domain.Constants; using GrammarNazi.Domain.Enums; using GrammarNazi.Domain.Services; using GrammarNazi.Domain.Utilities; using System.Text; using System.Threading.Tasks; using Telegram.Bot.Types; namespace GrammarNazi.Core.BotCommands.Telegram { public class LanguageCommand : BaseTelegramCommand, ITelegramBotCommand { private readonly IChatConfigurationService _chatConfigurationService; public string Command => TelegramBotCommands.Language; public LanguageCommand(IChatConfigurationService chatConfigurationService, ITelegramBotClientWrapper telegramBotClient) : base(telegramBotClient) { _chatConfigurationService = chatConfigurationService; } public async Task Handle(Message message) { await SendTypingNotification(message); var messageBuilder = new StringBuilder(); if (!await IsUserAdmin(message)) { messageBuilder.AppendLine("Only admins can use this command."); await Client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString(), replyToMessageId: message.MessageId); return; } var parameters = message.Text.Split(" "); if (parameters.Length == 1) { await ShowOptions<SupportedLanguages>(message, "Choose Language"); } else { bool parsedOk = int.TryParse(parameters[1], out int language); if (parsedOk && language.IsAssignableToEnum<SupportedLanguages>()) { var chatConfig = await _chatConfigurationService.GetConfigurationByChatId(message.Chat.Id); chatConfig.SelectedLanguage = (SupportedLanguages)language; await _chatConfigurationService.Update(chatConfig); await Client.SendTextMessageAsync(message.Chat.Id, "Language updated."); } else { await Client.SendTextMessageAsync(message.Chat.Id, $"Invalid parameter. Type {TelegramBotCommands.Language} <language_number> to set a language."); } } await NotifyIfBotIsNotAdmin(message); } } }
35.940299
167
0.634551
[ "MIT" ]
Jadhielv/grammar-nazi-bot
GrammarNazi.Core/BotCommands/Telegram/LanguageCommand.cs
2,410
C#
// **************************************************************************************** // **************************************************************************************** // Programmer: Paul F. Sirpenski // FileName: RssChannelSkipHours.cs // Copyright: Copyright 2019. Paul F. Sirpenski. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // **************************************************************************************** // **************************************************************************************** using System; using Sirpenski.Syndication.Rss20.Core; namespace Sirpenski.Syndication.Rss20 { /// <summary> /// The channel's skipHours collection identifies the hours of the day during which the feed is not updated (optional). /// This collection contains individual hour elements identifying the hours to skip. /// </summary> [Serializable] public class RssChannelSkipHours: RssCoreChannelSkipHours { } }
36.390244
124
0.553619
[ "Apache-2.0" ]
sirpenski/sirpenski-syndication-rss20
Sirpenski.Syndication.Rss20/Rss20/RssChannelSkipHours.cs
1,494
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Turmerik.WebApi.TestApp.Migrations { public partial class FirstCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(type: "TEXT", nullable: false), Name = table.Column<string>(type: "TEXT", maxLength: 256, nullable: true), NormalizedName = table.Column<string>(type: "TEXT", maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(type: "TEXT", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(type: "TEXT", nullable: false), Firstname = table.Column<string>(type: "TEXT", nullable: true), LastName = table.Column<string>(type: "TEXT", nullable: true), UserName = table.Column<string>(type: "TEXT", maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(type: "TEXT", maxLength: 256, nullable: true), Email = table.Column<string>(type: "TEXT", maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(type: "TEXT", maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(type: "INTEGER", nullable: false), PasswordHash = table.Column<string>(type: "TEXT", nullable: true), SecurityStamp = table.Column<string>(type: "TEXT", nullable: true), ConcurrencyStamp = table.Column<string>(type: "TEXT", nullable: true), PhoneNumber = table.Column<string>(type: "TEXT", nullable: true), PhoneNumberConfirmed = table.Column<bool>(type: "INTEGER", nullable: false), TwoFactorEnabled = table.Column<bool>(type: "INTEGER", nullable: false), LockoutEnd = table.Column<DateTimeOffset>(type: "TEXT", nullable: true), LockoutEnabled = table.Column<bool>(type: "INTEGER", nullable: false), AccessFailedCount = table.Column<int>(type: "INTEGER", nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), RoleId = table.Column<string>(type: "TEXT", nullable: false), ClaimType = table.Column<string>(type: "TEXT", nullable: true), ClaimValue = table.Column<string>(type: "TEXT", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(type: "INTEGER", nullable: false) .Annotation("Sqlite:Autoincrement", true), UserId = table.Column<string>(type: "TEXT", nullable: false), ClaimType = table.Column<string>(type: "TEXT", nullable: true), ClaimValue = table.Column<string>(type: "TEXT", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false), ProviderKey = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false), ProviderDisplayName = table.Column<string>(type: "TEXT", nullable: true), UserId = table.Column<string>(type: "TEXT", nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(type: "TEXT", nullable: false), RoleId = table.Column<string>(type: "TEXT", nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(type: "TEXT", nullable: false), LoginProvider = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false), Name = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false), Value = table.Column<string>(type: "TEXT", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
45.236364
108
0.496282
[ "MIT" ]
dantincu/turmerik
dotnet/__EXT__/Turmerik.WebApi.TestApp/Migrations/20210709071112_First-Create.cs
9,954
C#
using System; namespace OurUmbraco.Repository.Models { internal class PackageVersionSupport : IEquatable<PackageVersionSupport> { private readonly int _fileId; public PackageVersionSupport(int fileId, System.Version packageVersion, System.Version minUmbracoVersion) { _fileId = fileId; MinUmbracoVersion = minUmbracoVersion; PackageVersion = packageVersion; } public int FileId { get { return _fileId; } } public System.Version MinUmbracoVersion { get; private set; } public System.Version PackageVersion { get; private set; } public bool Equals(PackageVersionSupport other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return _fileId == other._fileId; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((PackageVersionSupport) obj); } public override int GetHashCode() { return _fileId; } public static bool operator ==(PackageVersionSupport left, PackageVersionSupport right) { return Equals(left, right); } public static bool operator !=(PackageVersionSupport left, PackageVersionSupport right) { return !Equals(left, right); } } }
29.944444
113
0.602968
[ "MIT" ]
AaronSadlerUK/OurUmbraco
OurUmbraco/Repository/Models/PackageVersionSupport.cs
1,619
C#
using System; using System.Collections.Generic; using System.Text; namespace PhotoOrganizer.Core { /// <summary> /// Utility class useful for giving descriptive, non-throwing reports on operations. /// </summary> public class Result { /// <summary> /// The message explaing the error. If the operation succeeded, then this returns String.Empty() /// </summary> public string Message { get; private set; } /// <summary> /// Returns true if the operation succeeded, else false. /// </summary> public bool Successful { get; private set; } /// <summary> /// Creates a FAILING result with the given message /// </summary> /// <param name="message">Message to explain failure</param> /// <param name="args">Optional array of objects to use when formatting the string.</param> private Result(string message) { Message = message; Successful = false; } /// <summary> /// Creates a PASSING result /// </summary> private Result() { Message = String.Empty; Successful = true; } /// <summary> /// Returns a Successful Result /// </summary> /// <returns></returns> public static Result Success() { return new Result(); } /// <summary> /// Returns a Result indicating FAILURE. /// </summary> /// <returns></returns> public static Result Failure() { return new Result() { Successful = false }; } /// <summary> /// Returns a Result inidicating FAILURE with the given message. /// </summary> /// <param name="message"></param> /// <returns></returns> public static Result Failure(string message) { return new Result(message); } } /// <summary> /// Utility class useful for giving descriptive, non-throwing reports on operations, and returning strongly-typed objects. /// </summary> public class Result<T> { /// <summary> /// The message explaing the error. If the operation succeeded, then this returns String.Empty() /// </summary> public string Message { get; private set; } /// <summary> /// Returns true if the operation succeeded, else false. /// </summary> public bool Successful { get; private set; } /// <summary> /// Contains data associated with the operation /// </summary> public T Data { get; private set; } /// <summary> /// Creates a FAILING result with the given message /// </summary> /// <param name="message">Message to explain failure</param> private Result(string message) { Message = message; Successful = false; } /// <summary> /// Creates a PASSING result /// </summary> private Result() { Message = String.Empty; Successful = true; } /// <summary> /// Returns a Successful Result with no data /// </summary> /// <returns></returns> public static Result<T> Success() { return new Result<T>(); } /// <summary> /// Returns a passing Result with the given data /// </summary> /// <param name="data"></param> /// <returns></returns> public static Result<T> Success(T data) { return new Result<T>() { Data = data }; } /// <summary> /// Returns a Result indicating FAILURE with the given message /// </summary> /// <param name="message">The message to explain the failure</param> /// <param name="args">Optional array of objects to use when formatting the string.</param> /// <returns>A result indicating FAILURE with the given message</returns> public static Result<T> Failure(string message) { return new Result<T>(message); } /// <summary> /// Returns a Result indicating FAILURE with the given message and data /// </summary> /// <param name="message">The message to explain the failure</param> /// <param name="args">Optional array of objects to use when formatting the string.</param> /// <returns>A result indicating FAILURE with the given message</returns> public static Result<T> Failure(string message, T data) { return new Result<T>(message) { Data = data }; } } }
30.832258
126
0.538816
[ "MIT" ]
greatest-gatsby/photo-organizer
PhotoOrganizer.Core/Result.cs
4,781
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Microsoft.AspNet.SignalR.Hubs { public class ReflectedHubDescriptorProvider : IHubDescriptorProvider { private readonly Lazy<IDictionary<string, HubDescriptor>> _hubs; private readonly Lazy<IAssemblyLocator> _locator; public ReflectedHubDescriptorProvider(IDependencyResolver resolver) { _locator = new Lazy<IAssemblyLocator>(resolver.Resolve<IAssemblyLocator>); _hubs = new Lazy<IDictionary<string, HubDescriptor>>(BuildHubsCache); } public IList<HubDescriptor> GetHubs() { return _hubs.Value .Select(kv => kv.Value) .Distinct() .ToList(); } public bool TryGetHub(string hubName, out HubDescriptor descriptor) { return _hubs.Value.TryGetValue(hubName, out descriptor); } protected IDictionary<string, HubDescriptor> BuildHubsCache() { // Getting all IHub-implementing types that apply var types = _locator.Value.GetAssemblies() .SelectMany(GetTypesSafe) .Where(IsHubType); // Building cache entries for each descriptor // Each descriptor is stored in dictionary under a key // that is it's name or the name provided by an attribute var cacheEntries = types .Select(type => new HubDescriptor { NameSpecified = (type.GetHubAttributeName() != null), Name = type.GetHubName(), HubType = type }) .ToDictionary(hub => hub.Name, hub => hub, StringComparer.OrdinalIgnoreCase); return cacheEntries; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "If we throw then it's not a hub type")] private static bool IsHubType(Type type) { try { return typeof(IHub).IsAssignableFrom(type) && !type.IsAbstract && (type.Attributes.HasFlag(TypeAttributes.Public) || type.Attributes.HasFlag(TypeAttributes.NestedPublic)); } catch { return false; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "If we throw then we have an empty type")] private static IEnumerable<Type> GetTypesSafe(Assembly a) { try { return a.GetTypes(); } catch { return Enumerable.Empty<Type>(); } } } }
36.920455
177
0.547245
[ "Apache-2.0" ]
AlaShiban/SignalR
src/Microsoft.AspNet.SignalR.Core/Hubs/Lookup/ReflectedHubDescriptorProvider.cs
3,251
C#
using System.Threading.Tasks; using SmartHotel.Clients.Core.Services.Hotel; using SmartHotel.Clients.Core.ViewModels.Base; using System.Collections.Generic; using System; using System.Windows.Input; using Xamarin.Forms; using System.Net.Http; using System.Diagnostics; using MvvmHelpers; using SmartHotel.Clients.Core.Extensions; using SmartHotel.Clients.Core.Exceptions; namespace SmartHotel.Clients.Core.ViewModels { public class BookingHotelsViewModel : ViewModelBase { ObservableRangeCollection<Models.Hotel> hotels; Models.City city; DateTime from; DateTime until; readonly IHotelService hotelService; public BookingHotelsViewModel(IHotelService hotelService) => this.hotelService = hotelService; public Models.City City { get => city; set => SetProperty(ref city, value); } public DateTime From { get => from; set => SetProperty(ref from, value); } public DateTime Until { get => until; set => SetProperty(ref until, value); } public ObservableRangeCollection<Models.Hotel> Hotels { get => hotels; set => SetProperty(ref hotels, value); } public ICommand HotelSelectedCommand => new Command<Models.Hotel>(OnSelectHotelAsync); public override async Task InitializeAsync(object navigationData) { if (navigationData != null) { var navigationParameter = navigationData as Dictionary<string, object>; City = navigationParameter["city"] as Models.City; From = (DateTime)navigationParameter["from"]; Until = (DateTime)navigationParameter["until"]; } try { IsBusy = true; var hotels = await hotelService.SearchAsync(City.Id); Hotels = hotels.ToObservableRangeCollection(); } catch (HttpRequestException httpEx) { Debug.WriteLine($"[Booking Hotels Step] Error retrieving data: {httpEx}"); if (!string.IsNullOrEmpty(httpEx.Message)) { await DialogService.ShowAlertAsync( string.Format(Resources.HttpRequestExceptionMessage, httpEx.Message), Resources.HttpRequestExceptionTitle, Resources.DialogOk); } } catch (ConnectivityException cex) { Debug.WriteLine($"[Booking Hotels Step] Connectivity Error: {cex}"); await DialogService.ShowAlertAsync("There is no Internet conection, try again later.", "Error", "Ok"); } catch (Exception ex) { Debug.WriteLine($"[Booking Hotels Step] Error: {ex}"); await DialogService.ShowAlertAsync( Resources.ExceptionMessage, Resources.ExceptionTitle, Resources.DialogOk); } finally { IsBusy = false; } } async void OnSelectHotelAsync(Models.Hotel item) { if (item != null) { var navigationParameter = new Dictionary<string, object> { { "hotel", item }, { "from", From }, { "until", Until }, }; await NavigationService.NavigateToAsync<BookingHotelViewModel>(navigationParameter); } } } }
31.794872
118
0.550538
[ "MIT" ]
ATH89/SmartHotel360_w8bghybo
Source/SmartHotel.Clients/SmartHotel.Clients/ViewModels/BookingHotelsViewModel.cs
3,722
C#
using System; using System.Collections.Specialized; using System.ComponentModel; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Media; using Xamarin.Forms.Internals; using Xamarin.Forms.PlatformConfiguration.WindowsSpecific; using WGrid = Windows.UI.Xaml.Controls.Grid; using WTextAlignment = Windows.UI.Xaml.TextAlignment; using WHorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment; using WVisibility = Windows.UI.Xaml.Visibility; using WStackPanel = Windows.UI.Xaml.Controls.StackPanel; using WImage = Windows.UI.Xaml.Controls.Image; using WTextBlock = Windows.UI.Xaml.Controls.TextBlock; using Specifics = Xamarin.Forms.PlatformConfiguration.WindowsSpecific.TabbedPage; using VisualElementSpecifics = Xamarin.Forms.PlatformConfiguration.WindowsSpecific.VisualElement; using PageSpecifics = Xamarin.Forms.PlatformConfiguration.WindowsSpecific.Page; using Windows.UI.Xaml.Input; namespace Xamarin.Forms.Platform.UWP { public class TabbedPageRenderer : IVisualElementRenderer, ITitleProvider, IToolbarProvider, IToolBarForegroundBinder { const string TabBarHeaderStackPanelName = "TabbedPageHeaderStackPanel"; const string TabBarHeaderImageName = "TabbedPageHeaderImage"; const string TabBarHeaderTextBlockName = "TabbedPageHeaderTextBlock"; const string TabBarHeaderGridName = "TabbedPageHeaderGrid"; Color _barBackgroundColor; Color _barTextColor; bool _disposed; bool _showTitle; WTextAlignment _oldBarTextBlockTextAlignment = WTextAlignment.Center; WHorizontalAlignment _oldBarTextBlockHorinzontalAlignment = WHorizontalAlignment.Center; VisualElementTracker<Page, Pivot> _tracker; ITitleProvider TitleProvider => this; public FormsPivot Control { get; private set; } public TabbedPage Element { get; private set; } protected VisualElementTracker<Page, Pivot> Tracker { get { return _tracker; } set { if (_tracker == value) return; if (_tracker != null) _tracker.Dispose(); _tracker = value; } } public void Dispose() { Dispose(true); } Brush ITitleProvider.BarBackgroundBrush { set { Control.ToolbarBackground = value; } } Brush ITitleProvider.BarForegroundBrush { set { Control.ToolbarForeground = value; } } bool ITitleProvider.ShowTitle { get { return _showTitle; } set { if (_showTitle == value) return; _showTitle = value; UpdateTitleVisibility(); } } string ITitleProvider.Title { get { return (string)Control?.Title; } set { if (Control != null && _showTitle) Control.Title = value; } } public Task<CommandBar> GetCommandBarAsync() { return (Control as IToolbarProvider)?.GetCommandBarAsync(); } public FrameworkElement ContainerElement { get { return Control; } } VisualElement IVisualElementRenderer.Element { get { return Element; } } public event EventHandler<VisualElementChangedEventArgs> ElementChanged; public SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint) { var constraint = new Windows.Foundation.Size(widthConstraint, heightConstraint); double oldWidth = Control.Width; double oldHeight = Control.Height; Control.Height = double.NaN; Control.Width = double.NaN; Control.Measure(constraint); var result = new Size(Math.Ceiling(Control.DesiredSize.Width), Math.Ceiling(Control.DesiredSize.Height)); Control.Width = oldWidth; Control.Height = oldHeight; return new SizeRequest(result); } UIElement IVisualElementRenderer.GetNativeElement() { return Control; } public void SetElement(VisualElement element) { if (element != null && !(element is TabbedPage)) throw new ArgumentException("Element must be a TabbedPage", "element"); TabbedPage oldElement = Element; Element = (TabbedPage)element; if (oldElement != null) { oldElement.PropertyChanged -= OnElementPropertyChanged; ((INotifyCollectionChanged)oldElement.Children).CollectionChanged -= OnPagesChanged; Control?.GetDescendantsByName<TextBlock>(TabBarHeaderTextBlockName).ForEach(t => { t.AccessKeyInvoked -= AccessKeyInvokedForTab; }); } if (element != null) { if (Control == null) { Control = new FormsPivot { Style = (Windows.UI.Xaml.Style)Windows.UI.Xaml.Application.Current.Resources["TabbedPageStyle"], }; Control.SelectionChanged += OnSelectionChanged; Tracker = new BackgroundTracker<Pivot>(Windows.UI.Xaml.Controls.Control.BackgroundProperty) { Element = (Page)element, Control = Control, Container = Control }; Control.Loaded += OnLoaded; Control.Unloaded += OnUnloaded; } Control.DataContext = Element; OnPagesChanged(Element.Children, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); UpdateCurrentPage(); UpdateToolbarPlacement(); ((INotifyCollectionChanged)Element.Children).CollectionChanged += OnPagesChanged; element.PropertyChanged += OnElementPropertyChanged; if (!string.IsNullOrEmpty(element.AutomationId)) Control.SetValue(Windows.UI.Xaml.Automation.AutomationProperties.AutomationIdProperty, element.AutomationId); } OnElementChanged(new VisualElementChangedEventArgs(oldElement, element)); } protected virtual void Dispose(bool disposing) { if (!disposing || _disposed) return; _disposed = true; Element?.SendDisappearing(); SetElement(null); Tracker = null; } protected virtual void OnElementChanged(VisualElementChangedEventArgs e) { ElementChanged?.Invoke(this, e); } void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(TabbedPage.CurrentPage)) { UpdateCurrentPage(); UpdateBarTextColor(); UpdateBarBackgroundColor(); } else if (e.PropertyName == TabbedPage.BarTextColorProperty.PropertyName) UpdateBarTextColor(); else if (e.PropertyName == TabbedPage.BarBackgroundColorProperty.PropertyName) UpdateBarBackgroundColor(); else if (e.PropertyName == PlatformConfiguration.WindowsSpecific.Page.ToolbarPlacementProperty.PropertyName) UpdateToolbarPlacement(); else if (e.PropertyName == Specifics.HeaderIconsEnabledProperty.PropertyName) UpdateBarIcons(); else if (e.PropertyName == Specifics.HeaderIconsSizeProperty.PropertyName) UpdateBarIcons(); else if (e.PropertyName == PageSpecifics.ToolbarPlacementProperty.PropertyName) UpdateToolbarPlacement(); } void OnLoaded(object sender, RoutedEventArgs args) { Element?.SendAppearing(); UpdateBarTextColor(); UpdateBarBackgroundColor(); UpdateBarIcons(); UpdateAccessKeys(); } void OnPagesChanged(object sender, NotifyCollectionChangedEventArgs e) { e.Apply(Element.Children, Control.Items); switch (e.Action) { case NotifyCollectionChangedAction.Add: case NotifyCollectionChangedAction.Remove: case NotifyCollectionChangedAction.Replace: if (e.NewItems != null) for (int i = 0; i< e.NewItems.Count; i++) ((Page)e.NewItems[i]).PropertyChanged += OnChildPagePropertyChanged; if (e.OldItems != null) for (int i = 0; i < e.OldItems.Count; i++) ((Page)e.OldItems[i]).PropertyChanged -= OnChildPagePropertyChanged; break; case NotifyCollectionChangedAction.Reset: foreach (var page in Element.Children) page.PropertyChanged += OnChildPagePropertyChanged; break; } Control.UpdateLayout(); EnsureBarColors(e.Action); } void EnsureBarColors(NotifyCollectionChangedAction action) { switch (action) { case NotifyCollectionChangedAction.Add: case NotifyCollectionChangedAction.Replace: case NotifyCollectionChangedAction.Reset: // Need to make sure any new items have the correct fore/background colors ApplyBarBackgroundColor(true); ApplyBarTextColor(true); break; } } void OnChildPagePropertyChanged(object sender, PropertyChangedEventArgs e) { var page = sender as Page; if (page != null) { // If AccessKeys properties are updated on a child (tab) we want to // update the access key on the native control. if (e.PropertyName == VisualElementSpecifics.AccessKeyProperty.PropertyName || e.PropertyName == VisualElementSpecifics.AccessKeyPlacementProperty.PropertyName || e.PropertyName == VisualElementSpecifics.AccessKeyHorizontalOffsetProperty.PropertyName || e.PropertyName == VisualElementSpecifics.AccessKeyVerticalOffsetProperty.PropertyName) UpdateAccessKeys(); } } void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if (Element == null) return; Page page = e.AddedItems.Count > 0 ? (Page)e.AddedItems[0] : null; Page currentPage = Element.CurrentPage; if (currentPage == page) return; currentPage?.SendDisappearing(); Element.CurrentPage = page; page?.SendAppearing(); } void OnUnloaded(object sender, RoutedEventArgs args) { Element?.SendDisappearing(); } Brush GetBarBackgroundBrush() { object defaultColor = new SolidColorBrush(Windows.UI.Colors.Transparent); if (Element.BarBackgroundColor.IsDefault && defaultColor != null) return (Brush)defaultColor; return Element.BarBackgroundColor.ToBrush(); } Brush GetBarForegroundBrush() { object defaultColor = Windows.UI.Xaml.Application.Current.Resources["ApplicationForegroundThemeBrush"]; if (Element.BarTextColor.IsDefault && defaultColor != null) return (Brush)defaultColor; return Element.BarTextColor.ToBrush(); } void UpdateBarBackgroundColor() { if (Element == null) return; var barBackgroundColor = Element.BarBackgroundColor; if (barBackgroundColor == _barBackgroundColor) return; _barBackgroundColor = barBackgroundColor; ApplyBarBackgroundColor(); } void ApplyBarBackgroundColor(bool force = false) { var controlToolbarBackground = Control.ToolbarBackground; if (controlToolbarBackground == null && _barBackgroundColor.IsDefault) return; var brush = GetBarBackgroundBrush(); if (brush == controlToolbarBackground && !force) return; TitleProvider.BarBackgroundBrush = brush; foreach (WGrid tabBarGrid in Control.GetDescendantsByName<WGrid>(TabBarHeaderGridName)) { tabBarGrid.Background = brush; } } void UpdateBarTextColor() { if (Element == null) return; var barTextColor = Element.BarTextColor; if (barTextColor == _barTextColor) return; _barTextColor = barTextColor; ApplyBarTextColor(); } void ApplyBarTextColor(bool force = false) { var controlToolbarForeground = Control.ToolbarForeground; if (controlToolbarForeground == null && _barTextColor.IsDefault) return; var brush = GetBarForegroundBrush(); if (brush == controlToolbarForeground && !force) return; TitleProvider.BarForegroundBrush = brush; foreach (WTextBlock tabBarTextBlock in Control.GetDescendantsByName<WTextBlock>(TabBarHeaderTextBlockName)) { tabBarTextBlock.Foreground = brush; } } void UpdateTitleVisibility() { Control.TitleVisibility = _showTitle ? WVisibility.Visible : WVisibility.Collapsed; } void UpdateCurrentPage() { Page page = Element.CurrentPage; var nav = page as NavigationPage; TitleProvider.ShowTitle = nav != null; // Enforce consistency rules on toolbar (show toolbar if visible Tab is Navigation Page) Control.ShouldShowToolbar = nav != null; if (page == null) return; Control.SelectedItem = page; } void UpdateBarIcons() { if (Control == null) return; if (Element.IsSet(Specifics.HeaderIconsEnabledProperty)) { bool headerIconsEnabled = Element.OnThisPlatform().GetHeaderIconsEnabled(); bool invalidateMeasure = false; // Get all stack panels affected by update. var stackPanels = Control.GetDescendantsByName<WStackPanel>(TabBarHeaderStackPanelName); foreach (var stackPanel in stackPanels) { int stackPanelChildCount = stackPanel.Children.Count; for (int i = 0; i < stackPanelChildCount; i++) { var stackPanelItem = stackPanel.Children[i]; if (stackPanelItem is WImage tabBarImage) { // Update icon image. if (tabBarImage.GetValue(FrameworkElement.NameProperty).ToString() == TabBarHeaderImageName) { if (headerIconsEnabled) { if (Element.IsSet(Specifics.HeaderIconsSizeProperty)) { Size iconSize = Element.OnThisPlatform().GetHeaderIconsSize(); tabBarImage.Height = iconSize.Height; tabBarImage.Width = iconSize.Width; } tabBarImage.HorizontalAlignment = WHorizontalAlignment.Center; tabBarImage.Visibility = WVisibility.Visible; } else { tabBarImage.Visibility = WVisibility.Collapsed; } invalidateMeasure = true; } } else if (stackPanelItem is WTextBlock tabBarTextblock) { // Update text block. if (tabBarTextblock.GetValue(FrameworkElement.NameProperty).ToString() == TabBarHeaderTextBlockName) { if (headerIconsEnabled) { // Remember old values so we can restore them if icons are collapsed. // NOTE, since all Textblock instances in this stack panel comes from the same // style, we just keep one copy of the value (since they should be identical). if (tabBarTextblock.TextAlignment != WTextAlignment.Center) { _oldBarTextBlockTextAlignment = tabBarTextblock.TextAlignment; tabBarTextblock.TextAlignment = WTextAlignment.Center; } if (tabBarTextblock.HorizontalAlignment != WHorizontalAlignment.Center) { _oldBarTextBlockHorinzontalAlignment = tabBarTextblock.HorizontalAlignment; tabBarTextblock.HorizontalAlignment = WHorizontalAlignment.Center; } } else { // Restore old values. tabBarTextblock.TextAlignment = _oldBarTextBlockTextAlignment; tabBarTextblock.HorizontalAlignment = _oldBarTextBlockHorinzontalAlignment; } } } } } // If items have been made visible or collapsed in panel, invalidate current control measures. if (invalidateMeasure) Control.InvalidateMeasure(); } } void UpdateToolbarPlacement() { Control.ToolbarPlacement = Element.OnThisPlatform().GetToolbarPlacement(); } protected void UpdateAccessKeys() { Control?.GetDescendantsByName<TextBlock>(TabBarHeaderTextBlockName).ForEach(UpdateAccessKey); } void AccessKeyInvokedForTab(UIElement sender, AccessKeyInvokedEventArgs arg) { var tab = sender as TextBlock; if (tab != null && tab.DataContext is Page page) Element.CurrentPage = page; } protected void UpdateAccessKey(TextBlock control) { if (control != null && control.DataContext is Page page) { var windowsElement = page.On<PlatformConfiguration.Windows>(); if (page.IsSet(VisualElementSpecifics.AccessKeyProperty)) { control.AccessKeyInvoked += AccessKeyInvokedForTab; } AccessKeyHelper.UpdateAccessKey(control, page); } } public void BindForegroundColor(AppBar appBar) { SetAppBarForegroundBinding(appBar); } public void BindForegroundColor(AppBarButton button) { SetAppBarForegroundBinding(button); } void SetAppBarForegroundBinding(FrameworkElement element) { element.SetBinding(Windows.UI.Xaml.Controls.Control.ForegroundProperty, new Windows.UI.Xaml.Data.Binding { Path = new PropertyPath("ToolbarForeground"), Source = Control, RelativeSource = new RelativeSource { Mode = RelativeSourceMode.TemplatedParent } }); } } }
29.532588
136
0.723879
[ "MIT" ]
Sinthya01/Xamarin.Forms
Xamarin.Forms.Platform.UAP/TabbedPageRenderer.cs
15,861
C#
using System; using System.Windows.Media; using PassWinmenu.Utilities; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; #nullable enable namespace PassWinmenu.Configuration { internal class BrushConverter : IYamlTypeConverter { public bool Accepts(Type type) { return type == typeof(Brush); } public object ReadYaml(IParser parser, Type type) { // A brush should be represented as a string value. var value = parser.Consume<Scalar>(); return Helpers.BrushFromColourString(value.Value); } public void WriteYaml(IEmitter emitter, object? value, Type type) { throw new NotImplementedException("Width serialisation is not supported yet."); } } }
23.129032
82
0.751743
[ "MIT" ]
P4ll/pass-winmenu
pass-winmenu/src/Configuration/BrushConverter.cs
717
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/msctf.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("EA1EA138-19DF-11D7-A6D2-00065B84435C")] [NativeTypeName("struct ITfCandidateListUIElement : ITfUIElement")] [NativeInheritance("ITfUIElement")] public unsafe partial struct ITfCandidateListUIElement { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(0)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) { return ((delegate* unmanaged<ITfCandidateListUIElement*, Guid*, void**, int>)(lpVtbl[0]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(1)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<ITfCandidateListUIElement*, uint>)(lpVtbl[1]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(2)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<ITfCandidateListUIElement*, uint>)(lpVtbl[2]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(3)] [return: NativeTypeName("HRESULT")] public int GetDescription([NativeTypeName("BSTR *")] ushort** pbstrDescription) { return ((delegate* unmanaged<ITfCandidateListUIElement*, ushort**, int>)(lpVtbl[3]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), pbstrDescription); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(4)] [return: NativeTypeName("HRESULT")] public int GetGUID([NativeTypeName("GUID *")] Guid* pguid) { return ((delegate* unmanaged<ITfCandidateListUIElement*, Guid*, int>)(lpVtbl[4]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), pguid); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(5)] [return: NativeTypeName("HRESULT")] public int Show([NativeTypeName("BOOL")] int bShow) { return ((delegate* unmanaged<ITfCandidateListUIElement*, int, int>)(lpVtbl[5]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), bShow); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(6)] [return: NativeTypeName("HRESULT")] public int IsShown([NativeTypeName("BOOL *")] int* pbShow) { return ((delegate* unmanaged<ITfCandidateListUIElement*, int*, int>)(lpVtbl[6]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), pbShow); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(7)] [return: NativeTypeName("HRESULT")] public int GetUpdatedFlags([NativeTypeName("DWORD *")] uint* pdwFlags) { return ((delegate* unmanaged<ITfCandidateListUIElement*, uint*, int>)(lpVtbl[7]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), pdwFlags); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(8)] [return: NativeTypeName("HRESULT")] public int GetDocumentMgr(ITfDocumentMgr** ppdim) { return ((delegate* unmanaged<ITfCandidateListUIElement*, ITfDocumentMgr**, int>)(lpVtbl[8]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), ppdim); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(9)] [return: NativeTypeName("HRESULT")] public int GetCount([NativeTypeName("UINT *")] uint* puCount) { return ((delegate* unmanaged<ITfCandidateListUIElement*, uint*, int>)(lpVtbl[9]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), puCount); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(10)] [return: NativeTypeName("HRESULT")] public int GetSelection([NativeTypeName("UINT *")] uint* puIndex) { return ((delegate* unmanaged<ITfCandidateListUIElement*, uint*, int>)(lpVtbl[10]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), puIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(11)] [return: NativeTypeName("HRESULT")] public int GetString([NativeTypeName("UINT")] uint uIndex, [NativeTypeName("BSTR *")] ushort** pstr) { return ((delegate* unmanaged<ITfCandidateListUIElement*, uint, ushort**, int>)(lpVtbl[11]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), uIndex, pstr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(12)] [return: NativeTypeName("HRESULT")] public int GetPageIndex([NativeTypeName("UINT *")] uint* pIndex, [NativeTypeName("UINT")] uint uSize, [NativeTypeName("UINT *")] uint* puPageCnt) { return ((delegate* unmanaged<ITfCandidateListUIElement*, uint*, uint, uint*, int>)(lpVtbl[12]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), pIndex, uSize, puPageCnt); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(13)] [return: NativeTypeName("HRESULT")] public int SetPageIndex([NativeTypeName("UINT *")] uint* pIndex, [NativeTypeName("UINT")] uint uPageCnt) { return ((delegate* unmanaged<ITfCandidateListUIElement*, uint*, uint, int>)(lpVtbl[13]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), pIndex, uPageCnt); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(14)] [return: NativeTypeName("HRESULT")] public int GetCurrentPage([NativeTypeName("UINT *")] uint* puPage) { return ((delegate* unmanaged<ITfCandidateListUIElement*, uint*, int>)(lpVtbl[14]))((ITfCandidateListUIElement*)Unsafe.AsPointer(ref this), puPage); } } }
46.485714
190
0.663337
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/um/msctf/ITfCandidateListUIElement.cs
6,510
C#
using System; using System.Diagnostics; using Xamarin.Forms; namespace TextSample { public class LabelPageCode : ContentPage { public LabelPageCode () { var layout = new StackLayout{ Padding = new Thickness (5, 10) }; layout.Children.Add (new Label { Text = "This is a default, non-customized label." }); layout.Children.Add (new Label { TextColor = Color.FromHex ("#77d065"), Text = "This is a green label." }); layout.Children.Add (new Label { Text = "This label has a font size of 30.", FontSize = 30 }); layout.Children.Add (new Label { Text = "This is bold text that uses character spacing.", FontAttributes = FontAttributes.Bold, CharacterSpacing = 5 }); layout.Children.Add (new Label { Text = "This is <strong style=\"color:red\">HTML</strong> text.", TextType = TextType.Html }); layout.Children.Add (new Label { Text = "This is underlined text.", TextDecorations = TextDecorations.Underline }); layout.Children.Add (new Label { Text = "This is text with strikethrough.", TextDecorations = TextDecorations.Strikethrough }); layout.Children.Add (new Label { Text = "This is underlined text with strikethrough.", TextDecorations = TextDecorations.Underline | TextDecorations.Strikethrough }); // Line height var lineHeightLabel = new Label { Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In facilisis nulla eu felis fringilla vulputate. Nullam porta eleifend lacinia. Donec at iaculis tellus.", LineBreakMode = LineBreakMode.WordWrap, MaxLines=2 }; var entry = new Entry { Placeholder = "Enter line height" }; entry.TextChanged += (sender, e) => { var lineHeight = ((Entry)sender).Text; try { lineHeightLabel.LineHeight = double.Parse(lineHeight); } catch (FormatException ex) { Debug.WriteLine($"Can't parse {lineHeight}. {ex.Message}"); } }; layout.Children.Add(entry); layout.Children.Add(lineHeightLabel); var formattedString = new FormattedString (); formattedString.Spans.Add (new Span{ Text = "Red bold, ", ForegroundColor = Color.Red, FontAttributes = FontAttributes.Bold }); var span = new Span { Text = "default, " }; span.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(async () => await DisplayAlert("Tapped", "This is a tapped Span.", "OK")) }); formattedString.Spans.Add(span); formattedString.Spans.Add (new Span { Text = "italic small.", FontAttributes = FontAttributes.Italic, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)) }); layout.Children.Add (new Label { FormattedText = formattedString }); var formattedStringWithLineHeightSet = new FormattedString(); formattedStringWithLineHeightSet.Spans.Add(new Span { LineHeight = 1.8, Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In a tincidunt sem. Phasellus mollis sit amet turpis in rutrum. Sed aliquam ac urna id scelerisque. " }); formattedStringWithLineHeightSet.Spans.Add(new Span { LineHeight = 1.8, Text = "Nullam feugiat sodales elit, et maximus nibh vulputate id." }); layout.Children.Add(new Label { FormattedText = formattedStringWithLineHeightSet, LineBreakMode = LineBreakMode.WordWrap }); this.Title = "Label Demo - Code"; this.Content = layout; } void OnLineHeightChanged(object sender, TextChangedEventArgs args) { } } }
60.047619
271
0.634946
[ "Apache-2.0" ]
772801206/xamarin-example
UserInterface/Text/TextSample/Views/LabelPageCode.cs
3,785
C#
using IL2Asm.BaseTypes; using System; namespace Plugs { public static class SystemPlugs { [AsmPlug("System.Char.ToString_String", Architecture.X86)] private static void CharToStringAsm(IAssembledMethod assembly) { assembly.AddAsm("push 12"); // 8 bytes for array metadata, then 2 bytes for char and 2 bytes for null termination assembly.AddAsm("push 0"); assembly.AddAsm($"call {assembly.HeapAllocatorMethod}"); // the array is now in eax assembly.AddAsm("mov dword [eax], 2"); // the array length of 2 assembly.AddAsm("mov dword [eax + 4], 2"); // the size per element of 2 assembly.AddAsm("pop ebx"); // the contents to put in the array assembly.AddAsm("mov ebx, [ebx]"); // place the contents in the array assembly.AddAsm("mov [eax + 8], bx"); // place the contents in the array assembly.AddAsm("mov word [eax + 10], 0"); // null terminate the string assembly.AddAsm("push eax"); // push the resulting 'string' object back on to the stack } [AsmPlug("System.Object..ctor_Void", Architecture.X86)] private static void ObjectConstructorAsm(IAssembledMethod assembly) { assembly.AddAsm("pop eax"); } [AsmPlug("System.Action`1.Invoke_Void_Var", Architecture.X86)] private static void ActionInvoke1Asm(IAssembledMethod assembly) { assembly.AddAsm("pop edi"); // pop the arg assembly.AddAsm("pop eax"); // pop the action assembly.AddAsm("mov ebx, [eax + 4]"); // grab the object we're calling this on assembly.AddAsm("push ebx"); // push the object assembly.AddAsm("push edi"); // push the arg again assembly.AddAsm("call [eax]"); } [AsmPlug("System.Action.Invoke_Void", Architecture.X86)] private static void ActionInvokeAsm(IAssembledMethod assembly) { assembly.AddAsm("pop eax"); assembly.AddAsm("call [eax]"); } [CSharpPlug("System.Threading.Thread.Sleep_Void_I4")] private static void ThreadingThreadSleep(int milliseconds) { uint start = Kernel.Devices.PIT.TickCount; uint end = start + Kernel.Devices.PIT.Frequency * (uint)milliseconds / 1000; if (start == end) end++; // delay was less than the accuracy of the timer, so always wait at least 1 tick while (Kernel.Devices.PIT.TickCount < end) ; } [AsmPlug("System.Array.Clear_Void_Class_I4_I4", Architecture.X86, AsmFlags.None)] private static void ArrayClearAsm(IAssembledMethod assembly) { var loopLabel = assembly.GetUniqueLabel("LOOP"); var endLabel = assembly.GetUniqueLabel("END"); var loopLabelByte = assembly.GetUniqueLabel("LOOP_BYTE"); assembly.AddAsm("mov ebx, [esp + 4]"); // length assembly.AddAsm("mov eax, [esp + 8]"); // index assembly.AddAsm("mov esi, [esp + 12]"); // start of array assembly.AddAsm("push ecx"); // we use ecx as 0 assembly.AddAsm("xor ecx, ecx"); assembly.AddAsm("mov edi, [esi + 4]"); // size per element assembly.AddAsm("push edx"); // multiply clobbers edx assembly.AddAsm("mul edi"); // eax now contains index*sizePerElement //assembly.AddAsm("pop edx"); // recover edx after clobber assembly.AddAsm("lea esi, [8 + esi + 1 * eax]"); // actual start of data // the length is in terms of elements, we need to translate to dwords // eax is no longer needed, so we can use it here assembly.AddAsm("mov eax, ebx"); assembly.AddAsm("mul edi"); // eax now contains the length in bytes assembly.AddAsm("pop edx"); // we need to work out whether we can do 4 bytes at a time, or only a single byte // ebx and edi is available for us to use assembly.AddAsm("mov ebx, edi"); assembly.AddAsm("and ebx, 0xfffffffc"); assembly.AddAsm("cmp ebx, edi"); assembly.AddAsm($"jne {loopLabelByte}"); // 32bit DWORD assembly.AddAsm("shr eax, 2"); // eax now contains the length in dwords assembly.AddAsm($"{loopLabel}:"); assembly.AddAsm("cmp eax, 0"); assembly.AddAsm($"je {endLabel}"); assembly.AddAsm("mov [esi], ecx"); assembly.AddAsm("add esi, 4"); assembly.AddAsm("dec eax"); assembly.AddAsm($"jmp {loopLabel}"); // END DWORD // 8bit BYTE assembly.AddAsm($"{loopLabelByte}:"); assembly.AddAsm("cmp eax, 0"); assembly.AddAsm($"je {endLabel}"); assembly.AddAsm("mov byte [esi], cl"); assembly.AddAsm("inc esi"); assembly.AddAsm("dec eax"); assembly.AddAsm($"jmp {loopLabelByte}"); // END BYTE assembly.AddAsm($"{endLabel}:"); assembly.AddAsm("pop ecx"); assembly.AddAsm("ret 12"); // pop all the pushed items off the stack } } }
44.791667
125
0.568372
[ "MIT" ]
giawa/GiawaOS
RedPandaOS/Plugs/SystemPlugs.cs
5,377
C#
using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using PnP.Core.Auth.Services.Builder.Configuration; using PnP.Core.Services.Builder.Configuration; using PnP.Scanning.Core.Authentication; using PnP.Scanning.Core.Scanners; using PnP.Scanning.Core.Services; using PnP.Scanning.Core.Storage; using PnP.Scanning.Process.Commands; using PnP.Scanning.Process.Services; using Serilog; using Serilog.Events; using Spectre.Console; using System.CommandLine; using System.CommandLine.Builder; using System.CommandLine.Parsing; namespace PnP.Scanning.Process { internal class Program { internal static async Task Main(string[] args) { bool isCliProcess = true; if (args.Length > 0 && args[0].Equals("scanner", StringComparison.OrdinalIgnoreCase)) { isCliProcess = false; } // Launching PnP.Scanning.Process.exe as CLI if (isCliProcess) { await AnsiConsole.Status().Spinner(Spinner.Known.BouncingBar).StartAsync("Version check...", async ctx => { var versions = await VersionManager.LatestVersionAsync(); // There's a newer version to download if (!string.IsNullOrEmpty(versions.Item2)) { AnsiConsole.WriteLine(); AnsiConsole.MarkupLine($"Version [yellow]{versions.Item2}[/] is available, you are currently using version {versions.Item1}"); AnsiConsole.WriteLine(); AnsiConsole.MarkupLine($"Download the latest version from [yellow]{VersionManager.newVersionDownloadUrl}[/]"); AnsiConsole.WriteLine(); } else { AnsiConsole.WriteLine(); AnsiConsole.MarkupLine($"You are using the latest version {versions.Item1}"); AnsiConsole.WriteLine(); } }); // Configure needed services var host = ConfigureCliHost(args); // Get ProcessManager instance from the cli executable var processManager = host.Services.GetRequiredService<ScannerManager>(); var dataProtectionProvider = host.Services.GetRequiredService<IDataProtectionProvider>(); var configurationData = host.Services.GetRequiredService<ConfigurationOptions>(); var root = new RootCommandHandler(processManager, dataProtectionProvider, configurationData).Create(); var builder = new CommandLineBuilder(root); var parser = builder.UseDefaults().Build(); if (args.Length == 0) { AnsiConsole.Write(new FigletText("Microsoft 365 Assessment").Centered().Color(Color.Green)); AnsiConsole.WriteLine(""); AnsiConsole.MarkupLine("Execute a command [gray](<enter> to quit)[/]: "); var consoleInput = Console.ReadLine(); // Possible enhancement: build custom tab completion for the "console mode" // To get suggestions // var result = parser.Parse(consoleInput).GetCompletions(); // Sample to start from: https://www.codeproject.com/Articles/1182358/Using-Autocomplete-in-Windows-Console-Applications while (!string.IsNullOrEmpty(consoleInput)) { AnsiConsole.WriteLine(""); await parser.InvokeAsync(consoleInput); AnsiConsole.WriteLine(""); AnsiConsole.MarkupLine("Execute a command [gray](<enter> to quit)[/]: "); consoleInput = Console.ReadLine(); } } else { await parser.InvokeAsync(args); } } else { // Use fully qualified paths as otherwise on MacOS the files end up in the wrong location string logFolder = Path.GetDirectoryName(Environment.ProcessPath); string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmm"); Log.Logger = new LoggerConfiguration() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() #if DEBUG .WriteTo.Console() #endif .WriteTo.File(Path.Combine(logFolder, $"log_{timestamp}.txt")) // Duplicate all log entries generated for an actual scan component // to a separate log file in the folder per scan .WriteTo.Map("ScanId", (scanId, wt) => wt.File(Path.Combine(logFolder, scanId, $"log_{scanId}.txt"))) .CreateLogger(); try { // Launching PnP.Scanning.Process.exe as Kestrel web server to which we'll communicate via gRPC // Get port on which the orchestrator has to listen int orchestratorPort = ScannerManager.DefaultScannerPort; if (args.Length >= 2) { if (int.TryParse(args[1], out int providedPort)) { orchestratorPort = providedPort; } } Log.Information($"Starting Microsoft 365 Assessment on port {orchestratorPort}"); // Add and configure needed services var host = ConfigureScannerHost(args, orchestratorPort); Log.Information($"Started Microsoft 365 Assessment on port {orchestratorPort}"); await host.RunAsync(); } catch (Exception ex) { Log.Fatal(ex, "Microsoft 365 Assessment terminated unexpectedly"); } finally { Log.CloseAndFlush(); } } } private static IHost ConfigureCliHost(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureLogging((context, logging) => { // Clear all previously registered providers, don't want logger output to mess with the CLI console output logging.ClearProviders(); }) .ConfigureServices((context, services) => { // Inject configuration data var customSettings = new ConfigurationOptions(); context.Configuration.Bind("CustomSettings", customSettings); services.AddSingleton(customSettings); services.AddDataProtection(); services.AddSingleton<ScannerManager>(); services.AddTransient<AuthenticationManager>(); }) .UseConsoleLifetime() .Build(); } private static IHost ConfigureScannerHost(string[] args, int orchestratorPort) { return Host.CreateDefaultBuilder(args) .UseSerilog() .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup<Scanner>>(); webBuilder.ConfigureKestrel(options => { options.ListenLocalhost(orchestratorPort, listenOptions => { listenOptions.Protocols = HttpProtocols.Http2; }); }); webBuilder.ConfigureServices((context, services) => { services.AddDataProtection(); // Add the PnP Core SDK library services.AddPnPCore(options => { // Set Graph first to false to optimize performance options.PnPContext.GraphFirst = false; // Remove the HTTP timeout to ensure the request does not end before the throttling is over options.HttpRequests.Timeout = -1; }); services.Configure<PnPCoreOptions>(context.Configuration.GetSection("PnPCore")); services.AddPnPCoreAuthentication(); services.Configure<PnPCoreAuthenticationOptions>(context.Configuration.GetSection("PnPCore")); services.AddSingleton<StorageManager>(); services.AddSingleton<CsomEventHub>(); services.AddSingleton<ScanManager>(); services.AddSingleton<TelemetryManager>(); services.AddTransient<SiteEnumerationManager>(); services.AddTransient<ReportManager>(); }); }) .UseConsoleLifetime() .Build(); } } }
44.382883
150
0.520146
[ "MIT" ]
pnp/pnpscanning
src/PnP.Scanning/PnP.Scanning.Process/Program.cs
9,855
C#
using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Semmle.Extraction.CSharp.Populators { internal class DirectiveVisitor : CSharpSyntaxWalker { private readonly Context cx; private readonly List<IEntity> branchesTaken = new(); /// <summary> /// Gets a list of `#if`, `#elif`, and `#else` entities where the branch /// is taken. /// </summary> public IEnumerable<IEntity> BranchesTaken => branchesTaken; public DirectiveVisitor(Context cx) : base(SyntaxWalkerDepth.StructuredTrivia) { this.cx = cx; } public override void VisitPragmaWarningDirectiveTrivia(PragmaWarningDirectiveTriviaSyntax node) { Entities.PragmaWarningDirective.Create(cx, node); } public override void VisitPragmaChecksumDirectiveTrivia(PragmaChecksumDirectiveTriviaSyntax node) { Entities.PragmaChecksumDirective.Create(cx, node); } public override void VisitDefineDirectiveTrivia(DefineDirectiveTriviaSyntax node) { Entities.DefineDirective.Create(cx, node); } public override void VisitUndefDirectiveTrivia(UndefDirectiveTriviaSyntax node) { Entities.UndefineDirective.Create(cx, node); } public override void VisitWarningDirectiveTrivia(WarningDirectiveTriviaSyntax node) { Entities.WarningDirective.Create(cx, node); } public override void VisitErrorDirectiveTrivia(ErrorDirectiveTriviaSyntax node) { Entities.ErrorDirective.Create(cx, node); } public override void VisitNullableDirectiveTrivia(NullableDirectiveTriviaSyntax node) { Entities.NullableDirective.Create(cx, node); } public override void VisitLineDirectiveTrivia(LineDirectiveTriviaSyntax node) { Entities.LineDirective.Create(cx, node); } private readonly Stack<Entities.RegionDirective> regionStarts = new Stack<Entities.RegionDirective>(); public override void VisitRegionDirectiveTrivia(RegionDirectiveTriviaSyntax node) { var region = Entities.RegionDirective.Create(cx, node); regionStarts.Push(region); } public override void VisitEndRegionDirectiveTrivia(EndRegionDirectiveTriviaSyntax node) { if (regionStarts.Count == 0) { cx.ExtractionError("Couldn't find start region", null, cx.CreateLocation(node.GetLocation()), null, Util.Logging.Severity.Warning); return; } var start = regionStarts.Pop(); Entities.EndRegionDirective.Create(cx, node, start); } private class IfDirectiveStackElement { public Entities.IfDirective Entity { get; } public int SiblingCount { get; set; } public IfDirectiveStackElement(Entities.IfDirective entity) { Entity = entity; } } private readonly Stack<IfDirectiveStackElement> ifStarts = new Stack<IfDirectiveStackElement>(); public override void VisitIfDirectiveTrivia(IfDirectiveTriviaSyntax node) { var ifStart = Entities.IfDirective.Create(cx, node); ifStarts.Push(new IfDirectiveStackElement(ifStart)); if (node.BranchTaken) branchesTaken.Add(ifStart); } public override void VisitEndIfDirectiveTrivia(EndIfDirectiveTriviaSyntax node) { if (ifStarts.Count == 0) { cx.ExtractionError("Couldn't find start if", null, cx.CreateLocation(node.GetLocation()), null, Util.Logging.Severity.Warning); return; } var start = ifStarts.Pop(); Entities.EndIfDirective.Create(cx, node, start.Entity); } public override void VisitElifDirectiveTrivia(ElifDirectiveTriviaSyntax node) { if (ifStarts.Count == 0) { cx.ExtractionError("Couldn't find start if", null, cx.CreateLocation(node.GetLocation()), null, Util.Logging.Severity.Warning); return; } var start = ifStarts.Peek(); var elIf = Entities.ElifDirective.Create(cx, node, start.Entity, start.SiblingCount++); if (node.BranchTaken) branchesTaken.Add(elIf); } public override void VisitElseDirectiveTrivia(ElseDirectiveTriviaSyntax node) { if (ifStarts.Count == 0) { cx.ExtractionError("Couldn't find start if", null, cx.CreateLocation(node.GetLocation()), null, Util.Logging.Severity.Warning); return; } var start = ifStarts.Peek(); var @else = Entities.ElseDirective.Create(cx, node, start.Entity, start.SiblingCount++); if (node.BranchTaken) branchesTaken.Add(@else); } } }
34.717105
110
0.615501
[ "MIT" ]
Bhagyanekraje/codeql
csharp/extractor/Semmle.Extraction.CSharp/Populators/DirectiveVisitor.cs
5,277
C#
using Auth; using Common; using BL; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Backend.Controllers { [Authorize] [Route("api/record")] public class RecordController : Controller { private IAuthService _authService; private int _userId; private IRecordOperations _recordOperaions; public RecordController(IRecordOperations recordOperations, IAuthService authService) { _authService = authService; _recordOperaions = recordOperations; Result<int> resultId = authService.GetId(User); _userId = resultId.Data; } [HttpGet] [Route("{id:int}")] public async Task<IActionResult> Get(int id) => new JsonResult(await _recordOperaions.Get(id, _userId)); [HttpPost] [Route("search")] public async Task<IActionResult> Get([FromBody]Fetch fetch) => new JsonResult(await _recordOperaions.Get(fetch, _userId)); [HttpPost] [Route("")] public async Task<IActionResult> Post([FromBody]RecordModel record) => new JsonResult(await _recordOperaions.Save(record, _userId)); [HttpPut] [Route("")] public async Task<IActionResult> Put([FromBody]RecordModel record) => new JsonResult(await _recordOperaions.Update(record, _userId)); [HttpDelete] [Route("{id:int}")] public async Task<IActionResult> Delete(int id) => new JsonResult(await _recordOperaions.Delete(id, _userId)); [HttpPost] [Route("{id:int}/photo")] public async Task<IActionResult> UploadImage(IFormFile file, int id) => new JsonResult(await _recordOperaions.UploadImage(id, file, _userId)); [HttpGet] [Route("{id:int}/photo")] public async Task<IActionResult> GetImage(int id) { var result = await _recordOperaions.GetImage(id, _userId); if (!result.IsSuccess) { return BadRequest(result); } return File(result.Data.File, result.Data.ContentType); } } }
32.228571
93
0.623227
[ "MIT" ]
rostrastegaev/Directory
Directory/Backend/Controllers/RecordController.cs
2,258
C#
using System; using System.Collections.Generic; using System.Linq; using Accord.Extensions.Math; using Accord.Math; using Accord.Math.Optimization; using QuantConnect; using QuantConnect.Algorithm; using QuantConnect.Data; using QuantConnect.Data.Consolidators; using QuantConnect.Data.Market; using QuantConnect.Indicators; namespace Strategies { public class VolatilityAlgorithm : QCAlgorithm { private string[] _stocks = {"SSO", "TMF", "IJR", "IJH", "XIV"}; private string _vxx = "VXX"; private string _xiv = "XIV"; private string _spy = "SPY"; private string _shortSpy = "SH"; private string[] _equities = { "SSO", "TMF", "IJR", "IJH", "XIV", "VXX", "SPY", "SH" }; private int _n = 0; private int[] _s; private int[] _x0; private double[] _x1; private Dictionary<Symbol, SymbolData> _symbolData; private BollingerBands _bb; private RollingWindow<decimal> _spyWvf; private const int WvfLimit = 14; public override void Initialize() { SetStartDate(2015, 1, 1); SetEndDate(DateTime.Now); SetCash(10000); foreach (var equity in _equities) { AddSecurity(SecurityType.Equity, equity, Resolution.Minute); } _s = new int[_stocks.Length]; _x0 = new int[_stocks.Length]; _x1 = Enumerable.Repeat(1d / _stocks.Length, _stocks.Length).ToArray(); _symbolData = new Dictionary<Symbol, SymbolData>(); _bb = new BollingerBands(_spy, 22, 1.05m, MovingAverageType.Simple); _spyWvf = new RollingWindow<decimal>(22); foreach (var stock in _stocks) { var closes = new RollingWindow<decimal>(17 * 390); var dailyCloses = new RollingWindow<TradeBar>(29); var dailyConsolidator = new TradeBarConsolidator(TimeSpan.FromDays(1)); dailyConsolidator.DataConsolidated += (sender, consolidated) => _symbolData[consolidated.Symbol].UpdateDaily(consolidated); SubscriptionManager.AddConsolidator(stock, dailyConsolidator); _symbolData.Add(stock, new SymbolData(closes, dailyCloses)); } var spyDailyCloses = new RollingWindow<TradeBar>(28); var spyDailyConsolidator = new TradeBarConsolidator(TimeSpan.FromDays(1)); spyDailyConsolidator.DataConsolidated += (sender, consolidated) => _symbolData[consolidated.Symbol].UpdateDaily(consolidated); SubscriptionManager.AddConsolidator(_spy, spyDailyConsolidator); _symbolData.Add(_spy, new SymbolData(null, spyDailyCloses)); var vxxDailyConsolidator = new TradeBarConsolidator(TimeSpan.FromDays(1)); vxxDailyConsolidator.DataConsolidated += (sender, consolidated) => _symbolData[consolidated.Symbol].UpdateDaily(consolidated); SubscriptionManager.AddConsolidator(_vxx, vxxDailyConsolidator); _symbolData.Add(_spy, new SymbolData(null, spyDailyCloses)); Schedule.On(DateRules.EveryDay(), TimeRules.AfterMarketOpen("SPY", 15d), () => { if (_symbolData[_spy].IsReady) return; var vxxCloses = _symbolData[_vxx].DailyHistory.Select(tb => tb.Close); var vxxLows = _symbolData[_vxx].DailyHistory.Select(tb => tb.Low); // William's VIX Fix indicator a.k.a. the Synthetic VIX var previousMax = vxxCloses.Take(28).Max(); var previousWvf = 100 * (previousMax - vxxLows.Skip(27).First()) / previousMax; var max = vxxCloses.Skip(1).Max(); var wvf = 100 * (max - vxxLows.Last()) / max; if (previousWvf < WvfLimit && wvf >= WvfLimit) { SetHoldings(_vxx, 0); SetHoldings(_xiv, 0.07); } else if (previousWvf > WvfLimit && wvf <= WvfLimit) { SetHoldings(_vxx, 0.07); SetHoldings(_xiv, 0); } }); Schedule.On(DateRules.EveryDay(), TimeRules.AfterMarketOpen("SPY", 15d), () => { if (_symbolData[_spy].IsReady) return; var spyCloses = _symbolData[_spy].NDaysDailyHistory(22).Select(tb => tb.Close); var spyLows = _symbolData[_spy].NDaysDailyHistory(22).Select(tb => tb.Low); var max = spyCloses.Max(); var wvf = 100 * (max - spyLows.Last()) / max; _bb.Update(DateTime.Now, wvf); _spyWvf.Add(wvf); var rangeHigh = _spyWvf.Max() * 0.9m; var latestClose = _symbolData[_spy].NDaysDailyHistory(1).First().Close; var spy_higher_then_Xdays_back = latestClose > _symbolData[_spy].NDaysDailyHistory(3).First().Close; var spy_lower_then_longterm = latestClose > _symbolData[_spy].NDaysDailyHistory(40).First().Close; var spy_lower_then_midterm = latestClose > _symbolData[_spy].NDaysDailyHistory(14).First().Close; // Alerts Criteria var alert2 = !(_spyWvf[0] >= _bb.UpperBand && _spyWvf[0] >= rangeHigh) && (_spyWvf[1] >= _bb.UpperBand && _spyWvf[2] >= rangeHigh); if ((alert2 || spy_higher_then_Xdays_back) && (spy_lower_then_longterm || spy_lower_then_midterm)) { SetHoldings(_spy, 0.3); SetHoldings(_shortSpy, 0); } else { SetHoldings(_spy, 0); SetHoldings(_shortSpy, 0.3); } }); Schedule.On(DateRules.EveryDay(), TimeRules.AfterMarketOpen("SPY", 15d), () => { if (_symbolData[_spy].IsReady) return; var returns = new List<double[]>(); // 28? foreach (var stock in _stocks) { _symbolData[stock].UpdateWeights(); returns.Add(_symbolData[stock].PercentReturn.Select(pr => (double) (pr / _symbolData[stock].Norm)).ToArray()); } var retNorm = _symbolData.Select(s => s.Value.Norm); var retNormMax = retNorm.Max(); var epsFactor = retNormMax > 0 ? 0.9m : 1.0m; var eps = (double) (epsFactor * retNormMax); var constraints = new List<LinearConstraint>(); constraints.Add(new LinearConstraint(Enumerable.Repeat(1.0, _stocks.Length).ToArray()) { ShouldBe = ConstraintType.EqualTo, Value = 1 }); constraints.Add(new LinearConstraint(retNorm.Select(x => (double) x).ToArray()) { ShouldBe = ConstraintType.GreaterThanOrEqualTo, Value = eps + eps * 0.01 }); // Add and subtract small bounce to achieve inequality? constraints.Add(new LinearConstraint(retNorm.Select(x => (double) x).ToArray()) { ShouldBe = ConstraintType.LesserThanOrEqualTo, Value = eps - eps * 0.01 }); // Add and subtract small bounce to achieve inequality? constraints.Add(new LinearConstraint(_stocks.Length) { VariablesAtIndices = Enumerable.Range(0, _stocks.Length).ToArray(), ShouldBe = ConstraintType.GreaterThanOrEqualTo, Value = 0 }); constraints.Add(new LinearConstraint(_stocks.Length) { VariablesAtIndices = Enumerable.Range(0, _stocks.Length).ToArray(), ShouldBe = ConstraintType.LesserThanOrEqualTo, Value = 1 }); var initialGuess = new double[_stocks.Length]; var f = new QuadraticObjectiveFunction(() => Variance(initialGuess, returns.ToMatrix())); var solver = new GoldfarbIdnani(f, constraints); solver.Minimize(); var weights = _x1; var totalWeight = weights.Sum(); if (solver.Status == GoldfarbIdnaniStatus.Success) { weights = solver.Solution; } for (var i = 0; i < _stocks.Length; i++) { SetHoldings(_stocks[i], weights[i] / totalWeight); } }); } public override void OnData(Slice slice) { foreach (var stock in _stocks) { _symbolData[stock].Update(slice[stock].Close); } } public double Variance(double[] x, double[,] y) { var aCov = y.Covariance(); return x.Dot(aCov.Dot(x)); } public double JacVariance(double[] x, double[,] y) { var aCov = y.Transpose().Covariance().Flatten(); return 2d * aCov.Dot(x); } public class SymbolData { private readonly RollingWindow<TradeBar> _dailyCloses; private readonly RollingWindow<decimal> _closes; public decimal Mean; public decimal StandardDeviation; public decimal Norm => Mean / StandardDeviation; public IEnumerable<TradeBar> DailyHistory => _dailyCloses.Reverse(); public IEnumerable<TradeBar> NDaysDailyHistory(int n) => _dailyCloses.Take(n).Reverse(); public IEnumerable<decimal> PercentReturn => PercentChange(_closes.Reverse().ToList()); public bool IsReady => _closes.IsReady; public SymbolData(RollingWindow<decimal> closes, RollingWindow<TradeBar> dailyCloses) { _closes = closes; _dailyCloses = dailyCloses; } public void Update(decimal close) { _closes.Add(close); } public void UpdateDaily(TradeBar bar) { _dailyCloses.Add(bar); } public void UpdateWeights() { var percentChanges = PercentReturn.ToList(); var mean = percentChanges.Average(); var sumOfSquaresOfDifferences = percentChanges.Select(val => (val - mean) * (val - mean)).Sum(); var sd = Sqrt(sumOfSquaresOfDifferences / percentChanges.Count); Mean = mean; StandardDeviation = sd; } public List<decimal> PercentChange(List<decimal> closes) { var percentChanges = new List<decimal>(); for (int i = 1; i < closes.Count; i++) { percentChanges.Add((closes[i] - closes[i - 1]) / closes[i - 1]); } return percentChanges; } public static decimal Sqrt(decimal x, decimal? guess = null) { var ourGuess = guess.GetValueOrDefault(x / 2m); var result = x / ourGuess; var average = (ourGuess + result) / 2m; return average == ourGuess ? average : Sqrt(x, average); } } } }
38.132013
139
0.543362
[ "MIT" ]
AnTeater-dev/Quant_HighFrequencyTrading_
Strategies C#/VolatilityAlgorithm.cs
11,556
C#
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using JsonSubTypes; using Newtonsoft.Json; using Bitmovin.Api.Sdk.Common; using Bitmovin.Api.Sdk.Models; namespace Bitmovin.Api.Sdk.Models { /// <summary> /// AnalyticsGreaterThanFilter /// </summary> public class AnalyticsGreaterThanFilter : AnalyticsAbstractFilter { [JsonProperty(PropertyName = "operator")] private readonly string _operator = "GT"; /// <summary> /// Value /// </summary> [JsonProperty(PropertyName = "value")] public Object Value { get; set; } } }
23.642857
69
0.669184
[ "MIT" ]
bitmovin/bitmovin-api-sdk-dotnet
src/Bitmovin.Api.Sdk/Models/AnalyticsGreaterThanFilter.cs
662
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AndNotDouble() { var test = new SimpleBinaryOpTest__AndNotDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndNotDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ( (alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray ) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned( ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1 ); Unsafe.CopyBlockUnaligned( ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2 ); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Double> _fld1; public Vector256<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned( ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>() ); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned( ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>() ); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndNotDouble testClass) { var result = Avx.AndNot(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotDouble testClass) { fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) { var result = Avx.AndNot( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndNotDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned( ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>() ); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned( ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>() ); } public SimpleBinaryOpTest__AndNotDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned( ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>() ); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned( ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>() ); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable( _data1, _data2, new Double[RetElementCount], LargestVectorSize ); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.AndNot( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.AndNot( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.AndNot( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx) .GetMethod( nameof(Avx.AndNot), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) } ) .Invoke( null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) } ); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx) .GetMethod( nameof(Avx.AndNot), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) } ) .Invoke( null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) } ); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx) .GetMethod( nameof(Avx.AndNot), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) } ) .Invoke( null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) } ); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.AndNot(_clsVar1, _clsVar2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Double>* pClsVar1 = &_clsVar1) fixed (Vector256<Double>* pClsVar2 = &_clsVar2) { var result = Avx.AndNot( Avx.LoadVector256((Double*)(pClsVar1)), Avx.LoadVector256((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.AndNot(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndNotDouble(); var result = Avx.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AndNotDouble(); fixed (Vector256<Double>* pFld1 = &test._fld1) fixed (Vector256<Double>* pFld2 = &test._fld2) { var result = Avx.AndNot( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.AndNot(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) { var result = Avx.AndNot( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.AndNot(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx.AndNot( Avx.LoadVector256((Double*)(&test._fld1)), Avx.LoadVector256((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult( Vector256<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "" ) { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned( ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>() ); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult( void* op1, void* op2, void* result, [CallerMemberName] string method = "" ) { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned( ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>() ); Unsafe.CopyBlockUnaligned( ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>() ); Unsafe.CopyBlockUnaligned( ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>() ); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult( Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "" ) { bool succeeded = true; if ( ( (~BitConverter.DoubleToInt64Bits(left[0])) & BitConverter.DoubleToInt64Bits(right[0]) ) != BitConverter.DoubleToInt64Bits(result[0]) ) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ( ( (~BitConverter.DoubleToInt64Bits(left[i])) & BitConverter.DoubleToInt64Bits(right[i]) ) != BitConverter.DoubleToInt64Bits(result[i]) ) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation( $"{nameof(Avx)}.{nameof(Avx.AndNot)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:" ); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation( $" result: ({string.Join(", ", result)})" ); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
36.941909
121
0.536224
[ "MIT" ]
belav/runtime
src/tests/JIT/HardwareIntrinsics/X86/Avx/AndNot.Double.cs
26,709
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.Collections.Generic; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.EntityFrameworkCore.Storage { /// <summary> /// <para> /// Exposes dependencies needed by <see cref="DatabaseFacade" />. /// </para> /// <para> /// This type is typically used by database providers (and other extensions). It is generally /// not used in application code. /// </para> /// <para> /// The service lifetime is <see cref="ServiceLifetime.Scoped" />. This means that each /// <see cref="DbContext" /> instance will use its own instance of this service. /// The implementation may depend on other services registered with any lifetime. /// The implementation does not need to be thread-safe. /// </para> /// </summary> public interface IDatabaseFacadeDependencies { /// <summary> /// The transaction manager. /// </summary> IDbContextTransactionManager TransactionManager { get; } /// <summary> /// The database creator. /// </summary> IDatabaseCreator DatabaseCreator { get; } /// <summary> /// The execution strategy factory. /// </summary> IExecutionStrategyFactory ExecutionStrategyFactory { get; } /// <summary> /// The registered database providers. /// </summary> IEnumerable<IDatabaseProvider> DatabaseProviders { get; } /// <summary> /// A command logger. /// </summary> IDiagnosticsLogger<DbLoggerCategory.Database.Command> CommandLogger { get; } /// <summary> /// The concurrency detector. /// </summary> IConcurrencyDetector ConcurrencyDetector { get; } } }
36.016949
111
0.610353
[ "Apache-2.0" ]
0b01/efcore
src/EFCore/Storage/IDatabaseFacadeDependencies.cs
2,125
C#
using System.Runtime.CompilerServices; namespace OpenMLTD.MilliSim.Core { /// <summary> /// Caller helper constants. /// </summary> internal static class CallerHelper { /// <summary> /// An empty string for <see cref="CallerMemberNameAttribute"/>. /// </summary> public const string EmptyName = ""; } }
22.375
72
0.606145
[ "MIT" ]
hozuki/MilliSim
src/OpenMLTD.MilliSim.Runtime/Core/CallerHelper.cs
358
C#
using Unity.Entities; using Unity.Physics; namespace $rootnamespace$ { public struct $safeitemname$<T> : ICollector<T> where T : struct, IQueryResult { public bool EarlyOutOnFirstHit => false; public float MaxFraction => 1f; public int NumHits { get; private set; } /// T can either be RayCastHit or ColliderCastHit. public T ClosestHit { get; set; } public Entity selfEntity; private CollisionWorld collisionWorld; /// <summary> /// This constructor is not required, but this shows a quick example of how these ray casts can be implemented. /// for this example we are ignoring the owner of the casted collider/raycast. /// </summary> /// <param name="entity">The entity that owns the Collider/Raycast that is being casted.</param> /// <param name="collisionWorld">The current Collision World.</param> public $safeitemname$(Entity entity, CollisionWorld collisionWorld) { ClosestHit = default; NumHits = 0; this.selfEntity = entity; this.collisionWorld = collisionWorld; } public bool AddHit(T hit) { var collisionEntity = collisionWorld.Bodies[hit.RigidBodyIndex].Entity; if (collisionEntity == selfEntity) { return false; } ClosestHit = hit; NumHits = 1; return true; } } }
30.06
119
0.594145
[ "MIT" ]
osobeso/Unity-DOTS-VS-Templates
src/Templates/HitCollector/GenericHitCollector.cs
1,505
C#
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; using UnityEngine.Profiling; namespace Wanderer.GameFramework { [CustomModuleEditor("FSM Module", 0.141f, 0.408f, 0.635f)] public class FSModuleEditor : ModuleEditorBase { private Vector2 _scrollPos = Vector2.zero; Dictionary<Type, List<Type>> _fsmTypes = new Dictionary<Type, List<Type>>(); Dictionary<Type, FSMStateType> _fsmStateType = new Dictionary<Type, FSMStateType>(); //图标 private Texture[] _fsmIcons; //当前正在运行的状态的 List<string> _currentStateFullNames = new List<string>(); public FSModuleEditor(string name, Color mainColor, GameMode gameMode) : base(name, mainColor, gameMode) { List<Type> types = new List<Type>(); _fsmTypes.Clear(); _fsmStateType.Clear(); // //获取所有程序的类型 Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { types.AddRange(assemblies[i].GetTypes()); } //整理类型是否满足状态 for (int i = 0; i < types.Count; i++) { Type t = types[i]; if (t.IsAbstract) continue; object[] objs = t.GetCustomAttributes(typeof(FSMAttribute), true); if (objs != null && objs.Length > 0) { FSMAttribute attr = objs[0] as FSMAttribute; if (attr != null) { _fsmStateType.Add(t, attr.StateType); if (_fsmTypes.TryGetValue(t.BaseType, out List<Type> fsmStates)) { fsmStates.Add(t); } else { fsmStates = new List<Type>(); fsmStates.Add(t); _fsmTypes.Add(t.BaseType, fsmStates); } } } } types.Clear(); //图标 _fsmIcons = new Texture2D[5]; _fsmIcons[0] = EditorGUIUtility.IconContent("PlayButton").image; _fsmIcons[1] = EditorGUIUtility.IconContent("d_SceneViewLighting").image; _fsmIcons[2] = EditorGUIUtility.IconContent("d_SceneViewLighting Off").image; _fsmIcons[3] = EditorGUIUtility.IconContent("preAudioAutoPlayOff").image; _fsmIcons[4] = EditorGUIUtility.IconContent("PauseButton").image; } public override void OnDrawGUI() { GUILayout.BeginVertical("HelpBox", GUILayout.Height(150)); _scrollPos = GUILayout.BeginScrollView(_scrollPos); //正在运行 _currentStateFullNames.Clear(); if (EditorApplication.isPlaying) { BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; FieldInfo prfieldInfo = typeof(FSManager).GetField("_fsms", flag); Dictionary<Type, FSMBase> fsms = (Dictionary<Type, FSMBase>)prfieldInfo.GetValue(GameMode.FSM); if (fsms != null) { foreach (var item in fsms.Values) { if (item == null) continue; prfieldInfo = item.GetType().GetField("_curState", flag); if (prfieldInfo != null) { string fullName = prfieldInfo.GetValue(item).GetType().FullName; _currentStateFullNames.Add(fullName); } } } } foreach (var item in _fsmTypes) { GUILayout.BeginVertical("Box"); GUILayout.Label(item.Key.FullName, EditorStyles.boldLabel); for (int i = 0; i < item.Value.Count; i++) { Type stateType = item.Value[i]; GUILayout.BeginHorizontal(); Texture ico = _fsmIcons[(int)_fsmStateType[stateType]]; if (_currentStateFullNames.Count > 0) { for (int m = 0; m < _currentStateFullNames.Count; m++) { if (_currentStateFullNames[m].Equals(stateType.FullName)) { ico = _fsmIcons[4]; break; } } } GUILayout.Label(ico, GUILayout.Width(20), GUILayout.Height(20)); GUILayout.Label(stateType.FullName); GUILayout.EndHorizontal(); } GUILayout.EndVertical(); } GUILayout.EndScrollView(); GUILayout.EndVertical(); } public override void OnClose() { _fsmTypes.Clear(); _fsmStateType.Clear(); _fsmIcons = null; } } }
39.453237
113
0.470642
[ "MIT" ]
coding2233/UnityGameFramework
Editor/GameMode/Module/FSModuleEditor.cs
5,560
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Routing; using System.Web.Mvc; namespace LineBotSDK { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
25.086957
99
0.587522
[ "MIT" ]
jackru6g6/LineBot
LineBotSDK/App_Start/RouteConfig.cs
579
C#
using System; using System.Buffers; using System.Collections.Generic; using System.IO; using System.IO.Pipelines; using System.Net.Http; using System.Net.Http.QPack; using System.Reflection; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Experimental; using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http3; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging; using Microsoft.Net.Http.Headers; using Moq; using Xunit; using Xunit.Abstractions; using static System.IO.Pipelines.DuplexPipe; using static Microsoft.AspNetCore.Server.Kestrel.Core.Tests.Http2TestBase; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class Http3TestBase : TestApplicationErrorLoggerLoggedTest, IDisposable { internal TestServiceContext _serviceContext; internal Http3Connection _connection; internal readonly TimeoutControl _timeoutControl; internal readonly Mock<IKestrelTrace> _mockKestrelTrace = new Mock<IKestrelTrace>(); internal readonly Mock<ITimeoutHandler> _mockTimeoutHandler = new Mock<ITimeoutHandler>(); internal readonly Mock<MockTimeoutControlBase> _mockTimeoutControl; internal readonly MemoryPool<byte> _memoryPool = SlabMemoryPoolFactory.Create(); protected Task _connectionTask; private TestMultiplexedConnectionContext _multiplexedContext; private readonly CancellationTokenSource _connectionClosingCts = new CancellationTokenSource(); protected readonly RequestDelegate _noopApplication; protected readonly RequestDelegate _echoApplication; protected readonly RequestDelegate _echoMethod; protected readonly RequestDelegate _echoPath; protected readonly RequestDelegate _echoHost; public Http3TestBase() { _timeoutControl = new TimeoutControl(_mockTimeoutHandler.Object); _mockTimeoutControl = new Mock<MockTimeoutControlBase>(_timeoutControl) { CallBase = true }; _timeoutControl.Debugger = Mock.Of<IDebugger>(); _noopApplication = context => Task.CompletedTask; _echoApplication = async context => { var buffer = new byte[Http3PeerSettings.MinAllowedMaxFrameSize]; var received = 0; while ((received = await context.Request.Body.ReadAsync(buffer, 0, buffer.Length)) > 0) { await context.Response.Body.WriteAsync(buffer, 0, received); } }; _echoMethod = context => { context.Response.Headers["Method"] = context.Request.Method; return Task.CompletedTask; }; _echoPath = context => { context.Response.Headers["path"] = context.Request.Path.ToString(); context.Response.Headers["rawtarget"] = context.Features.Get<IHttpRequestFeature>().RawTarget; return Task.CompletedTask; }; _echoHost = context => { context.Response.Headers[HeaderNames.Host] = context.Request.Headers[HeaderNames.Host]; return Task.CompletedTask; }; } public override void Initialize(TestContext context, MethodInfo methodInfo, object[] testMethodArguments, ITestOutputHelper testOutputHelper) { base.Initialize(context, methodInfo, testMethodArguments, testOutputHelper); _serviceContext = new TestServiceContext(LoggerFactory, _mockKestrelTrace.Object) { Scheduler = PipeScheduler.Inline, }; } protected async Task InitializeConnectionAsync(RequestDelegate application) { if (_connection == null) { CreateConnection(); } // Skip all heartbeat and lifetime notification feature registrations. _connectionTask = _connection.InnerProcessRequestsAsync(new DummyApplication(application)); await Task.CompletedTask; } internal async ValueTask<Http3RequestStream> InitializeConnectionAndStreamsAsync(RequestDelegate application) { await InitializeConnectionAsync(application); var controlStream1 = await CreateControlStream(0); var controlStream2 = await CreateControlStream(2); var controlStream3 = await CreateControlStream(3); return await CreateRequestStream(); } protected void CreateConnection() { var limits = _serviceContext.ServerOptions.Limits; var features = new FeatureCollection(); _multiplexedContext = new TestMultiplexedConnectionContext(this); var httpConnectionContext = new Http3ConnectionContext( connectionId: "TestConnectionId", connectionContext: _multiplexedContext, connectionFeatures: features, serviceContext: _serviceContext, memoryPool: _memoryPool, localEndPoint: null, remoteEndPoint: null); httpConnectionContext.TimeoutControl = _mockTimeoutControl.Object; _connection = new Http3Connection(httpConnectionContext); _mockTimeoutHandler.Setup(h => h.OnTimeout(It.IsAny<TimeoutReason>())) .Callback<TimeoutReason>(r => _connection.OnTimeout(r)); } private static PipeOptions GetInputPipeOptions(ServiceContext serviceContext, MemoryPool<byte> memoryPool, PipeScheduler writerScheduler) => new PipeOptions ( pool: memoryPool, readerScheduler: serviceContext.Scheduler, writerScheduler: writerScheduler, pauseWriterThreshold: serviceContext.ServerOptions.Limits.MaxRequestBufferSize ?? 0, resumeWriterThreshold: serviceContext.ServerOptions.Limits.MaxRequestBufferSize ?? 0, useSynchronizationContext: false, minimumSegmentSize: memoryPool.GetMinimumSegmentSize() ); private static PipeOptions GetOutputPipeOptions(ServiceContext serviceContext, MemoryPool<byte> memoryPool, PipeScheduler readerScheduler) => new PipeOptions ( pool: memoryPool, readerScheduler: readerScheduler, writerScheduler: serviceContext.Scheduler, pauseWriterThreshold: GetOutputResponseBufferSize(serviceContext), resumeWriterThreshold: GetOutputResponseBufferSize(serviceContext), useSynchronizationContext: false, minimumSegmentSize: memoryPool.GetMinimumSegmentSize() ); private static long GetOutputResponseBufferSize(ServiceContext serviceContext) { var bufferSize = serviceContext.ServerOptions.Limits.MaxResponseBufferSize; if (bufferSize == 0) { // 0 = no buffering so we need to configure the pipe so the writer waits on the reader directly return 1; } // null means that we have no back pressure return bufferSize ?? 0; } internal async ValueTask<Http3ControlStream> CreateControlStream(int id) { var stream = new Http3ControlStream(this); _multiplexedContext.AcceptQueue.Writer.TryWrite(stream.StreamContext); await stream.WriteStreamIdAsync(id); return stream; } internal ValueTask<Http3RequestStream> CreateRequestStream() { var stream = new Http3RequestStream(this, _connection); _multiplexedContext.AcceptQueue.Writer.TryWrite(stream.StreamContext); return new ValueTask<Http3RequestStream>(stream); } public ValueTask<ConnectionContext> StartBidirectionalStreamAsync() { var stream = new Http3RequestStream(this, _connection); // TODO put these somewhere to be read. return new ValueTask<ConnectionContext>(stream.StreamContext); } internal class Http3StreamBase { protected DuplexPipe.DuplexPipePair _pair; protected Http3TestBase _testBase; protected Http3Connection _connection; protected Task SendAsync(ReadOnlySpan<byte> span) { var writableBuffer = _pair.Application.Output; writableBuffer.Write(span); return FlushAsync(writableBuffer); } protected static async Task FlushAsync(PipeWriter writableBuffer) { await writableBuffer.FlushAsync().AsTask().DefaultTimeout(); } } internal class Http3RequestStream : Http3StreamBase, IHttpHeadersHandler, IProtocolErrorCodeFeature { internal ConnectionContext StreamContext { get; } public bool CanRead => true; public bool CanWrite => true; public long StreamId => 0; public long Error { get; set; } private readonly byte[] _headerEncodingBuffer = new byte[Http3PeerSettings.MinAllowedMaxFrameSize]; private QPackEncoder _qpackEncoder = new QPackEncoder(); private QPackDecoder _qpackDecoder = new QPackDecoder(8192); private long _bytesReceived; protected readonly Dictionary<string, string> _decodedHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public Http3RequestStream(Http3TestBase testBase, Http3Connection connection) { _testBase = testBase; _connection = connection; var inputPipeOptions = GetInputPipeOptions(_testBase._serviceContext, _testBase._memoryPool, PipeScheduler.ThreadPool); var outputPipeOptions = GetOutputPipeOptions(_testBase._serviceContext, _testBase._memoryPool, PipeScheduler.ThreadPool); _pair = DuplexPipe.CreateConnectionPair(inputPipeOptions, outputPipeOptions); StreamContext = new TestStreamContext(canRead: true, canWrite: true, _pair, this); } public async Task<bool> SendHeadersAsync(IEnumerable<KeyValuePair<string, string>> headers, bool endStream = false) { var outputWriter = _pair.Application.Output; var frame = new Http3RawFrame(); frame.PrepareHeaders(); var buffer = _headerEncodingBuffer.AsMemory(); var done = _qpackEncoder.BeginEncode(headers, buffer.Span, out var length); frame.Length = length; // TODO may want to modify behavior of input frames to mock different client behavior (client can send anything). Http3FrameWriter.WriteHeader(frame, outputWriter); await SendAsync(buffer.Span.Slice(0, length)); if (endStream) { await _pair.Application.Output.CompleteAsync(); } return done; } internal async Task SendDataAsync(Memory<byte> data, bool endStream = false) { var outputWriter = _pair.Application.Output; var frame = new Http3RawFrame(); frame.PrepareData(); frame.Length = data.Length; Http3FrameWriter.WriteHeader(frame, outputWriter); await SendAsync(data.Span); if (endStream) { await _pair.Application.Output.CompleteAsync(); } } internal async Task<Dictionary<string, string>> ExpectHeadersAsync() { var http3WithPayload = await ReceiveFrameAsync(); _qpackDecoder.Decode(http3WithPayload.PayloadSequence, this); return _decodedHeaders; } internal async Task<Memory<byte>> ExpectDataAsync() { var http3WithPayload = await ReceiveFrameAsync(); return http3WithPayload.Payload; } internal async Task<Http3FrameWithPayload> ReceiveFrameAsync(uint maxFrameSize = Http3PeerSettings.DefaultMaxFrameSize) { var frame = new Http3FrameWithPayload(); while (true) { var result = await _pair.Application.Input.ReadAsync().AsTask().DefaultTimeout(); var buffer = result.Buffer; var consumed = buffer.Start; var examined = buffer.Start; var copyBuffer = buffer; try { Assert.True(buffer.Length > 0); if (Http3FrameReader.TryReadFrame(ref buffer, frame, maxFrameSize, out var framePayload)) { consumed = examined = framePayload.End; frame.Payload = framePayload.ToArray(); return frame; } else { examined = buffer.End; } if (result.IsCompleted) { throw new IOException("The reader completed without returning a frame."); } } finally { _bytesReceived += copyBuffer.Slice(copyBuffer.Start, consumed).Length; _pair.Application.Input.AdvanceTo(consumed, examined); } } } internal async Task ExpectReceiveEndOfStream() { var result = await _pair.Application.Input.ReadAsync().AsTask().DefaultTimeout(); Assert.True(result.IsCompleted); } public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { _decodedHeaders[name.GetAsciiStringNonNullCharacters()] = value.GetAsciiOrUTF8StringNonNullCharacters(); } public void OnHeadersComplete(bool endHeaders) { } public void OnStaticIndexedHeader(int index) { var knownHeader = H3StaticTable.GetHeaderFieldAt(index); _decodedHeaders[((Span<byte>)knownHeader.Name).GetAsciiStringNonNullCharacters()] = HttpUtilities.GetAsciiOrUTF8StringNonNullCharacters((ReadOnlySpan<byte>)knownHeader.Value); } public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value) { _decodedHeaders[((Span<byte>)H3StaticTable.GetHeaderFieldAt(index).Name).GetAsciiStringNonNullCharacters()] = value.GetAsciiOrUTF8StringNonNullCharacters(); } internal async Task WaitForStreamErrorAsync(Http3ErrorCode protocolError, string expectedErrorMessage) { var readResult = await _pair.Application.Input.ReadAsync(); _testBase.Logger.LogTrace("Input is completed"); Assert.True(readResult.IsCompleted); Assert.Equal((long)protocolError, Error); if (expectedErrorMessage != null) { Assert.Contains(_testBase.LogMessages, m => m.Exception?.Message.Contains(expectedErrorMessage) ?? false); } } } internal class Http3FrameWithPayload : Http3RawFrame { public Http3FrameWithPayload() : base() { } // This does not contain extended headers public Memory<byte> Payload { get; set; } public ReadOnlySequence<byte> PayloadSequence => new ReadOnlySequence<byte>(Payload); } internal class Http3ControlStream : Http3StreamBase, IProtocolErrorCodeFeature { internal ConnectionContext StreamContext { get; } public bool CanRead => true; public bool CanWrite => false; public long StreamId => 0; public long Error { get; set; } public Http3ControlStream(Http3TestBase testBase) { _testBase = testBase; var inputPipeOptions = GetInputPipeOptions(_testBase._serviceContext, _testBase._memoryPool, PipeScheduler.ThreadPool); var outputPipeOptions = GetOutputPipeOptions(_testBase._serviceContext, _testBase._memoryPool, PipeScheduler.ThreadPool); _pair = DuplexPipe.CreateConnectionPair(inputPipeOptions, outputPipeOptions); StreamContext = new TestStreamContext(canRead: false, canWrite: true, _pair, this); } public async Task WriteStreamIdAsync(int id) { var writableBuffer = _pair.Application.Output; void WriteSpan(PipeWriter pw) { var buffer = pw.GetSpan(sizeHint: 8); var lengthWritten = VariableLengthIntegerHelper.WriteInteger(buffer, id); pw.Advance(lengthWritten); } WriteSpan(writableBuffer); await FlushAsync(writableBuffer); } } private class TestMultiplexedConnectionContext : MultiplexedConnectionContext { public readonly Channel<ConnectionContext> AcceptQueue = Channel.CreateUnbounded<ConnectionContext>(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true }); private readonly Http3TestBase _testBase; public TestMultiplexedConnectionContext(Http3TestBase testBase) { _testBase = testBase; } public override string ConnectionId { get; set; } public override IFeatureCollection Features { get; } public override IDictionary<object, object> Items { get; set; } public override void Abort() { } public override void Abort(ConnectionAbortedException abortReason) { } public override async ValueTask<ConnectionContext> AcceptAsync(CancellationToken cancellationToken = default) { while (await AcceptQueue.Reader.WaitToReadAsync()) { while (AcceptQueue.Reader.TryRead(out var connection)) { return connection; } } return null; } public override ValueTask<ConnectionContext> ConnectAsync(IFeatureCollection features = null, CancellationToken cancellationToken = default) { var stream = new Http3ControlStream(_testBase); // TODO put these somewhere to be read. return new ValueTask<ConnectionContext>(stream.StreamContext); } } private class TestStreamContext : ConnectionContext, IStreamDirectionFeature, IStreamIdFeature { private DuplexPipePair _pair; public TestStreamContext(bool canRead, bool canWrite, DuplexPipePair pair, IProtocolErrorCodeFeature feature) { _pair = pair; Features = new FeatureCollection(); Features.Set<IStreamDirectionFeature>(this); Features.Set<IStreamIdFeature>(this); Features.Set(feature); CanRead = canRead; CanWrite = canWrite; } public override string ConnectionId { get; set; } public long StreamId { get; } public override IFeatureCollection Features { get; } public override IDictionary<object, object> Items { get; set; } public override IDuplexPipe Transport { get { return _pair.Transport; } set { throw new NotImplementedException(); } } public bool CanRead { get; } public bool CanWrite { get; } public override void Abort(ConnectionAbortedException abortReason) { _pair.Application.Output.Complete(abortReason); } } } }
39.788679
191
0.608498
[ "Apache-2.0" ]
DavidKlempfner/aspnetcore
src/Servers/Kestrel/test/InMemory.FunctionalTests/Http3/Http3TestBase.cs
21,088
C#
using System; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Jobs; namespace BenchmarkDotNet.Samples.Other { // Math.Sqrt method uses different ASM instruction of different JIT versions: // LegacyJit x86: fsqrt (FPU) // LegacyJit x64: sqrtsd (SSE2) // RyuJIT x64: vsqrtsd (AVX) [AllJitsJob] public class Math_DoubleSqrt { private int counter; [Benchmark] public double SqrtX() { counter = (counter + 1) % 100; return Math.Sqrt(counter); } // See also: http://stackoverflow.com/questions/8847429/sse-slower-than-fpu // See also: http://stackoverflow.com/questions/8924729/using-avx-intrinsics-instead-of-sse-does-not-improve-speed-why // See also: http://www.agner.org/optimize/instruction_tables.pdf // See also: http://assemblyrequired.crashworks.org/timing-square-root/ } }
33.321429
126
0.658092
[ "MIT" ]
ivandrofly/BenchmarkDotNet
samples/BenchmarkDotNet.Samples/Other/Math_DoubleSqrt.cs
935
C#
using System; using System.Reflection; namespace YamlDotNet.Serialization { /// <summary> /// A simple container for <see cref="PropertyInfo"/> and <see cref="MemberInfo"/>, exposing some common methods /// for both types. /// </summary> internal sealed class PropertyOrField { public PropertyOrField(PropertyInfo property, string nameOverride, INamingConvention namingConvention) : this(nameOverride, namingConvention) { if (property == null) { throw new ArgumentNullException(nameof(property)); } _propertyInfo = property; _fieldInfo = null; _memberType = MemberType.Property; } public PropertyOrField(FieldInfo field, string nameOverride, INamingConvention namingConvention) : this(nameOverride, namingConvention) { if (field == null) { throw new ArgumentNullException(nameof(field)); } _propertyInfo = null; _fieldInfo = field; _memberType = MemberType.Field; } private PropertyOrField(string nameOverride, INamingConvention namingConvention) { _nameOverride = nameOverride; _namingConvention = namingConvention; } public void SetValue(object obj, object value) { switch (_memberType) { case MemberType.Property: _propertyInfo.SetValue(obj, value); break; case MemberType.Field: _fieldInfo.SetValue(obj, value); break; default: throw new ArgumentOutOfRangeException(); } } public object GetValue(object obj) { switch (_memberType) { case MemberType.Property: return _propertyInfo.GetValue(obj); case MemberType.Field: return _fieldInfo.GetValue(obj); default: throw new ArgumentOutOfRangeException(); } } public Type GetMemberType() { switch (_memberType) { case MemberType.Property: return _propertyInfo.PropertyType; case MemberType.Field: return _fieldInfo.FieldType; default: throw new ArgumentOutOfRangeException(); } } public T GetCustomAttribute<T>() where T : Attribute { switch (_memberType) { case MemberType.Property: return _propertyInfo.GetCustomAttribute<T>(true); case MemberType.Field: return _fieldInfo.GetCustomAttribute<T>(true); default: throw new ArgumentOutOfRangeException(); } } public bool CanRead { get { switch (_memberType) { case MemberType.Property: return _propertyInfo.CanRead; case MemberType.Field: return true; default: throw new ArgumentOutOfRangeException(); } } } public bool CanWrite { get { switch (_memberType) { case MemberType.Property: return _propertyInfo.CanWrite; case MemberType.Field: return true; default: throw new ArgumentOutOfRangeException(); } } } public string Name { get { // The name can still be whitespaces and so on. // This is permitted in CLS, and YAML. if (!string.IsNullOrEmpty(_nameOverride)) { return _nameOverride; } string name; switch (_memberType) { case MemberType.Property: name = _propertyInfo.Name; break; case MemberType.Field: name = _fieldInfo.Name; break; default: throw new ArgumentOutOfRangeException(); } if (_namingConvention != null) { name = _namingConvention.Apply(name); } return name; } } private enum MemberType { Property = 0, Field = 1 } private readonly MemberType _memberType; private readonly FieldInfo _fieldInfo; private readonly PropertyInfo _propertyInfo; private readonly string _nameOverride; private readonly INamingConvention _namingConvention; } }
32.270968
116
0.4996
[ "MIT" ]
hozuki/YamlDotNet.DataContract
YamlDotNet.DataContract/PropertyOrField.cs
5,004
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 BenchmarkDotNet.Attributes; using MicroBenchmarks; using System.Threading.Tasks; namespace System.Threading.Tests { [BenchmarkCategory(Categories.Libraries)] public class Perf_CancellationToken { private readonly CancellationToken _token = new CancellationTokenSource().Token; [Benchmark] public void RegisterAndUnregister_Serial() => _token.Register(() => { }).Dispose(); [Benchmark] public void Cancel() { var cts = new CancellationTokenSource(); cts.Token.Register(() => { }); cts.Cancel(); } private CancellationToken _token1 = new CancellationTokenSource().Token; private CancellationToken _token2 = new CancellationTokenSource().Token; private CancellationToken[] _tokens = new[] { new CancellationTokenSource().Token, new CancellationTokenSource().Token, new CancellationTokenSource().Token }; [Benchmark] public void CreateLinkedTokenSource1() => CancellationTokenSource.CreateLinkedTokenSource(_token1, default).Dispose(); [Benchmark] public void CreateLinkedTokenSource2() => CancellationTokenSource.CreateLinkedTokenSource(_token1, _token2).Dispose(); [Benchmark] public void CreateLinkedTokenSource3() => CancellationTokenSource.CreateLinkedTokenSource(_tokens).Dispose(); [Benchmark] public void CancelAfter() { using (var cts = new CancellationTokenSource()) { cts.CancelAfter(int.MaxValue - 1); } } } }
34.660377
166
0.661404
[ "MIT" ]
Cosifne/performance
src/benchmarks/micro/libraries/System.Threading/Perf.CancellationToken.cs
1,839
C#
using System; using OpenQA.Selenium; using Xunit.Gherkin.Quick; namespace bdd_tests { public abstract partial class TestBase : Feature, IDisposable { [And(@"I request a temporary change to hours of sale")] public void TemporaryChangeToHoursOfSale() { /* Page Title: Temporary Change to Hours of Sale */ // create test data var description = "Test automation event details"; // enter the event details var uiEventDetails = ngDriver.FindElement(By.CssSelector("textarea#description2")); uiEventDetails.SendKeys(description); // add a date from var uiDateFrom = ngDriver.FindElement(By.CssSelector("input#tempDateFrom")); uiDateFrom.Click(); // select the date SharedCalendarDate(); // add a date to var uiDateTo = ngDriver.FindElement(By.CssSelector("input#tempDateTo")); uiDateTo.Click(); // select the date SharedCalendarDate(); // select authorizedToSubmit checkbox var uiAuthorizedToSubmit = ngDriver.FindElement(By.Id("authorizedToSubmit")); uiAuthorizedToSubmit.Click(); // select signatureAgreement checkbox var uiSignatureAgreement = ngDriver.FindElement(By.Id("signatureAgreement")); uiSignatureAgreement.Click(); } [And(@"I request a before midnight temporary change to hours of sale")] public void TemporaryChangeToHoursOfSaleBeforeMidnight() { /* Page Title: Temporary Change to Hours of Sale (Before Midnight) */ TemporaryChangeToHoursOfSale(); } [And(@"I request an after midnight temporary change to hours of sale")] public void TemporaryChangeToHoursOfSaleAfterMidnight() { /* Page Title: Temporary Change to Hours of Sale (Before Midnight) */ TemporaryChangeToHoursOfSale(); } } }
30.970588
95
0.596391
[ "Apache-2.0" ]
BrendanBeachBC/jag-lcrb-carla-public
functional-tests/bdd-tests/TestBaseTemporaryChangeToHoursOfSale.cs
2,108
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; using System.Collections; using System.Collections.Generic; using Bridge.ClientTest.Collections.Generic.Base; using Bridge.Test.NUnit; #if true namespace Bridge.ClientTest.Collections.Generic { [Category(Constants.MODULE_ACTIVATOR)] [TestFixture(TestNameFormat = "SortedDictionary_IDictionary_NonGeneric_Tests - {0}")] public class SortedDictionary_IDictionary_NonGeneric_Tests: TestBase { #region IDictionary Helper Methods protected object GetNewKey(IDictionary dictionary) { int seed = 840; object missingKey = CreateTKey(seed++); while (dictionary.Contains(missingKey) || missingKey.Equals(null)) { missingKey = CreateTKey(seed++); } return missingKey; } protected IDictionary NonGenericIDictionaryFactory() { return new SortedDictionary<string, string>(); } protected object CreateTKey(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes = new byte[stringLength]; rand.NextBytes(bytes); return Convert.ToBase64String(bytes); } protected object CreateTValue(int seed) => CreateTKey(seed); protected Type ICollection_NonGeneric_CopyTo_IndexLargerThanArrayCount_ThrowType => typeof(ArgumentOutOfRangeException); #endregion #region IDictionary tests [Test] public void IDictionary_NonGeneric_ItemSet_NullValueWhenDefaultValueIsNonNull() { var data = ValidCollectionSizes(); foreach (var testCase in data) { int count = (int)testCase[0]; IDictionary dictionary = new SortedDictionary<string, int>(); Assert.Throws<ArgumentNullException>(() => dictionary[GetNewKey(dictionary)] = null); } } [Test] public void IDictionary_NonGeneric_ItemSet_KeyOfWrongType() { var data = ValidCollectionSizes(); foreach (var testCase in data) { int count = (int)testCase[0]; IDictionary dictionary = new SortedDictionary<string, string>(); Assert.Throws<ArgumentException>(() => dictionary[23] = CreateTValue(12345)); Assert.True(dictionary.Count == 0); } } [Test] public void IDictionary_NonGeneric_ItemSet_ValueOfWrongType() { var data = ValidCollectionSizes(); foreach (var testCase in data) { int count = (int)testCase[0]; IDictionary dictionary = new SortedDictionary<string, string>(); object missingKey = GetNewKey(dictionary); Assert.Throws<ArgumentException>(() => dictionary[missingKey] = 324); Assert.True(dictionary.Count == 0); } } [Test] public void IDictionary_NonGeneric_Add_KeyOfWrongType() { var data = ValidCollectionSizes(); foreach (var testCase in data) { int count = (int)testCase[0]; IDictionary dictionary = new SortedDictionary<string, string>(); object missingKey = 23; Assert.Throws<ArgumentException>(() => dictionary.Add(missingKey, CreateTValue(12345))); Assert.True(dictionary.Count == 0); } } [Test] public void IDictionary_NonGeneric_Add_ValueOfWrongType() { var data = ValidCollectionSizes(); foreach (var testCase in data) { int count = (int)testCase[0]; IDictionary dictionary = new SortedDictionary<string, string>(); object missingKey = GetNewKey(dictionary); Assert.Throws<ArgumentException>(() => dictionary.Add(missingKey, 324)); Assert.True(dictionary.Count == 0); } } [Test] public void IDictionary_NonGeneric_Add_NullValueWhenDefaultTValueIsNonNull() { var data = ValidCollectionSizes(); foreach (var testCase in data) { int count = (int)testCase[0]; IDictionary dictionary = new SortedDictionary<string, int>(); object missingKey = GetNewKey(dictionary); Assert.Throws<ArgumentNullException>(() => dictionary.Add(missingKey, null)); Assert.True(dictionary.Count == 0); } } [Test] public void IDictionary_NonGeneric_Contains_KeyOfWrongType() { var data = ValidCollectionSizes(); foreach (var testCase in data) { int count = (int)testCase[0]; IDictionary dictionary = new SortedDictionary<string, int>(); Assert.False(dictionary.Contains(1)); } } #endregion } } #endif
32.066667
128
0.584389
[ "Apache-2.0" ]
Drake53/CSharp.lua
test/BridgeNetTests/Batch1/src/Collections/Generic/SortedDictionary/SortedDictionary.Tests.cs
5,291
C#
using Aurora.Profiles; using CSScriptLibrary; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Threading; namespace Aurora.Devices { public class DeviceContainer { public Device Device { get; set; } public BackgroundWorker Worker = new BackgroundWorker(); public Thread UpdateThread { get; set; } = null; private Tuple<DeviceColorComposition, bool> currentComp = null; private bool newFrame = false; public DeviceContainer(Device device) { this.Device = device; Worker.DoWork += WorkerOnDoWork; Worker.RunWorkerCompleted += (sender, args) => { lock (Worker) { if (newFrame && !Worker.IsBusy) Worker.RunWorkerAsync(); } }; //Worker.WorkerSupportsCancellation = true; } private void WorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { newFrame = false; Device.UpdateDevice(currentComp.Item1, doWorkEventArgs, currentComp.Item2); } public void UpdateDevice(DeviceColorComposition composition, bool forced = false) { newFrame = true; currentComp = new Tuple<DeviceColorComposition, bool>(composition, forced); lock (Worker) { if (Worker.IsBusy) return; else Worker.RunWorkerAsync(); } /*lock (Worker) { try { if (!Worker.IsBusy) Worker.RunWorkerAsync(); } catch(Exception e) { Global.logger.LogLine(e.ToString(), Logging_Level.Error); } }*/ } } public class DeviceManager : IDisposable { private List<DeviceContainer> devices = new List<DeviceContainer>(); public DeviceContainer[] Devices { get { return devices.ToArray(); } } private bool anyInitialized = false; private bool retryActivated = false; private const int retryInterval = 5000; private const int retryAttemps = 3; private int retryAttemptsLeft = retryAttemps; private Thread retryThread; private bool _InitializeOnceAllowed = false; public int RetryAttempts { get { return retryAttemptsLeft; } } public event EventHandler NewDevicesInitialized; public DeviceManager() { devices.Add(new DeviceContainer(new Devices.Logitech.LogitechDevice())); // Logitech Device devices.Add(new DeviceContainer(new Devices.Corsair.CorsairDevice())); // Corsair Device devices.Add(new DeviceContainer(new Devices.Razer.RazerDevice())); // Razer Device devices.Add(new DeviceContainer(new Devices.Roccat.RoccatDevice())); // Roccat Device devices.Add(new DeviceContainer(new Devices.Clevo.ClevoDevice())); // Clevo Device devices.Add(new DeviceContainer(new Devices.CoolerMaster.CoolerMasterDevice())); // CoolerMaster Device devices.Add(new DeviceContainer(new Devices.AtmoOrbDevice.AtmoOrbDevice())); // AtmoOrb Ambilight Device devices.Add(new DeviceContainer(new Devices.SteelSeries.SteelSeriesDevice())); // SteelSeries Device devices.Add(new DeviceContainer(new Devices.SteelSeriesHID.SteelSeriesHIDDevice())); // SteelSeriesHID Device devices.Add(new DeviceContainer(new Devices.Wooting.WootingDevice())); // Wooting Device string devices_scripts_path = System.IO.Path.Combine(Global.ExecutingDirectory, "Scripts", "Devices"); if (Directory.Exists(devices_scripts_path)) { foreach (string device_script in Directory.EnumerateFiles(devices_scripts_path, "*.*")) { try { string ext = Path.GetExtension(device_script); switch (ext) { case ".py": var scope = Global.PythonEngine.ExecuteFile(device_script); dynamic main_type; if (scope.TryGetVariable("main", out main_type)) { dynamic script = Global.PythonEngine.Operations.CreateInstance(main_type); Device scripted_device = new Devices.ScriptedDevice.ScriptedDevice(script); devices.Add(new DeviceContainer(scripted_device)); } else Global.logger.Error("Script \"{0}\" does not contain a public 'main' class", device_script); break; case ".cs": System.Reflection.Assembly script_assembly = CSScript.LoadFile(device_script); foreach (Type typ in script_assembly.ExportedTypes) { dynamic script = Activator.CreateInstance(typ); Device scripted_device = new Devices.ScriptedDevice.ScriptedDevice(script); devices.Add(new DeviceContainer(scripted_device)); } break; default: Global.logger.Error("Script with path {0} has an unsupported type/ext! ({1})", device_script, ext); break; } } catch (Exception exc) { Global.logger.Error("An error occured while trying to load script {0}. Exception: {1}", device_script, exc); } } } } public void RegisterVariables() { //Register any variables foreach (var device in devices) Global.Configuration.VarRegistry.Combine(device.Device.GetRegisteredVariables()); } public void Initialize() { int devicesToRetryNo = 0; foreach (DeviceContainer device in devices) { if (device.Device.IsInitialized() || Global.Configuration.devices_disabled.Contains(device.Device.GetType())) continue; if (device.Device.Initialize()) anyInitialized = true; else devicesToRetryNo++; Global.logger.Info("Device, " + device.Device.GetDeviceName() + ", was" + (device.Device.IsInitialized() ? "" : " not") + " initialized"); } if (anyInitialized) { _InitializeOnceAllowed = true; NewDevicesInitialized?.Invoke(this, new EventArgs()); } if (devicesToRetryNo > 0 && !retryActivated) { retryActivated = true; retryThread = new Thread(RetryInitialize); retryThread.Start(); return; } } private void RetryInitialize() { for (int try_count = 0; try_count < retryAttemps; try_count++) { Global.logger.Info("Retrying Device Initialization"); int devicesAttempted = 0; bool _anyInitialized = false; foreach (DeviceContainer device in devices) { if (device.Device.IsInitialized() || Global.Configuration.devices_disabled.Contains(device.Device.GetType())) continue; devicesAttempted++; if (device.Device.Initialize()) _anyInitialized = true; Global.logger.Info("Device, " + device.Device.GetDeviceName() + ", was" + (device.Device.IsInitialized() ? "" : " not") + " initialized"); } retryAttemptsLeft--; //We don't need to continue the loop if we aren't trying to initialize anything if (devicesAttempted == 0) break; //There is only a state change if something suddenly becomes initialized if (_anyInitialized) { NewDevicesInitialized?.Invoke(this, new EventArgs()); anyInitialized = true; } Thread.Sleep(retryInterval); } } public void InitializeOnce() { if (!anyInitialized && _InitializeOnceAllowed) Initialize(); } public bool AnyInitialized() { return anyInitialized; } public Device[] GetInitializedDevices() { List<Device> ret = new List<Device>(); foreach (DeviceContainer device in devices) { if (device.Device.IsInitialized()) { ret.Add(device.Device); } } return ret.ToArray(); } public void Shutdown() { foreach (DeviceContainer device in devices) { if (device.Device.IsInitialized()) { device.Device.Shutdown(); Global.logger.Info("Device, " + device.Device.GetDeviceName() + ", was shutdown"); } } anyInitialized = false; } public void ResetDevices() { foreach (DeviceContainer device in devices) { if (device.Device.IsInitialized()) { device.Device.Reset(); } } } public void UpdateDevices(DeviceColorComposition composition, bool forced = false) { foreach (DeviceContainer device in devices) { if (device.Device.IsInitialized()) { if (Global.Configuration.devices_disabled.Contains(device.Device.GetType())) { //Initialized when it's supposed to be disabled? SMACK IT! device.Device.Shutdown(); continue; } device.UpdateDevice(composition, forced); } } } public string GetDevices() { string devices_info = ""; foreach (DeviceContainer device in devices) devices_info += device.Device.GetDeviceDetails() + "\r\n"; if (retryAttemptsLeft > 0) devices_info += "Retries: " + retryAttemptsLeft + "\r\n"; return devices_info; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). if (retryThread != null) { retryThread.Abort(); retryThread = null; } } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~DeviceManager() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #endregion } }
37.061453
159
0.489901
[ "MIT" ]
boristomas/Aurora
Project-Aurora/Project-Aurora/Devices/DeviceManager.cs
12,913
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Unleashed Mod Manager")] [assembly: AssemblyDescription("Unleashed Mod Manager")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Unleashed Mod Manager")] [assembly: AssemblyCopyright("Copyright © HyperBE32 and Contributors, 2022.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("277111e3-79d8-41b5-b0d7-7609dff6e36f")] [assembly: AssemblyVersion("2.0.0.8")] [assembly: AssemblyFileVersion("1.1.2.0")]
38.125
78
0.768852
[ "MIT" ]
HyperPolygon64/Unleashed-Mod-Manager
Unleashed-Mod-Manager/Properties/AssemblyInfo.cs
613
C#
using SimpleInjector; using XRayBuilder.Core.Config; using XRayBuilder.Core.Libraries.Bootstrap.Model; namespace XRayBuilderGUI.Config { public sealed class BootstrapConfig : IBootstrapSegment, IContainerSegment { public void Register(IBootstrapBuilder builder) { } public void Register(Container container) { container.RegisterSingleton<IXRayBuilderConfig, XRayBuilderConfig>(); } } }
25.5
81
0.701525
[ "MIT" ]
Ephemerality/xray-builder.gui
XRayBuilder/src/Config/BootstrapConfig.cs
459
C#
namespace BESL.Application { using System; using System.Reflection; using AutoMapper; using MediatR; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using BESL.Application.Infrastructure; using BESL.Application.Infrastructure.AutoMapper; using BESL.Application.Infrastructure.Validators; using BESL.Application.Interfaces; public static class DependencyInjection { public static IServiceCollection AddApplicationLayer(this IServiceCollection services, IConfiguration configuration) { configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); services.AddMediatR(typeof(DependencyInjection).Assembly); services.AddAutoMapper(new Assembly[] { typeof(AutoMapperProfile).Assembly }); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPerformanceBehaviour<,>)); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(CustomExceptionNotificationBehaviour<,>)); services.AddScoped<IFileValidate, GameImageFileValidate>(); return services; } } }
37.40625
124
0.727652
[ "MIT" ]
SonnyRR/BESL
BESL.Application/DependencyInjection.cs
1,199
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace FacebookLoginDemo { static class Program { /// <summary> /// アプリケーションのメイン エントリ ポイントです。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
21.869565
65
0.614314
[ "MIT" ]
peace098beat/Facebook-Login-Demo
FacebookLoginDemo/Program.cs
551
C#
namespace CefSharp.Puppeteer.Messaging { internal class SecurityHandleCertificateErrorResponse { public int EventId { get; set; } public string Action { get; set; } } }
19.8
57
0.666667
[ "MIT" ]
cefsharp/Puppeteer
lib/PuppeteerSharp/Messaging/SecurityHandleCertificateErrorResponse.cs
198
C#
using System; using System.Collections.Generic; using System.Data; using System.Text; namespace BusinessLogic.Entities { public interface IEntity<E> { E Construct(DataRow row); } }
15.615385
33
0.704433
[ "MIT" ]
IfElseRun/Tigerspike-Test
BusinessLogic/Entities/IEntity.cs
205
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net.Sockets; using System.Net; namespace IPZ_Salary_System_NEW { public partial class Autorization : Form { public Autorization() { InitializeComponent(); PasswordBox.PasswordChar = '*'; } private static bool choice = false; public bool logonSuccesfull() { return choice; } SyncronousSocket socket = new SyncronousSocket(); CLogin login = new CLogin(); public void Parser(string buf1, string buf2) { try { string key = "|"; // ключ яким будемо дешифрувати string dot = "."; int lastKey_Log = buf1.IndexOf("`"); // Відрізаємо ключ №2 (який потрібен для визначення довжини ключа №1)від повідомлення int lastKey_Pass = buf2.IndexOf("`"); int endKey_Log = buf1.Length - lastKey_Log - 1; // розмір ключа. на 1 менше! (5) int endKey_Pass = buf2.Length - lastKey_Pass - 1; int[] indexes_Log = new int[endKey_Log]; // масив для логінів int[] indexes_Pass = new int[endKey_Pass]; // для паролів // забираємо ключик, необхідний для визначення кінця основного ключа string logins = buf1.Replace("`", ""); string passwords = buf2.Replace("`", ""); int i = 0; int k = 1; // рахуємо розміри стрічок для логінів і паролів for (string j = key; j.Length != (endKey_Log + 1); j = j + dot) { indexes_Log[i] = logins.IndexOf(j) + k; indexes_Pass[i] = passwords.IndexOf(j) + k; i++; k++; } if (!LoginBox.Text.Equals("") && !PasswordBox.Text.Equals("")) { int v = 1; int r = 2; for (int j = 0; j < endKey_Log - 1; j++) { // Витягуємо логіни і паролі за допомогою отиманих розмірів ключів string Login = logins.Substring(indexes_Log[j], indexes_Log[v] - indexes_Log[j] - r); string Password = passwords.Substring(indexes_Pass[j], indexes_Pass[v] - indexes_Pass[j] - r); v++; r++; if (LoginBox.Text.Equals(Login) && PasswordBox.Text.Equals(Password)) { choice = true; logonSuccesfull(); // все ОК закриваємо форму. Відкриваємо головну форму в Program.cs this.Close(); } else Error_label.Text = "Неправильний логін або пароль!"; } } else Error_label.Text = "Введіть інформацію!"; } catch { //MessageBox.Show("Не отримано даних з серверу"); //this.Close(); } } public void button1_Click(object sender, EventArgs e) { try { socket.local_IP = IPAddress.Parse(LocacIpTextBox.Text); // відсилаємо адресу хоста в клас комунікації socket.Connection_Show("->Autorization" + "\n"); } catch { MessageBox.Show("Не правильно введена IP-адреса"); } login.Login_UserName = SyncronousSocket.rec_msg_dep; login.Login_Password = SyncronousSocket.rec_msg_wor; Parser(login.Login_UserName, login.Login_Password); // парсимо вхідні дані } private void Autorization_Load(object sender, EventArgs e) { try { //socket.local_IP = IPAddress.Parse(LocacIpTextBox.Text); // socket.Connection_Show("->Autorization" + "\n"); // підключаємось до серверу } catch(Exception ex) { MessageBox.Show(ex.ToString()); Application.Exit(); } } private void Autorization_FormClosing(object sender, FormClosingEventArgs e) { //if(e.CloseReason == CloseReason.WindowsShutDown) //{ // SyncronousSocket socket = new SyncronousSocket(); // socket.Connection_Show("->ExitClient \n"); //} } } }
30.053435
128
0.605283
[ "Apache-2.0" ]
DIma-Kush/salary_system_project_2016
client/Autorization.cs
4,438
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; namespace VSX.UniversalVehicleCombat { /// <summary> /// This class provides a control script for an AI space fighter. /// </summary> public class AISpaceFighterControl : MonoBehaviour, IVehicleInput { private VehicleControlClass vehicleControlClass = VehicleControlClass.SpaceshipFighter; public VehicleControlClass VehicleControlClass { get { return vehicleControlClass; } } BehaviourBlackboard blackboard; [HideInInspector] public BehaviourState currentBehaviourState = BehaviourState.Patrolling; [HideInInspector] public CombatState currentCombatState; [Header("Base PID Coefficients")] [SerializeField] private Vector3 throttlePIDCoeffs = new Vector3(0.1f, 0.1f, 0.01f); [SerializeField] private Vector3 steeringPIDCoeffs = new Vector3(0.1f, 0.1f, 0.01f); [Header("Control Limits")] [SerializeField] private Vector3 maxRotationAngles = new Vector3(360, 360, 45); [Header("Behaviours")] [SerializeField] private CombatBehaviour combatBehaviourPrefab; private CombatBehaviour combatBehaviour; [SerializeField] private ObstacleAvoidanceBehaviour obstacleAvoidanceBehaviourPrefab; private ObstacleAvoidanceBehaviour obstacleAvoidanceBehaviour; public ObstacleAvoidanceBehaviour ObstacleAvoidanceBehaviour { get { return obstacleAvoidanceBehaviour; } } [SerializeField] private PatrolBehaviour patrolBehaviourPrefab; private PatrolBehaviour patrolBehaviour; private GroupMember groupMember; private bool running = false; public bool Running { get { return running; } } private bool controlsDisabled = false; /// <summary> /// Set the controls to be disabled temporarily. /// </summary> public bool ControlsDisabled { get { return controlsDisabled; } set { controlsDisabled = value; } } /// <summary> /// Initialize this vehicle input script /// </summary> /// <param name="agent"></param> public void Initialize(GameAgent agent) { blackboard = new BehaviourBlackboard(); groupMember = agent.GetComponent<GroupMember>(); if (groupMember != null && agent.IsInVehicle) groupMember.ResetPatrolTargetToNearest(); blackboard.GroupMember = groupMember; // Instantiate the behaviours if (obstacleAvoidanceBehaviourPrefab != null) { obstacleAvoidanceBehaviour = Instantiate(obstacleAvoidanceBehaviourPrefab, transform) as ObstacleAvoidanceBehaviour; obstacleAvoidanceBehaviour.Initialize(blackboard); } if (combatBehaviourPrefab != null) { combatBehaviour = Instantiate(combatBehaviourPrefab, transform) as CombatBehaviour; combatBehaviour.Initialize(blackboard); } if (patrolBehaviourPrefab != null) { patrolBehaviour = Instantiate(patrolBehaviourPrefab, transform) as PatrolBehaviour; patrolBehaviour.Initialize(blackboard); } blackboard.Initialize(steeringPIDCoeffs, throttlePIDCoeffs, maxRotationAngles); blackboard.SetVehicle(agent.Vehicle); } /// <summary> /// Begin running this vehicle input script. /// </summary> public void Begin() { running = true; } /// <summary> /// Finish running this vehicle input script. /// </summary> public void Finish() { running = false; } /// <summary> /// Set the target (e.g. by the group manager) /// </summary> /// <param name="newTarget">The new target for this game agent.</param> public void SetTarget(ITrackable newTarget) { blackboard.Vehicle.Radar.SetSelectedTarget (newTarget); } // Fire or stop firing weapons void WeaponActions() { if (!blackboard.Vehicle.HasWeapons) return; if (blackboard.canFirePrimaryWeapon) { blackboard.Vehicle.Weapons.StartFiringOnTrigger(0); } else { blackboard.Vehicle.Weapons.StopFiringOnTrigger(0); } if (blackboard.canFireSecondaryWeapon) { blackboard.Vehicle.Weapons.StartFiringOnTrigger(1); } else { blackboard.Vehicle.Weapons.StopFiringOnTrigger(1); } } // Called every frame public void Update() { if (!running) return; if (!controlsDisabled) { // Do obstacle avoidance first if (obstacleAvoidanceBehaviour != null) { obstacleAvoidanceBehaviour.Tick(); } // Set the state to combat if there is a target if (blackboard.Vehicle.HasRadar && blackboard.Vehicle.Radar.HasSelectedTarget && combatBehaviour != null) { if (currentBehaviourState != BehaviourState.Combat) { blackboard.integralSteeringVals = Vector3.zero; blackboard.integralThrottleVals = Vector3.zero; currentBehaviourState = BehaviourState.Combat; } } else { // Set the state to patrolling if there is no target if (currentBehaviourState != BehaviourState.Patrolling) { blackboard.integralSteeringVals = Vector3.zero; blackboard.canFirePrimaryWeapon = false; blackboard.canFireSecondaryWeapon = false; if (groupMember != null) groupMember.ResetPatrolTargetToNearest(); currentBehaviourState = BehaviourState.Patrolling; } } // Tick the appropriate behavior according to the current state switch (currentBehaviourState) { case BehaviourState.Combat: combatBehaviour.Tick(); break; default: patrolBehaviour.Tick(); break; } // Implement thrust and steering if (blackboard.Vehicle.HasEngines) { blackboard.throttleValues = new Vector3(0f, 0f, (1f - blackboard.obstacleAvoidanceStrength * 0.5f) * blackboard.throttleValues.z); blackboard.Vehicle.Engines.SetRotationInputs(blackboard.steeringValues); blackboard.Vehicle.Engines.SetTranslationInputs(blackboard.throttleValues); } // Implement weapon actions WeaponActions(); } } } }
26.565401
137
0.668679
[ "MIT" ]
jackdarker/Spaceshooter1
Assets/SpaceCombatKit/Scripts/SpaceCombat/AI/AISpaceFighterControl.cs
6,298
C#
using HTTP.Enums; using System; namespace MvcFramework.Attributes.Http { public abstract class BaseHttpAttribute : Attribute { public string ActionName { get; set; } public string Url { get; set; } public abstract HttpRequestMethod Method { get; } } }
19.466667
57
0.664384
[ "MIT" ]
emilia98/CSharpWebSoftUni
C# Web Basics/10. MVC Introduction - Exercise/SIS/WebServer/Attributes/Http/BaseHttpAttribute.cs
294
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace UsbScreen { class Convert { } /// <summary> /// 打开串口 /// </summary> [ValueConversion(typeof(bool), typeof(string))] public class ConnectOrDisconnect : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool) value) return "断开"; else return "连接"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } /// <summary> /// 启用插件 /// </summary> [ValueConversion(typeof(bool), typeof(string))] public class EnableOrDisable : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return "停用"; else return "启用"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } /// <summary> /// 反向bool /// </summary> [ValueConversion(typeof(bool), typeof(bool))] public class boolNot : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return !(bool)value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return !(bool)value; } } }
25.388889
103
0.592451
[ "Apache-2.0" ]
chenxuuu/USB-Screen
ProjectCDC/Client/UsbScreen/Convert.cs
1,864
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Applications.Containers.Models { public partial class ContainerAppLogin : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(Routes)) { writer.WritePropertyName("routes"); writer.WriteObjectValue(Routes); } if (Optional.IsDefined(PreserveUrlFragmentsForLogins)) { writer.WritePropertyName("preserveUrlFragmentsForLogins"); writer.WriteBooleanValue(PreserveUrlFragmentsForLogins.Value); } if (Optional.IsCollectionDefined(AllowedExternalRedirectUrls)) { writer.WritePropertyName("allowedExternalRedirectUrls"); writer.WriteStartArray(); foreach (var item in AllowedExternalRedirectUrls) { writer.WriteStringValue(item); } writer.WriteEndArray(); } if (Optional.IsDefined(CookieExpiration)) { writer.WritePropertyName("cookieExpiration"); writer.WriteObjectValue(CookieExpiration); } if (Optional.IsDefined(Nonce)) { writer.WritePropertyName("nonce"); writer.WriteObjectValue(Nonce); } writer.WriteEndObject(); } internal static ContainerAppLogin DeserializeContainerAppLogin(JsonElement element) { Optional<LoginRoutes> routes = default; Optional<bool> preserveUrlFragmentsForLogins = default; Optional<IList<string>> allowedExternalRedirectUrls = default; Optional<CookieExpiration> cookieExpiration = default; Optional<LoginNonce> nonce = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("routes")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } routes = LoginRoutes.DeserializeLoginRoutes(property.Value); continue; } if (property.NameEquals("preserveUrlFragmentsForLogins")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } preserveUrlFragmentsForLogins = property.Value.GetBoolean(); continue; } if (property.NameEquals("allowedExternalRedirectUrls")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<string> array = new List<string>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(item.GetString()); } allowedExternalRedirectUrls = array; continue; } if (property.NameEquals("cookieExpiration")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } cookieExpiration = CookieExpiration.DeserializeCookieExpiration(property.Value); continue; } if (property.NameEquals("nonce")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } nonce = LoginNonce.DeserializeLoginNonce(property.Value); continue; } } return new ContainerAppLogin(routes.Value, Optional.ToNullable(preserveUrlFragmentsForLogins), Optional.ToList(allowedExternalRedirectUrls), cookieExpiration.Value, nonce.Value); } } }
39.570248
190
0.523183
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/containerapps/Azure.ResourceManager.Applications.Containers/src/Generated/Models/ContainerAppLogin.Serialization.cs
4,788
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using WardrobeApp.Models; namespace WardrobeApp.Controllers { public class BottomsController : Controller { private ClothingProjectEntities db = new ClothingProjectEntities(); // GET: Bottoms public ActionResult Index() { var bottoms = db.Bottoms.Include(b => b.Occassion).Include(b => b.Season); return View(bottoms.ToList()); } // GET: Bottoms/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Bottom bottom = db.Bottoms.Find(id); if (bottom == null) { return HttpNotFound(); } return View(bottom); } // GET: Bottoms/Create public ActionResult Create() { ViewBag.OccassionID = new SelectList(db.Occassions, "OccassionID", "OccassionType"); ViewBag.SeasonID = new SelectList(db.Seasons, "SeasonID", "Season1"); return View(); } // POST: Bottoms/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "BottomID,BottomName,BottomPhoto,BottomColor,SeasonID,OccassionID")] Bottom bottom) { if (ModelState.IsValid) { db.Bottoms.Add(bottom); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.OccassionID = new SelectList(db.Occassions, "OccassionID", "OccassionType", bottom.OccassionID); ViewBag.SeasonID = new SelectList(db.Seasons, "SeasonID", "Season1", bottom.SeasonID); return View(bottom); } // GET: Bottoms/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Bottom bottom = db.Bottoms.Find(id); if (bottom == null) { return HttpNotFound(); } ViewBag.OccassionID = new SelectList(db.Occassions, "OccassionID", "OccassionType", bottom.OccassionID); ViewBag.SeasonID = new SelectList(db.Seasons, "SeasonID", "Season1", bottom.SeasonID); return View(bottom); } // POST: Bottoms/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "BottomID,BottomName,BottomPhoto,BottomColor,SeasonID,OccassionID")] Bottom bottom) { if (ModelState.IsValid) { db.Entry(bottom).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.OccassionID = new SelectList(db.Occassions, "OccassionID", "OccassionType", bottom.OccassionID); ViewBag.SeasonID = new SelectList(db.Seasons, "SeasonID", "Season1", bottom.SeasonID); return View(bottom); } // GET: Bottoms/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Bottom bottom = db.Bottoms.Find(id); if (bottom == null) { return HttpNotFound(); } return View(bottom); } // POST: Bottoms/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Bottom bottom = db.Bottoms.Find(id); db.Bottoms.Remove(bottom); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
33.773723
134
0.562135
[ "Unlicense" ]
JuliePretzlaff/JavaScriptWardrobe
WardrobeApp/Controllers/BottomsController.cs
4,629
C#
using Abp.Authorization; using LLMall.Authorization.Roles; using LLMall.Authorization.Users; namespace LLMall.Authorization { public class PermissionChecker : PermissionChecker<Role, User> { public PermissionChecker(UserManager userManager) : base(userManager) { } } }
21.266667
66
0.689655
[ "MIT" ]
sunven/LLMall
aspnet-core/src/LLMall.Core/Authorization/PermissionChecker.cs
321
C#
using System; using System.Collections.Generic; using System.Linq; namespace BookLibrary { class Program { static void Main() { int n = int.Parse(Console.ReadLine()); Library lib = new Library { Name = "bookStorage", books = new List<Books>() }; for (int i = 0; i < n; i++) { List<string> info = Console.ReadLine().Split(' ').ToList(); string title = info[0]; string author = info[1]; decimal price = decimal.Parse(info[5]); if (lib.books.All(a => a.Author != author)) { Books newBook = new Books { Author = author, Price = price }; lib.books.Add(newBook); } else { Books toUpgrade = lib.books.First(a => a.Author == author); toUpgrade.Price += price; } } foreach (Books book in lib.books .OrderByDescending(p => p.Price) .ThenBy(a => a.Author)) { Console.WriteLine($"{book.Author} -> {book.Price:f2}"); } } } } class Library { public string Name { get; set; } public List<Books> books { get; set; } } class Books { public string Author { get; set; } public decimal Price { get; set; } }
26.112903
79
0.409512
[ "MIT" ]
fastline32/TechModule
Objects and Classes - Exercises/05.BookLibrary/Program.cs
1,621
C#
using Starlight.Models.Core; using System; using System.Collections.Generic; using System.Text; namespace Starlight.Models { public class MapAttribute : CoreDataModel { public int X { get; set; } public int Y { get; set; } public MapAttributeType Type { get; set; } } }
19.3125
50
0.656958
[ "MIT" ]
Eclipse-Origins/Starlight
src/Starlight/Models/MapAttribute.cs
311
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using WhatSport.Domain.Models; namespace WhatSport.Infrastructure.EntityConfigurations { internal class ScoreEntityTypeConfiguration : IEntityTypeConfiguration<Score> { public void Configure(EntityTypeBuilder<Score> builder) { builder.ToTable("Scores"); builder.HasKey(s => s.Id); builder.Property(s => s.Id).ValueGeneratedOnAdd(); builder.HasOne(s => s.Match).WithMany(m => m.Scores).HasForeignKey(s => s.MatchId).OnDelete(DeleteBehavior.Restrict); } } }
35.222222
129
0.695584
[ "MIT" ]
SergioMorenoFernandez/WhatSport
WhatSport.Infrastructure/EntityConfigurations/ScoreEntityTypeConfiguration.cs
636
C#
using Cake.Core; using Cake.Core.IO; using Cake.Testing; using Moq; namespace Cake.SevenZip.Tests.Fixtures; public class SevenZipAliasesFixture : SevenZipRunnerFixture { internal ICakeContext Context { get; } public SevenZipAliasesFixture() { var argumentsMoq = new Mock<ICakeArguments>(); var registryMoq = new Mock<IRegistry>(); var dataService = new Mock<ICakeDataService>(); Context = new CakeContext( FileSystem, Environment, Globber, new FakeLog(), argumentsMoq.Object, ProcessRunner, registryMoq.Object, Tools, dataService.Object, Configuration); } protected override void RunTool() { Context.SevenZip(Settings); } }
23.647059
59
0.614428
[ "MIT" ]
nils-a/Cake.7zip
src/Cake.7zip.Tests/Fixtures/SevenZipAliasesFixture.cs
804
C#
using System; namespace MeetingBlog.POOP { internal class BadDateException : Exception { public BadDateException(string message) :base(message) { } } }
18.090909
63
0.59799
[ "Apache-2.0" ]
gurmitteotia/meetings-blog
MeetingBlog/POOP/BadDateException.cs
201
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Models.Api20201208 { using Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="HealthBotUpdateParameters" /> /// </summary> public partial class HealthBotUpdateParametersTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="HealthBotUpdateParameters" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="HealthBotUpdateParameters" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="HealthBotUpdateParameters" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="HealthBotUpdateParameters" />.</param> /// <returns> /// an instance of <see cref="HealthBotUpdateParameters" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Models.Api20201208.IHealthBotUpdateParameters ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.HealthBot.Models.Api20201208.IHealthBotUpdateParameters).IsAssignableFrom(type)) { return sourceValue; } try { return HealthBotUpdateParameters.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return HealthBotUpdateParameters.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return HealthBotUpdateParameters.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
52.169014
249
0.588418
[ "MIT" ]
3quanfeng/azure-powershell
src/HealthBot/generated/api/Models/Api20201208/HealthBotUpdateParameters.TypeConverter.cs
7,267
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EntityLayer { using System; using System.Collections.Generic; public partial class OrderDetail { public int OrderId { get; set; } public int ProductId { get; set; } public Nullable<int> Quantity { get; set; } public Nullable<decimal> Price { get; set; } public virtual Order Order { get; set; } public virtual Product Product { get; set; } } }
32.923077
85
0.522196
[ "MIT" ]
mhkarazeybek/.NET
ECommerceExample/EntityLayer/OrderDetail.cs
856
C#
using System.Collections.Generic; using System.Xml; using JetBrains.Metadata.Reader.API; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Modules; using JetBrains.ReSharper.Psi.Resolve; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Util; using JetBrains.Util.DataStructures; namespace JetBrains.ReSharper.Plugins.FSharp.Psi.Impl.DeclaredElement { public abstract class DeclaredElementBase : IClrDeclaredElement { public bool CaseSensitiveName => true; public bool IsSynthetic() => false; public IList<IDeclaration> GetDeclarations() => EmptyList<IDeclaration>.Instance; public IList<IDeclaration> GetDeclarationsIn(IPsiSourceFile sourceFile) => EmptyList<IDeclaration>.Instance; public bool HasDeclarationsIn(IPsiSourceFile sourceFile) => false; public HybridCollection<IPsiSourceFile> GetSourceFiles() => HybridCollection<IPsiSourceFile>.Empty; public bool HasAttributeInstance(IClrTypeName clrName, AttributesSource attributesSource) => false; public IList<IAttributeInstance> GetAttributeInstances(AttributesSource attributesSource) => EmptyList<IAttributeInstance>.Instance; public IList<IAttributeInstance> GetAttributeInstances(IClrTypeName clrName, AttributesSource attributesSource) => EmptyList<IAttributeInstance>.Instance; public XmlNode GetXMLDoc(bool inherit) => null; public XmlNode GetXMLDescriptionSummary(bool inherit) => null; public abstract string ShortName { get; } public abstract bool IsValid(); public abstract PsiLanguageType PresentationLanguage { get; } public abstract IPsiModule Module { get; } public abstract IPsiServices GetPsiServices(); public abstract ITypeElement GetContainingType(); public abstract ITypeMember GetContainingTypeMember(); public abstract ISubstitution IdSubstitution { get; } public abstract DeclaredElementType GetElementType(); } public abstract class FSharpDeclaredElementBase : DeclaredElementBase { public override PsiLanguageType PresentationLanguage => FSharpLanguage.Instance; } }
39.884615
136
0.795082
[ "Apache-2.0" ]
DedSec256/fsharp-support
ReSharper.FSharp/src/FSharp.Psi/src/Impl/DeclaredElement/FSharpDeclaredElementBase.cs
2,074
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.IO; using System.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using System.Reflection; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; #if WINHTTPHANDLER_TEST using HttpClientHandler = System.Net.Http.WinHttpClientHandler; #endif public abstract partial class HttpClientHandlerTestBase : FileCleanupTestBase { public readonly ITestOutputHelper _output; protected virtual Version UseVersion => HttpVersion.Version11; public HttpClientHandlerTestBase(ITestOutputHelper output) { _output = output; } protected virtual HttpClient CreateHttpClient() => CreateHttpClient(CreateHttpClientHandler()); protected HttpClient CreateHttpClient(HttpMessageHandler handler) => new HttpClient(handler) { DefaultRequestVersion = UseVersion }; protected static HttpClient CreateHttpClient(string useVersionString) => CreateHttpClient(CreateHttpClientHandler(useVersionString), useVersionString); protected static HttpClient CreateHttpClient(HttpMessageHandler handler, string useVersionString) => new HttpClient(handler) { DefaultRequestVersion = Version.Parse(useVersionString) }; protected HttpClientHandler CreateHttpClientHandler() => CreateHttpClientHandler(UseVersion); protected static HttpClientHandler CreateHttpClientHandler(string useVersionString) => CreateHttpClientHandler(Version.Parse(useVersionString)); protected LoopbackServerFactory LoopbackServerFactory => GetFactoryForVersion(UseVersion); protected static LoopbackServerFactory GetFactoryForVersion(Version useVersion) { return useVersion.Major switch { #if NETCOREAPP 3 => Http3LoopbackServerFactory.Singleton, 2 => Http2LoopbackServerFactory.Singleton, #endif _ => Http11LoopbackServerFactory.Singleton }; } // For use by remote server tests public static readonly IEnumerable<object[]> RemoteServersMemberData = Configuration.Http.RemoteServersMemberData; protected HttpClient CreateHttpClientForRemoteServer(Configuration.Http.RemoteServer remoteServer) { return CreateHttpClientForRemoteServer(remoteServer, CreateHttpClientHandler()); } protected HttpClient CreateHttpClientForRemoteServer(Configuration.Http.RemoteServer remoteServer, HttpMessageHandler httpClientHandler) { HttpMessageHandler wrappedHandler = httpClientHandler; // WinHttpHandler will downgrade to 1.1 if you set Transfer-Encoding: chunked. // So, skip this verification if we're not using SocketsHttpHandler. if (PlatformDetection.SupportsAlpn && !IsWinHttpHandler) { wrappedHandler = new VersionCheckerHttpHandler(httpClientHandler, remoteServer.HttpVersion); } return new HttpClient(wrappedHandler) { DefaultRequestVersion = remoteServer.HttpVersion }; } private sealed class VersionCheckerHttpHandler : DelegatingHandler { private readonly Version _expectedVersion; public VersionCheckerHttpHandler(HttpMessageHandler innerHandler, Version expectedVersion) : base(innerHandler) { _expectedVersion = expectedVersion; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (request.Version != _expectedVersion) { throw new Exception($"Unexpected request version: expected {_expectedVersion}, saw {request.Version}"); } HttpResponseMessage response = await base.SendAsync(request, cancellationToken); if (response.Version != _expectedVersion) { throw new Exception($"Unexpected response version: expected {_expectedVersion}, saw {response.Version}"); } return response; } } } }
39.824561
144
0.692952
[ "MIT" ]
Drawaes/runtime
src/libraries/Common/tests/System/Net/Http/HttpClientHandlerTestBase.cs
4,540
C#
namespace Graph { /// <summary> /// Represents a collection of SkipListNodes. This class differs from the base class - NodeList - /// in that it contains an internal method to increment or decrement the height of the SkipListNodeList. /// Incrementing the height adds a new neighbor to the list, decrementing the height removes the /// top-most neighbor. /// </summary> /// <typeparam name="T">The type of data stored in the SkipListNode instances that are contained /// within this SkipListNodeList.</typeparam> public class SkipListNodeList<T> : NodeList<T> { public SkipListNodeList(int height) : base(height) { } /// <summary> /// Increases the size of the SkipListNodeList by one, adding a default SkipListNode. /// </summary> internal void IncrementHeight() { // add a dummy entry base.Items.Add(default(Node<T>)); } /// <summary> /// Decreases the size of the SkipListNodeList by one, removing the "top-most" SkipListNode. /// </summary> internal void DecrementHeight() { // delete the last entry base.Items.RemoveAt(base.Items.Count - 1); } } }
36.6
109
0.607338
[ "MIT" ]
xandronus/datastruct
SkipListNodeList.cs
1,281
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.BotService.V20171201.Outputs { [OutputType] public sealed class DirectLineChannelResponse { /// <summary> /// The channel name /// Expected value is 'DirectLineChannel'. /// </summary> public readonly string ChannelName; /// <summary> /// The set of properties specific to Direct Line channel resource /// </summary> public readonly Outputs.DirectLineChannelPropertiesResponse? Properties; [OutputConstructor] private DirectLineChannelResponse( string channelName, Outputs.DirectLineChannelPropertiesResponse? properties) { ChannelName = channelName; Properties = properties; } } }
29.243243
81
0.659889
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/BotService/V20171201/Outputs/DirectLineChannelResponse.cs
1,082
C#
using System; using System.Collections.Generic; using System.Text; namespace Pangea.Domain { /// <summary> /// Extract the country code of the phone number /// </summary> public interface ICountryCodeProvider { /// <summary> /// Return the country calling code when it can be found. /// </summary> /// <param name="phoneNumber">The part of the phone number that contains the numbers</param> /// <returns>Either the country calling code or null</returns> int? GetCountryCallingCodeFrom(string phoneNumber); /// <summary> /// Resolves the country calling code for the given country /// </summary> /// <param name="isoTwoLetterCountryName">The 'ISO 3166-1 alpha-2' name of the country</param> /// <returns>The country calling code. For instance when given NL the result will be 31</returns> int? GetCountryCallingCodeFor(string isoTwoLetterCountryName); } }
36.222222
105
0.656442
[ "MIT" ]
rubenrorije/Pangea.Domain
Pangea.Domain/ICountryCodeProvider.cs
980
C#
using WG.Entities; using Common; using System; using System.Linq; using System.Collections.Generic; namespace WG.Controllers.payment_method.payment_method_master { public class PaymentMethodMaster_PaymentMethodDTO : DataDTO { public long Id { get; set; } public string Code { get; set; } public string Name { get; set; } public string Description { get; set; } public PaymentMethodMaster_PaymentMethodDTO() {} public PaymentMethodMaster_PaymentMethodDTO(PaymentMethod PaymentMethod) { this.Id = PaymentMethod.Id; this.Code = PaymentMethod.Code; this.Name = PaymentMethod.Name; this.Description = PaymentMethod.Description; } } public class PaymentMethodMaster_PaymentMethodFilterDTO : FilterDTO { public long? Id { get; set; } public string Code { get; set; } public string Name { get; set; } public string Description { get; set; } public PaymentMethodOrder OrderBy { get; set; } } }
28.815789
80
0.632877
[ "MIT" ]
blyzer/CodeGenerator
CodeGeneration/Controllers/payment-method/payment-method-master/PaymentMethodMaster_PaymentMethodDTO.cs
1,095
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("viewcad_wpf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("viewcad_wpf")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
42.321429
98
0.709283
[ "MIT" ]
CADindustries/viewcad_wpf
viewcad_wpf/Properties/AssemblyInfo.cs
2,373
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("ReadOnlyPracticing")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReadOnlyPracticing")] [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("98f89d93-3f80-4fb5-9173-f89778c167fe")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.081081
84
0.747339
[ "MIT" ]
fr0wsTyl/TelerikAcademy-2015
Telerik - C# OOP/Practicing/ReadOnlyPracticing/Properties/AssemblyInfo.cs
1,412
C#
namespace CookBeyondLimits.Data.Models { public class RecipeAllergen { public int RecipeId { get; set; } public virtual Recipe Recipe { get; set; } public int AllergenId { get; set; } public virtual Allergen Allergen { get; set; } } }
20.214286
54
0.614841
[ "MIT" ]
tAtanas0va/CookBeyondLimits
Data/CookBeyondLimits.Data.Models/RecipeAllergen.cs
285
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 disable using System; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Implementation.Interactive { internal sealed class InteractiveDocumentNavigationService : IDocumentNavigationService { public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) => true; public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) => false; public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) => false; public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) { if (workspace is not InteractiveWorkspace interactiveWorkspace) { Debug.Fail("InteractiveDocumentNavigationService called with incorrect workspace!"); return false; } var textView = interactiveWorkspace.Window.TextView; var document = interactiveWorkspace.CurrentSolution.GetDocument(documentId); var textSnapshot = document.GetTextSynchronously(cancellationToken).FindCorrespondingEditorTextSnapshot(); if (textSnapshot == null) { return false; } var snapshotSpan = new SnapshotSpan(textSnapshot, textSpan.Start, textSpan.Length); var virtualSnapshotSpan = new VirtualSnapshotSpan(snapshotSpan); if (!textView.TryGetSurfaceBufferSpan(virtualSnapshotSpan, out var surfaceBufferSpan)) { return false; } textView.Selection.Select(surfaceBufferSpan.Start, surfaceBufferSpan.End); textView.ViewScroller.EnsureSpanVisible(surfaceBufferSpan.SnapshotSpan, EnsureSpanVisibleOptions.AlwaysCenter); // Moving the caret must be the last operation involving surfaceBufferSpan because // it might update the version number of textView.TextSnapshot (VB does line commit // when the caret leaves a line which might cause pretty listing), which must be // equal to surfaceBufferSpan.SnapshotSpan.Snapshot's version number. textView.Caret.MoveTo(surfaceBufferSpan.Start); textView.VisualElement.Focus(); return true; } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken) => throw new NotSupportedException(); public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken) => throw new NotSupportedException(); } }
46.118421
174
0.722967
[ "MIT" ]
AlekseyTs/roslyn
src/EditorFeatures/Core.Wpf/Interactive/InteractiveDocumentNavigationService.cs
3,507
C#
using System.Collections.Generic; using System.Linq; using SmartValley.Domain.Entities; namespace SmartValley.WebApi.Estimates.Responses { public class ScoringCriteriaGroupResponse { public string Key { get; set; } public int Order { get; set; } public IReadOnlyCollection<ScoringCriterionResponse> Criteria { get; set; } public static ScoringCriteriaGroupResponse Create(string key, IReadOnlyCollection<ScoringCriterion> criteria) { return new ScoringCriteriaGroupResponse { Key = key, Order = criteria.First().GroupOrder, Criteria = criteria.Select(ScoringCriterionResponse.From).ToArray() }; } } }
32.32
118
0.602723
[ "MIT" ]
SmartValleyEcosystem/smartvalley
SmartValley.WebApi/Estimates/Responses/ScoringCriteriaGroupResponse.cs
810
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core.Transform; using Aliyun.Acs.live.Model.V20161101; using System; using System.Collections.Generic; namespace Aliyun.Acs.live.Transform.V20161101 { public class DescribeLiveMixNotifyConfigResponseUnmarshaller { public static DescribeLiveMixNotifyConfigResponse Unmarshall(UnmarshallerContext context) { DescribeLiveMixNotifyConfigResponse describeLiveMixNotifyConfigResponse = new DescribeLiveMixNotifyConfigResponse(); describeLiveMixNotifyConfigResponse.HttpResponse = context.HttpResponse; describeLiveMixNotifyConfigResponse.RequestId = context.StringValue("DescribeLiveMixNotifyConfig.RequestId"); describeLiveMixNotifyConfigResponse.NotifyUrl = context.StringValue("DescribeLiveMixNotifyConfig.NotifyUrl"); return describeLiveMixNotifyConfigResponse; } } }
42.538462
120
0.782399
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-live/Live/Transform/V20161101/DescribeLiveMixNotifyConfigResponseUnmarshaller.cs
1,659
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("HmsNetworkCommon")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HmsNetworkCommon")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("4.0.20.301")] [assembly: AssemblyFileVersion("1.0.0.0")]
34.555556
78
0.734191
[ "MIT" ]
agspires/Xamarin.Android.Huawei.Hms-master
HmsNetworkCommon/Properties/AssemblyInfo.cs
934
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.Data.Entity.ChangeTracking.Internal; using Microsoft.Data.Entity.Metadata; using Moq; using Xunit; namespace Microsoft.Data.Entity.Tests.ChangeTracking.Internal { public class SimpleEntityKeyTest { [Fact] public void Value_property_is_strongly_typed() { Assert.IsType<int>(new SimpleEntityKey<int>(new Mock<IEntityType>().Object, 77).Value); } [Fact] public void Base_class_value_property_returns_same_as_strongly_typed_value_property() { var key = new SimpleEntityKey<int>(new Mock<IEntityType>().Object, 77); Assert.Equal(77, key.Value); Assert.Equal(77, ((EntityKey)key).Value); } [Fact] public void Only_keys_with_the_same_value_type_and_entity_type_test_as_equal() { var type1 = new Mock<IEntityType>().Object; var type2 = new Mock<IEntityType>().Object; Assert.True(new SimpleEntityKey<int>(type1, 77).Equals(new SimpleEntityKey<int>(type1, 77))); Assert.False(new SimpleEntityKey<int>(type1, 77).Equals(null)); Assert.False(new SimpleEntityKey<int>(type1, 77).Equals(new CompositeEntityKey(type1, new object[] { 77 }))); Assert.False(new SimpleEntityKey<int>(type1, 77).Equals(new SimpleEntityKey<int>(type1, 88))); Assert.False(new SimpleEntityKey<int>(type1, 77).Equals(new SimpleEntityKey<long>(type1, 77))); Assert.False(new SimpleEntityKey<int>(type1, 77).Equals(new SimpleEntityKey<int>(type2, 77))); } [Fact] public void Only_keys_with_the_same_value_and_type_return_same_hashcode() { var type1 = new Mock<IEntityType>().Object; var type2 = new Mock<IEntityType>().Object; Assert.Equal(new SimpleEntityKey<int>(type1, 77).GetHashCode(), new SimpleEntityKey<int>(type1, 77).GetHashCode()); Assert.NotEqual(new SimpleEntityKey<int>(type1, 77).GetHashCode(), new SimpleEntityKey<int>(type1, 88).GetHashCode()); Assert.NotEqual(new SimpleEntityKey<int>(type1, 77).GetHashCode(), new SimpleEntityKey<int>(type2, 77).GetHashCode()); } } }
44.425926
130
0.667361
[ "Apache-2.0" ]
craiggwilson/EntityFramework
test/EntityFramework.Core.Tests/ChangeTracking/Internal/SimpleEntityKeyTest.cs
2,399
C#
using System; namespace ContaBancaria { public class Cliente { public Cliente() { this.Id = 0; this.Nome = ""; this.Cpf = ""; } public int Id { get; set; } public string Nome { get; set; } public string Cpf { get; set; } } }
16.25
40
0.449231
[ "MIT" ]
camilasmarques/fundamentals-OOP
ContaBancaria/Cliente.cs
327
C#
using Aiursoft.Handler.Models; using System.Collections.Generic; namespace Aiursoft.Wrapgate.SDK.Models.ViewModels { public class ViewMyRecordsViewModel : AiurProtocol { public string AppId { get; set; } public List<WrapRecord> Records { get; set; } } }
23.666667
54
0.704225
[ "MIT" ]
gaufung/Infrastructures
src/Infrastructure/Wrapgate.SDK/Models/ViewModels/ViewMyRecordsViewModel.cs
286
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Utilities; using Microsoft.MixedReality.Toolkit.Utilities.Editor; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Events; namespace Microsoft.MixedReality.Toolkit.UI { /// <summary> /// Event base class for events attached to Interactables. /// </summary> [System.Serializable] public class InteractableEvent { /// <summary> /// Base Event used to initialize EventReceiver class /// </summary> public UnityEvent Event = new UnityEvent(); /// <summary> /// ReceiverBase instantiation for this InteractableEvent. Used at runtime by Interactable class /// </summary> [NonSerialized] public ReceiverBase Receiver; /// <summary> /// Defines the type of Receiver to associate. Type must be a class that extends ReceiverBase /// </summary> public Type ReceiverType { get { if (receiverType == null) { if (string.IsNullOrEmpty(AssemblyQualifiedName)) { return null; } receiverType = Type.GetType(AssemblyQualifiedName); } return receiverType; } set { if (!value.IsSubclassOf(typeof(ReceiverBase))) { Debug.LogWarning($"Cannot assign type {value} that does not extend {typeof(ReceiverBase)} to ThemeDefinition"); return; } if (receiverType != value) { receiverType = value; ClassName = receiverType.Name; AssemblyQualifiedName = receiverType.AssemblyQualifiedName; } } } // Unity cannot serialize System.Type, thus must save AssemblyQualifiedName // Field here for Runtime use [NonSerialized] private Type receiverType; [SerializeField] private string ClassName; [SerializeField] private string AssemblyQualifiedName; [SerializeField] private List<InspectorPropertySetting> Settings = new List<InspectorPropertySetting>(); /// <summary> /// Create the event and setup the values from the inspector. If the asset is invalid, /// returns null. /// </summary> public static ReceiverBase CreateReceiver(InteractableEvent iEvent) { if (string.IsNullOrEmpty(iEvent.ClassName)) { // If the class name of this event is empty, the asset is invalid and loading types will throw errors. Return null. return null; } // Temporary workaround // This is to fix a bug in GA where the AssemblyQualifiedName was never actually saved. Functionality would work in editor...but never on device player if (iEvent.ReceiverType == null) { var correctType = TypeCacheUtility.GetSubClasses<ReceiverBase>().Where(s => s?.Name == iEvent.ClassName).First(); iEvent.ReceiverType = correctType; } ReceiverBase newEvent = (ReceiverBase)Activator.CreateInstance(iEvent.ReceiverType, iEvent.Event); InspectorGenericFields<ReceiverBase>.LoadSettings(newEvent, iEvent.Settings); return newEvent; } } }
33.861111
163
0.581898
[ "MIT" ]
AdrianaMusic/MixedRealityToolkit-Unity
Assets/MRTK/SDK/Features/UX/Interactable/Scripts/Events/InteractableEvent.cs
3,659
C#
/* * * (c) Copyright Ascensio System Limited 2010-2020 * * 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 ASC.Mail.Net.SIP.Message { #region usings using System; using System.Text; #endregion /// <summary> /// Implements SIP "Event" value. Defined in RFC 3265. /// </summary> /// <remarks> /// <code> /// RFC 3265 Syntax: /// Event = event-type *( SEMI event-param ) /// event-param = generic-param / ( "id" EQUAL token ) /// </code> /// </remarks> public class SIP_t_Event : SIP_t_ValueWithParams { #region Members private string m_EventType = ""; #endregion #region Properties /// <summary> /// Gets or sets event type. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null vallue is passed.</exception> /// <exception cref="ArgumentException">Is raised when emptu string passed.</exception> public string EventType { get { return m_EventType; } set { if (value == null) { throw new ArgumentNullException("EventType"); } if (value == "") { throw new ArgumentException("Property EventType value can't be '' !"); } m_EventType = value; } } /// <summary> /// Gets or sets 'id' parameter value. Value null means not specified. /// </summary> public string ID { get { SIP_Parameter parameter = Parameters["id"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (string.IsNullOrEmpty(value)) { Parameters.Remove("id"); } else { Parameters.Set("id", value); } } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="value">SIP 'Event' value.</param> public SIP_t_Event(string value) { Parse(value); } #endregion #region Methods /// <summary> /// Parses "Event" from specified value. /// </summary> /// <param name="value">SIP "Event" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "Event" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* Event = event-type *( SEMI event-param ) event-param = generic-param / ( "id" EQUAL token ) */ if (reader == null) { throw new ArgumentNullException("reader"); } // event-type string word = reader.ReadWord(); if (word == null) { throw new SIP_ParseException("SIP Event 'event-type' value is missing !"); } m_EventType = word; // Parse parameters ParseParameters(reader); } /// <summary> /// Converts this to valid "Event" value. /// </summary> /// <returns>Returns "Event" value.</returns> public override string ToStringValue() { /* Event = event-type *( SEMI event-param ) event-param = generic-param / ( "id" EQUAL token ) */ StringBuilder retVal = new StringBuilder(); // event-type retVal.Append(m_EventType); // Add parameters retVal.Append(ParametersToString()); return retVal.ToString(); } #endregion } }
28.047619
101
0.499717
[ "Apache-2.0" ]
Ektai-Solution-Pty-Ltd/CommunityServer
module/ASC.Mail.Autoreply/ASC.Mail.Core/Net/SIP/Message/SIP_t_Event.cs
5,301
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Monster : MonoBehaviour { public float ReflectAmplitude = 10; public Vector3 Reflect(Vector3 targetPosition){ if (this.gameObject.GetComponent<Life> () && this.gameObject.GetComponent<Life> ().IsDead()) { return Vector3.zero; } return ((targetPosition - this.transform.position).normalized)*ReflectAmplitude; } }
26.3125
96
0.760095
[ "MIT" ]
pixel-stuff/LD41-NoName
Assets/Monster.cs
423
C#
using System.Collections; using UnityEngine; public class BloodSpatterEffect : MonoBehaviour { [SerializeField] private Texture2D bloodTexture = null; [SerializeField] private Texture2D bloodNormalMap = null; [SerializeField] [Range(0.0f, 1.0f)] private float bloodAmount = 0.0f; [SerializeField] [Range(0.0f, 1.0f)] private float minBloodAmount = 0.0f; [SerializeField] [Range(0.0f, 1.0f)] private float distortion = 0.0f; [SerializeField] private bool autoFade = false; [SerializeField] private float fadeSpeed = 0.5f; [SerializeField] private Shader shader = null; private Material material = null; private void Update() { // implement the auto fade if (autoFade && bloodAmount > 0.0f) { bloodAmount -= fadeSpeed * Time.deltaTime; bloodAmount = Mathf.Max(bloodAmount, minBloodAmount); distortion = bloodAmount * 0.1f; } } private void OnRenderImage(RenderTexture source, RenderTexture destination) { if (shader == null) { return; } if (material == null) { material = new Material(shader); } if (bloodTexture != null) { material.SetTexture("_BloodTex", bloodTexture); } if (bloodNormalMap != null) { material.SetTexture("_BloodBump", bloodNormalMap); } material.SetFloat("_Distortion", distortion); material.SetFloat("_BloodAmount", bloodAmount); Graphics.Blit(source, destination, material); } }
31.795918
81
0.633504
[ "MIT" ]
csci4160u/examples
10b_and_11a_Interaction/Assets/Scripts/BloodSpatterEffect.cs
1,560
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using PlayEngine.Helpers; namespace librpc.Packets { public class ProcessInfoResponsePacket : IPacket { public UInt32 memorySectionsCount; public List<MemorySection> listMemorySections; public override Byte[] serialize() { throw new InvalidOperationException(); } public static ProcessInfoResponsePacket deserialize(Byte[] bufPacket) { var result = new ProcessInfoResponsePacket(); result.memorySectionsCount = BitConverter.ToUInt32(bufPacket, 0); result.listMemorySections = new List<MemorySection>((Int32)result.memorySectionsCount); for (Int32 i = 4, j = 0; i < bufPacket.Length - 1; i += Marshal.SizeOf(typeof(MemorySection)), j++) { result.listMemorySections.Add(new MemorySection() { name = dotNetExtensions.getNullTerminatedString(bufPacket, i), start = BitConverter.ToUInt64(bufPacket, i + 32), end = BitConverter.ToUInt64(bufPacket, i + 32 + 8), offset = BitConverter.ToUInt64(bufPacket, i + 32 + 8 + 8), protection = (VM_PROT)BitConverter.ToUInt32(bufPacket, i + 32 + 8 + 8 + 8), index = j }); } return result; } } }
38.542857
110
0.638251
[ "MIT" ]
berkay2578/PlayEngine
PlayEngine/Helpers/librpc/Packets/ProcessInfoResponsePacket.cs
1,351
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq.Expressions; using AntData.ORM; using AntData.ORM.Common; using AntData.ORM.Data; using AntData.ORM.DataProvider; using AntData.ORM.Expressions; using AntData.ORM.Extensions; using AntData.ORM.Mapping; using AntData.ORM.SqlProvider; namespace AntData.ORM.DataProvider.Oracle { public class OracleDataProvider : DynamicDataProviderBase { public OracleDataProvider() : this(ProviderName.Oracle, new OracleMappingSchema()) { } protected OracleDataProvider(string name, MappingSchema mappingSchema) : base(name, mappingSchema) { //SqlProviderFlags.IsCountSubQuerySupported = false; SqlProviderFlags.IsIdentityParameterRequired = true; SqlProviderFlags.MaxInListValuesCount = 1000; SetCharField("Char", (r,i) => r.GetString(i).TrimEnd()); SetCharField("NChar", (r,i) => r.GetString(i).TrimEnd()); // ReaderExpressions[new ReaderInfo { FieldType = typeof(decimal), ToType = typeof(TimeSpan) }] = // (Expression<Func<IDataReader,int,TimeSpan>>)((rd,n) => new TimeSpan((long)rd.GetDecimal(n))); _sqlOptimizer = new OracleSqlOptimizer(SqlProviderFlags); } Type _oracleBFile; Type _oracleBinary; Type _oracleBlob; Type _oracleClob; Type _oracleDate; Type _oracleDecimal; Type _oracleIntervalDS; Type _oracleIntervalYM; Type _oracleRef; Type _oracleRefCursor; Type _oracleString; Type _oracleTimeStamp; Type _oracleTimeStampLTZ; Type _oracleTimeStampTZ; Type _oracleXmlType; Type _oracleXmlStream; protected override void OnConnectionTypeCreated(Type connectionType) { var typesNamespace = OracleTools.AssemblyName + ".Types."; _oracleBFile = connectionType.AssemblyEx().GetType(typesNamespace + "OracleBFile", true); _oracleBinary = connectionType.AssemblyEx().GetType(typesNamespace + "OracleBinary", true); _oracleBlob = connectionType.AssemblyEx().GetType(typesNamespace + "OracleBlob", true); _oracleClob = connectionType.AssemblyEx().GetType(typesNamespace + "OracleClob", true); _oracleDate = connectionType.AssemblyEx().GetType(typesNamespace + "OracleDate", true); _oracleDecimal = connectionType.AssemblyEx().GetType(typesNamespace + "OracleDecimal", true); _oracleIntervalDS = connectionType.AssemblyEx().GetType(typesNamespace + "OracleIntervalDS", true); _oracleIntervalYM = connectionType.AssemblyEx().GetType(typesNamespace + "OracleIntervalYM", true); _oracleRefCursor = connectionType.AssemblyEx().GetType(typesNamespace + "OracleRefCursor", true); _oracleString = connectionType.AssemblyEx().GetType(typesNamespace + "OracleString", true); _oracleTimeStamp = connectionType.AssemblyEx().GetType(typesNamespace + "OracleTimeStamp", true); _oracleTimeStampLTZ = connectionType.AssemblyEx().GetType(typesNamespace + "OracleTimeStampLTZ", true); _oracleTimeStampTZ = connectionType.AssemblyEx().GetType(typesNamespace + "OracleTimeStampTZ", true); _oracleRef = connectionType.AssemblyEx().GetType(typesNamespace + "OracleRef", false); _oracleXmlType = connectionType.AssemblyEx().GetType(typesNamespace + "OracleXmlType", false); _oracleXmlStream = connectionType.AssemblyEx().GetType(typesNamespace + "OracleXmlStream", false); SetProviderField(_oracleBFile, _oracleBFile, "GetOracleBFile"); SetProviderField(_oracleBinary, _oracleBinary, "GetOracleBinary"); SetProviderField(_oracleBlob, _oracleBlob, "GetOracleBlob"); SetProviderField(_oracleClob, _oracleClob, "GetOracleClob"); SetProviderField(_oracleDate, _oracleDate, "GetOracleDate"); SetProviderField(_oracleDecimal, _oracleDecimal, "GetOracleDecimal"); SetProviderField(_oracleIntervalDS, _oracleIntervalDS, "GetOracleIntervalDS"); SetProviderField(_oracleIntervalYM, _oracleIntervalYM, "GetOracleIntervalYM"); SetProviderField(_oracleString, _oracleString, "GetOracleString"); SetProviderField(_oracleTimeStamp, _oracleTimeStamp, "GetOracleTimeStamp"); SetProviderField(_oracleTimeStampLTZ, _oracleTimeStampLTZ, "GetOracleTimeStampLTZ"); SetProviderField(_oracleTimeStampTZ, _oracleTimeStampTZ, "GetOracleTimeStampTZ"); try { if (_oracleRef != null) SetProviderField(_oracleRef, _oracleRef, "GetOracleRef"); } catch { } try { if (_oracleXmlType != null) SetProviderField(_oracleXmlType, _oracleXmlType, "GetOracleXmlType"); } catch { } var dataReaderParameter = Expression.Parameter(DataReaderType, "r"); var indexParameter = Expression.Parameter(typeof(int), "i"); { // static DateTimeOffset GetOracleTimeStampTZ(OracleDataReader rd, int idx) // { // var tstz = rd.GetOracleTimeStampTZ(idx); // return new DateTimeOffset( // tstz.Year, tstz.Month, tstz.Day, // tstz.Hour, tstz.Minute, tstz.Second, (int)tstz.Millisecond, // TimeSpan.Parse(tstz.TimeZone.TrimStart('+'))); // } var tstz = Expression.Parameter(_oracleTimeStampTZ, "tstz"); ReaderExpressions[new ReaderInfo { ToType = typeof(DateTimeOffset), ProviderFieldType = _oracleTimeStampTZ }] = Expression.Lambda( Expression.Block( new[] { tstz }, new Expression[] { Expression.Assign(tstz, Expression.Call(dataReaderParameter, "GetOracleTimeStampTZ", null, indexParameter)), Expression.New( MemberHelper.ConstructorOf(() => new DateTimeOffset(0,0,0,0,0,0,0,new TimeSpan())), Expression.PropertyOrField(tstz, "Year"), Expression.PropertyOrField(tstz, "Month"), Expression.PropertyOrField(tstz, "Day"), Expression.PropertyOrField(tstz, "Hour"), Expression.PropertyOrField(tstz, "Minute"), Expression.PropertyOrField(tstz, "Second"), Expression.Convert(Expression.PropertyOrField(tstz, "Millisecond"), typeof(int)), Expression.Call( MemberHelper.MethodOf(() => TimeSpan.Parse("")), Expression.Call( Expression.PropertyOrField(tstz, "TimeZone"), MemberHelper.MethodOf(() => "".TrimStart(' ')), Expression.NewArrayInit(typeof(char), Expression.Constant('+')))) ) }), dataReaderParameter, indexParameter); } { // static DateTimeOffset GetOracleTimeStampLTZ(OracleDataReader rd, int idx) // { // var tstz = rd.GetOracleTimeStampLTZ(idx).ToOracleTimeStampTZ(); // return new DateTimeOffset( // tstz.Year, tstz.Month, tstz.Day, // tstz.Hour, tstz.Minute, tstz.Second, (int)tstz.Millisecond, // TimeSpan.Parse(tstz.TimeZone.TrimStart('+'))); // } var tstz = Expression.Parameter(_oracleTimeStampTZ, "tstz"); ReaderExpressions[new ReaderInfo { ToType = typeof(DateTimeOffset), ProviderFieldType = _oracleTimeStampLTZ }] = Expression.Lambda( Expression.Block( new[] { tstz }, new Expression[] { Expression.Assign( tstz, Expression.Call( Expression.Call(dataReaderParameter, "GetOracleTimeStampLTZ", null, indexParameter), "ToOracleTimeStampTZ", null, null)), Expression.New( MemberHelper.ConstructorOf(() => new DateTimeOffset(0,0,0,0,0,0,0,new TimeSpan())), Expression.PropertyOrField(tstz, "Year"), Expression.PropertyOrField(tstz, "Month"), Expression.PropertyOrField(tstz, "Day"), Expression.PropertyOrField(tstz, "Hour"), Expression.PropertyOrField(tstz, "Minute"), Expression.PropertyOrField(tstz, "Second"), Expression.Convert(Expression.PropertyOrField(tstz, "Millisecond"), typeof(int)), Expression.Call( MemberHelper.MethodOf(() => TimeSpan.Parse("")), Expression.Call( Expression.PropertyOrField(tstz, "TimeZone"), MemberHelper.MethodOf(() => "".TrimStart(' ')), Expression.NewArrayInit(typeof(char), Expression.Constant('+')))) ) }), dataReaderParameter, indexParameter); } { // value = new OracleTimeStampTZ(dto.Year, dto.Month, dto.Day, dto.Hour, dto.Minute, dto.Second, dto.Millisecond, zone); var dto = Expression.Parameter(typeof(DateTimeOffset), "dto"); var zone = Expression.Parameter(typeof(string), "zone"); _createOracleTimeStampTZ = Expression.Lambda<Func<DateTimeOffset,string,object>>( Expression.Convert( Expression.New( _oracleTimeStampTZ.GetConstructorEx(new[] { typeof(int), typeof(int), typeof(int), typeof(int), typeof(int), typeof(int), typeof(int), typeof(string) }), Expression.PropertyOrField(dto, "Year"), Expression.PropertyOrField(dto, "Month"), Expression.PropertyOrField(dto, "Day"), Expression.PropertyOrField(dto, "Hour"), Expression.PropertyOrField(dto, "Minute"), Expression.PropertyOrField(dto, "Second"), Expression.PropertyOrField(dto, "Millisecond"), zone), typeof(object)), dto, zone ).Compile(); } _setSingle = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "BinaryFloat"); _setDouble = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "BinaryDouble"); _setText = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "Clob"); _setNText = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "NClob"); _setImage = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "Blob"); _setBinary = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "Blob"); _setVarBinary = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "Blob"); _setDate = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "Date"); _setSmallDateTime = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "Date"); _setDateTime2 = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "TimeStamp"); _setDateTimeOffset = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "TimeStampTZ"); _setGuid = GetSetParameter(connectionType, "OracleParameter", "OracleDbType", "OracleDbType", "Raw"); MappingSchema.AddScalarType(_oracleBFile, GetNullValue(_oracleBFile), true, DataType.VarChar); // ? MappingSchema.AddScalarType(_oracleBinary, GetNullValue(_oracleBinary), true, DataType.VarBinary); MappingSchema.AddScalarType(_oracleBlob, GetNullValue(_oracleBlob), true, DataType.Blob); // ? MappingSchema.AddScalarType(_oracleClob, GetNullValue(_oracleClob), true, DataType.NText); MappingSchema.AddScalarType(_oracleDate, GetNullValue(_oracleDate), true, DataType.DateTime); MappingSchema.AddScalarType(_oracleDecimal, GetNullValue(_oracleDecimal), true, DataType.Decimal); MappingSchema.AddScalarType(_oracleIntervalDS, GetNullValue(_oracleIntervalDS), true, DataType.Time); // ? MappingSchema.AddScalarType(_oracleIntervalYM, GetNullValue(_oracleIntervalYM), true, DataType.Date); // ? MappingSchema.AddScalarType(_oracleRefCursor, GetNullValue(_oracleRefCursor), true, DataType.Binary); // ? MappingSchema.AddScalarType(_oracleString, GetNullValue(_oracleString), true, DataType.NVarChar); MappingSchema.AddScalarType(_oracleTimeStamp, GetNullValue(_oracleTimeStamp), true, DataType.DateTime2); MappingSchema.AddScalarType(_oracleTimeStampLTZ, GetNullValue(_oracleTimeStampLTZ), true, DataType.DateTimeOffset); MappingSchema.AddScalarType(_oracleTimeStampTZ, GetNullValue(_oracleTimeStampTZ), true, DataType.DateTimeOffset); if (_oracleRef != null) MappingSchema.AddScalarType(_oracleRef, GetNullValue(_oracleRef), true, DataType.Binary); // ? if (_oracleXmlType != null) MappingSchema.AddScalarType(_oracleXmlType, GetNullValue(_oracleXmlType), true, DataType.Xml); if (_oracleXmlStream != null) MappingSchema.AddScalarType(_oracleXmlStream, GetNullValue(_oracleXmlStream), true, DataType.Xml); // ? } static object GetNullValue(Type type) { var getValue = Expression.Lambda<Func<object>>(Expression.Convert(Expression.Field(null, type, "Null"), typeof(object))); try { return getValue.Compile()(); } catch (Exception) { return getValue.Compile()(); } } public override string ParameterSymbol { get { return ":"; } } public override bool InsertWinthIdentityWithNoCache { get { return true; } } public override string ConnectionNamespace { get { return OracleTools.AssemblyName + ".Client"; } } protected override string ConnectionTypeName { get { return "{0}.{1}, {0}".Args(OracleTools.AssemblyName, "Client.OracleConnection"); } } protected override string DataReaderTypeName { get { return "{0}.{1}, {0}".Args(OracleTools.AssemblyName, "Client.OracleDataReader"); } } public bool IsXmlTypeSupported { get { return _oracleXmlType != null; } } public override ISqlBuilder CreateSqlBuilder() { return new OracleSqlBuilder(GetSqlOptimizer(), SqlProviderFlags, MappingSchema.ValueToSqlConverter); } readonly ISqlOptimizer _sqlOptimizer; public override ISqlOptimizer GetSqlOptimizer() { return _sqlOptimizer; } Func<DateTimeOffset,string,object> _createOracleTimeStampTZ; public override void SetParameter(IDbDataParameter parameter, string name, DataType dataType, object value) { switch (dataType) { case DataType.DateTimeOffset: if (value is DateTimeOffset) { var dto = (DateTimeOffset)value; var zone = dto.Offset.ToString("hh\\:mm"); if (!zone.StartsWith("-") && !zone.StartsWith("+")) zone = "+" + zone; value = _createOracleTimeStampTZ(dto, zone); } break; case DataType.Boolean: dataType = DataType.Byte; if (value is bool) value = (bool)value ? (byte)1 : (byte)0; break; case DataType.Guid: if (value is Guid) value = ((Guid)value).ToByteArray(); break; case DataType.Time: // According to http://docs.oracle.com/cd/E16655_01/win.121/e17732/featOraCommand.htm#ODPNT258 // Inference of DbType and OracleDbType from Value: TimeSpan - Object - IntervalDS // if (value is TimeSpan) dataType = DataType.Undefined; break; } if (dataType == DataType.Undefined && value is string && ((string)value).Length >= 4000) { dataType = DataType.NText; } base.SetParameter(parameter, name, dataType, value); } public override Type ConvertParameterType(Type type, DataType dataType) { if (type.IsNullable()) type = type.ToUnderlying(); switch (dataType) { case DataType.DateTimeOffset : if (type == typeof(DateTimeOffset)) return _oracleTimeStampTZ; break; case DataType.Boolean : if (type == typeof(bool)) return typeof(byte); break; case DataType.Guid : if (type == typeof(Guid)) return typeof(byte[]); break; } return base.ConvertParameterType(type, dataType); } static Action<IDbDataParameter> _setSingle; static Action<IDbDataParameter> _setDouble; static Action<IDbDataParameter> _setText; static Action<IDbDataParameter> _setNText; static Action<IDbDataParameter> _setImage; static Action<IDbDataParameter> _setBinary; static Action<IDbDataParameter> _setVarBinary; static Action<IDbDataParameter> _setDate; static Action<IDbDataParameter> _setSmallDateTime; static Action<IDbDataParameter> _setDateTime2; static Action<IDbDataParameter> _setDateTimeOffset; static Action<IDbDataParameter> _setGuid; protected override void SetParameterType(IDbDataParameter parameter, DataType dataType) { if (parameter is BulkCopyReader.Parameter) return; switch (dataType) { case DataType.Byte : parameter.DbType = DbType.Int16; break; case DataType.SByte : parameter.DbType = DbType.Int16; break; case DataType.UInt16 : parameter.DbType = DbType.Int32; break; case DataType.UInt32 : parameter.DbType = DbType.Int64; break; case DataType.UInt64 : parameter.DbType = DbType.Decimal; break; case DataType.VarNumeric : parameter.DbType = DbType.Decimal; break; case DataType.Single : _setSingle (parameter); break; case DataType.Double : _setDouble (parameter); break; case DataType.Text : _setText (parameter); break; case DataType.NText : _setNText (parameter); break; case DataType.Image : _setImage (parameter); break; case DataType.Binary : _setBinary (parameter); break; case DataType.VarBinary : _setVarBinary (parameter); break; case DataType.Date : _setDate (parameter); break; case DataType.SmallDateTime : _setSmallDateTime (parameter); break; case DataType.DateTime2 : _setDateTime2 (parameter); break; case DataType.DateTimeOffset : _setDateTimeOffset (parameter); break; case DataType.Guid : _setGuid (parameter); break; default : base.SetParameterType(parameter, dataType); break; } } #region BulkCopy //OracleBulkCopy _bulkCopy; public override BulkCopyRowsCopied BulkCopy<T>(DataConnection dataConnection, BulkCopyOptions options, IEnumerable<T> source) { //if (_bulkCopy == null) // _bulkCopy = new OracleBulkCopy(this, GetConnectionType()); return new OracleBulkCopy().BulkCopy( options.BulkCopyType == BulkCopyType.Default ? OracleTools.DefaultBulkCopyType : options.BulkCopyType, dataConnection, options, source); } #endregion #region Merge public override int Merge<T>(DataConnection dataConnection, Expression<Func<T,bool>> deletePredicate, bool delete, IEnumerable<T> source, string tableName, string databaseName, string schemaName) { if (delete) throw new LinqToDBException("Oracle MERGE statement does not support DELETE by source."); return new OracleMerge().Merge(dataConnection, deletePredicate, delete, source, tableName, databaseName, schemaName); } #endregion } }
43.481818
140
0.68064
[ "MIT" ]
yuzd/AntData.ORM
AntData/AntData.ORM/DataProvider/Oracle/OracleDataProvider.cs
19,134
C#
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the root of the repo. /* This file provides controller methods to get data from MS Graph. */ using Microsoft.Identity.Client; using System.Configuration; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web.Http; using System; using System.Net; using System.Net.Http; using Office_Add_in_ASPNET_SSO_WebAPI.Helpers; namespace Office_Add_in_ASPNET_SSO_WebAPI.Controllers { [Authorize] public class ValuesController : ApiController { // GET api/values public async Task<HttpResponseMessage> Get() { // OWIN middleware validated the audience, but the scope must also be validated. It must contain "access_as_user". string[] addinScopes = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value.Split(' '); if (!(addinScopes.Contains("access_as_user"))) { return HttpErrorHelper.SendErrorToClient(HttpStatusCode.Unauthorized, null, "Missing access_as_user."); } // Assemble all the information that is needed to get a token for Microsoft Graph using the "on behalf of" flow. // Beginning with MSAL.NET 3.x.x and later, the bootstrapContext is just the bootstrap token itself. string bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext.ToString(); UserAssertion userAssertion = new UserAssertion(bootstrapContext); var cca = ConfidentialClientApplicationBuilder.Create(ConfigurationManager.AppSettings["ida:ClientID"]) .WithRedirectUri(ConfigurationManager.AppSettings["ida:Domain"]) .WithClientSecret(ConfigurationManager.AppSettings["ida:Password"]) .WithAuthority(ConfigurationManager.AppSettings["ida:Authority"]) .Build(); // MSAL.NET adds the profile itself. It will throw an error if you add it redundantly here. string[] graphScopes = { "https://graph.microsoft.com/Files.Read.All" }; // Get the access token for Microsoft Graph. AcquireTokenOnBehalfOfParameterBuilder parameterBuilder = null; AuthenticationResult authResult = null; try { parameterBuilder = cca.AcquireTokenOnBehalfOf(graphScopes, userAssertion); authResult = await parameterBuilder.ExecuteAsync(); } catch (MsalServiceException e) { // Handle request for multi-factor authentication. if (e.Message.StartsWith("AADSTS50076")) { string responseMessage = String.Format("{{\"AADError\":\"AADSTS50076\",\"Claims\":{0}}}", e.Claims); return HttpErrorHelper.SendErrorToClient(HttpStatusCode.Forbidden, null, responseMessage); // The client should recall the getAccessToken function and pass the claims string as the // authChallenge value in the function's Options parameter. } // Handle lack of consent (AADSTS65001) and invalid scope (permission). if ((e.Message.StartsWith("AADSTS65001")) || (e.Message.StartsWith("AADSTS70011: The provided value for the input parameter 'scope' is not valid."))) { return HttpErrorHelper.SendErrorToClient(HttpStatusCode.Forbidden, e, null); } // Handle all other MsalServiceExceptions. else { throw e; } } return await GraphApiHelper.GetOneDriveFileNames(authResult.AccessToken); } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } } }
39.817308
165
0.638976
[ "MIT" ]
ElizabethSamuel-MSFT/PnP-OfficeAddins
Samples/auth/Office-Add-in-ASPNET-SSO/Complete/Office-Add-in-ASPNET-SSO-WebAPI/Controllers/ValuesController.cs
4,143
C#
using OrchardCore.ContentManagement.Metadata; using OrchardCore.ContentManagement.Metadata.Settings; using OrchardCore.Data.Migration; namespace OrchardCore.Html { public class Migrations : DataMigration { IContentDefinitionManager _contentDefinitionManager; public Migrations(IContentDefinitionManager contentDefinitionManager) { _contentDefinitionManager = contentDefinitionManager; } public int Create() { _contentDefinitionManager.AlterPartDefinition("HtmlBodyPart", builder => builder .Attachable() .WithDescription("Provides an HTML Body for your content item.")); return 2; } } }
29.04
92
0.680441
[ "BSD-3-Clause" ]
AlexGuedes1986/FutbolCubano
src/OrchardCore.Modules/OrchardCore.Html/Migrations.cs
726
C#
// This class is based on NuGet's NuGetVersionFactory class from https://github.com/NuGet/NuGet.Client // NuGet is licensed under the Apache license: https://github.com/NuGet/NuGet.Client/blob/dev/LICENSE.txt using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Octopus.Client.Model.Versioning; // ReSharper disable once CheckNamespace namespace Octopus.Client.Model { public partial class SemanticVersion { /// <summary> /// Creates a NuGetVersion from a string representing the semantic version. /// </summary> public static SemanticVersion Parse(string value, bool preserveMissingComponents = false) { if (String.IsNullOrEmpty(value)) { throw new ArgumentException("Value cannot be null or an empty string", nameof(value)); } SemanticVersion ver = null; if (!TryParse(value, out ver, preserveMissingComponents)) { throw new ArgumentException($"'{value}' is not a valid version string", nameof(value)); } return ver; } /// <summary> /// Parses a version string using loose semantic versioning rules that allows 2-4 version components followed /// by an optional special version. /// </summary> public static bool TryParse(string value, out SemanticVersion version, bool preserveMissingComponents = false) { version = null; if (value != null) { Version systemVersion = null; // trim the value before passing it in since we not strict here var sections = ParseSections(value.Trim()); // null indicates the string did not meet the rules if (sections != null && !string.IsNullOrEmpty(sections.Item1)) { var versionPart = sections.Item1; if (versionPart.IndexOf('.') < 0) { // System.Version requires at least a 2 part version to parse. versionPart += ".0"; } if (Version.TryParse(versionPart, out systemVersion)) { // labels if (sections.Item2 != null && !sections.Item2.All(s => IsValidPart(s, false))) { return false; } // build metadata if (sections.Item3 != null && !IsValid(sections.Item3, true)) { return false; } var ver = preserveMissingComponents ? systemVersion : NormalizeVersionValue(systemVersion); var originalVersion = value; if (originalVersion.IndexOf(' ') > -1) { originalVersion = value.Replace(" ", ""); } version = new SemanticVersion(version: ver, releaseLabels: sections.Item2, metadata: sections.Item3 ?? string.Empty, originalVersion: originalVersion); return true; } } } return false; } /// <summary> /// Parses a version string using strict SemVer rules. /// </summary> public static bool TryParseStrict(string value, out SemanticVersion version) { version = null; StrictSemanticVersion semVer = null; if (TryParse(value, out semVer)) { version = new SemanticVersion(semVer.Major, semVer.Minor, semVer.Patch, 0, semVer.ReleaseLabels, semVer.Metadata); } return true; } /// <summary> /// Creates a legacy version string using System.Version /// </summary> private static string GetLegacyString(Version version, IEnumerable<string> releaseLabels, string metadata) { var sb = new StringBuilder(version.ToString()); if (releaseLabels != null) { sb.AppendFormat(CultureInfo.InvariantCulture, "-{0}", String.Join(".", releaseLabels)); } if (!String.IsNullOrEmpty(metadata)) { sb.AppendFormat(CultureInfo.InvariantCulture, "+{0}", metadata); } return sb.ToString(); } private static IEnumerable<string> ParseReleaseLabels(string releaseLabels) { if (!String.IsNullOrEmpty(releaseLabels)) { return releaseLabels.Split('.'); } return null; } } }
34.608108
130
0.505467
[ "Apache-2.0" ]
BlythMeister/OctopusClients
source/Octopus.Server.Client/Model/Versioning/SemanticVersionFactory.cs
5,124
C#
using SmartTraitsDefs; namespace SmartTraits.Tests.Stage5 { [TraitInterface] interface IAddress { string Address { get; set; } string City { get; set; } string State { get; set; } string ZipCode { get; set; } string GetAddress(); } }
18.3125
36
0.576792
[ "MIT" ]
baskren/smarttraits
SmartTraits.Demo/Stage5/Interfaces/IAddress.cs
295
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using Rtsp.Messages; namespace Rtsp.Messages.Tests { [TestFixture] public class RtspMessageTest { //Put a name on test to permit VSNunit to handle them. [Test] [TestCase("OPTIONS * RTSP/1.0", RtspRequest.RequestType.OPTIONS, TestName = "GetRtspMessageRequest-OPTIONS")] [TestCase("SETUP rtsp://audio.example.com/twister/audio.en RTSP/1.0", RtspRequest.RequestType.SETUP, TestName = "GetRtspMessageRequest-SETUP")] [TestCase("PLAY rtsp://audio.example.com/twister/audio.en RTSP/1.0", RtspRequest.RequestType.PLAY, TestName = "GetRtspMessageRequest-PLAY")] public void GetRtspMessageRequest(string requestLine, RtspRequest.RequestType requestType) { RtspMessage oneMessage = RtspMessage.GetRtspMessage(requestLine); Assert.IsInstanceOfType(typeof(RtspRequest), oneMessage); RtspRequest oneRequest = oneMessage as RtspRequest; Assert.AreEqual(requestType, oneRequest.RequestTyped); } //Put a name on test to permit VSNunit to handle them. [Test] [TestCase("RTSP/1.0 551 Option not supported", 551, "Option not supported", TestName = "GetRtspMessageResponse-551")] public void GetRtspMessageResponse(string requestLine, int returnCode, string returnMessage) { RtspMessage oneMessage = RtspMessage.GetRtspMessage(requestLine); Assert.IsInstanceOfType(typeof(RtspResponse), oneMessage); RtspResponse oneResponse = oneMessage as RtspResponse; Assert.AreEqual(returnCode, oneResponse.ReturnCode); Assert.AreEqual(returnMessage, oneResponse.ReturnMessage); } } }
42.97619
151
0.701385
[ "MIT" ]
CurtHubb/SharpRTSP_Xamarin
RTSP.Tests/Messages/RTSPMessageTest.cs
1,807
C#
// <copyright> // Copyright 2013 by the Spark Development Network // // 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. // </copyright> // using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using Newtonsoft.Json; using Rock; using Rock.Constants; using Rock.Data; using Rock.Model; using Rock.Security; using Rock.Web.Cache; using Rock.Web.UI; using Rock.Web.UI.Controls; namespace RockWeb.Blocks.CheckIn { /// <summary> /// /// </summary> [DisplayName( "Check-in Configuration" )] [Category( "Check-in" )] [Description( "Helps to configure the check-in workflow." )] public partial class CheckinConfiguration : RockBlock, IDetailBlock { #region Properties private List<Guid> ProcessedGroupTypeIds = new List<Guid>(); private List<Guid> ProcessedGroupIds = new List<Guid>(); private List<GroupType> GroupTypesState = new List<GroupType>(); private List<Group> CheckinGroupsState = new List<Group>(); private Dictionary<Guid, List<CheckinGroupTypeEditor.CheckinLabelAttributeInfo>> GroupTypeCheckinLabelAttributesState = new Dictionary<Guid, List<CheckinGroupTypeEditor.CheckinLabelAttributeInfo>>(); #endregion #region Base Control Methods /// <summary> /// Restores the view-state information from a previous user control request that was saved by the <see cref="M:System.Web.UI.UserControl.SaveViewState" /> method. /// </summary> /// <param name="savedState">An <see cref="T:System.Object" /> that represents the user control state to be restored.</param> protected override void LoadViewState( object savedState ) { base.LoadViewState( savedState ); string json = ViewState["GroupTypesState"] as string; if ( string.IsNullOrWhiteSpace( json ) ) { GroupTypesState = new List<GroupType>(); } else { GroupTypesState = JsonConvert.DeserializeObject<List<GroupType>>( json ); } json = ViewState["CheckinGroupsState"] as string; if ( string.IsNullOrWhiteSpace( json ) ) { CheckinGroupsState = new List<Group>(); } else { CheckinGroupsState = JsonConvert.DeserializeObject<List<Group>>( json ); } json = ViewState["GroupTypeCheckinLabelAttributesState"] as string; if ( string.IsNullOrWhiteSpace( json ) ) { GroupTypeCheckinLabelAttributesState = new Dictionary<Guid, List<CheckinGroupTypeEditor.CheckinLabelAttributeInfo>>(); } else { GroupTypeCheckinLabelAttributesState = JsonConvert.DeserializeObject<Dictionary<Guid, List<CheckinGroupTypeEditor.CheckinLabelAttributeInfo>>>( json ); } BuildGroupTypeEditorControls(); } /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit( EventArgs e ) { base.OnInit( e ); // Save and Cancel should not confirm exit btnSave.OnClientClick = string.Format( "javascript:$('#{0}').val('');return true;", confirmExit.ClientID ); btnCancel.OnClientClick = string.Format( "javascript:$('#{0}').val('');return true;", confirmExit.ClientID ); } /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); if ( !Page.IsPostBack ) { ShowDetail( PageParameter( "groupTypeId" ).AsInteger() ); } else { // assume if there is a PostBack, that something changed and that confirmExit should be enabled confirmExit.Enabled = true; } // handle sort events string postbackArgs = Request.Params["__EVENTARGUMENT"]; if ( !string.IsNullOrWhiteSpace( postbackArgs ) ) { string[] nameValue = postbackArgs.Split( new char[] { ':' } ); if ( nameValue.Count() == 2 ) { string eventParam = nameValue[0]; if ( eventParam.Equals( "re-order-grouptype" ) || eventParam.Equals( "re-order-group" ) ) { string[] values = nameValue[1].Split( new char[] { ';' } ); if ( values.Count() == 2 ) { SortGroupTypeListContents( eventParam, values ); } } } } } /// <summary> /// Saves any user control view-state changes that have occurred since the last page postback. /// </summary> /// <returns> /// Returns the user control's current view state. If there is no view state associated with the control, it returns null. /// </returns> protected override object SaveViewState() { SaveGroupTypeControls(); var jsonSetting = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = new Rock.Utility.IgnoreUrlEncodedKeyContractResolver() }; ViewState["GroupTypesState"] = JsonConvert.SerializeObject( GroupTypesState, Formatting.None, jsonSetting ); ViewState["CheckinGroupsState"] = JsonConvert.SerializeObject( CheckinGroupsState, Formatting.None, jsonSetting ); ViewState["GroupTypeCheckinLabelAttributesState"] = JsonConvert.SerializeObject( GroupTypeCheckinLabelAttributesState, Formatting.None, jsonSetting ); return base.SaveViewState(); } /// <summary> /// Sorts the group type list contents. /// </summary> /// <param name="eventParam">The event parameter.</param> /// <param name="values">The values.</param> private void SortGroupTypeListContents( string eventParam, string[] values ) { if ( eventParam.Equals( "re-order-grouptype" ) ) { var allCheckinGroupTypeEditors = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>(); Guid groupTypeGuid = new Guid( values[0] ); int newIndex = int.Parse( values[1] ); CheckinGroupTypeEditor sortedGroupTypeEditor = allCheckinGroupTypeEditors.FirstOrDefault( a => a.GroupTypeGuid.Equals( groupTypeGuid ) ); if ( sortedGroupTypeEditor != null ) { var siblingGroupTypes = allCheckinGroupTypeEditors.Where( a => a.ParentGroupTypeEditor == sortedGroupTypeEditor.ParentGroupTypeEditor ).ToList(); Control parentControl = sortedGroupTypeEditor.Parent; parentControl.Controls.Remove( sortedGroupTypeEditor ); if ( newIndex >= siblingGroupTypes.Count() ) { parentControl.Controls.Add( sortedGroupTypeEditor ); } else { parentControl.Controls.AddAt( newIndex, sortedGroupTypeEditor ); } } } else if ( eventParam.Equals( "re-order-group" ) ) { var allCheckinGroupEditors = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupEditor>(); Guid groupGuid = new Guid( values[0] ); int newIndex = int.Parse( values[1] ); CheckinGroupEditor sortedGroupEditor = allCheckinGroupEditors.FirstOrDefault( a => a.GroupGuid.Equals( groupGuid ) ); if ( sortedGroupEditor != null ) { var siblingGroupEditors = allCheckinGroupEditors .Where( a => a.GroupTypeId == sortedGroupEditor.GroupTypeId && a.Parent.ClientID == sortedGroupEditor.Parent.ClientID ) .ToList(); Control parentControl = sortedGroupEditor.Parent; // parent control has other controls, so just just remove all the checkingroupeditors, sort them, and add them back in the new order foreach ( var item in siblingGroupEditors ) { parentControl.Controls.Remove( item ); } siblingGroupEditors.Remove( sortedGroupEditor ); if ( newIndex >= siblingGroupEditors.Count() ) { siblingGroupEditors.Add( sortedGroupEditor ); } else { siblingGroupEditors.Insert( newIndex, sortedGroupEditor ); } foreach ( var item in siblingGroupEditors ) { parentControl.Controls.Add( item ); } ExpandGroupEditorParent( sortedGroupEditor ); } } } #endregion Control Methods #region Dynamic Controls /// <summary> /// Saves the state of the group type controls to viewstate. /// </summary> private void SaveGroupTypeControls() { var rockContext = new RockContext(); // save all the base grouptypes (along with their children) to viewstate GroupTypesState = new List<GroupType>(); foreach ( var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType<CheckinGroupTypeEditor>() ) { var groupType = checkinGroupTypeEditor.GetCheckinGroupType( rockContext ); GroupTypesState.Add( groupType ); } // get all GroupTypes' editors to save groups and labels var recursiveGroupTypeEditors = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>().ToList(); // save each GroupTypes' Groups to ViewState (since GroupType.Groups are not Serialized) CheckinGroupsState = new List<Group>(); foreach ( var editor in recursiveGroupTypeEditors ) { var groupType = editor.GetCheckinGroupType( rockContext ); CheckinGroupsState.AddRange( groupType.Groups ); } // save all the checkinlabels for all the grouptypes (recursively) to viewstate GroupTypeCheckinLabelAttributesState = new Dictionary<Guid, List<CheckinGroupTypeEditor.CheckinLabelAttributeInfo>>(); foreach ( var checkinGroupTypeEditor in recursiveGroupTypeEditors ) { GroupTypeCheckinLabelAttributesState.Add( checkinGroupTypeEditor.GroupTypeGuid, checkinGroupTypeEditor.CheckinLabels ); } } /// <summary> /// Builds the state of the group type editor controls from view. /// </summary> private void BuildGroupTypeEditorControls() { phCheckinGroupTypes.Controls.Clear(); var rockContext = new RockContext(); // GroupTypeViewStateList only contains parent GroupTypes, so get all the child GroupTypes and assign their groups var allGroupTypesList = GroupTypesState.Flatten<GroupType>( gt => gt.ChildGroupTypes ); // load each GroupTypes' Groups from ViewState (since GroupType.Groups are not Serialized) foreach ( var groupTypeGroups in CheckinGroupsState.GroupBy( g => g.GroupType.Guid ) ) { var groupType = allGroupTypesList.FirstOrDefault( a => a.Guid == groupTypeGroups.Key ); if ( groupType != null ) { groupType.Groups = new List<Group>(); foreach ( var group in groupTypeGroups ) { groupType.Groups.Add( group ); } } } // Build out Parent GroupTypes controls (Child GroupTypes controls are built recursively) ProcessedGroupTypeIds = new List<Guid>(); foreach ( var groupType in GroupTypesState ) { CreateGroupTypeEditorControls( groupType, phCheckinGroupTypes, rockContext ); } } /// <summary> /// Creates the group type editor controls. /// </summary> /// <param name="groupType">Type of the group.</param> /// <param name="parentControl">The parent control.</param> /// <param name="rockContext">The rock context.</param> /// <param name="createExpanded">if set to <c>true</c> [create expanded].</param> private void CreateGroupTypeEditorControls( GroupType groupType, Control parentControl, RockContext rockContext, bool createExpanded = false ) { ProcessedGroupTypeIds.Add( groupType.Guid ); CheckinGroupTypeEditor groupTypeEditor = new CheckinGroupTypeEditor(); groupTypeEditor.ID = "GroupTypeEditor_" + groupType.Guid.ToString( "N" ); groupTypeEditor.SetGroupType( groupType.Id, groupType.Guid, groupType.Name, groupType.InheritedGroupTypeId ); groupTypeEditor.AddGroupClick += groupTypeEditor_AddGroupClick; groupTypeEditor.AddGroupTypeClick += groupTypeEditor_AddGroupTypeClick; groupTypeEditor.DeleteCheckinLabelClick += groupTypeEditor_DeleteCheckinLabelClick; groupTypeEditor.AddCheckinLabelClick += groupTypeEditor_AddCheckinLabelClick; groupTypeEditor.DeleteGroupTypeClick += groupTypeEditor_DeleteGroupTypeClick; groupTypeEditor.CheckinLabels = null; if ( createExpanded ) { groupTypeEditor.Expanded = true; } if ( GroupTypeCheckinLabelAttributesState.ContainsKey( groupType.Guid ) ) { groupTypeEditor.CheckinLabels = GroupTypeCheckinLabelAttributesState[groupType.Guid]; } if ( groupTypeEditor.CheckinLabels == null ) { // load CheckInLabels from Database if they haven't been set yet groupTypeEditor.CheckinLabels = new List<CheckinGroupTypeEditor.CheckinLabelAttributeInfo>(); groupType.LoadAttributes( rockContext ); List<string> labelAttributeKeys = CheckinGroupTypeEditor.GetCheckinLabelAttributes( groupType.Attributes, rockContext ) .OrderBy( a => a.Value.Order ) .Select( a => a.Key ).ToList(); BinaryFileService binaryFileService = new BinaryFileService( rockContext ); foreach ( string key in labelAttributeKeys ) { var attributeValue = groupType.GetAttributeValue( key ); Guid binaryFileGuid = attributeValue.AsGuid(); var fileName = binaryFileService.Queryable().Where( a => a.Guid == binaryFileGuid ).Select( a => a.FileName ).FirstOrDefault(); if ( fileName != null ) { groupTypeEditor.CheckinLabels.Add( new CheckinGroupTypeEditor.CheckinLabelAttributeInfo { AttributeKey = key, BinaryFileGuid = binaryFileGuid, FileName = fileName } ); } } } parentControl.Controls.Add( groupTypeEditor ); // get the GroupType from the control just in case the InheritedFrom changed var childGroupGroupType = groupTypeEditor.GetCheckinGroupType( rockContext ); // Find the groups of this type, who's parent is null, or another group type ( "root" groups ). var allGroupIds = groupType.Groups.Select( g => g.Id).ToList(); ProcessedGroupIds = new List<Guid>(); foreach ( var childGroup in groupType.Groups .Where( g => !g.ParentGroupId.HasValue || !allGroupIds.Contains( g.ParentGroupId.Value ) ) .OrderBy( a => a.Order ) .ThenBy( a => a.Name ) ) { childGroup.GroupType = childGroupGroupType; CreateGroupEditorControls( childGroup, groupTypeEditor, rockContext, false ); } foreach ( var childGroupType in groupType.ChildGroupTypes .Where( t => !ProcessedGroupTypeIds.Contains( t.Guid ) ) .OrderBy( a => a.Order ) .ThenBy( a => a.Name ) ) { CreateGroupTypeEditorControls( childGroupType, groupTypeEditor, rockContext ); } } /// <summary> /// Handles the DeleteGroupTypeClick event of the groupTypeEditor control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void groupTypeEditor_DeleteGroupTypeClick( object sender, EventArgs e ) { CheckinGroupTypeEditor groupTypeEditor = sender as CheckinGroupTypeEditor; var rockContext = new RockContext(); var groupType = GroupTypeCache.Read( groupTypeEditor.GroupTypeGuid ); if ( groupType != null ) { // Warn if this GroupType or any of its child grouptypes (recursive) is being used as an Inherited Group Type. Probably shouldn't happen, but just in case if ( IsInheritedGroupTypeRecursive( groupType, rockContext ) ) { nbDeleteWarning.Text = "WARNING - Cannot delete. This group type or one of its child group types is assigned as an inherited group type."; nbDeleteWarning.Visible = true; return; } } groupTypeEditor.Parent.Controls.Remove( groupTypeEditor ); } /// <summary> /// Determines whether [is inherited group type recursive] [the specified group type]. /// </summary> /// <param name="groupType">Type of the group.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> private static bool IsInheritedGroupTypeRecursive( GroupTypeCache groupType, RockContext rockContext, List<int> typesChecked = null ) { // Track the groups that have been checked since group types can have themselves as a child typesChecked = typesChecked ?? new List<int>(); if ( !typesChecked.Contains( groupType.Id ) ) { typesChecked.Add( groupType.Id ); if ( new GroupTypeService( rockContext ).Queryable().Any( a => a.InheritedGroupType.Guid == groupType.Guid ) ) { return true; } foreach ( var childGroupType in groupType.ChildGroupTypes.Where( t => !typesChecked.Contains( t.Id ) ) ) { if ( IsInheritedGroupTypeRecursive( childGroupType, rockContext, typesChecked ) ) { return true; } } } return false; } /// <summary> /// Handles the Click event of the lbAddCheckinArea control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbAddCheckinArea_Click( object sender, EventArgs e ) { int parentGroupTypeId = this.PageParameter( "groupTypeid" ).AsInteger(); var rockContext = new RockContext(); GroupType parentGroupType = new GroupTypeService( rockContext ).Get( parentGroupTypeId ); // CheckinArea is GroupType entity GroupType checkinArea = new GroupType(); checkinArea.Guid = Guid.NewGuid(); checkinArea.IsSystem = false; checkinArea.ShowInNavigation = false; checkinArea.TakesAttendance = true; checkinArea.AttendanceRule = AttendanceRule.AddOnCheckIn; checkinArea.AttendancePrintTo = PrintTo.Default; checkinArea.ParentGroupTypes = new List<GroupType>(); checkinArea.ParentGroupTypes.Add( parentGroupType ); ProcessedGroupTypeIds = new List<Guid>(); CreateGroupTypeEditorControls( checkinArea, phCheckinGroupTypes, rockContext, true ); } /// <summary> /// Handles the AddGroupTypeClick event of the groupTypeEditor control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void groupTypeEditor_AddGroupTypeClick( object sender, EventArgs e ) { var rockContext = new RockContext(); CheckinGroupTypeEditor parentEditor = sender as CheckinGroupTypeEditor; parentEditor.Expanded = true; // CheckinArea is GroupType entity GroupType checkinArea = new GroupType(); checkinArea.Guid = Guid.NewGuid(); checkinArea.IsSystem = false; checkinArea.ShowInNavigation = false; checkinArea.TakesAttendance = true; checkinArea.AttendanceRule = AttendanceRule.AddOnCheckIn; checkinArea.AttendancePrintTo = PrintTo.Default; checkinArea.ParentGroupTypes = new List<GroupType>(); checkinArea.ParentGroupTypes.Add( parentEditor.GetCheckinGroupType( rockContext ) ); ProcessedGroupTypeIds = new List<Guid>(); CreateGroupTypeEditorControls( checkinArea, parentEditor, rockContext, true ); } /// <summary> /// Handles the AddGroupClick event of the groupTypeEditor control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void groupTypeEditor_AddGroupClick( object sender, EventArgs e ) { CheckinGroupTypeEditor parentGroupTypeEditor = sender as CheckinGroupTypeEditor; parentGroupTypeEditor.Expanded = true; Group checkinGroup = new Group(); checkinGroup.Guid = Guid.NewGuid(); checkinGroup.IsActive = true; checkinGroup.IsPublic = true; checkinGroup.IsSystem = false; checkinGroup.Order = parentGroupTypeEditor.Controls.OfType<CheckinGroupEditor>().Count(); // set GroupType by Guid (just in case the parent groupType hasn't been added to the database yet) checkinGroup.GroupType = new GroupType { Guid = parentGroupTypeEditor.GroupTypeGuid }; var rockContext = new RockContext(); ProcessedGroupIds = new List<Guid>(); CreateGroupEditorControls( checkinGroup, parentGroupTypeEditor, rockContext, true ); } /// <summary> /// Creates the group editor controls. /// </summary> /// <param name="group">The group.</param> /// <param name="parentControl">The parent control.</param> /// <param name="rockContext">The rock context.</param> /// <param name="createExpanded">if set to <c>true</c> [create expanded].</param> private void CreateGroupEditorControls( Group group, Control parentControl, RockContext rockContext, bool createExpanded = false ) { ProcessedGroupIds.Add( group.Guid ); CheckinGroupEditor groupEditor = new CheckinGroupEditor(); groupEditor.ID = "GroupEditor_" + group.Guid.ToString( "N" ); if ( createExpanded ) { groupEditor.Expanded = true; } parentControl.Controls.Add( groupEditor ); groupEditor.SetGroup( group, rockContext ); var locationService = new LocationService( rockContext ); var locationQry = locationService.Queryable().Select( a => new { a.Id, a.ParentLocationId, a.Name } ); groupEditor.Locations = new List<CheckinGroupEditor.LocationGridItem>(); foreach ( var location in group.GroupLocations.Select( a => a.Location ).OrderBy( o => o.Name ) ) { var gridItem = new CheckinGroupEditor.LocationGridItem(); gridItem.LocationId = location.Id; gridItem.Name = location.Name; gridItem.FullNamePath = location.Name; gridItem.ParentLocationId = location.ParentLocationId; var parentLocationId = location.ParentLocationId; while ( parentLocationId != null ) { var parentLocation = locationQry.FirstOrDefault( a => a.Id == parentLocationId ); gridItem.FullNamePath = parentLocation.Name + " > " + gridItem.FullNamePath; parentLocationId = parentLocation.ParentLocationId; } groupEditor.Locations.Add( gridItem ); } groupEditor.AddGroupClick += groupEditor_AddGroupClick; groupEditor.AddLocationClick += groupEditor_AddLocationClick; groupEditor.DeleteLocationClick += groupEditor_DeleteLocationClick; groupEditor.DeleteGroupClick += groupEditor_DeleteGroupClick; foreach ( var childGroup in group.Groups .Where( a => !ProcessedGroupIds.Contains( a.Guid ) && a.GroupType.Guid == group.GroupType.Guid ) .OrderBy( a => a.Order ).ThenBy( a => a.Name ) ) { childGroup.GroupType = group.GroupType; CreateGroupEditorControls( childGroup, groupEditor, rockContext, false ); } } /// <summary> /// Handles the AddGroupClick event of the groupTypeEditor control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void groupEditor_AddGroupClick( object sender, EventArgs e ) { CheckinGroupEditor parentGroupEditor = sender as CheckinGroupEditor; parentGroupEditor.Expanded = true; Group checkinGroup = new Group(); checkinGroup.Guid = Guid.NewGuid(); checkinGroup.IsActive = true; checkinGroup.IsPublic = true; checkinGroup.IsSystem = false; // set GroupType by Guid (just in case the parent groupType hasn't been added to the database yet) checkinGroup.GroupType = new GroupType { Guid = parentGroupEditor.GetParentGroupTypeEditor().GroupTypeGuid }; var rockContext = new RockContext(); ProcessedGroupIds = new List<Guid>(); CreateGroupEditorControls( checkinGroup, parentGroupEditor, rockContext, true ); } /// <summary> /// Handles the DeleteGroupClick event of the groupEditor control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void groupEditor_DeleteGroupClick( object sender, EventArgs e ) { CheckinGroupEditor groupEditor = sender as CheckinGroupEditor; GroupService groupService = new GroupService( new RockContext() ); Group groupDB = groupService.Get( groupEditor.GroupGuid ); if ( groupDB != null ) { string errorMessage; if ( !groupService.CanDelete( groupDB, out errorMessage ) ) { nbDeleteWarning.Text = "WARNING - Cannot Delete: " + errorMessage; nbDeleteWarning.Visible = true; return; } } groupEditor.Parent.Controls.Remove( groupEditor ); } #endregion ViewState and Dynamic Controls #region CheckinLabel Add/Delete /// <summary> /// Handles the AddCheckinLabelClick event of the groupTypeEditor control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void groupTypeEditor_AddCheckinLabelClick( object sender, EventArgs e ) { CheckinGroupTypeEditor checkinGroupTypeEditor = sender as CheckinGroupTypeEditor; // set a hidden field value for the GroupType Guid so we know which GroupType to add the label to hfAddCheckinLabelGroupTypeGuid.Value = checkinGroupTypeEditor.GroupTypeGuid.ToString(); Guid binaryFileTypeCheckinLabelGuid = new Guid( Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL ); var binaryFileService = new BinaryFileService( new RockContext() ); ddlCheckinLabel.Items.Clear(); ddlCheckinLabel.AutoPostBack = false; ddlCheckinLabel.Required = true; ddlCheckinLabel.Items.Add( new ListItem() ); var list = binaryFileService.Queryable().Where( a => a.BinaryFileType.Guid.Equals( binaryFileTypeCheckinLabelGuid ) && a.IsTemporary == false ).OrderBy( a => a.FileName ).ToList(); foreach ( var item in list ) { // add checkinlabels to dropdownlist if they aren't already a checkin label for this grouptype if ( !checkinGroupTypeEditor.CheckinLabels.Select( a => a.BinaryFileGuid ).Contains( item.Guid ) ) { ddlCheckinLabel.Items.Add( new ListItem( item.FileName, item.Guid.ToString() ) ); } } mdAddCheckinLabel.Show(); } /// <summary> /// Handles the DeleteCheckinLabelClick event of the groupTypeEditor control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void groupTypeEditor_DeleteCheckinLabelClick( object sender, RowEventArgs e ) { CheckinGroupTypeEditor checkinGroupTypeEditor = sender as CheckinGroupTypeEditor; string attributeKey = e.RowKeyValue as string; var label = checkinGroupTypeEditor.CheckinLabels.FirstOrDefault( a => a.AttributeKey == attributeKey ); checkinGroupTypeEditor.CheckinLabels.Remove( label ); checkinGroupTypeEditor.Expanded = true; } /// <summary> /// Handles the Click event of the btnAddCheckinLabel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnAddCheckinLabel_Click( object sender, EventArgs e ) { var groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>().FirstOrDefault( a => a.GroupTypeGuid == new Guid( hfAddCheckinLabelGroupTypeGuid.Value ) ); groupTypeEditor.Expanded = true; var checkinLabelAttributeInfo = new CheckinGroupTypeEditor.CheckinLabelAttributeInfo(); checkinLabelAttributeInfo.BinaryFileGuid = ddlCheckinLabel.SelectedValue.AsGuid(); checkinLabelAttributeInfo.FileName = ddlCheckinLabel.SelectedItem.Text; // have the attribute key just be the filename without spaces, but make sure it is not a duplicate string attributeKey = checkinLabelAttributeInfo.FileName.Replace( " ", string.Empty ); checkinLabelAttributeInfo.AttributeKey = attributeKey; int duplicateInc = 1; while ( groupTypeEditor.CheckinLabels.Select( a => a.AttributeKey ).Contains( attributeKey + duplicateInc.ToString() ) ) { // append number to end until it isn't a duplicate checkinLabelAttributeInfo.AttributeKey += attributeKey + duplicateInc.ToString(); duplicateInc++; } groupTypeEditor.CheckinLabels.Add( checkinLabelAttributeInfo ); mdAddCheckinLabel.Hide(); pnlDetails.Visible = true; } #endregion CheckinLabel Add/Delete #region Location Add/Delete /// <summary> /// Handles the AddLocationClick event of the groupEditor control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void groupEditor_AddLocationClick( object sender, EventArgs e ) { CheckinGroupEditor checkinGroupEditor = sender as CheckinGroupEditor; // set a hidden field value for the Group Guid so we know which Group to add the location to hfAddLocationGroupGuid.Value = checkinGroupEditor.GroupGuid.ToString(); checkinGroupEditor.Expanded = true; ExpandGroupEditorParent( checkinGroupEditor ); mdLocationPicker.Show(); } /// <summary> /// Handles the DeleteLocationClick event of the groupEditor control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void groupEditor_DeleteLocationClick( object sender, RowEventArgs e ) { CheckinGroupEditor checkinGroupEditor = sender as CheckinGroupEditor; checkinGroupEditor.Expanded = true; ExpandGroupEditorParent( checkinGroupEditor ); var location = checkinGroupEditor.Locations.FirstOrDefault( a => a.LocationId == e.RowKeyId ); checkinGroupEditor.Locations.Remove( location ); } /// <summary> /// Handles the Click event of the btnAddLocation control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnAddLocation_Click( object sender, EventArgs e ) { CheckinGroupEditor checkinGroupEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupEditor>().FirstOrDefault( a => a.GroupGuid == new Guid( hfAddLocationGroupGuid.Value ) ); // Add the location (ignore if they didn't pick one, or they picked one that already is selected) var location = new LocationService( new RockContext() ).Get( locationPicker.SelectedValue.AsInteger() ); if ( location != null ) { if ( !checkinGroupEditor.Locations.Any( a => a.LocationId == location.Id ) ) { CheckinGroupEditor.LocationGridItem gridItem = new CheckinGroupEditor.LocationGridItem(); gridItem.LocationId = location.Id; gridItem.Name = location.Name; gridItem.FullNamePath = location.Name; gridItem.ParentLocationId = location.ParentLocationId; var parentLocation = location.ParentLocation; while ( parentLocation != null ) { gridItem.FullNamePath = parentLocation.Name + " > " + gridItem.FullNamePath; parentLocation = parentLocation.ParentLocation; } checkinGroupEditor.Locations.Add( gridItem ); } } checkinGroupEditor.Expanded = true; ExpandGroupEditorParent( checkinGroupEditor ); mdLocationPicker.Hide(); } #endregion Location Add/Delete /// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click( object sender, EventArgs e ) { bool hasValidationErrors = false; var rockContext = new RockContext(); GroupTypeService groupTypeService = new GroupTypeService( rockContext ); GroupService groupService = new GroupService( rockContext ); AttributeService attributeService = new AttributeService( rockContext ); GroupLocationService groupLocationService = new GroupLocationService( rockContext ); int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt(); var groupTypeUIList = new List<GroupType>(); foreach ( var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType<CheckinGroupTypeEditor>().ToList() ) { var groupType = checkinGroupTypeEditor.GetCheckinGroupType( rockContext ); groupTypeUIList.Add( groupType ); } var groupTypeDBList = new List<GroupType>(); var groupTypesToDelete = new List<GroupType>(); var groupsToDelete = new List<Group>(); var groupTypesToAddUpdate = new List<GroupType>(); var groupsToAddUpdate = new List<Group>(); GroupType parentGroupTypeDB = groupTypeService.Get( parentGroupTypeId ); GroupType parentGroupTypeUI = parentGroupTypeDB.Clone( false ); parentGroupTypeUI.ChildGroupTypes = groupTypeUIList; PopulateDeleteLists( groupTypesToDelete, groupsToDelete, parentGroupTypeDB, parentGroupTypeUI ); PopulateAddUpdateLists( groupTypesToAddUpdate, groupsToAddUpdate, parentGroupTypeUI ); int binaryFileFieldTypeID = FieldTypeCache.Read( Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid() ).Id; rockContext.WrapTransaction( () => { // delete in reverse order to get deepest child items first groupsToDelete.Reverse(); foreach ( var groupToDelete in groupsToDelete ) { groupService.Delete( groupToDelete ); } // delete in reverse order to get deepest child items first groupTypesToDelete.Reverse(); foreach ( var groupTypeToDelete in groupTypesToDelete ) { groupTypeService.Delete( groupTypeToDelete ); } rockContext.SaveChanges(); // Add/Update grouptypes and groups that are in the UI // Note: We'll have to save all the groupTypes without changing the DB value of ChildGroupTypes, then come around again and save the ChildGroupTypes // since the ChildGroupTypes may not exist in the database yet foreach ( GroupType groupTypeUI in groupTypesToAddUpdate ) { GroupType groupTypeDB = groupTypeService.Get( groupTypeUI.Guid ); if ( groupTypeDB == null ) { groupTypeDB = new GroupType(); groupTypeDB.Id = 0; groupTypeDB.Guid = groupTypeUI.Guid; groupTypeDB.IsSystem = false; groupTypeDB.ShowInNavigation = false; groupTypeDB.ShowInGroupList = false; groupTypeDB.TakesAttendance = true; groupTypeDB.AttendanceRule = AttendanceRule.None; groupTypeDB.AttendancePrintTo = PrintTo.Default; groupTypeDB.AllowMultipleLocations = true; groupTypeDB.EnableLocationSchedules = true; GroupTypeRole defaultRole = new GroupTypeRole(); defaultRole.Name = "Member"; groupTypeDB.Roles.Add( defaultRole ); } groupTypeDB.Name = groupTypeUI.Name; groupTypeDB.Order = groupTypeUI.Order; groupTypeDB.InheritedGroupTypeId = groupTypeUI.InheritedGroupTypeId; groupTypeDB.Attributes = groupTypeUI.Attributes; groupTypeDB.AttributeValues = groupTypeUI.AttributeValues; if ( groupTypeDB.Id == 0 ) { groupTypeService.Add( groupTypeDB ); } if ( !groupTypeDB.IsValid ) { hasValidationErrors = true; CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>().First( a => a.GroupTypeGuid == groupTypeDB.Guid ); groupTypeEditor.Expanded = true; return; } rockContext.SaveChanges(); groupTypeDB.SaveAttributeValues( rockContext ); // get fresh from database to make sure we have Id so we can update the CheckinLabel Attributes groupTypeDB = groupTypeService.Get( groupTypeDB.Guid ); // rebuild the CheckinLabel attributes from the UI (brute-force) foreach ( var labelAttributeDB in CheckinGroupTypeEditor.GetCheckinLabelAttributes( groupTypeDB.Attributes, rockContext ) ) { var attribute = attributeService.Get( labelAttributeDB.Value.Guid ); Rock.Web.Cache.AttributeCache.Flush( attribute.Id ); attributeService.Delete( attribute ); } // Make sure default role is set if ( !groupTypeDB.DefaultGroupRoleId.HasValue && groupTypeDB.Roles.Any() ) { groupTypeDB.DefaultGroupRoleId = groupTypeDB.Roles.First().Id; } rockContext.SaveChanges(); int labelOrder = 0; foreach ( var checkinLabelAttributeInfo in GroupTypeCheckinLabelAttributesState[groupTypeUI.Guid] ) { var attribute = new Rock.Model.Attribute(); attribute.AttributeQualifiers.Add( new AttributeQualifier { Key = "binaryFileType", Value = Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL } ); attribute.Guid = Guid.NewGuid(); attribute.FieldTypeId = binaryFileFieldTypeID; attribute.EntityTypeId = EntityTypeCache.GetId( typeof( GroupType ) ); attribute.EntityTypeQualifierColumn = "Id"; attribute.EntityTypeQualifierValue = groupTypeDB.Id.ToString(); attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileGuid.ToString(); attribute.Key = checkinLabelAttributeInfo.AttributeKey; attribute.Name = checkinLabelAttributeInfo.FileName; attribute.Order = labelOrder++; if ( !attribute.IsValid ) { hasValidationErrors = true; CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupTypeEditor>().First( a => a.GroupTypeGuid == groupTypeDB.Guid ); groupTypeEditor.Expanded = true; return; } attributeService.Add( attribute ); } rockContext.SaveChanges(); } // Add/Update Groups foreach ( var groupUI in groupsToAddUpdate ) { Group groupDB = groupService.Get( groupUI.Guid ); if ( groupDB == null ) { groupDB = new Group(); groupDB.Guid = groupUI.Guid; } groupDB.Name = groupUI.Name; // delete any GroupLocations that were removed in the UI foreach ( var groupLocationDB in groupDB.GroupLocations.ToList() ) { if ( !groupUI.GroupLocations.Select( a => a.LocationId ).Contains( groupLocationDB.LocationId ) ) { groupLocationService.Delete( groupLocationDB ); } } // add any GroupLocations that were added in the UI foreach ( var groupLocationUI in groupUI.GroupLocations ) { if ( !groupDB.GroupLocations.Select( a => a.LocationId ).Contains( groupLocationUI.LocationId ) ) { GroupLocation groupLocationDB = new GroupLocation { LocationId = groupLocationUI.LocationId }; groupDB.GroupLocations.Add( groupLocationDB ); } } groupDB.Order = groupUI.Order; // get GroupTypeId from database in case the groupType is new groupDB.GroupTypeId = groupTypeService.Get( groupUI.GroupType.Guid ).Id; var parentGroupUI = groupsToAddUpdate.Where( g => g.Groups.Any( g2 => g2.Guid.Equals( groupUI.Guid ) ) ).FirstOrDefault(); if ( parentGroupUI != null ) { groupDB.ParentGroupId = groupService.Get( parentGroupUI.Guid ).Id; } groupDB.Attributes = groupUI.Attributes; groupDB.AttributeValues = groupUI.AttributeValues; if ( groupDB.Id == 0 ) { groupService.Add( groupDB ); } if ( !groupDB.IsValid ) { hasValidationErrors = true; hasValidationErrors = true; CheckinGroupEditor groupEditor = phCheckinGroupTypes.ControlsOfTypeRecursive<CheckinGroupEditor>().First( a => a.GroupGuid == groupDB.Guid ); groupEditor.Expanded = true; return; } rockContext.SaveChanges(); groupDB.SaveAttributeValues(); } /* now that we have all the grouptypes saved, now lets go back and save them again with the current UI ChildGroupTypes */ // save main parentGroupType with current UI ChildGroupTypes parentGroupTypeDB.ChildGroupTypes = new List<GroupType>(); parentGroupTypeDB.ChildGroupTypes.Clear(); foreach ( var childGroupTypeUI in parentGroupTypeUI.ChildGroupTypes ) { var childGroupTypeDB = groupTypeService.Get( childGroupTypeUI.Guid ); parentGroupTypeDB.ChildGroupTypes.Add( childGroupTypeDB ); } rockContext.SaveChanges(); // loop thru all the other GroupTypes in the UI and save their childgrouptypes foreach ( var groupTypeUI in groupTypesToAddUpdate ) { var groupTypeDB = groupTypeService.Get( groupTypeUI.Guid ); groupTypeDB.ChildGroupTypes = new List<GroupType>(); groupTypeDB.ChildGroupTypes.Clear(); groupTypeDB.ChildGroupTypes.Add( groupTypeDB ); foreach ( var childGroupTypeUI in groupTypeUI.ChildGroupTypes ) { var childGroupTypeDB = groupTypeService.Get( childGroupTypeUI.Guid ); groupTypeDB.ChildGroupTypes.Add( childGroupTypeDB ); } } rockContext.SaveChanges(); AttributeCache.FlushEntityAttributes(); Rock.CheckIn.KioskDevice.FlushAll(); } ); if ( !hasValidationErrors ) { NavigateToParentPage(); } } /// <summary> /// Populates the delete lists (recursive) /// </summary> /// <param name="groupTypesToDelete">The group types to delete.</param> /// <param name="groupsToDelete">The groups to delete.</param> /// <param name="groupTypeDB">The group type DB.</param> /// <param name="groupTypeUI">The group type UI.</param> private static void PopulateDeleteLists( List<GroupType> groupTypesToDelete, List<Group> groupsToDelete, GroupType groupTypeDB, GroupType groupTypeUI ) { // limit to child group types that are not Templates int[] templateGroupTypes = new int[] { DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE).Id, DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_FILTER).Id }; // delete non-template childgrouptypes that were deleted in this ui foreach ( var childGroupTypeDB in groupTypeDB.ChildGroupTypes.Where( g => g.Id != groupTypeDB.Id ) ) { if ( !templateGroupTypes.Contains( childGroupTypeDB.GroupTypePurposeValueId ?? 0 ) ) { GroupType childGroupTypeUI = null; if ( groupTypeUI != null ) { childGroupTypeUI = groupTypeUI.ChildGroupTypes.FirstOrDefault( a => a.Guid == childGroupTypeDB.Guid ); } PopulateDeleteLists( groupTypesToDelete, groupsToDelete, childGroupTypeDB, childGroupTypeUI ); if ( childGroupTypeUI == null ) { groupTypesToDelete.Add( childGroupTypeDB ); // delete all the groups that are in the GroupType that is getting deleted foreach ( var group in childGroupTypeDB.Groups ) { groupsToDelete.Add( group ); } } else { // delete all the groups that are no longer in the UI for this groupType foreach ( var childGroupDB in childGroupTypeDB.Groups ) { bool groupExistsInUI = false; foreach( var group in childGroupTypeUI.Groups ) { if ( GroupFound( group, childGroupDB.Guid ) ) { groupExistsInUI = true; break; } } if ( !groupExistsInUI ) { groupsToDelete.Add( childGroupDB ); } } } } } } private static bool GroupFound( Group group, Guid groupGuid ) { // Does this group match if ( group.Guid.Equals( groupGuid ) ) { return true; } // Do any of the child groups match if ( group.Groups != null ) { foreach ( var childGroup in group.Groups ) { if ( GroupFound( childGroup, groupGuid ) ) { return true; } } } return false; } /// <summary> /// Populates the add update lists. /// </summary> /// <param name="groupTypesToAddUpdate">The group types to add update.</param> /// <param name="groupsToAddUpdate">The groups to add update.</param> /// <param name="groupTypeUI">The group type UI.</param> private static void PopulateAddUpdateLists( List<GroupType> groupTypesToAddUpdate, List<Group> groupsToAddUpdate, GroupType groupTypeUI ) { int groupTypeSortOrder = 0; int groupSortOrder = 0; foreach ( var childGroupTypeUI in groupTypeUI.ChildGroupTypes ) { PopulateAddUpdateLists( groupTypesToAddUpdate, groupsToAddUpdate, childGroupTypeUI ); childGroupTypeUI.Order = groupTypeSortOrder++; groupTypesToAddUpdate.Add( childGroupTypeUI ); foreach ( var groupUI in childGroupTypeUI.Groups ) { groupUI.Order = groupSortOrder++; groupsToAddUpdate.Add( groupUI ); PopulateGroupList( groupUI, groupsToAddUpdate ); } } } private static void PopulateGroupList( Group groupUI, List<Group> groupsToAddUpdate ) { int groupSortOrder = 0; foreach ( var childGroupUI in groupUI.Groups ) { childGroupUI.Order = groupSortOrder++; groupsToAddUpdate.Add( childGroupUI ); PopulateGroupList( childGroupUI, groupsToAddUpdate ); } } /// <summary> /// Handles the Click event of the btnCancel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnCancel_Click( object sender, EventArgs e ) { NavigateToParentPage(); } /// <summary> /// Shows the detail. /// </summary> /// <param name="groupTypeId">The group type identifier.</param> public void ShowDetail( int groupTypeId ) { // hide the details panel until we verify the page params are good and that the user has edit access pnlDetails.Visible = false; var rockContext = new RockContext(); GroupTypeService groupTypeService = new GroupTypeService( rockContext ); GroupType parentGroupType = groupTypeService.Get( groupTypeId ); if ( parentGroupType == null ) { pnlDetails.Visible = false; return; } lCheckinAreasTitle.Text = parentGroupType.Name.FormatAsHtmlTitle(); hfParentGroupTypeId.Value = parentGroupType.Id.ToString(); nbEditModeMessage.Text = string.Empty; if ( !IsUserAuthorized( Authorization.EDIT ) ) { // this UI doesn't have a ReadOnly mode, so just show a message and keep the Detail panel hidden nbEditModeMessage.Heading = "Information"; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( "check-in configuration" ); return; } pnlDetails.Visible = true; // limit to child group types that are not Templates int[] templateGroupTypes = new int[] { DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE).Id, DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_FILTER).Id }; List<GroupType> checkinGroupTypes = parentGroupType.ChildGroupTypes.Where( a => !templateGroupTypes.Contains( a.GroupTypePurposeValueId ?? 0 ) ).ToList(); // Load the Controls foreach ( GroupType groupType in checkinGroupTypes.OrderBy( a => a.Order ).ThenBy( a => a.Name ) ) { CreateGroupTypeEditorControls( groupType, phCheckinGroupTypes, rockContext ); } } private void ExpandGroupEditorParent( CheckinGroupEditor groupEditor ) { if ( groupEditor.Parent is CheckinGroupEditor ) { ( (CheckinGroupEditor)groupEditor.Parent ).Expanded = true; } else if ( groupEditor.Parent is CheckinGroupTypeEditor ) { ( (CheckinGroupTypeEditor)groupEditor.Parent ).Expanded = true; } } } }
46.126783
207
0.579588
[ "Apache-2.0", "Unlicense" ]
ThursdayChurch/rockweb.thursdaychurch.org
Blocks/CheckIn/CheckinConfiguration.ascx.cs
58,214
C#
using System; using System.Runtime.Serialization; using System.Text.Json.Serialization; using Allocine.ExtensionMethods; namespace AlloCine { [DataContract(Name = "period")] public class Period { [JsonPropertyName("dateStart")] private string DateStartString { get { throw new NotImplementedException(); } set { DateStart = value.toDate(); } } public DateTime DateStart { get; set; } [JsonPropertyName("dateEnd")] private string DateEndString { get { throw new NotImplementedException(); } set { DateEnd = value.toDate(); } } public DateTime DateEnd { get; set; } } }
24.689655
56
0.599162
[ "Apache-2.0" ]
gromez/allocine-api
CS/AlloCineAPI/Period.cs
718
C#
#region LICENSE /* Sora - A Modular Bancho written in C# Copyright (C) 2019 Robin A. P. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #endregion using Sora.Interfaces; using Sora.Objects; using Sora.Packets.Client; namespace Sora.EventArgs { public class BanchoSendUserStatusArgs : IEventArgs, INeedPresence { public UserStatus status; public Presence pr { get; set; } } }
29.857143
76
0.724402
[ "MIT" ]
Tiller431/yes
Sora/Sora/EventArgs/BanchoEventArgs/BanchoSendUserStatusArgs.cs
1,045
C#
using Azure; using Azure.Core; using Azure.Storage; namespace Audit.AzureStorageBlobs.ConfigurationApi { public interface IAzureBlobCredentialConfiguration { /// <summary> /// The azure storage service URL /// </summary> IAzureBlobCredentialConfiguration Url(string url); /// <summary> /// The credentials to authenticate /// </summary> IAzureBlobCredentialConfiguration Credential(StorageSharedKeyCredential credential); /// <summary> /// The credentials to authenticate /// </summary> IAzureBlobCredentialConfiguration Credential(AzureSasCredential credential); /// <summary> /// The credentials to authenticate /// </summary> IAzureBlobCredentialConfiguration Credential(TokenCredential credential); } }
31.444444
92
0.664311
[ "MIT" ]
CesarSP99/Audit.NET
src/Audit.NET.AzureStorageBlobs/ConfigurationApi/IAzureBlobCredentialConfiguration.cs
851
C#