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 (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.CSharp7.DocumentationRules { using StyleCop.Analyzers.Test.DocumentationRules; public class SA1630CSharp7UnitTests : SA1630UnitTests { } }
29.583333
91
0.771831
[ "MIT" ]
AraHaan/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/DocumentationRules/SA1630CSharp7UnitTests.cs
357
C#
using CreateUserFields.Common; using CreateUserFields.Domain; using SAPbobsCOM; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CreateUserFields.Infra { public class SAPFieldRepository : ISAPFieldRepository { private Company _company; public SAPFieldRepository(Company company) { _company = company; } public IEnumerable<FieldMD> GetAll(string tableName) { var sql = $@"SELECT [FieldID], [TableID], [AliasID], [Descr] FROM [CUFD] WHERE [TableID]='{tableName}'".TSqlToAnsi(); var rs = _company.ExecuteRS(sql); var fields = new List<FieldMD>(); while (!rs.EoF) { var field = new FieldMD { FieldID = rs.Fields.Item(nameof(FieldMD.FieldID)).Value.To<int>(), AliasID = rs.Fields.Item(nameof(FieldMD.AliasID)).Value.ToString(), Descr = rs.Fields.Item(nameof(FieldMD.Descr)).Value.ToString(), TableID = rs.Fields.Item(nameof(FieldMD.TableID)).Value.ToString() }; fields.Add(field); rs.MoveNext(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(rs); return fields; } public void Remove(string tableName, int fieldId) { var fieldMd = _company.GetBusinessObject(BoObjectTypes.oUserFields) as UserFieldsMD; _company.Connect(); if (fieldMd.GetByKey(tableName, fieldId)) { var success = fieldMd.Remove() == 0; if (!success) { var code = _company.GetLastErrorCode(); if (code == -1120) { System.Runtime.InteropServices.Marshal.ReleaseComObject(fieldMd); } throw new Exception(_company.GetLastErrorDescription()); } } System.Runtime.InteropServices.Marshal.ReleaseComObject(fieldMd); } } }
33.684932
97
0.490037
[ "Apache-2.0" ]
Mosheh/SboCreateUserFields
src/CreateUserFields/Infra/SAPFields.cs
2,461
C#
using System; using System.Collections.Generic; using Data; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.EntityFrameworkCore; using Models.Diagnosis; using Moq; using WebAPI.Controllers; using Xunit; namespace Tests.Controller { public class DiagnosisControllerTest { readonly DbContextOptions<CloudCureDbContext> _options; public DiagnosisControllerTest() { _options = new DbContextOptionsBuilder<CloudCureDbContext>() .UseSqlite("Filename = diagnosisControllerTests.db; Foreign Keys=False").Options; Seed(); } [Fact] public void CreateReturnsOkDiagnosis() { var repository = new Mock<IDiagnosisRepository>(); var controller = new DiagnosisController(repository.Object); var diagnosis = GetDiagnosis(); var result = controller.Add(diagnosis); var okResponse = (IStatusCodeActionResult)result; Assert.Equal(201, okResponse.StatusCode); } [Fact] public void GetAllReturnsOKDiagnosis() { using (var context = new CloudCureDbContext(_options)) { IDiagnosisRepository repo = new DiagnosisRepository(context); var controller = new DiagnosisController(repo); var result = controller.GetAll(); var response = (IStatusCodeActionResult)result; Assert.Equal(200, response.StatusCode); } } [Fact] public void DeleteShouldReturnOKDiagnosis() { using (var context = new CloudCureDbContext(_options)) { IDiagnosisRepository repo = new DiagnosisRepository(context); var controller = new DiagnosisController(repo); var result = controller.Delete(1); var response = (IStatusCodeActionResult)result; Assert.Equal(200, response.StatusCode); } } [Fact] public void UpdateShouldReturnOKDiagnosis() { var repository = new Mock<IDiagnosisRepository>(); var controller = new DiagnosisController(repository.Object); var diagnosis = GetDiagnosis(); diagnosis.IsFinalized = false; var entry = controller.Add(diagnosis); var result = controller.Update(2, diagnosis); var okResponse = (IStatusCodeActionResult)result; Assert.Equal(200, okResponse.StatusCode); } [Fact] public void GetbyPatientIdWithNavShouldReturnOK() { using (var context = new CloudCureDbContext(_options)) { IDiagnosisRepository repo = new DiagnosisRepository(context); var controller = new DiagnosisController(repo); var result = controller.GetByPatientIdWithNav(1); var response = (IStatusCodeActionResult)result; Assert.Equal(200, response.StatusCode); } } [Fact] public void GetbyDiagnosisWithNavShouldReturnOK() { var repository = new Mock<IDiagnosisRepository>(); var controller = new DiagnosisController(repository.Object); var results = controller.GetAllDiagnosisByPatientIdWithNav(1); var okResponse = (IStatusCodeActionResult)results; Assert.Equal(200, okResponse.StatusCode); } [Fact] public void GetAllShouldGiveBadRequest() { using (var context = new CloudCureDbContext(_options)) { IDiagnosisRepository repo = new DiagnosisRepository(context); var controller = new DiagnosisController(repo); context.Database.EnsureDeleted(); var result = controller.GetAll(); var response = (IStatusCodeActionResult)result; Assert.Equal(400, response.StatusCode); } } [Fact] public void CreateShouldGiveBadRequest() { using (var context = new CloudCureDbContext(_options)) { IDiagnosisRepository repo = new DiagnosisRepository(context); var controller = new DiagnosisController(repo); var result = controller.Add(null); var response = (IStatusCodeActionResult)result; Assert.Equal(400, response.StatusCode); } } [Fact] public void GetByIdShouldGiveBadRequest() { using (var context = new CloudCureDbContext(_options)) { IDiagnosisRepository repo = new DiagnosisRepository(context); var controller = new DiagnosisController(repo); var result = controller.GetById(-1); var response = (IStatusCodeActionResult)result; Assert.Equal(400, response.StatusCode); } } [Fact] public void UpdateShouldGiveBadRequest() { using (var context = new CloudCureDbContext(_options)) { IDiagnosisRepository repo = new DiagnosisRepository(context); var controller = new DiagnosisController(repo); var result = controller.Update(-1, null); var response = (IStatusCodeActionResult)result; Assert.Equal(400, response.StatusCode); } } [Fact] public void DeleteShouldGiveBadRequest() { using (var context = new CloudCureDbContext(_options)) { IDiagnosisRepository repo = new DiagnosisRepository(context); var controller = new DiagnosisController(repo); var result = controller.Delete(-1); var response = (IStatusCodeActionResult)result; Assert.Equal(400, response.StatusCode); } } [Fact] public void GetByPatientIdWithNavShouldGiveBadRequest() { using (var context = new CloudCureDbContext(_options)) { IDiagnosisRepository repo = new DiagnosisRepository(context); var controller = new DiagnosisController(repo); var result = controller.GetByPatientIdWithNav(-1); var response = (IStatusCodeActionResult)result; Assert.Equal(400, response.StatusCode); } } [Fact] public void GetAllDiagnosisByPatientIdWithNavShouldGiveBadRequest() { using (var context = new CloudCureDbContext(_options)) { IDiagnosisRepository repo = new DiagnosisRepository(context); var controller = new DiagnosisController(repo); var result = controller.GetAllDiagnosisByPatientIdWithNav(-1); var response = (IStatusCodeActionResult)result; Assert.Equal(400, response.StatusCode); } } private static Models.Diagnosis.Diagnosis GetDiagnosis() { Models.Diagnosis.Diagnosis d = new Models.Diagnosis.Diagnosis { PatientId = 1, EncounterDate = new DateTime(2021, 12, 27), Vitals = new Vitals { DiagnosisId = 1, Systolic = 120, Diastolic = 80, OxygenSat = 96.5, HeartRate = 70, RespiratoryRate = 12, Temperature = 98.6, Height = 75, Weight = 145 }, Assessment = new Assessment { DiagnosisId = 1, PainAssessment = "asdfas", PainScale = 2, ChiefComplaint = "dfdssdf", HistoryOfPresentIllness = "dssdfs" }, DoctorDiagnosis = "He's fine", RecommendedTreatment = "Live life", IsFinalized = true }; return d; } private void Seed() { using (var context = new CloudCureDbContext(_options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.Diagnoses.Add(GetDiagnosis()); context.SaveChanges(); } } } }
34.590361
105
0.556368
[ "Unlicense" ]
kamlesh-microsoft/CloudCure
Backend/Tests/Controller/DiagnosisControllerTest.cs
8,613
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Boc.Commands; using Boc.Domain; using LaYumba.Functional; using Unit = System.ValueTuple; using Examples; using Microsoft.AspNetCore.Http; using static Microsoft.AspNetCore.Http.Results; namespace Boc.Chapter9 { public static class Program { public async static Task Run() { var app = WebApplication.Create(); Func<MakeTransfer, IResult> handleSaveTransfer = ConfigureSaveTransferHandler(app.Configuration); app.MapPost("/Transfer/Future", handleSaveTransfer); await app.RunAsync(); } static Func<MakeTransfer, IResult> ConfigureSaveTransferHandler(IConfiguration config) { // persistence layer ConnectionString connString = config.GetSection("ConnectionString").Value; SqlTemplate InsertTransferSql = "INSERT ..."; var save = connString.TryExecute(InsertTransferSql); var validate = Validation.DateNotPast(clock: () => DateTime.UtcNow); return HandleSaveTransfer(validate, save); } static Func<MakeTransfer, IResult> HandleSaveTransfer ( Validator<MakeTransfer> validate , Func<MakeTransfer, Exceptional<Unit>> save) => transfer => validate(transfer).Map(save).Match ( Invalid: err => BadRequest(err), Valid: result => result.Match ( Exception: _ => StatusCode(StatusCodes.Status500InternalServerError), Success: _ => Ok() ) ); } }
27.557377
106
0.643664
[ "MIT" ]
la-yumba/functional-csharp-code-2
Examples/Chapter09/Boc/FP/Program.cs
1,683
C#
// Copyright 2018 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 LightBDD.Framework.Scenarios.Extended; using LightBDD.XUnit2; namespace Steeltoe.Cli.Test { public class InitFeature : FeatureSpecs { [Scenario] public void InitHelp() { Runner.RunScenario( given => a_dotnet_project("init_help"), when => the_developer_runs_cli_command("init --help"), then => the_cli_should_output(new[] { "Initialize Steeltoe Developer Tools", $"Usage: {Program.Name} init [options]", "Options:", "-F|--force Initialize the project even if already initialized", "-?|-h|--help Show help information", }) ); } [Scenario] public void InitTooManyArgs() { Runner.RunScenario( given => a_dotnet_project("init_too_many_args"), when => the_developer_runs_cli_command("init arg1"), then => the_cli_should_fail_parse("Unrecognized command or argument 'arg1'") ); } [Scenario] public void Init() { Runner.RunScenario( given => a_dotnet_project("init"), when => the_developer_runs_cli_command("init"), then => the_cli_should_output("Initialized Steeltoe Developer Tools") ); } [Scenario] public void InitForce() { Runner.RunScenario( given => a_steeltoe_project("init_force"), when => the_developer_runs_cli_command("init"), then => the_cli_should_error(ErrorCode.Tooling, "Steeltoe Developer Tools already initialized"), when => the_developer_runs_cli_command("init --force"), then => the_cli_should_output("Initialized Steeltoe Developer Tools") ); } } }
35.708333
112
0.584597
[ "Apache-2.0" ]
spring-operator/Tooling
test/Steeltoe.Cli.Test/InitFeature.cs
2,573
C#
namespace Infrastructure.MessageLog { using System; using System.Collections.Generic; using System.Text; using Infrastructure.Messaging; public interface IEventQuery : IEnumerable<IEvent> { IEnumerable<IEvent> Execute(); IEventQuery FromSourceType(string sourceType); IEventQuery FromSourceId(string sourceId); IEventQuery FromAssemblyName(string assemblyName); IEventQuery FromNamespace(string @namespace); IEventQuery WithFullName(string fullname); IEventQuery WithTypeName(string typeName); IEventQuery Until(DateTime date); } }
23.444444
58
0.706161
[ "MIT" ]
albel1205/Nail
CQRS.Infrastructure/MessageLog/IEventQuery.cs
635
C#
#pragma warning disable 1591 // Disable missing XML comment namespace AntDesign.Select { public enum ResponsiveTag { Responsive } }
15.4
60
0.681818
[ "MIT" ]
ANDA334911390/ant-design-blazor
components/select/ResponsiveTag.cs
156
C#
using System; namespace ApiClient { public class TeamStatistics { public int TotalPlays { get; set; } public int TotalYards { get; set; } public double YardsPerPlay { get; set; } public int Penalties { get; set; } public int PenaltyYards { get; set; } public int PassingAttempts { get; set; } public int PassingCompletions { get; set; } public int PassingYards { get; set; } public int PassingTouchdowns { get; set; } public double PassingAverage { get; set; } public int RushingAttempts { get; set; } public int RushingYards { get; set; } public double RushingAverage { get; set; } public int ReceivingCompletions { get; set; } public int ReceivingYards { get; set; } public double ReceivingAverage { get; set; } public int Turnovers { get; set; } public int Fumbles { get; set; } public int FumblesLost { get; set; } public int Interceptions { get; set; } public TimeSpan TimeOfPossession { get; set; } public double DefensiveSacks { get; set; } public int DefensiveSackYardage { get; set; } public int KickingFieldGoalLong { get; set; } public int KickingExtraPointAttempted { get; set; } public int KickingExtraPointMakes { get; set; } public int Kickoffs { get; set; } public int KickoffTotalYards { get; set; } public int KickoffLong { get; set; } public int PuntingAttempts { get; set; } public double PuntingAverageYards { get; set; } public int PassesDefended { get; set; } public int FirstDownAttempts { get; set; } public int SecondDownAttempts { get; set; } public int ThirdDownAttempts { get; set; } public int FourthDownAttempts { get; set; } public int FirstDownConversions { get; set; } public int SecondDownConversions { get; set; } public int ThirdDownConversions { get; set; } public double ThirdDownConversionPercentage { get; set; } public int FourthDownConversions { get; set; } public double FourthDownConversionPercentage { get; set; } public int FirstDownsRushing { get; set; } public int FirstDownsPassing { get; set; } public int FirstDownsPenalty { get; set; } public int FirstDowns { get; set; } public int RecoveryFumbles { get; set; } } }
28.953488
66
0.617269
[ "MIT" ]
jon-adams/ds-hsgc-api-samples
c#/ApiClient/Models/TeamStatistics.cs
2,492
C#
using System; using System.Threading.Tasks; using Abp.Authorization.Users; using Abp.Domain.Uow; using Abp.MultiTenancy; using Abp.Runtime.Security; using Microsoft.EntityFrameworkCore; using Afonsoft.Ranking.Authorization.Users; using Afonsoft.Ranking.Authorization.Users.Dto; using Afonsoft.Ranking.MultiTenancy; using Shouldly; namespace Afonsoft.Ranking.Tests.Authorization.Users { // ReSharper disable once InconsistentNaming public class UserAppService_Link_Tests : UserAppServiceTestBase { private readonly IUserLinkAppService _userLinkAppService; private readonly IUserLinkManager _userLinkManager; private readonly UserManager _userManager; private readonly TenantManager _tenantManager; private readonly IUnitOfWorkManager _unitOfWorkManager; public UserAppService_Link_Tests() { _userLinkAppService = Resolve<IUserLinkAppService>(); _userLinkManager = Resolve<IUserLinkManager>(); _userManager = Resolve<UserManager>(); _tenantManager = Resolve<TenantManager>(); _unitOfWorkManager = Resolve<IUnitOfWorkManager>(); } [MultiTenantFact] public async Task Should_Link_User_To_Host_Admin() { LoginAsHostAdmin(); await LinkUserAndTestAsync(string.Empty); } [MultiTenantFact] public async Task Should_Link_User_To_Default_Tenant_Admin() { LoginAsDefaultTenantAdmin(); await LinkUserAndTestAsync(AbpTenantBase.DefaultTenantName); } [MultiTenantFact] public async Task Should_Link_User_To_Different_Tenant_User() { //Arrange LoginAsHostAdmin(); var testTenantId = await CreateTestTenantAndTestUser(); //Act LoginAsDefaultTenantAdmin(); await _userLinkAppService.LinkToUser(new LinkToUserInput { TenancyName = "Test", UsernameOrEmailAddress = "test", Password = "123qwe" }); //Assert var defaultTenantAdmin = await UsingDbContextAsync(context => context.Users.FirstOrDefaultAsync(u => u.TenantId == AbpSession.TenantId && u.Id == AbpSession.UserId)); var defaultTenantAccount = await _userLinkManager.GetUserAccountAsync(defaultTenantAdmin.ToUserIdentifier()); var testUser = await UsingDbContextAsync(testTenantId, context => context.Users.FirstOrDefaultAsync(u => u.UserName == "test")); var testUserAccount = await _userLinkManager.GetUserAccountAsync(testUser.ToUserIdentifier()); defaultTenantAccount.UserLinkId.ShouldBe(testUserAccount.UserLinkId); defaultTenantAccount.UserLinkId.ShouldBe(defaultTenantAccount.Id); } [MultiTenantFact] public async Task Should_Link_User_To_Already_Linked_User() { //Arrange LoginAsHostAdmin(); var testTenantId = await CreateTestTenantAndTestUser(); LoginAsDefaultTenantAdmin(); await CreateTestUsersForAccountLinkingAsync(); var linkToTestTenantUserInput = new LinkToUserInput { TenancyName = "Test", UsernameOrEmailAddress = "test", Password = "123qwe" }; //Act //Link Default\admin -> Test\test await _userLinkAppService.LinkToUser(linkToTestTenantUserInput); LoginAsTenant(AbpTenantBase.DefaultTenantName, "jnash"); //Link Default\jnash->Test\test await _userLinkAppService.LinkToUser(linkToTestTenantUserInput); //Assert var defaultTenantAdmin = await UsingDbContextAsync(context => context.Users.FirstOrDefaultAsync(u => u.TenantId == AbpSession.TenantId && u.UserName == AbpUserBase.AdminUserName)); var defaultTenantAdminAccount = await _userLinkManager.GetUserAccountAsync(defaultTenantAdmin.ToUserIdentifier()); var jnash = await UsingDbContextAsync(context => context.Users.FirstOrDefaultAsync(u => u.UserName == "jnash")); var jnashAccount = await _userLinkManager.GetUserAccountAsync(jnash.ToUserIdentifier()); var testTenantUser = await UsingDbContextAsync(testTenantId, context => context.Users.FirstOrDefaultAsync(u => u.UserName == "test")); var testTenantUserAccount = await _userLinkManager.GetUserAccountAsync(testTenantUser.ToUserIdentifier()); jnashAccount.UserLinkId.ShouldBe(jnashAccount.Id); defaultTenantAdminAccount.UserLinkId.ShouldBe(jnashAccount.Id); testTenantUserAccount.UserLinkId.ShouldBe(jnashAccount.Id); jnashAccount.UserLinkId.ShouldBe(defaultTenantAdminAccount.UserLinkId); jnashAccount.UserLinkId.ShouldBe(testTenantUserAccount.UserLinkId); } private async Task<int> CreateTestTenantAndTestUser() { var testTenant = new Tenant("Test", "test") { ConnectionString = SimpleStringCipher.Instance.Encrypt("Server=localhost; Database=RankingTest_" + Guid.NewGuid().ToString("N") + "; Trusted_Connection=True;") }; await _tenantManager.CreateAsync(testTenant); using (var uow = _unitOfWorkManager.Begin()) { using (_unitOfWorkManager.Current.SetTenantId(testTenant.Id)) { var testUser = new User { EmailAddress = "test@test.com", IsEmailConfirmed = true, Name = "Test", Surname = "User", UserName = "test", Password = "AM4OLBpptxBYmM79lGOX9egzZk3vIQU3d/gFCJzaBjAPXzYIK3tQ2N7X4fcrHtElTw==", //123qwe TenantId = testTenant.Id, }; await _userManager.CreateAsync(testUser); UsingDbContext(null, context => { context.UserAccounts.Add(new UserAccount { TenantId = testUser.TenantId, UserId = testUser.Id, UserName = testUser.UserName, EmailAddress = testUser.EmailAddress }); }); } await uow.CompleteAsync(); return testTenant.Id; } } private async Task LinkUserAndTestAsync(string tenancyName) { //Arrange await CreateTestUsersForAccountLinkingAsync(); //Act await _userLinkAppService.LinkToUser(new LinkToUserInput { TenancyName = tenancyName, UsernameOrEmailAddress = "jnash", Password = "123qwe" }); //Assert var linkedUser = await UsingDbContextAsync(context => context.Users.FirstOrDefaultAsync(u => u.UserName == "jnash")); var linkedUserAccount = await _userLinkManager.GetUserAccountAsync(linkedUser.ToUserIdentifier()); var currentUser = await UsingDbContextAsync(context => context.Users.FirstOrDefaultAsync(u => u.Id == AbpSession.UserId)); var currentUserAccount = await _userLinkManager.GetUserAccountAsync(currentUser.ToUserIdentifier()); linkedUserAccount.UserLinkId.HasValue.ShouldBe(true); currentUserAccount.UserLinkId.HasValue.ShouldBe(true); linkedUserAccount.ShouldNotBe(null); currentUserAccount.ShouldNotBe(null); if (currentUserAccount.UserLinkId != null) { linkedUserAccount.UserLinkId?.ShouldBe(currentUserAccount.UserLinkId.Value); } } private async Task CreateTestUsersForAccountLinkingAsync() { using (var uow = _unitOfWorkManager.Begin()) { await _userManager.CreateAsync(CreateUserEntity("jnash", "John", "Nash", "jnsh2000@testdomain.com")); await _userManager.CreateAsync(CreateUserEntity("adams_d", "Douglas", "Adams", "adams_d@gmail.com")); await _userManager.CreateAsync(CreateUserEntity("artdent", "Arthur", "Dent", "ArthurDent@yahoo.com")); await uow.CompleteAsync(); } } } }
41.687805
192
0.621226
[ "MIT" ]
afonsoft/Ranking
test/Afonsoft.Ranking.Tests/Authorization/Users/UserAppService_Link_Tests.cs
8,548
C#
using System; using System.Collections.Generic; using System.Linq; using ETicaret.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; namespace ETicaret.Data { public static class SeedData { public async static void Initialize(IServiceProvider serviceProvider) { Console.WriteLine("Çekirdek veriler yazılıyor..."); //Random r = new Random(); -----> r //ETicaretContext context = new ETicaretContext(); -----> context using (var context = new ETicaretContext(serviceProvider.GetRequiredService< DbContextOptions<ETicaretContext>>())) { context.Database.Migrate(); //silinen veritabanını da yeniden oluşturur(migration'lara göre) // Urunler tablosunda herhangi bir kayıt varsa if (context.Urunler.Any()) { return; // Hiç bir şey yapmadan çık. Çünkü veritabanı zaten tohumlanmış. } //tohum rol var roleManager = serviceProvider.GetRequiredService<RoleManager<AppRole>>(); await roleManager.CreateAsync(new AppRole{Name="Admin"}); await roleManager.CreateAsync(new AppRole{Name="Manager"}); await roleManager.CreateAsync(new AppRole{Name="Member"}); // user tohumlamaya başlıyoruz var adminberkay = new AppUser{UserName="biproberkay@gmail.com", Email="biproberkay@gmail.com", EmailConfirmed=true}; var managerberkay = new AppUser{UserName="managerberkay@gmail.com", Email="managerberkay@gmail.com", EmailConfirmed=true}; var memberberkay = new AppUser{UserName="memberberkay@gmail.com", Email="memberberkay@gmail.com", EmailConfirmed=true}; var userManager =serviceProvider.GetRequiredService<UserManager<AppUser>>(); // oluşturulan appuser instance lari usermanager a verip identity yapısı için bir user oluşturuyoruz. // identity sisteminde ancak usermanager klasından kullanıcı oluşturulabiliyor. await userManager.CreateAsync(adminberkay,"Qaz123+"); await userManager.CreateAsync(managerberkay,"Qaz123+"); await userManager.CreateAsync(memberberkay,"Qaz123+"); // user a rol atama işlemini tohumluyoruz...⏬ await userManager.AddToRoleAsync(adminberkay,"Admin");//bu bir komut await userManager.AddToRoleAsync(managerberkay,"Manager");//bu bir komut await userManager.AddToRoleAsync(memberberkay,"Member");//bu bir komut var urunler = new Urun[] { new Urun { Ad = "Ayakkabı", Aciklama = "Rahat, şık ve ucuz...",Fiyat = 99.99M, //urunler[0] Resimler = new List<Resim>() { new Resim { DosyaAdi = "10268547481650.jpg" }, new Resim { DosyaAdi = "10268547579954.jpg" }, new Resim { DosyaAdi = "10268547678258.jpg" }, new Resim { DosyaAdi = "10268547743794.jpg" }, } }, new Urun { Ad = "Kol saati", Aciklama = "Rahat, şık ve pahalı...", Fiyat = 199.99M, //urunler[1] Resimler = new List<Resim> { new Resim { DosyaAdi = "kolsaati.jfif" }, } }, new Urun { Ad = "Drone", Aciklama = "Uçar, kaçar...",Fiyat = 399.90M, //urunler[2] Resimler = new List<Resim>() { new Resim { DosyaAdi = "10072484479026.jpg" }, new Resim { DosyaAdi = "10072484511794.jpg" }, new Resim { DosyaAdi = "10072484577330.jpg" }, new Resim { DosyaAdi = "10072484610098.jpg" }, new Resim { DosyaAdi = "10395470102578.jpg" }, }, }, new Urun { Ad = "Oyuncu Faresi", Aciklama = "Yüksek hassasiyet..",Fiyat = 299.90M, //urunler[3] Resimler = new List<Resim>() { new Resim { DosyaAdi = "9730068119602.jpg" }, new Resim { DosyaAdi = "9730068152370.jpg" }, new Resim { DosyaAdi = "9730068185138.jpg" }, new Resim { DosyaAdi = "9730068217906.jpg" }, new Resim { DosyaAdi = "9730068250674.jpg" }, new Resim { DosyaAdi = "9730068283442.jpg" }, }, }, new Urun { Ad = "Kemer", Aciklama = "Yılan derisinden...",Fiyat = 599.90M, //urunler[4] Resimler = new List<Resim>() { new Resim { DosyaAdi = "kemer.jpg" }, }, }, new Urun { Ad = "Mouse", Aciklama = "Her yüzeyde çalışır...",Fiyat = 89.90M, //urunler[5] Resimler = new List<Resim>() { new Resim { DosyaAdi = "mouse.jpg" }, }, }, new Urun { Ad = "Ateş Ölçer", Aciklama = "Tam ölçer, hızlı ölçer",Fiyat = 189.90M, //urunler[6] Resimler = new List<Resim>() { new Resim { DosyaAdi = "9973508210738.jpg" }, new Resim { DosyaAdi = "9973508276274.jpg" }, }, }, new Urun { Ad = "Davul", Aciklama = "Az yer kaplar....",Fiyat = 829.90M, //urunler[7] Resimler = new List<Resim>() { new Resim { DosyaAdi = "10049148190770.jpg" }, }, }, new Urun { Ad = "Parfüm", Aciklama = "Kalıcıdır...",Fiyat = 329.90M, //urunler[8] Resimler = new List<Resim>() { new Resim { DosyaAdi = "10125668220978.jpg" }, }, }, new Urun { Ad = "Yemek Masası", Aciklama = "Balkonunuza çok yakışacak...",Fiyat = 899.90M, //urunler[9] Resimler = new List<Resim>() { new Resim { DosyaAdi = "10165918564402.jpg" }, }, }, new Urun { Ad = "Bisiklet", Aciklama = "Hafif ve dayanıklı...",Fiyat = 999.90M, //urunler[10] Resimler = new List<Resim>() { new Resim { DosyaAdi = "10183905771570.jpg" }, }, }, new Urun { Ad = "Makyaj Kalemi", Aciklama = "Boyar, çizer...",Fiyat = 49.90M, //urunler[11] Resimler = new List<Resim>() { new Resim { DosyaAdi = "10399240159282.jpg" }, }, }, new Urun { Ad = "Drone 2", Aciklama = "Otomatik iniş-kalkış...",Fiyat = 899.90M, //urunler[12] Resimler = new List<Resim>() { new Resim { DosyaAdi = "drone.jpg" }, }, }, }; context.Urunler.AddRange(urunler); var kategoriler = new Kategori[] { new Kategori {Adi = "Elektronik"}, //kategoriler[0] new Kategori {Adi = "Moda"}, //kategoriler[1] new Kategori {Adi = "Ev/Yaşam/Kırtasiye/Ofis"}, //kategoriler[2] new Kategori {Adi = "Oto/Bahçe/Yapı Market"}, //kategoriler[3] new Kategori {Adi = "Anne/Bebek/Oyuncak"}, //kategoriler[4] new Kategori {Adi = "Spor/Outdoor"}, //kategoriler[5] new Kategori {Adi = "Kozmetik/Kişisel Bakım"}, //kategoriler[6] new Kategori {Adi = "Süpermarket/Pet Shop"}, //kategoriler[7] new Kategori {Adi = "Kitap/Müzik/Film/Hobi"}, //kategoriler[8] }; context.Kategoriler.AddRange(kategoriler); var kategorilerVeUrunleri = new KategoriUrun[] { new KategoriUrun{Urun = urunler[0], Kategori = kategoriler[1]}, //Ayakkabı-->Moda new KategoriUrun{Urun = urunler[1], Kategori = kategoriler[1]}, //Kol Saati-->Moda new KategoriUrun{Urun = urunler[2], Kategori = kategoriler[0]}, //Drone -->Elektronik new KategoriUrun{Urun = urunler[2], Kategori = kategoriler[8]}, //Drone -->Hobi new KategoriUrun{Urun = urunler[0], Kategori = kategoriler[5]}, new KategoriUrun{Urun = urunler[3], Kategori = kategoriler[0]}, new KategoriUrun{Urun = urunler[4], Kategori = kategoriler[1]}, new KategoriUrun{Urun = urunler[5], Kategori = kategoriler[0]}, new KategoriUrun{Urun = urunler[6], Kategori = kategoriler[0]}, new KategoriUrun{Urun = urunler[6], Kategori = kategoriler[4]}, new KategoriUrun{Urun = urunler[7], Kategori = kategoriler[0]}, new KategoriUrun{Urun = urunler[7], Kategori = kategoriler[8]}, new KategoriUrun{Urun = urunler[8], Kategori = kategoriler[6]}, new KategoriUrun{Urun = urunler[8], Kategori = kategoriler[1]}, new KategoriUrun{Urun = urunler[9], Kategori = kategoriler[2]}, new KategoriUrun{Urun = urunler[9], Kategori = kategoriler[3]}, new KategoriUrun{Urun = urunler[10], Kategori = kategoriler[5]}, new KategoriUrun{Urun = urunler[11], Kategori = kategoriler[6]}, new KategoriUrun{Urun = urunler[12], Kategori = kategoriler[0]}, new KategoriUrun{Urun = urunler[12], Kategori = kategoriler[8]}, }; context.KategorilerVeUrunleri.AddRange(kategorilerVeUrunleri); context.SaveChanges(); var logger = serviceProvider.GetRequiredService<ILogger<Program>>(); logger.LogInformation("Çekirdek veriler başarıyla yazıldı"); } } } }
52.185841
138
0.454892
[ "Apache-2.0" ]
Bilgisayar-Programciligi/Programlama
Programlama-3/10 - ETicaretSQLite_Identity_role/Data/SeedData.cs
11,878
C#
using System.Collections.Generic; using API.BLL.Base; using API.BLL.UseCases.RolesAndRights.Entities; using API.BLL.UseCases.RolesAndRights.Transformer; namespace API.BLL.UseCases.RolesAndRights.Daos { public interface IRoleRightDao : IDao<RoleRight, RoleRightIdent, RoleRightTransformer> { List<RoleRight> FindByCustomRoleIdent(RoleIdent ident); bool DeleteHardByRoleIdents(ISet<RoleIdent> roleIdent); } }
33.461538
90
0.783908
[ "MIT" ]
ThomasTebbe93/.Net-6-Authentication-API-with-react-ui
API/BLL/UseCases/RolesAndRights/Daos/IRoleRightDao.cs
435
C#
using UnityEngine; using System.Collections; using UnityEditor; using System.Collections.Generic; using System.Reflection; using System.Linq; /* VertexPainterWindow * - Jason Booth * * Uses Unity 5.0+ MeshRenderer.additionalVertexStream so that you can paint per-instance vertex colors on your meshes. * A component is added to your mesh to serialize this data and set it at load time. This is more effecient than making * duplicate meshes, and certainly less painful than saving them as separate asset files on disk. However, if you only have * one copy of the vertex information in your game and want to burn it into the original mesh, you can use the save feature * to save a new version of your mesh with the data burned into the verticies, avoiding the need for the runtime component. * * In other words, bake it if you need to instance the paint job - however, if you want tons of the same instances painted * uniquely in your scene, keep the component version and skip the baking.. * * One possible optimization is to have the component free the array after updating the mesh when in play mode.. * * Also supports burning data into the UV channels, in case you want some additional channels to work with, which also * happen to be full 32bit floats. You can set a viewable range; so if your floats go from 0-120, it will remap it to * 0-1 for display in the shader. That way you can always see your values, even when they go out of color ranges. * * Note that as of this writing Unity has a bug in the additionalVertexStream function. The docs claim the data applied here * will supply or overwrite the data in the mesh, however, this is not true. Rather, it will only replace the data that's * there - if your mesh has no color information, it will not upload the color data in additionalVertexStream, which is sad * because the original mesh doesn't need this data. As a workaround, if your mesh does not have color channels on the verts, * they will be created for you. * * There is another bug in additionalVertexStream, in that the mesh keeps disapearing in edit mode. So the component * which holds the data caches the mesh and keeps assigning it in the Update call, but only when running in the editor * and not in play mode. * * Really, the additionalVertexStream mesh should be owned by the MeshRenderer and saved as part of the objects instance * data. That's essentially what the VertexInstaceStream component does, but it's annoying and wasteful of memory to do * it this way since it doesn't need to be on the CPU at all. Enlighten somehow does this with the UVs it generates * this way, but appears to be handled specially. Oh, Unity.. */ namespace JBooth.VertexPainterPro { public partial class VertexPainterWindow : EditorWindow { enum Tab { Paint = 0, Deform, Flow, Utility, Custom } string[] tabNames = { "Paint", "Deform", "Flow", "Utility", "Custom" }; static string sSwatchKey = "VertexPainter_Swatches"; ColorSwatches swatches = null; #if __MEGASPLAT__ Tab tab = Tab.Custom; #else Tab tab = Tab.Paint; #endif bool hideMeshWireframe = false; bool DrawClearButton(string label) { if (GUILayout.Button(label, GUILayout.Width(46))) { return (EditorUtility.DisplayDialog("Confirm", "Clear " + label + " data?", "ok", "cancel")); } return false; } static Dictionary<string, bool> rolloutStates = new Dictionary<string, bool>(); static GUIStyle rolloutStyle; public static bool DrawRollup(string text, bool defaultState = true, bool inset = false) { if (rolloutStyle == null) { rolloutStyle = GUI.skin.box; rolloutStyle.normal.textColor = EditorGUIUtility.isProSkin ? Color.white : Color.black; } GUI.contentColor = EditorGUIUtility.isProSkin ? Color.white : Color.black; if (inset == true) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.GetControlRect(GUILayout.Width(40)); } if (!rolloutStates.ContainsKey(text)) { rolloutStates[text] = defaultState; } if (GUILayout.Button(text, rolloutStyle, new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(20)})) { rolloutStates[text] = !rolloutStates[text]; } if (inset == true) { EditorGUILayout.GetControlRect(GUILayout.Width(40)); EditorGUILayout.EndHorizontal(); } return rolloutStates[text]; } Vector2 scroll; void OnGUI() { if (Selection.activeGameObject == null) { EditorGUILayout.LabelField("No objects selected. Please select an object with a MeshFilter and Renderer"); return; } if (swatches == null) { swatches = ColorSwatches.CreateInstance<ColorSwatches>(); if (EditorPrefs.HasKey(sSwatchKey)) { JsonUtility.FromJsonOverwrite(EditorPrefs.GetString(sSwatchKey), swatches); } if (swatches == null) { swatches = ColorSwatches.CreateInstance<ColorSwatches>(); EditorPrefs.SetString(sSwatchKey, JsonUtility.ToJson(swatches, false)); } } DrawChannelGUI(); var ot = tab; tab = (Tab)GUILayout.Toolbar((int)tab, tabNames); if (ot != tab) { UpdateDisplayMode(); } if (tab == Tab.Paint) { scroll = EditorGUILayout.BeginScrollView(scroll); DrawPaintGUI(); } else if (tab == Tab.Deform) { scroll = EditorGUILayout.BeginScrollView(scroll); DrawDeformGUI(); } else if (tab == Tab.Flow) { scroll = EditorGUILayout.BeginScrollView(scroll); DrawFlowGUI(); } else if (tab == Tab.Utility) { scroll = EditorGUILayout.BeginScrollView(scroll); DrawUtilityGUI(); } else if (tab == Tab.Custom) { DrawCustomGUI(); } EditorGUILayout.EndScrollView(); } void DrawChannelGUI() { EditorGUILayout.Separator(); GUI.skin.box.normal.textColor = Color.white; if (DrawRollup("Vertex Painter")) { bool oldEnabled = enabled; enabled = GUILayout.Toggle(enabled, "Active (ESC)"); if (enabled != oldEnabled) { InitMeshes(); UpdateDisplayMode(); } var oldShow = showVertexShader; EditorGUILayout.BeginHorizontal(); showVertexShader = GUILayout.Toggle(showVertexShader, "Show Vertex Data (ctrl-V)"); if (oldShow != showVertexShader) { UpdateDisplayMode(); } bool emptyStreams = false; for (int i = 0; i < jobs.Length; ++i) { if (!jobs[i].HasStream()) emptyStreams = true; } EditorGUILayout.EndHorizontal(); if (emptyStreams) { if (GUILayout.Button("Add Streams")) { for (int i = 0; i < jobs.Length; ++i) { jobs[i].EnforceStream(); } UpdateDisplayMode(); } } brushVisualization = (BrushVisualization)EditorGUILayout.EnumPopup("Brush Visualization", brushVisualization); EditorGUILayout.BeginHorizontal(); showVertexPoints = GUILayout.Toggle(showVertexPoints, "Show Brush Influence"); showVertexSize = EditorGUILayout.Slider(showVertexSize, 0.2f, 10); showVertexColor = EditorGUILayout.ColorField(showVertexColor, GUILayout.Width(40)); showNormals = GUILayout.Toggle(showNormals, "N"); showTangents = GUILayout.Toggle(showTangents, "T"); EditorGUILayout.EndHorizontal(); bool oldHideMeshWireframe = hideMeshWireframe; hideMeshWireframe = !GUILayout.Toggle(!hideMeshWireframe, "Show Wireframe (ctrl-W)"); if (hideMeshWireframe != oldHideMeshWireframe) { for (int i = 0; i < jobs.Length; ++i) { SetWireframeDisplay(jobs[i].renderer, hideMeshWireframe); } } bool hasColors = false; bool hasUV0 = false; bool hasUV1 = false; bool hasUV2 = false; bool hasUV3 = false; bool hasPositions = false; bool hasNormals = false; bool hasStream = false; for (int i = 0; i < jobs.Length; ++i) { var stream = jobs[i]._stream; if (stream != null) { int vertexCount = jobs[i].verts.Length; hasStream = true; hasColors = (stream.colors != null && stream.colors.Length == vertexCount); hasUV0 = (stream.uv0 != null && stream.uv0.Count == vertexCount); hasUV1 = (stream.uv1 != null && stream.uv1.Count == vertexCount); hasUV2 = (stream.uv2 != null && stream.uv2.Count == vertexCount); hasUV3 = (stream.uv3 != null && stream.uv3.Count == vertexCount); hasPositions = (stream.positions != null && stream.positions.Length == vertexCount); hasNormals = (stream.normals != null && stream.normals.Length == vertexCount); } } if (hasStream && (hasColors || hasUV0 || hasUV1 || hasUV2 || hasUV3 || hasPositions || hasNormals)) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Clear Channel:"); if (hasColors && DrawClearButton("Colors")) { for (int i = 0; i < jobs.Length; ++i) { Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear"); var stream = jobs[i].stream; stream.colors = null; stream.Apply(); } Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } if (hasColors && DrawClearButton("RGB")) { for (int i = 0; i < jobs.Length; ++i) { Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear"); var stream = jobs[i].stream; Color[] src = jobs[i].meshFilter.sharedMesh.colors; int count = jobs[i].meshFilter.sharedMesh.colors.Length; for (int j = 0; j < count; ++j) { stream.colors[j].r = src[j].r; stream.colors[j].g = src[j].g; stream.colors[j].b = src[j].b; } stream.Apply(); } Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } if (hasUV0 && DrawClearButton("UV0")) { for (int i = 0; i < jobs.Length; ++i) { Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear"); var stream = jobs[i].stream; stream.uv0 = null; stream.Apply(); } Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } if (hasUV1 && DrawClearButton("UV1")) { for (int i = 0; i < jobs.Length; ++i) { Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear"); var stream = jobs[i].stream; stream.uv1 = null; stream.Apply(); } Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } if (hasUV2 && DrawClearButton("UV2")) { for (int i = 0; i < jobs.Length; ++i) { Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear"); var stream = jobs[i].stream; stream.uv2 = null; stream.Apply(); } Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } if (hasUV3 && DrawClearButton("UV3")) { for (int i = 0; i < jobs.Length; ++i) { Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear"); var stream = jobs[i].stream; stream.uv3 = null; stream.Apply(); } Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } if (hasPositions && DrawClearButton("Pos")) { for (int i = 0; i < jobs.Length; ++i) { Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear"); jobs[i].stream.positions = null; Mesh m = jobs[i].stream.GetModifierMesh(); if (m != null) m.vertices = jobs[i].meshFilter.sharedMesh.vertices; jobs[i].stream.Apply(); } Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } if (hasNormals && DrawClearButton("Norm")) { for (int i = 0; i < jobs.Length; ++i) { Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear"); jobs[i].stream.normals = null; jobs[i].stream.tangents = null; jobs[i].stream.Apply(); } Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } EditorGUILayout.EndHorizontal(); } else if (hasStream) { if (GUILayout.Button("Remove Unused Stream Components")) { RevertMat(); for (int i = 0; i < jobs.Length; ++i) { if (jobs[i].HasStream()) { DestroyImmediate(jobs[i].stream); } } UpdateDisplayMode(); } } } EditorGUILayout.Separator(); GUILayout.Box("", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(1)}); EditorGUILayout.Separator(); } void DrawBrushSettingsGUI() { brushSize = EditorGUILayout.Slider("Brush Size", brushSize, 0.01f, 30.0f); brushFlow = EditorGUILayout.Slider("Brush Flow", brushFlow, 0.1f, 128.0f); brushFalloff = EditorGUILayout.Slider("Brush Falloff", brushFalloff, 0.1f, 3.5f); if (tab == Tab.Paint && flowTarget != FlowTarget.ColorBA && flowTarget != FlowTarget.ColorRG) { flowRemap01 = EditorGUILayout.Toggle("use 0->1 mapping", flowRemap01); } EditorGUILayout.Separator(); GUILayout.Box("", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(1)}); EditorGUILayout.Separator(); } void DrawCustomGUI() { if (DrawRollup("Brush Settings")) { customBrush = EditorGUILayout.ObjectField("Brush", customBrush, typeof(VertexPainterCustomBrush), false) as VertexPainterCustomBrush; DrawBrushSettingsGUI(); } scroll = EditorGUILayout.BeginScrollView(scroll); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Fill")) { if (OnBeginStroke != null) { OnBeginStroke(jobs); } for (int i = 0; i < jobs.Length; ++i) { Undo.RecordObject(jobs[i].stream, "Vertex Painter Fill"); FillMesh(jobs[i]); } Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); if (OnEndStroke != null) { OnEndStroke(); } } EditorGUILayout.EndHorizontal(); if (customBrush != null) { customBrush.DrawGUI(); } } void DrawPaintGUI() { GUILayout.Box("Brush Settings", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(20)}); var oldBM = brushMode; brushMode = (BrushTarget)EditorGUILayout.EnumPopup("Target Channel", brushMode); if (oldBM != brushMode) { UpdateDisplayMode(); } if (brushMode == BrushTarget.Color || brushMode == BrushTarget.RGB || brushMode == BrushTarget.UV0_AsColor || brushMode == BrushTarget.UV1_AsColor || brushMode == BrushTarget.UV2_AsColor || brushMode == BrushTarget.UV3_AsColor) { brushColorMode = (BrushColorMode)EditorGUILayout.EnumPopup("Blend Mode", (System.Enum)brushColorMode); if (brushColorMode == BrushColorMode.Overlay || brushColorMode == BrushColorMode.Normal) { bool showAlpha = brushMode != BrushTarget.RGB; brushColor = EditorGUILayout.ColorField(new GUIContent("Brush Color"), brushColor, true, showAlpha, false, null); if (GUILayout.Button("Reset Palette", EditorStyles.miniButton, GUILayout.Width(80), GUILayout.Height(16))) { if (swatches != null) { DestroyImmediate(swatches); } swatches = ColorSwatches.CreateInstance<ColorSwatches>(); EditorPrefs.SetString(sSwatchKey, JsonUtility.ToJson(swatches, false)); } GUILayout.BeginHorizontal(); for (int i = 0; i < swatches.colors.Length; ++i) { if (GUILayout.Button("", EditorStyles.textField, GUILayout.Width(16), GUILayout.Height(16))) { brushColor = swatches.colors[i]; } EditorGUI.DrawRect(new Rect(GUILayoutUtility.GetLastRect().x + 1, GUILayoutUtility.GetLastRect().y + 1, 14, 14), swatches.colors[i]); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); for (int i = 0; i < swatches.colors.Length; i++) { if (GUILayout.Button("+", EditorStyles.miniButton, GUILayout.Width(16), GUILayout.Height(12))) { swatches.colors[i] = brushColor; EditorPrefs.SetString(sSwatchKey, JsonUtility.ToJson(swatches, false)); } } GUILayout.EndHorizontal(); } } else if (brushMode == BrushTarget.ValueR || brushMode == BrushTarget.ValueG || brushMode == BrushTarget.ValueB || brushMode == BrushTarget.ValueA) { brushValue = (int)EditorGUILayout.Slider("Brush Value", (float)brushValue, 0.0f, 256.0f); } else { floatBrushValue = EditorGUILayout.FloatField("Brush Value", floatBrushValue); var oldUVRange = uvVisualizationRange; uvVisualizationRange = EditorGUILayout.Vector2Field("Visualize Range", uvVisualizationRange); if (oldUVRange != uvVisualizationRange) { UpdateDisplayMode(); } } DrawBrushSettingsGUI(); //GUILayout.Box("", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(1)}); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Fill")) { if (OnBeginStroke != null) { OnBeginStroke(jobs); } for (int i = 0; i < jobs.Length; ++i) { Undo.RecordObject(jobs[i].stream, "Vertex Painter Fill"); FillMesh(jobs[i]); } if (OnEndStroke != null) { OnEndStroke(); } Undo.CollapseUndoOperations(Undo.GetCurrentGroup()); } if (GUILayout.Button("Random")) { for (int i = 0; i < jobs.Length; ++i) { Undo.RecordObject(jobs[i].stream, "Vertex Painter Fill"); RandomMesh(jobs[i]); } } EditorGUILayout.EndHorizontal(); } void DrawDeformGUI() { GUILayout.Box("Brush Settings", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(20)}); pull = (Event.current.shift); vertexMode = (VertexMode)EditorGUILayout.EnumPopup("Vertex Mode", vertexMode); vertexContraint = (VertexContraint)EditorGUILayout.EnumPopup("Vertex Constraint", vertexContraint); DrawBrushSettingsGUI(); EditorGUILayout.LabelField(pull ? "Pull (shift)" : "Push (shift)"); } void DrawFlowGUI() { GUILayout.Box("Brush Settings", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(20)}); var oldV = flowVisualization; flowVisualization = (FlowVisualization)EditorGUILayout.EnumPopup("Visualize", flowVisualization); if (flowVisualization != oldV) { UpdateDisplayMode(); } var ft = flowTarget; flowTarget = (FlowTarget)EditorGUILayout.EnumPopup("Target", flowTarget); if (flowTarget != ft) { UpdateDisplayMode(); } flowBrushType = (FlowBrushType)EditorGUILayout.EnumPopup("Mode", flowBrushType); DrawBrushSettingsGUI(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.Space(); if (GUILayout.Button("Reset")) { Vector2 norm = new Vector2(0.5f, 0.5f); foreach (PaintJob job in jobs) { PrepBrushMode(job); switch (flowTarget) { case FlowTarget.ColorRG: job.stream.SetColorRG(norm, job.verts.Length); break; case FlowTarget.ColorBA: job.stream.SetColorBA(norm, job.verts.Length); break; case FlowTarget.UV0_XY: job.stream.SetUV0_XY(norm, job.verts.Length); break; case FlowTarget.UV0_ZW: job.stream.SetUV0_ZW(norm, job.verts.Length); break; case FlowTarget.UV1_XY: job.stream.SetUV1_XY(norm, job.verts.Length); break; case FlowTarget.UV1_ZW: job.stream.SetUV1_ZW(norm, job.verts.Length); break; case FlowTarget.UV2_XY: job.stream.SetUV2_XY(norm, job.verts.Length); break; case FlowTarget.UV2_ZW: job.stream.SetUV2_ZW(norm, job.verts.Length); break; case FlowTarget.UV3_XY: job.stream.SetUV3_XY(norm, job.verts.Length); break; case FlowTarget.UV3_ZW: job.stream.SetUV3_ZW(norm, job.verts.Length); break; } } } EditorGUILayout.Space(); EditorGUILayout.EndHorizontal(); } List<IVertexPainterUtility> utilities = new List<IVertexPainterUtility>(); void InitPluginUtilities() { if (utilities == null || utilities.Count == 0) { var interfaceType = typeof(IVertexPainterUtility); var all = System.AppDomain.CurrentDomain.GetAssemblies() .SelectMany(x => x.GetTypes()) .Where(x => interfaceType.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract) .Select(x => System.Activator.CreateInstance(x)); foreach (var o in all) { IVertexPainterUtility u = o as IVertexPainterUtility; if (u != null) { utilities.Add(u); } } utilities = utilities.OrderBy(o=>o.GetName()).ToList(); } } void DrawUtilityGUI() { InitPluginUtilities(); for (int i = 0; i < utilities.Count; ++i) { var u = utilities[i]; if (DrawRollup(u.GetName(), false)) { u.OnGUI(jobs); } } } void OnFocus() { if (painting) { EndStroke(); } #if UNITY_2019_1_OR_NEWER SceneView.duringSceneGui -= this.OnSceneGUI; SceneView.duringSceneGui += this.OnSceneGUI; #else SceneView.onSceneGUIDelegate -= this.OnSceneGUI; SceneView.onSceneGUIDelegate += this.OnSceneGUI; #endif Undo.undoRedoPerformed -= this.OnUndo; Undo.undoRedoPerformed += this.OnUndo; this.titleContent = new GUIContent("Vertex Paint"); Repaint(); } void OnInspectorUpdate() { // unfortunate... Repaint (); } void OnSelectionChange() { InitMeshes(); this.Repaint(); } void OnDestroy() { bool show = showVertexShader; showVertexShader = false; UpdateDisplayMode(); showVertexShader = show; DestroyImmediate(VertexInstanceStream.vertexShaderMat); #if UNITY_2019_1_OR_NEWER SceneView.duringSceneGui -= this.OnSceneGUI; #else SceneView.onSceneGUIDelegate -= this.OnSceneGUI; #endif } } }
37.350778
155
0.531601
[ "MIT" ]
ManageableIT/VertexPaint
Editor/VertexPainterWindow_GUI.cs
26,407
C#
using MySql.Data.MySqlClient; using Projeto_Integrador_1.Util; using System; using System.Collections.Generic; namespace Projeto_Integrador_1.Connection { class Financeiro : Config { public Financeiro() { } public bool Success; public string Message; public List<dynamic> Results = new List<dynamic>(); public int Id { get; set; } public string Nome { get; set; } public string Tipo { get; set; } public int Referencia { get; set; } public string CentroCusto { get; set; } public string FormaPagamento { get; set; } public string Status { get; set; } public string DataEmissao { get; set; } public string DataVencimento { get; set; } public string Valor { get; set; } public string Documento { get; set; } public string Ocorrencia { get; set; } public string QtdParcelas { get; set; } public string Parcelas { get; set; } public string Observacoes { get; set; } public void Create() { string sql = "INSERT INTO `financeiro` (`nome`, `tipo`, `referencia`, `centro_custo`, `forma_pagamento`, `status`, `data_emissao`, `data_vencimento`, `valor`, `documento`, `ocorrencia`, `qtd_parcelas`, `parcelas`, `observacoes`) VALUES (@nome, @tipo, @referencia, @centro_custo, @forma_pagamento, @status, @data_emissao, @data_vencimento, @valor, @documento, @ocorrencia, @qtd_parcelas, @parcelas, @observacoes);"; try { OpenConnection(); MySqlCommand query = new MySqlCommand(sql, Connection); query.Parameters.AddWithValue("@nome", Nome); query.Parameters.AddWithValue("@tipo", Tipo); query.Parameters.AddWithValue("@referencia", Referencia); query.Parameters.AddWithValue("@centro_custo", CentroCusto); query.Parameters.AddWithValue("@forma_pagamento", FormaPagamento); query.Parameters.AddWithValue("@status", Status); query.Parameters.AddWithValue("@data_emissao", DateTime.Parse(DataEmissao)); query.Parameters.AddWithValue("@data_vencimento", DateTime.Parse(DataVencimento)); query.Parameters.AddWithValue("@valor", Valor); query.Parameters.AddWithValue("@documento", Documento); query.Parameters.AddWithValue("@ocorrencia", Ocorrencia); query.Parameters.AddWithValue("@qtd_parcelas", Converter.ToIntDB(QtdParcelas, true)); query.Parameters.AddWithValue("@parcelas", Parcelas); query.Parameters.AddWithValue("@observacoes", Observacoes); query.ExecuteNonQuery(); CloseConnection(); Success = true; Message = "Financeiro salvo com sucesso."; } catch (Exception e) { Success = false; Message = e.Message; } } public void Update() { string sql = "UPDATE `financeiro` SET `nome` = @nome, `tipo` = @tipo, `referencia` = @referencia, `centro_custo` = @centro_custo, `forma_pagamento` = @forma_pagamento, `status` = @status, `data_emissao` = @data_emissao, `data_vencimento` = @data_vencimento, `valor` = @valor, `documento` = @documento, `ocorrencia` = @ocorrencia, `qtd_parcelas` = @qtd_parcelas, `parcelas` = @parcelas, `observacoes` = @observacoes WHERE `id` = @id LIMIT 1;"; try { OpenConnection(); MySqlCommand query = new MySqlCommand(sql, Connection); query.Parameters.AddWithValue("@nome", Nome); query.Parameters.AddWithValue("@tipo", Tipo); query.Parameters.AddWithValue("@referencia", Referencia); query.Parameters.AddWithValue("@centro_custo", CentroCusto); query.Parameters.AddWithValue("@forma_pagamento", FormaPagamento); query.Parameters.AddWithValue("@status", Status); query.Parameters.AddWithValue("@data_emissao", DateTime.Parse(DataEmissao)); query.Parameters.AddWithValue("@data_vencimento", DateTime.Parse(DataVencimento)); query.Parameters.AddWithValue("@valor", Valor); query.Parameters.AddWithValue("@documento", Documento); query.Parameters.AddWithValue("@ocorrencia", Ocorrencia); query.Parameters.AddWithValue("@qtd_parcelas", Converter.ToIntDB(QtdParcelas, true)); query.Parameters.AddWithValue("@parcelas", Parcelas); query.Parameters.AddWithValue("@observacoes", Observacoes); query.Parameters.AddWithValue("@id", Id); query.ExecuteNonQuery(); CloseConnection(); Success = true; Message = "Financeiro salvo com sucesso."; } catch (Exception e) { Success = false; Message = e.Message; } } public void Get() { string sql = "SELECT * FROM `financeiro` WHERE `id` = @id LIMIT 1;"; try { OpenConnection(); MySqlCommand query = new MySqlCommand(sql, Connection); query.Parameters.AddWithValue("@id", Id); MySqlDataReader data = query.ExecuteReader(); data.Read(); Results.Add(new { Id = data["id"], Nome = data["nome"], Tipo = data["tipo"], Referencia = data["referencia"], CentroCusto = data["centro_custo"], FormaPagamento = data["forma_pagamento"], Status = data["status"], DataEmissao = Converter.DateToString(data["data_emissao"], "dd/MM/yyyy"), DataVencimento = Converter.DateToString(data["data_vencimento"], "dd/MM/yyyy"), Valor = data["valor"], Documento = data["documento"], Ocorrencia = data["ocorrencia"], QtdParcelas = data["qtd_parcelas"], Parcelas = data["parcelas"], Observacoes = data["observacoes"] }); Success = true; } catch (Exception e) { Success = false; Message = e.Message; } } public void GetAll() { string sql = "SELECT * FROM `financeiro`;"; try { OpenConnection(); MySqlCommand query = new MySqlCommand(sql, Connection); MySqlDataReader data = query.ExecuteReader(); while (data.Read()) { Results.Add(new { Id = data["id"], Nome = data["nome"], Tipo = data["tipo"], Referencia = data["referencia"], CentroCusto = data["centro_custo"], FormaPagamento = data["forma_pagamento"], Status = data["status"], DataEmissao = Converter.DateToString(data["data_emissao"], "dd/MM/yyyy"), DataVencimento = Converter.DateToString(data["data_vencimento"], "dd/MM/yyyy"), Valor = data["valor"], Documento = data["documento"], Ocorrencia = data["ocorrencia"], QtdParcelas = data["qtd_parcelas"], Parcelas = data["parcelas"], Observacoes = data["observacoes"] }); } Success = true; } catch (Exception e) { Success = false; Message = e.Message; } } public void Delete() { string sql = "DELETE FROM `financeiro` WHERE `id` = @id LIMIT 1;"; try { OpenConnection(); MySqlCommand query = new MySqlCommand(sql, Connection); query.Parameters.AddWithValue("@id", Id); query.ExecuteNonQuery(); CloseConnection(); Success = true; Message = "Financeiro excluido com sucesso."; } catch (Exception e) { Success = false; Message = e.Message; } } } }
43.348485
454
0.532564
[ "MIT" ]
igorscheffer/Projeto-Integrador-1
Projeto Integrador 1/Projeto Integrador 1/Connection/Financeiro.cs
8,585
C#
using System; using Newtonsoft.Json; namespace DependencyInjection.Infrastructure.WeatherApiModels { public class Forecast { [JsonProperty("dt")] public long Dt { get; set; } [JsonProperty("main")] public Main Main { get; set; } [JsonProperty("weather")] public Weather[] Weather { get; set; } [JsonProperty("clouds")] public Clouds Clouds { get; set; } [JsonProperty("wind")] public Wind Wind { get; set; } [JsonProperty("rain", NullValueHandling = NullValueHandling.Ignore)] public Rain Rain { get; set; } [JsonProperty("sys")] public Sys Sys { get; set; } [JsonProperty("dt_txt")] public string DtTxt { get; set; } } }
24.03125
76
0.582575
[ "MIT" ]
BrunaReveriegoEY/dependencyinjection
autofac/DependencyInjection.Infrastructure/WeatherApiModels/Forecast.cs
769
C#
using Messaging.PersistentTcp.Utilities; using Newtonsoft.Json; namespace Messaging.PersistentTcp.Serializers { public class JsonSerializer<T> : ISerializer<T> { public byte[] Serialize(T obj) => JsonConvert.SerializeObject(obj).ToBytesUTF8(); public T Deserialize(byte[] bytes) => JsonConvert.DeserializeObject<T>(bytes.ToStringUTF8()); } }
31
101
0.728495
[ "MIT" ]
JustoSenka/SimpleMessagingService
Messaging.PersistentTcp/Serializers/JsonSerializer.cs
374
C#
using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using WalletKeeper.API.Demo.DataContexts; using WalletKeeper.Core.Domain.Entities; using WalletKeeper.Core.Domain.Exceptions; namespace WalletKeeper.API.Demo.Factories { public class UserClaimsPrincipalFactory : IUserClaimsPrincipalFactory<User> { private readonly ApplicationDataContext _dataContext; private readonly ILogger<UserClaimsPrincipalFactory> _logger; public UserClaimsPrincipalFactory( ApplicationDataContext dataContext, ILogger<UserClaimsPrincipalFactory> logger ) { _dataContext = dataContext ?? throw new ArgumentNullException(nameof(dataContext)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task<ClaimsPrincipal> CreateAsync(User user) { if (user == null) { throw new BusinessException("User is not exists!"); } var claimsIdentity = GenerateClaimsIdentity(user); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); return await Task.FromResult(claimsPrincipal); } private ClaimsIdentity GenerateClaimsIdentity(User user) { var identity = new ClaimsIdentity("Identity.Application", ClaimTypes.Name, ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); identity.AddClaim(new Claim(ClaimTypes.Email, user.Email)); var roles = _dataContext.UserRoles .Where(ur => ur.UserId == user.Id) .Join(_dataContext.Roles, ur => ur.RoleId, r => r.Id, (ur, r) => r) .Distinct(); foreach (var role in roles) { identity.AddClaim(new Claim(ClaimTypes.Role, role.Name)); } return identity; } } }
29.451613
95
0.755203
[ "MIT" ]
jeydo6/WalletKeeper
WalletKeeper.API.Demo/Factories/UserClaimsPrincipalFactory.cs
1,828
C#
using VehicleCostsMonitor.Web.Infrastructure.Attributes; namespace VehicleCostsMonitor.Tests.Helpers.ValidationTargets { public class ValidationTargetValid { public int FirstNumber { get; set; } [EqualOrGreaterThan(nameof(FirstNumber))] public int SecondNumber { get; set; } } }
24.461538
61
0.716981
[ "MIT" ]
msotiroff/Asp.Net-Core-Projects
source/VehicleCostsMonitor.Tests/Helpers/ValidationTargets/ValidationTargetValid.cs
320
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.AspNet.Routing; using Microsoft.AspNet.Routing.Template; using Microsoft.Extensions.Logging; namespace Microsoft.AspNet.Mvc.Routing { /// <summary> /// Used to build an <see cref="InnerAttributeRoute"/>. Represents an individual URL-matching route that will be /// aggregated into the <see cref="InnerAttributeRoute"/>. /// </summary> public class AttributeRouteMatchingEntry { /// <summary> /// The order of the template. /// </summary> public int Order { get; set; } /// <summary> /// The precedence of the template. /// </summary> public decimal Precedence { get; set; } public IRouter Target { get; set; } public string RouteName { get; set; } public string RouteTemplate { get; set; } public TemplateMatcher TemplateMatcher { get; set; } public IReadOnlyDictionary<string, IRouteConstraint> Constraints { get; set; } } }
31.131579
116
0.658495
[ "Apache-2.0" ]
VGGeorgiev/Mvc
src/Microsoft.AspNet.Mvc.Core/Routing/AttributeRouteMatchingEntry.cs
1,183
C#
using ProtoBuf.Internal; using ProtoBuf.Serializers; using System; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace ProtoBuf.Meta { internal static class TypeModelExtensions { [MethodImpl(ProtoReader.HotPath)] internal static bool HasOption(this TypeModel model, TypeModel.TypeModelOptions options) { var modelOptions = model == null ? TypeModel.DefaultOptions : model.Options; return (modelOptions & options) != 0; } [MethodImpl(ProtoReader.HotPath)] internal static bool OmitsOption(this TypeModel model, TypeModel.TypeModelOptions options) { var modelOptions = model == null ? TypeModel.DefaultOptions : model.Options; return (modelOptions & options) == 0; } } /// <summary> /// Provides protobuf serialization support for a number of types /// </summary> public abstract partial class TypeModel { /// <summary> /// Gets a cached serializer for a type, as offered by a given provider /// </summary> [MethodImpl(ProtoReader.HotPath)] protected static ISerializer<T> GetSerializer<TProvider, T>() where TProvider : class => SerializerCache<TProvider, T>.InstanceField; /// <summary> /// Specifies optional behaviors associated with a type model /// </summary> [Flags] public enum TypeModelOptions { /// <summary> /// No additional options /// </summary> None = 0, /// <summary> /// Should the deserializer attempt to avoid duplicate copies of the same string? /// </summary> InternStrings = 1 << 0, /// <summary> /// Should the <c>Kind</c> be included on date/time values? /// </summary> IncludeDateTimeKind = 1 << 1, /// <summary> /// Should zero-length packed arrays be serialized? (this is the v2 behavior, but skipping them is more efficient) /// </summary> SkipZeroLengthPackedArrays = 1 << 2, /// <summary> /// Should root-values allow "packed" encoding? (v2 does not support this) /// </summary> AllowPackedEncodingAtRoot = 1 << 3, } /// <summary> /// Specifies optional behaviors associated with this model /// </summary> public virtual TypeModelOptions Options => DefaultOptions; internal const TypeModelOptions DefaultOptions = 0; // important: WriteConstructorsAndOverrides only overrides if different /// <summary> /// Resolve a System.Type to the compiler-specific type /// </summary> [Obsolete] protected internal Type MapType(Type type) => type; #pragma warning disable RCS1163 // Unused parameter. /// <summary> /// Resolve a System.Type to the compiler-specific type /// </summary> [Obsolete] protected internal Type MapType(Type type, bool demand) => type; #pragma warning restore RCS1163 // Unused parameter. internal static WireType GetWireType(TypeModel model, DataFormat format, Type type) { if (type.IsEnum) return WireType.Varint; if (model != null && model.CanSerializeContractType(type)) { return format == DataFormat.Group ? WireType.StartGroup : WireType.String; } switch (Helpers.GetTypeCode(type)) { case ProtoTypeCode.Int64: case ProtoTypeCode.UInt64: return format == DataFormat.FixedSize ? WireType.Fixed64 : WireType.Varint; case ProtoTypeCode.Int16: case ProtoTypeCode.Int32: case ProtoTypeCode.UInt16: case ProtoTypeCode.UInt32: case ProtoTypeCode.Boolean: case ProtoTypeCode.SByte: case ProtoTypeCode.Byte: case ProtoTypeCode.Char: return format == DataFormat.FixedSize ? WireType.Fixed32 : WireType.Varint; case ProtoTypeCode.Double: return WireType.Fixed64; case ProtoTypeCode.Single: return WireType.Fixed32; case ProtoTypeCode.String: case ProtoTypeCode.DateTime: case ProtoTypeCode.Decimal: case ProtoTypeCode.ByteArray: case ProtoTypeCode.TimeSpan: case ProtoTypeCode.Guid: case ProtoTypeCode.Uri: return WireType.String; } return WireType.None; } /// <summary> /// Indicates whether a type is known to the model /// </summary> internal virtual bool IsKnownType<T>(CompatibilityLevel ambient) => (TypeHelper<T>.IsReferenceType | !TypeHelper<T>.CanBeNull) // don't claim T? && GetSerializerCore<T>(ambient) != null; internal const SerializerFeatures FromAux = (SerializerFeatures)(1 << 30); /// <summary> /// This is the more "complete" version of Serialize, which handles single instances of mapped types. /// The value is written as a complete field, including field-header and (for sub-objects) a /// length-prefix /// In addition to that, this provides support for: /// - basic values; individual int / string / Guid / etc /// - IEnumerable sequences of any type handled by TrySerializeAuxiliaryType /// /// </summary> internal bool TrySerializeAuxiliaryType(ref ProtoWriter.State state, Type type, DataFormat format, int tag, object value, bool isInsideList, object parentList) { PrepareDeserialize(value, ref type); WireType wireType = GetWireType(this, format, type); if (DynamicStub.CanSerialize(type, this, out var features)) { var scope = NormalizeAuxScope(features, isInsideList, type); try { if (!DynamicStub.TrySerializeAny(tag, wireType.AsFeatures() | FromAux, type, this, ref state, value)) ThrowUnexpectedType(type, this); } catch (Exception ex) { ThrowHelper.ThrowProtoException(ex.Message + $"; scope: {scope}, features: {features}; type: {type.NormalizeName()}", ex); } return true; } // now attempt to handle sequences (including arrays and lists) if (value is IEnumerable sequence) { if (isInsideList) ThrowNestedListsNotSupported(parentList?.GetType()); foreach (object item in sequence) { if (item == null) ThrowHelper.ThrowNullReferenceException(); if (!TrySerializeAuxiliaryType(ref state, null, format, tag, item, true, sequence)) { ThrowUnexpectedType(item.GetType(), this); } } return true; } return false; } static ObjectScope NormalizeAuxScope(SerializerFeatures features, bool isInsideList, Type type) { switch (features.GetCategory()) { case SerializerFeatures.CategoryRepeated: if (isInsideList) ThrowNestedListsNotSupported(type); ThrowHelper.ThrowNotSupportedException("A repeated type was not expected as an aux type: " + type.NormalizeName()); return ObjectScope.NakedMessage; case SerializerFeatures.CategoryMessage: return ObjectScope.WrappedMessage; case SerializerFeatures.CategoryMessageWrappedAtRoot: return isInsideList ? ObjectScope.WrappedMessage : ObjectScope.LikeRoot; case SerializerFeatures.CategoryScalar: return ObjectScope.Scalar; default: features.ThrowInvalidCategory(); return default; } } /// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied stream. /// </summary> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="dest">The destination stream to write to.</param> public void Serialize(Stream dest, object value) { var state = ProtoWriter.State.Create(dest, this); try { SerializeRootFallback(ref state, value); } finally { state.Dispose(); } } /// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied stream. /// </summary> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="dest">The destination stream to write to.</param> /// <param name="context">Additional information about this serialization operation.</param> public void Serialize(Stream dest, object value, SerializationContext context) { var state = ProtoWriter.State.Create(dest, this, context); try { SerializeRootFallback(ref state, value); } finally { state.Dispose(); } } /// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied writer. /// </summary> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="dest">The destination stream to write to.</param> /// <param name="userState">Additional information about this serialization operation.</param> public void Serialize(IBufferWriter<byte> dest, object value, object userState = default) { var state = ProtoWriter.State.Create(dest, this, userState); try { SerializeRootFallback(ref state, value); } finally { state.Dispose(); } } internal void SerializeRootFallback(ref ProtoWriter.State state, object value) { var type = value.GetType(); try { if (!DynamicStub.TrySerializeRoot(type, this, ref state, value)) { #if FEAT_DYNAMIC_REF state.SetRootObject(value); #endif if (!TrySerializeAuxiliaryType(ref state, type, DataFormat.Default, TypeModel.ListItemTag, value, false, null)) { ThrowUnexpectedType(type, this); } state.Close(); } } catch { state.Abandon(); throw; } } /// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied stream. /// </summary> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="dest">The destination stream to write to.</param> /// <param name="userState">Additional information about this serialization operation.</param> public long Serialize<T>(Stream dest, T value, object userState = null) { var state = ProtoWriter.State.Create(dest, this, userState); try { return SerializeImpl<T>(ref state, value); } finally { state.Dispose(); } } /// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied writer. /// </summary> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="dest">The destination stream to write to.</param> /// <param name="userState">Additional information about this serialization operation.</param> public long Serialize<T>(IBufferWriter<byte> dest, T value, object userState = null) { var state = ProtoWriter.State.Create(dest, this, userState); try { return SerializeImpl<T>(ref state, value); } finally { state.Dispose(); } } /// <summary> /// Calculates the length of a protocol-buffer payload for an item /// </summary> public MeasureState<T> Measure<T>(T value, object userState = null, long abortAfter = -1) => new MeasureState<T>(this, value, userState, abortAfter); /// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied writer. /// </summary> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="dest">The destination writer to write to.</param> [Obsolete(ProtoReader.PreferStateAPI, false)] public void Serialize(ProtoWriter dest, object value) { ProtoWriter.State state = dest.DefaultState(); SerializeRootFallback(ref state, value); } internal static long SerializeImpl<T>(ref ProtoWriter.State state, T value) { if (TypeHelper<T>.CanBeNull && TypeHelper<T>.ValueChecker.IsNull(value)) return 0; var serializer = TryGetSerializer<T>(state.Model); if (serializer == null) { Debug.Assert(state.Model != null, "Model is null"); long position = state.GetPosition(); state.Model.SerializeRootFallback(ref state, value); return state.GetPosition() - position; } else { return state.SerializeRoot<T>(value, serializer); } } /// <summary> /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed /// data - useful with network IO. /// </summary> /// <param name="type">The type being merged.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="style">How to encode the length prefix.</param> /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int fieldNumber) => DeserializeWithLengthPrefix(source, value, type, style, fieldNumber, null, out long _); /// <summary> /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed /// data - useful with network IO. /// </summary> /// <param name="type">The type being merged.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="style">How to encode the length prefix.</param> /// <param name="expectedField">The tag used as a prefix to each record (only used with base-128 style prefixes).</param> /// <param name="resolver">Used to resolve types on a per-field basis.</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, TypeResolver resolver) => DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out long _); /// <summary> /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed /// data - useful with network IO. /// </summary> /// <param name="type">The type being merged.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="style">How to encode the length prefix.</param> /// <param name="expectedField">The tag used as a prefix to each record (only used with base-128 style prefixes).</param> /// <param name="resolver">Used to resolve types on a per-field basis.</param> /// <param name="bytesRead">Returns the number of bytes consumed by this operation (includes length-prefix overheads and any skipped data).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, TypeResolver resolver, out int bytesRead) { object result = DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out long bytesRead64, out bool _, null); bytesRead = checked((int)bytesRead64); return result; } /// <summary> /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed /// data - useful with network IO. /// </summary> /// <param name="type">The type being merged.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="style">How to encode the length prefix.</param> /// <param name="expectedField">The tag used as a prefix to each record (only used with base-128 style prefixes).</param> /// <param name="resolver">Used to resolve types on a per-field basis.</param> /// <param name="bytesRead">Returns the number of bytes consumed by this operation (includes length-prefix overheads and any skipped data).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, TypeResolver resolver, out long bytesRead) => DeserializeWithLengthPrefix(source, value, type, style, expectedField, resolver, out bytesRead, out bool _, null); private object DeserializeWithLengthPrefix(Stream source, object value, Type type, PrefixStyle style, int expectedField, TypeResolver resolver, out long bytesRead, out bool haveObject, SerializationContext context) { haveObject = false; bool skip; long len; bytesRead = 0; if (type == null && (style != PrefixStyle.Base128 || resolver == null)) { ThrowHelper.ThrowInvalidOperationException("A type must be provided unless base-128 prefixing is being used in combination with a resolver"); } do { bool expectPrefix = expectedField > 0 || resolver != null; len = ProtoReader.ReadLongLengthPrefix(source, expectPrefix, style, out int actualField, out int tmpBytesRead); if (tmpBytesRead == 0) return value; bytesRead += tmpBytesRead; if (len < 0) return value; switch (style) { case PrefixStyle.Base128: if (expectPrefix && expectedField == 0 && type == null && resolver != null) { type = resolver(actualField); skip = type == null; } else { skip = expectedField != actualField; } break; default: skip = false; break; } if (skip) { if (len == long.MaxValue) ThrowHelper.ThrowInvalidOperationException(); ProtoReader.Seek(source, len, null); bytesRead += len; } } while (skip); var state = ProtoReader.State.Create(source, this, context, len); try { if (IsDefined(type) && !type.IsEnum) { value = Deserialize(ObjectScope.LikeRoot, ref state, type, value); } else { if (!(TryDeserializeAuxiliaryType(ref state, DataFormat.Default, TypeModel.ListItemTag, type, ref value, true, false, true, false, null) || len == 0)) { TypeModel.ThrowUnexpectedType(type, this); // throws } } bytesRead += state.GetPosition(); } finally { state.Dispose(); } haveObject = true; return value; } /// <summary> /// Reads a sequence of consecutive length-prefixed items from a stream, using /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag /// are directly comparable to serializing multiple items in succession /// (use the <see cref="TypeModel.ListItemTag"/> tag to emulate the implicit behavior /// when serializing a list/array). When a tag is /// specified, any records with different tags are silently omitted. The /// tag is ignored. The tag is ignores for fixed-length prefixes. /// </summary> /// <param name="source">The binary stream containing the serialized records.</param> /// <param name="style">The prefix style used in the data.</param> /// <param name="expectedField">The tag of records to return (if non-positive, then no tag is /// expected and all records are returned).</param> /// <param name="resolver">On a field-by-field basis, the type of object to deserialize (can be null if "type" is specified). </param> /// <param name="type">The type of object to deserialize (can be null if "resolver" is specified).</param> /// <returns>The sequence of deserialized objects.</returns> public IEnumerable DeserializeItems(System.IO.Stream source, Type type, PrefixStyle style, int expectedField, TypeResolver resolver) { return DeserializeItems(source, type, style, expectedField, resolver, null); } /// <summary> /// Reads a sequence of consecutive length-prefixed items from a stream, using /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag /// are directly comparable to serializing multiple items in succession /// (use the <see cref="TypeModel.ListItemTag"/> tag to emulate the implicit behavior /// when serializing a list/array). When a tag is /// specified, any records with different tags are silently omitted. The /// tag is ignored. The tag is ignores for fixed-length prefixes. /// </summary> /// <param name="source">The binary stream containing the serialized records.</param> /// <param name="style">The prefix style used in the data.</param> /// <param name="expectedField">The tag of records to return (if non-positive, then no tag is /// expected and all records are returned).</param> /// <param name="resolver">On a field-by-field basis, the type of object to deserialize (can be null if "type" is specified). </param> /// <param name="type">The type of object to deserialize (can be null if "resolver" is specified).</param> /// <returns>The sequence of deserialized objects.</returns> /// <param name="context">Additional information about this serialization operation.</param> public IEnumerable DeserializeItems(System.IO.Stream source, Type type, PrefixStyle style, int expectedField, TypeResolver resolver, SerializationContext context) { return new DeserializeItemsIterator(this, source, type, style, expectedField, resolver, context); } /// <summary> /// Reads a sequence of consecutive length-prefixed items from a stream, using /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag /// are directly comparable to serializing multiple items in succession /// (use the <see cref="TypeModel.ListItemTag"/> tag to emulate the implicit behavior /// when serializing a list/array). When a tag is /// specified, any records with different tags are silently omitted. The /// tag is ignored. The tag is ignores for fixed-length prefixes. /// </summary> /// <typeparam name="T">The type of object to deserialize.</typeparam> /// <param name="source">The binary stream containing the serialized records.</param> /// <param name="style">The prefix style used in the data.</param> /// <param name="expectedField">The tag of records to return (if non-positive, then no tag is /// expected and all records are returned).</param> /// <returns>The sequence of deserialized objects.</returns> public IEnumerable<T> DeserializeItems<T>(Stream source, PrefixStyle style, int expectedField) { return DeserializeItems<T>(source, style, expectedField, null); } /// <summary> /// Reads a sequence of consecutive length-prefixed items from a stream, using /// either base-128 or fixed-length prefixes. Base-128 prefixes with a tag /// are directly comparable to serializing multiple items in succession /// (use the <see cref="TypeModel.ListItemTag"/> tag to emulate the implicit behavior /// when serializing a list/array). When a tag is /// specified, any records with different tags are silently omitted. The /// tag is ignored. The tag is ignores for fixed-length prefixes. /// </summary> /// <typeparam name="T">The type of object to deserialize.</typeparam> /// <param name="source">The binary stream containing the serialized records.</param> /// <param name="style">The prefix style used in the data.</param> /// <param name="expectedField">The tag of records to return (if non-positive, then no tag is /// expected and all records are returned).</param> /// <returns>The sequence of deserialized objects.</returns> /// <param name="context">Additional information about this serialization operation.</param> public IEnumerable<T> DeserializeItems<T>(Stream source, PrefixStyle style, int expectedField, SerializationContext context) { return new DeserializeItemsIterator<T>(this, source, style, expectedField, context); } private sealed class DeserializeItemsIterator<T> : DeserializeItemsIterator, IEnumerator<T>, IEnumerable<T> { IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this; } public new T Current { get { return (T)base.Current; } } void IDisposable.Dispose() { } public DeserializeItemsIterator(TypeModel model, Stream source, PrefixStyle style, int expectedField, SerializationContext context) : base(model, source, typeof(T), style, expectedField, null, context) { } } private class DeserializeItemsIterator : IEnumerator, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { return this; } private bool haveObject; private object current; public bool MoveNext() { if (haveObject) { current = model.DeserializeWithLengthPrefix(source, null, type, style, expectedField, resolver, out long _, out haveObject, context); } return haveObject; } void IEnumerator.Reset() { ThrowHelper.ThrowNotSupportedException(); } public object Current { get { return current; } } private readonly Stream source; private readonly Type type; private readonly PrefixStyle style; private readonly int expectedField; private readonly TypeResolver resolver; private readonly TypeModel model; private readonly SerializationContext context; public DeserializeItemsIterator(TypeModel model, Stream source, Type type, PrefixStyle style, int expectedField, TypeResolver resolver, SerializationContext context) { haveObject = true; this.source = source; this.type = type; this.style = style; this.expectedField = expectedField; this.resolver = resolver; this.model = model; this.context = context; } } /// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied stream, /// with a length-prefix. This is useful for socket programming, /// as DeserializeWithLengthPrefix can be used to read the single object back /// from an ongoing stream. /// </summary> /// <param name="type">The type being serialized.</param> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="style">How to encode the length prefix.</param> /// <param name="dest">The destination stream to write to.</param> /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param> public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber) { SerializeWithLengthPrefix(dest, value, type, style, fieldNumber, null); } /// <summary> /// Writes a protocol-buffer representation of the given instance to the supplied stream, /// with a length-prefix. This is useful for socket programming, /// as DeserializeWithLengthPrefix can be used to read the single object back /// from an ongoing stream. /// </summary> /// <param name="type">The type being serialized.</param> /// <param name="value">The existing instance to be serialized (cannot be null).</param> /// <param name="style">How to encode the length prefix.</param> /// <param name="dest">The destination stream to write to.</param> /// <param name="fieldNumber">The tag used as a prefix to each record (only used with base-128 style prefixes).</param> /// <param name="context">Additional information about this serialization operation.</param> public void SerializeWithLengthPrefix(Stream dest, object value, Type type, PrefixStyle style, int fieldNumber, SerializationContext context) { if (type == null) { if (value == null) ThrowHelper.ThrowArgumentNullException(nameof(value)); type = value.GetType(); } var state = ProtoWriter.State.Create(dest, this, context); try { switch (style) { case PrefixStyle.None: if (!DynamicStub.TrySerializeRoot(type, this, ref state, value)) ThrowUnexpectedType(type, this); break; case PrefixStyle.Base128: case PrefixStyle.Fixed32: case PrefixStyle.Fixed32BigEndian: state.WriteObject(value, type, style, fieldNumber); break; default: ThrowHelper.ThrowArgumentOutOfRangeException(nameof(style)); break; } state.Flush(); state.Close(); } catch { state.Abandon(); throw; } finally { state.Dispose(); } } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <param name="type">The type (including inheritance) to consider.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public object Deserialize(Stream source, object value, Type type) { using var state = ProtoReader.State.Create(source, this, null, ProtoReader.TO_EOF); return state.DeserializeRootFallback(value, type); } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <param name="type">The type (including inheritance) to consider.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> /// <param name="context">Additional information about this serialization operation.</param> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public object Deserialize(Stream source, object value, Type type, SerializationContext context) { using var state = ProtoReader.State.Create(source, this, context, ProtoReader.TO_EOF); return state.DeserializeRootFallback(value, type); } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <typeparam name="T">The type (including inheritance) to consider.</typeparam> /// <param name="userState">Additional information about this serialization operation.</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public T Deserialize<T>(Stream source, T value = default, object userState = null) { using var state = ProtoReader.State.Create(source, this, userState); return state.DeserializeRootImpl<T>(value); } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <typeparam name="T">The type (including inheritance) to consider.</typeparam> /// <param name="userState">Additional information about this serialization operation.</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public T Deserialize<T>(ReadOnlyMemory<byte> source, T value = default, object userState = null) { using var state = ProtoReader.State.Create(source, this, userState); return state.DeserializeRootImpl<T>(value); } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <typeparam name="T">The type (including inheritance) to consider.</typeparam> /// <param name="userState">Additional information about this serialization operation.</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public unsafe T Deserialize<T>(ReadOnlySpan<byte> source, T value = default, object userState = null) { // as an implementation detail, we sometimes need to be able to use iterator blocks etc - which // means we need to be able to persist the span as a memory; the only way to do this // *safely and reliably* is to pint the span for the duration of the deserialize, and throw the // pointer into a custom MemoryManager<byte> (pool the manager to reduce allocs) fixed (byte* ptr = source) { FixedMemoryManager wrapper = null; ProtoReader.State state = default; try { wrapper = Pool<FixedMemoryManager>.TryGet() ?? new FixedMemoryManager(); state = ProtoReader.State.Create(wrapper.Init(ptr, source.Length), this, userState); return state.DeserializeRootImpl<T>(value); } finally { state.Dispose(); Pool<FixedMemoryManager>.Put(wrapper); } } } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <typeparam name="T">The type (including inheritance) to consider.</typeparam> /// <param name="userState">Additional information about this serialization operation.</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public T Deserialize<T>(ReadOnlySequence<byte> source, T value = default, object userState = null) { using var state = ProtoReader.State.Create(source, this, userState); return state.DeserializeRootImpl<T>(value); } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <typeparam name="T">The type (including inheritance) to consider.</typeparam> /// <param name="userState">Additional information about this serialization operation.</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public object Deserialize(Type type, Stream source, object value = default, object userState = null, long length = ProtoReader.TO_EOF) { using var state = ProtoReader.State.Create(source, this, userState, length); return state.DeserializeRootFallback(value, type); } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <typeparam name="T">The type (including inheritance) to consider.</typeparam> /// <param name="userState">Additional information about this serialization operation.</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public object Deserialize(Type type, ReadOnlyMemory<byte> source, object value = default, object userState = null) { using var state = ProtoReader.State.Create(source, this, userState); return state.DeserializeRootFallback(value, type); } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <typeparam name="T">The type (including inheritance) to consider.</typeparam> /// <param name="userState">Additional information about this serialization operation.</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public unsafe object Deserialize(Type type, ReadOnlySpan<byte> source, object value = default, object userState = null) { // as an implementation detail, we sometimes need to be able to use iterator blocks etc - which // means we need to be able to persist the span as a memory; the only way to do this // *safely and reliably* is to pint the span for the duration of the deserialize, and throw the // pointer into a custom MemoryManager<byte> (pool the manager to reduce allocs) fixed (byte* ptr = source) { FixedMemoryManager wrapper = null; ProtoReader.State state = default; try { wrapper = Pool<FixedMemoryManager>.TryGet() ?? new FixedMemoryManager(); state = ProtoReader.State.Create(wrapper.Init(ptr, source.Length), this, userState); return state.DeserializeRootFallback(value, type); } finally { state.Dispose(); Pool<FixedMemoryManager>.Put(wrapper); } } } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <typeparam name="T">The type (including inheritance) to consider.</typeparam> /// <param name="userState">Additional information about this serialization operation.</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> public object Deserialize(Type type, ReadOnlySequence<byte> source, object value = default, object userState = null) { using var state = ProtoReader.State.Create(source, this, userState); return state.DeserializeRootFallback(value, type); } internal static bool PrepareDeserialize(object value, ref Type type) { if (type == null || type == typeof(object)) { if (value == null) ThrowHelper.ThrowArgumentNullException(nameof(type)); type = value.GetType(); } bool autoCreate = true; Type underlyingType = Nullable.GetUnderlyingType(type); if (underlyingType == null) { type = DynamicStub.GetEffectiveType(type); } else { type = underlyingType; autoCreate = false; } return autoCreate; } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <param name="type">The type (including inheritance) to consider.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="length">The number of bytes to consume.</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public object Deserialize(Stream source, object value, System.Type type, int length) => Deserialize(source, value, type, length, null); /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <param name="type">The type (including inheritance) to consider.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="length">The number of bytes to consume.</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public object Deserialize(Stream source, object value, System.Type type, long length) => Deserialize(source, value, type, length, null); /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <param name="type">The type (including inheritance) to consider.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="length">The number of bytes to consume (or -1 to read to the end of the stream).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> /// <param name="context">Additional information about this serialization operation.</param> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public object Deserialize(Stream source, object value, System.Type type, int length, SerializationContext context) => Deserialize(source, value, type, length == int.MaxValue ? long.MaxValue : (long)length, context); /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <param name="type">The type (including inheritance) to consider.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary stream to apply to the instance (cannot be null).</param> /// <param name="length">The number of bytes to consume (or -1 to read to the end of the stream).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> /// <param name="context">Additional information about this serialization operation.</param> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public object Deserialize(Stream source, object value, System.Type type, long length, SerializationContext context) { var state = ProtoReader.State.Create(source, this, context, length); try { bool autoCreate = PrepareDeserialize(value, ref type); if (!DynamicStub.TryDeserializeRoot(type, this, ref state, ref value, autoCreate)) { value = state.DeserializeRootFallback(value, type); } return value; } finally { state.Dispose(); } } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <param name="type">The type (including inheritance) to consider.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary payload to apply to the instance.</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> /// <param name="userState">Additional information about this serialization operation.</param> public object Deserialize(ReadOnlyMemory<byte> source, Type type, object value = default, object userState = default) { var state = ProtoReader.State.Create(source, this, userState); try { bool autoCreate = PrepareDeserialize(value, ref type); if (!DynamicStub.TryDeserializeRoot(type, this, ref state, ref value, autoCreate)) { value = state.DeserializeRootFallback(value, type); } return value; } finally { state.Dispose(); } } /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <param name="type">The type (including inheritance) to consider.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The binary payload to apply to the instance.</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> /// <param name="userState">Additional information about this serialization operation.</param> public object Deserialize(ReadOnlySequence<byte> source, Type type, object value = default, object userState = default) { var state = ProtoReader.State.Create(source, this, userState); try { bool autoCreate = PrepareDeserialize(value, ref type); if (!DynamicStub.TryDeserializeRoot(type, this, ref state, ref value, autoCreate)) { value = state.DeserializeRootFallback(value, type); } return value; } finally { state.Dispose(); } } /// <summary> /// Applies a protocol-buffer reader to an existing instance (which may be null). /// </summary> /// <param name="type">The type (including inheritance) to consider.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="source">The reader to apply to the instance (cannot be null).</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> [Obsolete(ProtoReader.PreferStateAPI, false)] public object Deserialize(ProtoReader source, object value, Type type) => source.DefaultState().DeserializeRootFallbackWithModel(value, type, this); internal object DeserializeRootAny(ref ProtoReader.State state, Type type, object value, bool autoCreate) { if (!DynamicStub.TryDeserializeRoot(type, this, ref state, ref value, autoCreate)) { // this returns true to say we actively found something, but a value is assigned either way (or throws) TryDeserializeAuxiliaryType(ref state, DataFormat.Default, TypeModel.ListItemTag, type, ref value, true, false, autoCreate, false, null); } return value; } private bool TryDeserializeList(ref ProtoReader.State state, DataFormat format, int tag, Type listType, Type itemType, ref object value) { bool found = false; object nextItem = null; IList list = value as IList; var arraySurrogate = list == null ? (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(itemType), nonPublic: true) : null; while (TryDeserializeAuxiliaryType(ref state, format, tag, itemType, ref nextItem, true, true, true, true, value ?? listType)) { found = true; if (value == null && arraySurrogate == null) { value = CreateListInstance(listType, itemType); list = value as IList; } if (list != null) { list.Add(nextItem); } else { arraySurrogate.Add(nextItem); } nextItem = null; } if (arraySurrogate != null) { Array newArray; if (value != null) { if (arraySurrogate.Count == 0) { // we'll stay with what we had, thanks } else { Array existing = (Array)value; newArray = Array.CreateInstance(itemType, existing.Length + arraySurrogate.Count); Array.Copy(existing, newArray, existing.Length); arraySurrogate.CopyTo(newArray, existing.Length); value = newArray; } } else { newArray = Array.CreateInstance(itemType, arraySurrogate.Count); arraySurrogate.CopyTo(newArray, 0); value = newArray; } } return found; } private static object CreateListInstance(Type listType, Type itemType) { Type concreteListType = listType; if (listType.IsArray) { return Array.CreateInstance(itemType, 0); } if (!listType.IsClass || listType.IsAbstract || Helpers.GetConstructor(listType, Type.EmptyTypes, true) == null) { string fullName; bool handled = false; if (listType.IsInterface && (fullName = listType.FullName) != null && fullName.IndexOf("Dictionary") >= 0) // have to try to be frugal here... { if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IDictionary<,>)) { Type[] genericTypes = listType.GetGenericArguments(); concreteListType = typeof(System.Collections.Generic.Dictionary<,>).MakeGenericType(genericTypes); handled = true; } if (!handled && listType == typeof(IDictionary)) { concreteListType = typeof(Hashtable); handled = true; } } if (!handled) { concreteListType = typeof(System.Collections.Generic.List<>).MakeGenericType(itemType); handled = true; } if (!handled) { concreteListType = typeof(ArrayList); #pragma warning disable IDE0059 // unnecessary assignment; I can reason better with it here, in case we need to add more scenarios handled = true; #pragma warning restore IDE0059 } } return Activator.CreateInstance(concreteListType, nonPublic: true); } internal bool TryDeserializeAuxiliaryType(ref ProtoReader.SolidState state, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem, bool autoCreate, bool insideList, object parentListOrType) { var liquid = state.Liquify(); var result = TryDeserializeAuxiliaryType(ref liquid, format, tag, type, ref value, skipOtherFields, asListItem, autoCreate, insideList, parentListOrType); state = liquid.Solidify(); return result; } /// <summary> /// <para> /// This is the more "complete" version of Deserialize, which handles single instances of mapped types. /// The value is read as a complete field, including field-header and (for sub-objects) a /// length-prefix..kmc /// </para> /// <para> /// In addition to that, this provides support for: /// - basic values; individual int / string / Guid / etc /// - IList sets of any type handled by TryDeserializeAuxiliaryType /// </para> /// </summary> internal bool TryDeserializeAuxiliaryType(ref ProtoReader.State state, DataFormat format, int tag, Type type, ref object value, bool skipOtherFields, bool asListItem, bool autoCreate, bool insideList, object parentListOrType) { if (type == null) ThrowHelper.ThrowArgumentNullException(nameof(type)); WireType wiretype = GetWireType(this, format, type); bool found = false; if (wiretype == WireType.None) { #pragma warning disable CS0618 // don't matter; we want to kill the entire aux flow if (!TypeHelper.ResolveUniqueEnumerableT(type, out Type itemType)) #pragma warning restore CS0618 itemType = null; if (itemType == null && type.IsArray && type.GetArrayRank() == 1 && type != typeof(byte[])) { itemType = type.GetElementType(); } if (itemType != null) { if (insideList) TypeModel.ThrowNestedListsNotSupported((parentListOrType as Type) ?? (parentListOrType?.GetType())); found = TryDeserializeList(ref state, format, tag, type, itemType, ref value); if (!found && autoCreate) { value = CreateListInstance(type, itemType); } return found; } // otherwise, not a happy bunny... ThrowUnexpectedType(type, this); } if (!DynamicStub.CanSerialize(type, this, out var features)) ThrowHelper.ThrowInvalidOperationException($"Unable to deserialize aux type: " + type.NormalizeName()); // to treat correctly, should read all values while (true) { // for convenience (re complex exit conditions), additional exit test here: // if we've got the value, are only looking for one, and we aren't a list - then exit #pragma warning disable RCS1218 // Simplify code branching. if (found && asListItem) break; #pragma warning restore RCS1218 // Simplify code branching. // read the next item int fieldNumber = state.ReadFieldHeader(); if (fieldNumber <= 0) break; if (fieldNumber != tag) { if (skipOtherFields) { state.SkipField(); continue; } state.ThrowInvalidOperationException($"Expected field {tag}, but found {fieldNumber}"); } found = true; state.Hint(wiretype); // handle signed data etc // this calls back into DynamicStub.TryDeserialize (with success assertion), // so will handle primitives etc var scope = NormalizeAuxScope(features, insideList, type); value = Deserialize(scope, ref state, type, value); } if (!found && !asListItem && autoCreate) { if (type != typeof(string)) { value = Activator.CreateInstance(type, nonPublic: true); } } return found; } [MethodImpl(MethodImplOptions.NoInlining)] internal static TypeModel SetDefaultModel(TypeModel newValue) { switch (newValue) { case null: case NullModel _: // set to the null instance, but only if the field is null Interlocked.CompareExchange(ref s_defaultModel, NullModel.Singleton, null); break; default: // something more exotic? (presumably RuntimeTypeModel); yeah, OK Interlocked.Exchange(ref s_defaultModel, newValue); break; } return Volatile.Read(ref s_defaultModel); } private static TypeModel s_defaultModel; internal static void ResetDefaultModel() => Volatile.Write(ref s_defaultModel, null); internal static TypeModel DefaultModel => s_defaultModel ?? SetDefaultModel(null); internal sealed class NullModel : TypeModel { private NullModel() { } private static readonly NullModel s_Singleton = new NullModel(); public static TypeModel Singleton { [MethodImpl(MethodImplOptions.NoInlining)] get => s_Singleton; } protected override ISerializer<T> GetSerializer<T>() => null; } /// <summary> /// Creates a new runtime model, to which the caller /// can add support for a range of types. A model /// can be used "as is", or can be compiled for /// optimal performance. /// </summary> [Obsolete("Use RuntimeTypeModel.Create", true)] public static TypeModel Create() { ThrowHelper.ThrowNotSupportedException(); return default; } /// <summary> /// Create a model that serializes all types from an /// assembly specified by type /// </summary> [Obsolete("Use RuntimeTypeModel.CreateForAssembly", true)] public static TypeModel CreateForAssembly<T>() { ThrowHelper.ThrowNotSupportedException(); return default; } /// <summary> /// Create a model that serializes all types from an /// assembly specified by type /// </summary> [Obsolete("Use RuntimeTypeModel.CreateForAssembly", true)] public static TypeModel CreateForAssembly(Type type) { ThrowHelper.ThrowNotSupportedException(); return default; } /// <summary> /// Create a model that serializes all types from an assembly /// </summary> [Obsolete("Use RuntimeTypeModel.CreateForAssembly", true)] public static TypeModel CreateForAssembly(Assembly assembly) { ThrowHelper.ThrowNotSupportedException(); return default; } /// <summary> /// Indicates whether the supplied type is explicitly modelled by the model /// </summary> public bool IsDefined(Type type) => IsDefined(type, default); /// <summary> /// Indicates whether the supplied type is explicitly modelled by the model /// </summary> internal bool IsDefined(Type type, CompatibilityLevel ambient) => type != null && DynamicStub.IsKnownType(type, this, ambient); /// <summary> /// Get a typed serializer for <typeparamref name="T"/> /// </summary> protected virtual ISerializer<T> GetSerializer<T>() => this as ISerializer<T>; internal virtual ISerializer<T> GetSerializerCore<T>(CompatibilityLevel ambient) => GetSerializer<T>(); [MethodImpl(MethodImplOptions.NoInlining)] private static ISerializer<T> NoSerializer<T>(TypeModel model) { string suffix = null; if (model is NullModel) { suffix = "; you may need to ensure that RuntimeTypeModel.Initialize has been invoked"; } ThrowHelper.ThrowInvalidOperationException($"No serializer for type {typeof(T).NormalizeName()} is available for model {model?.ToString() ?? "(none)"}{suffix}"); return default; } [MethodImpl(MethodImplOptions.NoInlining)] private static ISubTypeSerializer<T> NoSubTypeSerializer<T>(TypeModel model) where T : class { ThrowHelper.ThrowInvalidOperationException($"No sub-type serializer for type {typeof(T).NormalizeName()} is available for model {model?.ToString() ?? "(none)"}"); return default; } internal static T CreateInstance<T>(ISerializationContext context, ISerializer<T> serializer = null) { if (TypeHelper<T>.IsReferenceType) { serializer ??= TypeModel.TryGetSerializer<T>(context?.Model); T obj = default; if (serializer is IFactory<T> factory) obj = factory.Create(context); // note we already know this is a ref-type if (obj is null) obj = ActivatorCreate<T>(); return obj; } else { return default; } } [MethodImpl(MethodImplOptions.NoInlining)] internal static T ActivatorCreate<T>() { try { return (T)Activator.CreateInstance(typeof(T), nonPublic: true); } catch (MissingMethodException mme) { TypeModel.ThrowCannotCreateInstance(typeof(T), mme); return default; } } [MethodImpl(MethodImplOptions.NoInlining)] internal static ISerializer<T> GetSerializer<T>(TypeModel model, CompatibilityLevel ambient = default) => SerializerCache<PrimaryTypeProvider, T>.InstanceField ?? model?.GetSerializerCore<T>(ambient) ?? NoSerializer<T>(model); /// <summary> /// Gets the inbuilt serializer relevant to a specific <see cref="CompatibilityLevel"/> (and <see cref="DataFormat"/>). /// Returns null if there is no defined inbuilt serializer. /// </summary> #if DEBUG // I always want these explicitly specified in the library code; so: enforce that public static ISerializer<T> GetInbuiltSerializer<T>(CompatibilityLevel compatibilityLevel, DataFormat dataFormat) #else public static ISerializer<T> GetInbuiltSerializer<T>(CompatibilityLevel compatibilityLevel = default, DataFormat dataFormat = DataFormat.Default) #endif { ISerializer<T> serializer; if (compatibilityLevel >= CompatibilityLevel.Level300) { if (dataFormat == DataFormat.FixedSize) { serializer = SerializerCache<Level300FixedSerializer, T>.InstanceField; if (serializer is object) return serializer; } serializer = SerializerCache<Level300DefaultSerializer, T>.InstanceField; if (serializer is object) return serializer; } #pragma warning disable CS0618 else if (compatibilityLevel >= CompatibilityLevel.Level240 || dataFormat == DataFormat.WellKnown) #pragma warning restore CS0618 { serializer = SerializerCache<Level240DefaultSerializer, T>.InstanceField; if (serializer is object) return serializer; } return SerializerCache<PrimaryTypeProvider, T>.InstanceField; } [MethodImpl(MethodImplOptions.NoInlining)] internal static IRepeatedSerializer<T> GetRepeatedSerializer<T>(TypeModel model) { if (model?.GetSerializer<T>() is IRepeatedSerializer<T> serializer) return serializer; NoSerializer<T>(model); return default; } [MethodImpl(MethodImplOptions.NoInlining)] internal static ISerializer<T> TryGetSerializer<T>(TypeModel model) => SerializerCache<PrimaryTypeProvider, T>.InstanceField ?? model?.GetSerializer<T>(); [MethodImpl(MethodImplOptions.NoInlining)] internal static ISubTypeSerializer<T> GetSubTypeSerializer<T>(TypeModel model) where T : class => model?.GetSerializer<T>() as ISubTypeSerializer<T> ?? NoSubTypeSerializer<T>(model); /// <summary> /// Applies a protocol-buffer stream to an existing instance (which may be null). /// </summary> /// <param name="type">Represents the type (including inheritance) to consider.</param> /// <param name="value">The existing instance to be modified (can be null).</param> /// <param name="state">Reader state</param> /// <param name="scope">The style of serialization to adopt</param> /// <returns>The updated instance; this may be different to the instance argument if /// either the original instance was null, or the stream defines a known sub-type of the /// original instance.</returns> internal object Deserialize(ObjectScope scope, ref ProtoReader.State state, Type type, object value) { if (!DynamicStub.TryDeserialize(scope, type, this, ref state, ref value)) { ThrowHelper.ThrowNotSupportedException($"{nameof(Deserialize)} is not supported for {type.NormalizeName()} by {this}"); } return value; } /// <summary> /// Indicates the type of callback to be used /// </summary> protected internal enum CallbackType { /// <summary> /// Invoked before an object is serialized /// </summary> BeforeSerialize, /// <summary> /// Invoked after an object is serialized /// </summary> AfterSerialize, /// <summary> /// Invoked before an object is deserialized (or when a new instance is created) /// </summary> BeforeDeserialize, /// <summary> /// Invoked after an object is deserialized /// </summary> AfterDeserialize } /// <summary> /// Create a deep clone of the supplied instance; any sub-items are also cloned. /// </summary> public T DeepClone<T>(T value, object userState = null) { #if PLAT_ISREF if (!System.Runtime.CompilerServices.RuntimeHelpers.IsReferenceOrContainsReferences<T>()) return value; // whether it is trivial or complex, we already have a full clone of a value-type #endif if (TypeHelper<T>.CanBeNull && TypeHelper<T>.ValueChecker.IsNull(value)) return value; var serializer = TryGetSerializer<T>(this); if (serializer == null) { return (T)DeepCloneFallback(typeof(T), value); } else if ((serializer.Features & SerializerFeatures.CategoryScalar) != 0) { // scalars should be immutable; if not: that's on you! return value; } else { using var ms = new MemoryStream(); Serialize<T>(ms, value, userState); ms.Position = 0; return Deserialize<T>(ms, default, userState); } } /// <summary> /// Create a deep clone of the supplied instance; any sub-items are also cloned. /// </summary> public object DeepClone(object value) { if (value == null) return null; Type type = value.GetType(); return DynamicStub.TryDeepClone(type, this, ref value) ? value : DeepCloneFallback(type, value); } private object DeepCloneFallback(Type type, object value) { // must be some kind of aux scenario, then using MemoryStream ms = new MemoryStream(); var writeState = ProtoWriter.State.Create(ms, this, null); PrepareDeserialize(value, ref type); try { if (!TrySerializeAuxiliaryType(ref writeState, type, DataFormat.Default, TypeModel.ListItemTag, value, false, null)) ThrowUnexpectedType(type, this); writeState.Close(); } catch { writeState.Abandon(); throw; } finally { writeState.Dispose(); } ms.Position = 0; var readState = ProtoReader.State.Create(ms, this, null, ProtoReader.TO_EOF); try { value = null; // start from scratch! TryDeserializeAuxiliaryType(ref readState, DataFormat.Default, TypeModel.ListItemTag, type, ref value, true, false, true, false, null); } finally { readState.Dispose(); } return value; } /// <summary> /// Indicates that while an inheritance tree exists, the exact type encountered was not /// specified in that hierarchy and cannot be processed. /// </summary> protected internal static void ThrowUnexpectedSubtype(Type expected, Type actual) { if (!DynamicStub.IsTypeEquivalent(expected, actual)) { ThrowHelper.ThrowInvalidOperationException("Unexpected sub-type: " + actual.FullName); } } /// <summary> /// Indicates that while an inheritance tree exists, the exact type encountered was not /// specified in that hierarchy and cannot be processed. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowUnexpectedSubtype<T>(T value) where T : class { if (IsSubType<T>(value)) ThrowUnexpectedSubtype(typeof(T), value.GetType()); } /// <summary> /// Indicates that while an inheritance tree exists, the exact type encountered was not /// specified in that hierarchy and cannot be processed. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ThrowUnexpectedSubtype<T, TConstruct>(T value) where T : class where TConstruct : class, T { if (IsSubType<T>(value) && value.GetType() != typeof(TConstruct)) ThrowUnexpectedSubtype(typeof(T), value.GetType()); } /// <summary> /// Returns whether the object provided is a subtype of the expected type /// </summary> public static bool IsSubType<T>(T value) where T : class => value != null && typeof(T) != value.GetType(); /// <summary> /// Indicates that the given type was not expected, and cannot be processed. /// </summary> protected internal static void ThrowUnexpectedType(Type type, TypeModel model) { string fullName = type == null ? "(unknown)" : type.FullName; if (type != null) { Type baseType = type.BaseType; if (baseType != null && baseType .IsGenericType && baseType.GetGenericTypeDefinition().Name == "GeneratedMessage`2") { ThrowHelper.ThrowInvalidOperationException( "Are you mixing protobuf-net and protobuf-csharp-port? See https://stackoverflow.com/q/11564914/23354; type: " + fullName); } } try { ThrowHelper.ThrowInvalidOperationException("Type is not expected, and no contract can be inferred: " + fullName); } catch (Exception ex) when (model != null) { ex.Data["TypeModel"] = model.ToString(); throw; } } [MethodImpl(MethodImplOptions.NoInlining)] internal static void ThrowNestedListsNotSupported(Type type) => ThrowHelper.ThrowNestedDataNotSupported(type); /// <summary> /// Indicates that the given type cannot be constructed; it may still be possible to /// deserialize into existing instances. /// </summary> public static void ThrowCannotCreateInstance(Type type, Exception inner = null) { ThrowHelper.ThrowProtoException("No parameterless constructor found for " + (type?.FullName ?? "(null)"), inner); } internal static string SerializeType(TypeModel model, System.Type type) { if (model != null) { TypeFormatEventHandler handler = model.DynamicTypeFormatting; if (handler != null) { TypeFormatEventArgs args = new TypeFormatEventArgs(type); handler(model, args); if (!string.IsNullOrEmpty(args.FormattedName)) return args.FormattedName; } } return type.AssemblyQualifiedName; } internal static Type DeserializeType(TypeModel model, string value) { if (model != null) { TypeFormatEventHandler handler = model.DynamicTypeFormatting; if (handler != null) { TypeFormatEventArgs args = new TypeFormatEventArgs(value); handler(model, args); if (args.Type != null) return args.Type; } } return Type.GetType(value); } /// <summary> /// Returns true if the type supplied is either a recognised contract type, /// or a *list* of a recognised contract type. /// </summary> /// <remarks>Note that primitives always return false, even though the engine /// will, if forced, try to serialize such</remarks> /// <returns>True if this type is recognised as a serializable entity, else false</returns> public bool CanSerializeContractType(Type type) => CanSerialize(type, false, true, true, out _); /// <summary> /// Returns true if the type supplied is a basic type with inbuilt handling, /// a recognised contract type, or a *list* of a basic / contract type. /// </summary> public bool CanSerialize(Type type) => CanSerialize(type, true, true, true, out _); /// <summary> /// Returns true if the type supplied is a basic type with inbuilt handling, /// or a *list* of a basic type with inbuilt handling /// </summary> public bool CanSerializeBasicType(Type type) => CanSerialize(type, true, false, true, out _); internal bool CanSerialize(Type type, bool allowBasic, bool allowContract, bool allowLists, out SerializerFeatures category) { if (type == null) ThrowHelper.ThrowArgumentNullException(nameof(type)); static bool CheckIfNullableT(ref Type type) { Type tmp = Nullable.GetUnderlyingType(type); if (tmp != null) { type = tmp; return true; } return false; } do { if (DynamicStub.CanSerialize(type, this, out var features)) { category = features.GetCategory(); switch (category) { case SerializerFeatures.CategoryRepeated: return allowLists && DoCheckLists(type, this, allowBasic, allowContract); case SerializerFeatures.CategoryMessage: return allowContract; case SerializerFeatures.CategoryScalar: case SerializerFeatures.CategoryMessageWrappedAtRoot: return allowBasic; } } } while (CheckIfNullableT(ref type)); static bool DoCheckLists(Type type, TypeModel model, bool allowBasic, bool allowContract) { // is it a list? #pragma warning disable CS0618 // this is a legit usage return TypeHelper.ResolveUniqueEnumerableT(type, out var itemType) && model.CanSerialize(itemType, allowBasic, allowContract, false, out _); #pragma warning restore CS0618 } category = default; return false; } /// <summary> /// Suggest a .proto definition for the given type /// </summary> /// <param name="type">The type to generate a .proto definition for, or <c>null</c> to generate a .proto that represents the entire model</param> /// <returns>The .proto definition as a string</returns> public string GetSchema(Type type) => GetSchema(type, ProtoSyntax.Default); /// <summary> /// Suggest a .proto definition for the given type /// </summary> /// <param name="type">The type to generate a .proto definition for, or <c>null</c> to generate a .proto that represents the entire model</param> /// <returns>The .proto definition as a string</returns> /// <param name="syntax">The .proto syntax to use for the operation</param> public string GetSchema(Type type, ProtoSyntax syntax) { SchemaGenerationOptions options; if (type is null && syntax == ProtoSyntax.Default) { options = SchemaGenerationOptions.Default; } else { options = new SchemaGenerationOptions { Syntax = syntax }; if (type is object) options.Types.Add(type); } return GetSchema(options); } /// <summary> /// Suggest a .proto definition for the given configuration /// </summary> /// <returns>The .proto definition as a string</returns> /// <param name="options">Options for schema generation</param> public virtual string GetSchema(SchemaGenerationOptions options) { ThrowHelper.ThrowNotSupportedException(); return default; } #pragma warning disable RCS1159 // Use EventHandler<T>. /// <summary> /// Used to provide custom services for writing and parsing type names when using dynamic types. Both parsing and formatting /// are provided on a single API as it is essential that both are mapped identically at all times. /// </summary> public event TypeFormatEventHandler DynamicTypeFormatting; #pragma warning restore RCS1159 // Use EventHandler<T>. /// <summary> /// Creates a new IFormatter that uses protocol-buffer [de]serialization. /// </summary> /// <returns>A new IFormatter to be used during [de]serialization.</returns> /// <param name="type">The type of object to be [de]deserialized by the formatter.</param> public System.Runtime.Serialization.IFormatter CreateFormatter(Type type) { return new Formatter(this, type); } internal sealed class Formatter : System.Runtime.Serialization.IFormatter { private readonly TypeModel model; private readonly Type type; internal Formatter(TypeModel model, Type type) { if (model == null) ThrowHelper.ThrowArgumentNullException(nameof(model)); if (type == null) ThrowHelper.ThrowArgumentNullException(nameof(model)); this.model = model; this.type = type; } public System.Runtime.Serialization.SerializationBinder Binder { get; set; } public System.Runtime.Serialization.StreamingContext Context { get; set; } public object Deserialize(Stream serializationStream) { using var state = ProtoReader.State.Create(serializationStream, model, Context); return state.DeserializeRootFallback(null, type); } public void Serialize(Stream serializationStream, object graph) { var state = ProtoWriter.State.Create(serializationStream, model, Context); try { model.SerializeRootFallback(ref state, graph); } finally { state.Dispose(); } } public System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get; set; } } #if DEBUG // this is used by some unit tests only, to ensure no buffering when buffering is disabled /// <summary> /// If true, buffering of nested objects is disabled /// </summary> public bool ForwardsOnly { get; set; } #endif [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static Type ResolveKnownType(string name, Assembly assembly) { if (string.IsNullOrEmpty(name)) return null; try { Type type = Type.GetType(name); if (type != null) return type; } catch { } try { int i = name.IndexOf(','); string fullName = (i > 0 ? name.Substring(0, i) : name).Trim(); if (assembly == null) assembly = Assembly.GetCallingAssembly(); Type type = assembly?.GetType(fullName); if (type != null) return type; } catch { } return null; } /// <summary> /// The field number that is used as a default when serializing/deserializing a list of objects. /// The data is treated as repeated message with field number 1. /// </summary> public const int ListItemTag = 1; } }
48.015789
288
0.5821
[ "Apache-2.0" ]
b25/protobuf-net
src/protobuf-net.Core/Meta/TypeModel.cs
91,232
C#
using Disqord.Models; namespace Disqord.Rest.AuditLogs { public sealed class RestOverwriteCreatedAuditLog : RestAuditLog { public OverwriteData Data { get; } internal RestOverwriteCreatedAuditLog(RestDiscordClient client, AuditLogModel log, AuditLogEntryModel entry) : base(client, log, entry) { Data = new OverwriteData(client, entry, true); } } }
28.133333
144
0.665877
[ "MIT" ]
FenikkusuKoneko/Disqord
src/Disqord.Rest/Entities/Rest/Guild/AuditLogs/Overwrite/RestOverwriteCreatedAuditLog.cs
424
C#
using System.Threading.Tasks; using WUApiLib; namespace devmon_library.Core { internal sealed class UpdateSearcherCallback : ISearchCompletedCallback { private readonly IUpdateSearcher _updateSearcher; private readonly TaskCompletionSource<ISearchResult> _taskCompletionSource; public UpdateSearcherCallback(IUpdateSearcher updateSearcher, TaskCompletionSource<ISearchResult> taskCompletionSource) { _updateSearcher = updateSearcher; _taskCompletionSource = taskCompletionSource; } public void Invoke(ISearchJob searchJob, ISearchCompletedCallbackArgs callbackArgs) { ISearchResult result = _updateSearcher.EndSearch(searchJob); _taskCompletionSource.SetResult(result); } } }
33.5
127
0.7301
[ "MIT" ]
Officeclip/devmon_agent
devmon_library/Core/UpdateSearcherCallback.cs
806
C#
#region License // Copyright (c) 2019 Jake Fowler // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Concurrent; using System.Linq.Expressions; using System.Reflection; namespace Cmdty.TimePeriodValueTypes { public static class TimePeriodFactory<T> where T : ITimePeriod<T> { // TODO look at whether dictionary is necessary as key type information is already held in the generic type T of TimePeriodFactory private static readonly ConcurrentDictionary<Type, Func<DateTime, T>> Creators = new ConcurrentDictionary<Type, Func<DateTime, T>>(); // TODO after benchmarking, potentially populate this dictionary with factory methods of known TimePeriod types public static T FromDateTime(DateTime dateTime) { var timePeriodType = typeof(T); var creator = Creators.GetOrAdd(timePeriodType, ConstructCreator); return creator(dateTime); } // TODO benchmark performance private static Func<DateTime, T> ConstructCreator(Type type) { var dateTimeParameter = Expression.Parameter(typeof(DateTime)); // TODO look at other overloads of Type.GetMethod which specify argument types MethodInfo staticFactoryMethod = type.GetMethod("FromDateTime", BindingFlags.Public | BindingFlags.Static); // TODO look for constructors which accept single DateTime parameters if (staticFactoryMethod == null) throw new ArgumentException($"Type {type.Name} does not contain public static method FromDateTime"); var expression = Expression.Call(staticFactoryMethod, dateTimeParameter); var lambda2 = Expression.Lambda<Func<DateTime, T>>(expression, dateTimeParameter); return lambda2.Compile(); } } public static class TimePeriodFactory { public static T FromDateTime<T>(DateTime dateTime) where T : ITimePeriod<T> { return TimePeriodFactory<T>.FromDateTime(dateTime); } } }
41.337662
138
0.700597
[ "MIT" ]
cmdty/time-period-value-types
src/Cmdty.TimePeriodValueTypes/TimePeriodFactory.cs
3,185
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ToStringReadableOptions.cs" company="OBeautifulCode"> // Copyright (c) OBeautifulCode 2018. All rights reserved. // </copyright> // <auto-generated> // Sourced from NuGet package. Will be overwritten with package update except in OBeautifulCode.Type.Recipes source. // </auto-generated> // -------------------------------------------------------------------------------------------------------------------- namespace OBeautifulCode.Type.Recipes { using System; /// <summary> /// Extensions methods on type <see cref="Type"/>. /// </summary> [Flags] #if !OBeautifulCodeTypeRecipesProject internal #else public #endif enum ToStringReadableOptions { /// <summary> /// None (default). /// Use this option to generate the most succinct representation of the specified type. /// </summary> None = 0, /// <summary> /// Include the namespace of the type. /// If the type is generic then also include the namespace of all generic argument types. /// </summary> IncludeNamespace = 1, /// <summary> /// Include details (name and version) about the assembly that contains the type. /// If the type is generic then also include details about the assembly that contains /// all of the generic argument types. /// </summary> IncludeAssemblyDetails, } }
35.409091
120
0.539795
[ "MIT" ]
NaosProject/Naos.HubSpot
Naos.HubSpot.Domain.Test/.recipes/OBeautifulCode.Type/ToStringReadableOptions.cs
1,560
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Add number ranges to a service provider. /// The response is either SuccessResponse or ErrorResponse. /// <see cref="SuccessResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""3f28429898a57a7f7846d3877b22df9f:612""}]")] public class ServiceProviderRouteListEnterpriseTrunkNumberRangeAddListRequest22 : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _serviceProviderId; [XmlElement(ElementName = "serviceProviderId", IsNullable = false, Namespace = "")] [Group(@"3f28429898a57a7f7846d3877b22df9f:612")] [MinLength(1)] [MaxLength(30)] public string ServiceProviderId { get => _serviceProviderId; set { ServiceProviderIdSpecified = true; _serviceProviderId = value; } } [XmlIgnore] protected bool ServiceProviderIdSpecified { get; set; } private List<BroadWorksConnector.Ocip.Models.EnterpriseTrunkNumberRange> _numberRange = new List<BroadWorksConnector.Ocip.Models.EnterpriseTrunkNumberRange>(); [XmlElement(ElementName = "numberRange", IsNullable = false, Namespace = "")] [Group(@"3f28429898a57a7f7846d3877b22df9f:612")] public List<BroadWorksConnector.Ocip.Models.EnterpriseTrunkNumberRange> NumberRange { get => _numberRange; set { NumberRangeSpecified = true; _numberRange = value; } } [XmlIgnore] protected bool NumberRangeSpecified { get; set; } } }
33.2
167
0.647088
[ "MIT" ]
Rogn/broadworks-connector-net
BroadworksConnector/Ocip/Models/ServiceProviderRouteListEnterpriseTrunkNumberRangeAddListRequest22.cs
1,992
C#
using System; using System.Collections.Generic; using Lucene.Net.Documents; using Orchard; using Orchard.Indexing; using Orchard.Localization; using Orchard.Utility.Extensions; namespace Lucene.Models { public class LuceneDocumentIndex : IDocumentIndex { public List<AbstractField> Fields { get; private set; } private string _name; private string _stringValue; private int _intValue; private double _doubleValue; private bool _analyze; private bool _store; private bool _removeTags; private TypeCode _typeCode; public int ContentItemId { get; private set; } public LuceneDocumentIndex(int documentId, Localizer t) { Fields = new List<AbstractField>(); SetContentItemId(documentId); IsDirty = false; _typeCode = TypeCode.Empty; T = t; } public Localizer T { get; set; } public bool IsDirty { get; private set; } public IDocumentIndex Add(string name, string value) { PrepareForIndexing(); _name = name; _stringValue = value; _typeCode = TypeCode.String; IsDirty = true; return this; } public IDocumentIndex Add(string name, DateTime value) { return Add(name, DateTools.DateToString(value, DateTools.Resolution.MILLISECOND)); } public IDocumentIndex Add(string name, int value) { PrepareForIndexing(); _name = name; _intValue = value; _typeCode = TypeCode.Int32; IsDirty = true; return this; } public IDocumentIndex Add(string name, bool value) { return Add(name, value ? 1 : 0); } public IDocumentIndex Add(string name, double value) { PrepareForIndexing(); _name = name; _doubleValue = value; _typeCode = TypeCode.Single; IsDirty = true; return this; } public IDocumentIndex Add(string name, object value) { return Add(name, value.ToString()); } public IDocumentIndex RemoveTags() { _removeTags = true; return this; } public IDocumentIndex Store() { _store = true; return this; } public IDocumentIndex Analyze() { _analyze = true; return this; } public IDocumentIndex SetContentItemId(int contentItemId) { ContentItemId = contentItemId; Fields.Add(new Field("id", contentItemId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); return this; } public void PrepareForIndexing() { switch(_typeCode) { case TypeCode.String: if(_removeTags) { _stringValue = _stringValue.RemoveTags(true); } Fields.Add(new Field(_name, _stringValue ?? String.Empty, _store ? Field.Store.YES : Field.Store.NO, _analyze ? Field.Index.ANALYZED : Field.Index.NOT_ANALYZED)); break; case TypeCode.Int32: Fields.Add(new NumericField(_name, _store ? Field.Store.YES : Field.Store.NO, true).SetIntValue(_intValue)); break; case TypeCode.Single: Fields.Add(new NumericField(_name, _store ? Field.Store.YES : Field.Store.NO, true).SetDoubleValue(_doubleValue)); break; case TypeCode.Empty: break; default: throw new OrchardException(T("Unexpected index type")); } _removeTags = false; _analyze = false; _store = false; _typeCode = TypeCode.Empty; } } }
31.312977
109
0.533886
[ "BSD-3-Clause" ]
1996dylanriley/Orchard
src/Orchard.Web/Modules/Lucene/Models/LuceneDocumentIndex.cs
4,104
C#
using System; using Limbo.Umbraco.Seo.Models.Sitemaps; using Skybrud.Essentials.Enums; using Umbraco.Cms.Core.Models.PublishedContent; using Umbraco.Cms.Core.PropertyEditors; namespace Limbo.Umbraco.Seo.Editors.Sitemaps { public class SitemapFrequencyValueConverter : PropertyValueConverterBase { public override bool IsConverter(IPublishedPropertyType propertyType) { return propertyType.EditorAlias == SitemapFrequencyEditor.EditorAlias; } public override Type GetPropertyValueType(IPublishedPropertyType propertyType) { return typeof(SitemapChangeFrequency); } public override PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType) { return PropertyCacheLevel.Element; } public override object ConvertSourceToIntermediate(IPublishedElement owner, IPublishedPropertyType propertyType, object source, bool preview) { return EnumUtils.ParseEnum(source as string, SitemapChangeFrequency.Unspecified); } public override object ConvertIntermediateToXPath(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview) { return inter; } } }
38.909091
189
0.756231
[ "MIT" ]
Mantus667/Limbo.Umbraco.Seo
src/Limbo.Umbraco.Seo/Editors/Sitemaps/SitemapFrequencyValueConverter.cs
1,286
C#
using SBC.Cryptography.ECC; using SBC.SmartContract; using SBC.Wallets; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace SBC.UI { internal partial class CreateMultiSigContractDialog : Form { private ECPoint[] publicKeys; public CreateMultiSigContractDialog() { InitializeComponent(); } public Contract GetContract() { publicKeys = listBox1.Items.OfType<string>().Select(p => ECPoint.DecodePoint(p.HexToBytes(), ECCurve.Secp256r1)).ToArray(); return Contract.CreateMultiSigContract((int)numericUpDown2.Value, publicKeys); } public KeyPair GetKey() { HashSet<ECPoint> hashSet = new HashSet<ECPoint>(publicKeys); return Program.CurrentWallet.GetAccounts().FirstOrDefault(p => p.HasKey && hashSet.Contains(p.GetKey().PublicKey))?.GetKey(); } private void numericUpDown2_ValueChanged(object sender, EventArgs e) { button6.Enabled = numericUpDown2.Value > 0; } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { button5.Enabled = listBox1.SelectedIndices.Count > 0; } private void textBox5_TextChanged(object sender, EventArgs e) { button4.Enabled = textBox5.TextLength > 0; } private void button4_Click(object sender, EventArgs e) { listBox1.Items.Add(textBox5.Text); textBox5.Clear(); numericUpDown2.Maximum = listBox1.Items.Count; } private void button5_Click(object sender, EventArgs e) { listBox1.Items.RemoveAt(listBox1.SelectedIndex); numericUpDown2.Maximum = listBox1.Items.Count; } } }
30.245902
137
0.633062
[ "MIT" ]
FDship/SBC
SBC-Gui/UI/CreateMultiSigContractDialog.cs
1,847
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace QCloud.CosApi.Common { public static class Extension { public static long ToUnixTime(this DateTime nowTime) { DateTime startTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); return (long)Math.Round((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero); } } }
26.647059
109
0.644592
[ "MIT" ]
KirbyXcode/SMS_OSS_COS
COS/Common/Extension.cs
455
C#
using Autofac; using NLayer.Configuration; using NLayer.HealthCheck; using NLayer.Logging; using NLayer.Logging.NLog; namespace NLayer.PL.IoC.Autofac.Modules { /// <summary> /// Adds components in the container. /// </summary> public class InfrastructureModule : Module { #region Overrides of Module /// <summary>Override to add registrations to the container.</summary> /// <remarks> /// Note that the ContainerBuilder parameter is unique to this module. /// </remarks> /// <param name="builder">The builder through which components can be /// registered.</param> protected override void Load(ContainerBuilder builder) { builder.RegisterType<LogFactory>() .As<ILogFactory>(); builder.RegisterType<ConfigReader>() .As<IConfigReader>() .SingleInstance(); builder.RegisterType<HealthChecker>() .As<IHealthChecker>() .SingleInstance(); } #endregion } }
28.526316
78
0.596863
[ "Apache-2.0" ]
ZyshchykMaksim/NLayer.NET
NLayer.NET.PL/IoC/Autofac/Modules/InfrastructureModule.cs
1,086
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.Generic; using System.Text; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class CommonFormattingHelpers { public static readonly Comparison<SuppressOperation> SuppressOperationComparer = (o1, o2) => { return o1.TextSpan.Start - o2.TextSpan.Start; }; public static readonly Comparison<IndentBlockOperation> IndentBlockOperationComparer = (o1, o2) => { // smaller one goes left var s = o1.TextSpan.Start - o2.TextSpan.Start; if (s != 0) { return s; } // bigger one goes left var e = o2.TextSpan.End - o1.TextSpan.End; if (e != 0) { return e; } return 0; }; public static IEnumerable<ValueTuple<SyntaxToken, SyntaxToken>> ConvertToTokenPairs(this SyntaxNode root, IList<TextSpan> spans) { Contract.ThrowIfNull(root); Contract.ThrowIfFalse(spans.Count > 0); if (spans.Count == 1) { // special case, if there is only one span, return right away yield return root.ConvertToTokenPair(spans[0]); yield break; } var pairs = new List<ValueTuple<SyntaxToken, SyntaxToken>>(); var previousOne = root.ConvertToTokenPair(spans[0]); // iterate through each spans and make sure each one doesn't overlap each other for (var i = 1; i < spans.Count; i++) { var currentOne = root.ConvertToTokenPair(spans[i]); if (currentOne.Item1.SpanStart <= previousOne.Item2.Span.End) { // oops, looks like two spans are overlapping each other. merge them previousOne = ValueTuple.Create(previousOne.Item1, previousOne.Item2.Span.End < currentOne.Item2.Span.End ? currentOne.Item2 : previousOne.Item2); continue; } // okay, looks like things are in good shape yield return previousOne; // move to next one previousOne = currentOne; } // give out the last one yield return previousOne; } public static ValueTuple<SyntaxToken, SyntaxToken> ConvertToTokenPair(this SyntaxNode root, TextSpan textSpan) { Contract.ThrowIfNull(root); Contract.ThrowIfTrue(textSpan.IsEmpty); var startToken = root.FindToken(textSpan.Start); // empty token, get previous non-zero length token if (startToken.IsMissing) { // if there is no previous token, startToken will be set to SyntaxKind.None startToken = startToken.GetPreviousToken(); } // span is on leading trivia if (textSpan.Start < startToken.SpanStart) { // if there is no previous token, startToken will be set to SyntaxKind.None startToken = startToken.GetPreviousToken(); } // adjust position where we try to search end token var endToken = (root.FullSpan.End <= textSpan.End) ? root.GetLastToken(includeZeroWidth: true) : root.FindToken(textSpan.End); // empty token, get next token if (endToken.IsMissing) { endToken = endToken.GetNextToken(); } // span is on trailing trivia if (endToken.Span.End < textSpan.End) { endToken = endToken.GetNextToken(); } // make sure tokens are not SyntaxKind.None startToken = (startToken.RawKind != 0) ? startToken : root.GetFirstToken(includeZeroWidth: true); endToken = (endToken.RawKind != 0) ? endToken : root.GetLastToken(includeZeroWidth: true); // token is in right order Contract.ThrowIfFalse(startToken.Equals(endToken) || startToken.Span.End <= endToken.SpanStart); return ValueTuple.Create(startToken, endToken); } public static bool IsInvalidTokenRange(this SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken) { // given token must be token exist excluding EndOfFile token. if (startToken.RawKind == 0 || endToken.RawKind == 0) { return true; } if (startToken.Equals(endToken)) { return false; } // regular case. // start token can't be end of file token and start token must be before end token if it's not the same token. return root.FullSpan.End == startToken.SpanStart || startToken.FullSpan.End > endToken.FullSpan.Start; } public static int GetTokenColumn(this SyntaxTree tree, SyntaxToken token, int tabSize) { Contract.ThrowIfNull(tree); Contract.ThrowIfTrue(token.RawKind == 0); var startPosition = token.SpanStart; var line = tree.GetText().Lines.GetLineFromPosition(startPosition); return line.GetColumnFromLineOffset(startPosition - line.Start, tabSize); } public static string GetText(this SourceText text, SyntaxToken token1, SyntaxToken token2) { return (token1.RawKind == 0) ? text.ToString(TextSpan.FromBounds(0, token2.SpanStart)) : text.ToString(TextSpan.FromBounds(token1.Span.End, token2.SpanStart)); } public static string GetTextBetween(SyntaxToken token1, SyntaxToken token2) { var builder = new StringBuilder(); AppendTextBetween(token1, token2, builder); return builder.ToString(); } public static void AppendTextBetween(SyntaxToken token1, SyntaxToken token2, StringBuilder builder) { Contract.ThrowIfTrue(token1.RawKind == 0 && token2.RawKind == 0); Contract.ThrowIfTrue(token1.Equals(token2)); if (token1.RawKind == 0) { AppendLeadingTriviaText(token2, builder); return; } if (token2.RawKind == 0) { AppendTrailingTriviaText(token1, builder); return; } var token1PartOftoken2LeadingTrivia = token1.FullSpan.Start > token2.FullSpan.Start; if (token1.FullSpan.End == token2.FullSpan.Start) { AppendTextBetweenTwoAdjacentTokens(token1, token2, builder); return; } AppendTrailingTriviaText(token1, builder); for (var token = token1.GetNextToken(includeZeroWidth: true); token.FullSpan.End <= token2.FullSpan.Start; token = token.GetNextToken(includeZeroWidth: true)) { builder.Append(token.ToFullString()); } AppendPartialLeadingTriviaText(token2, builder, token1.TrailingTrivia.FullSpan.End); } private static void AppendTextBetweenTwoAdjacentTokens(SyntaxToken token1, SyntaxToken token2, StringBuilder builder) { AppendTrailingTriviaText(token1, builder); AppendLeadingTriviaText(token2, builder); } private static void AppendLeadingTriviaText(SyntaxToken token, StringBuilder builder) { if (!token.HasLeadingTrivia) { return; } foreach (var trivia in token.LeadingTrivia) { builder.Append(trivia.ToFullString()); } } /// <summary> /// If the token1 is expected to be part of the leading trivia of the token2 then the trivia /// before the token1FullSpanEnd, which the fullspan end of the token1 should be ignored /// </summary> private static void AppendPartialLeadingTriviaText(SyntaxToken token, StringBuilder builder, int token1FullSpanEnd) { if (!token.HasLeadingTrivia) { return; } foreach (var trivia in token.LeadingTrivia) { if (trivia.FullSpan.End <= token1FullSpanEnd) { continue; } builder.Append(trivia.ToFullString()); } } private static void AppendTrailingTriviaText(SyntaxToken token, StringBuilder builder) { if (!token.HasTrailingTrivia) { return; } foreach (var trivia in token.TrailingTrivia) { builder.Append(trivia.ToFullString()); } } /// <summary> /// this will create a span that includes its trailing trivia of its previous token and leading trivia of its next token /// for example, for code such as "class A { int ...", if given tokens are "A" and "{", this will return span [] of "class[ A { ]int ..." /// which included trailing trivia of "class" which is previous token of "A", and leading trivia of "int" which is next token of "{" /// </summary> public static TextSpan GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(SyntaxToken startToken, SyntaxToken endToken) { // most of cases we can just ask previous and next token to create the span, but in some corner cases such as omitted token case, // those navigation function doesn't work, so we have to explore the tree ourselves to create correct span var startPosition = GetStartPositionOfSpan(startToken); var endPosition = GetEndPositionOfSpan(endToken); return TextSpan.FromBounds(startPosition, endPosition); } private static int GetEndPositionOfSpan(SyntaxToken token) { var nextToken = token.GetNextToken(); if (nextToken.RawKind != 0) { return nextToken.SpanStart; } var backwardPosition = token.FullSpan.End; var parentNode = GetParentThatContainsGivenSpan(token.Parent, backwardPosition, forward: false); if (parentNode == null) { // reached the end of tree return token.FullSpan.End; } Contract.ThrowIfFalse(backwardPosition < parentNode.FullSpan.End); nextToken = parentNode.FindToken(backwardPosition + 1); Contract.ThrowIfTrue(nextToken.RawKind == 0); return nextToken.SpanStart; } public static int GetStartPositionOfSpan(SyntaxToken token) { var previousToken = token.GetPreviousToken(); if (previousToken.RawKind != 0) { return previousToken.Span.End; } // first token in the tree var forwardPosition = token.FullSpan.Start; if (forwardPosition <= 0) { return 0; } var parentNode = GetParentThatContainsGivenSpan(token.Parent, forwardPosition, forward: true); if (parentNode == null) { return Contract.FailWithReturn<int>("This can't happen"); } Contract.ThrowIfFalse(parentNode.FullSpan.Start < forwardPosition); previousToken = parentNode.FindToken(forwardPosition + 1); Contract.ThrowIfTrue(previousToken.RawKind == 0); return previousToken.Span.End; } private static SyntaxNode GetParentThatContainsGivenSpan(SyntaxNode node, int position, bool forward) { while (node != null) { var fullSpan = node.FullSpan; if (forward) { if (fullSpan.Start < position) { return node; } } else { if (position > fullSpan.End) { return node; } } node = node.Parent; } return null; } public static bool HasAnyWhitespaceElasticTrivia(SyntaxToken previousToken, SyntaxToken currentToken) { if ((!previousToken.ContainsAnnotations && !currentToken.ContainsAnnotations) || (!previousToken.HasTrailingTrivia && !currentToken.HasLeadingTrivia)) { return false; } return previousToken.TrailingTrivia.HasAnyWhitespaceElasticTrivia() || currentToken.LeadingTrivia.HasAnyWhitespaceElasticTrivia(); } public static bool IsNull<T>(T t) where T : class { return t == null; } public static bool IsNotNull<T>(T t) where T : class { return !IsNull(t); } public static TextSpan GetFormattingSpan(SyntaxNode root, TextSpan span) { Contract.ThrowIfNull(root); var startToken = root.FindToken(span.Start).GetPreviousToken(); var endToken = root.FindTokenFromEnd(span.End).GetNextToken(); var startPosition = startToken.SpanStart; var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End; return TextSpan.FromBounds(startPosition, endPosition); } } }
36.382429
171
0.576065
[ "Apache-2.0" ]
Sliptory/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CommonFormattingHelpers.cs
14,082
C#
namespace AcademyRPG { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class Giant : Character, IControllable, IFighter , IGatherer { private int attackPoints; private bool hasGatheredStone; public Giant(string name, Point position) : base(name, position, 0) { this.HitPoints = 200; this.AttackPoints = 150; } public int AttackPoints { get { return this.attackPoints; } set { this.attackPoints = value; } } public int DefensePoints { get { return 80; } } public int GetTargetIndex(List<WorldObject> availableTargets) { for (int i = 0; i < availableTargets.Count; i++) { if (availableTargets[i].Owner != this.Owner && availableTargets[i].Owner != 0) { return i; } } return -1; } public bool TryGather(IResource resource) { if (resource.Type == ResourceType.Stone) { if (!hasGatheredStone) { this.attackPoints += 100; this.hasGatheredStone = true; } return true; } return false; } } }
24.40678
94
0.476389
[ "MIT" ]
Konstantin-Todorov/CSharpOOP
C#OOP-Exams/TTTAcademyRPG/AcademyRPG/AcademyRPG/Giant.cs
1,442
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using EchoRenderer.Mathematics.Intersections; namespace EchoRenderer.Mathematics.Accelerators { /// <summary> /// A binary hierarchical spacial partitioning acceleration structure. /// Works best with medium sized quantities of geometries and tokens. /// There must be more than one token and <see cref="AxisAlignedBoundingBox"/> to process. /// </summary> public class BoundingVolumeHierarchy : TraceAccelerator { public BoundingVolumeHierarchy(PressedPack pack, IReadOnlyList<AxisAlignedBoundingBox> aabbs, IReadOnlyList<uint> tokens) : base(pack, aabbs, tokens) { int[] indices = Enumerable.Range(0, aabbs.Count).ToArray(); BranchBuilder builder = new BranchBuilder(aabbs); BranchBuilder.Node root = builder.Build(indices); int index = 1; nodes = new Node[builder.NodeCount]; nodes[0] = CreateNode(root, out maxDepth); Node CreateNode(BranchBuilder.Node node, out int depth) { if (node.IsLeaf) { depth = 1; return Node.CreateLeaf(node.aabb, tokens[node.index]); } int children = index; index += 2; nodes[children] = CreateNode(node.child0, out int depth0); nodes[children + 1] = CreateNode(node.child1, out int depth1); depth = Math.Max(depth0, depth1) + 1; return Node.CreateNode(node.aabb, children); } } public override int Hash { get { int hash = maxDepth; foreach (Node node in nodes) hash = (hash * 397) ^ node.GetHashCode(); return hash; } } readonly Node[] nodes; readonly int maxDepth; public override void GetIntersection(ref HitQuery query) { if (nodes == null) return; if (nodes.Length == 1) { uint token = nodes[0].token; //If root is the only node/leaf pack.GetIntersection(ref query, token); } else { ref readonly Node root = ref nodes[0]; float local = root.aabb.Intersect(query.ray); if (local < query.distance) Traverse(ref query); } } public override int GetIntersectionCost(in Ray ray, ref float distance) { if (nodes == null) return 0; ref readonly Node root = ref nodes[0]; float hit = root.aabb.Intersect(ray); if (hit >= distance) return 1; return GetIntersectionCost(root, ray, ref distance) + 1; } public override unsafe int FillAABB(uint depth, Span<AxisAlignedBoundingBox> span) { int length = 1 << (int)depth; if (length > span.Length) throw new Exception($"{nameof(span)} is not large enough! Length: '{span.Length}'"); int* stack0 = stackalloc int[length]; int* stack1 = stackalloc int[length]; int* next0 = stack0; int* next1 = stack1; *next0++ = 0; //Root at 0 int head = 0; //Result head for (uint i = 0; i < depth; i++) { while (next0 != stack0) { int index = *--next0; ref readonly Node node = ref nodes[index]; if (!node.IsLeaf) { *next1++ = node.children; *next1++ = node.children + 1; } else span[head++] = node.aabb; //If leaf then we write it to the result } //Swap the two stacks Swap(ref next0, ref next1); Swap(ref stack0, ref stack1); [MethodImpl(MethodImplOptions.AggressiveInlining)] void Swap(ref int* pointer0, ref int* pointer1) { var storage = pointer0; pointer0 = pointer1; pointer1 = storage; } } //Export results while (next0 != stack0) { ref readonly Node node = ref nodes[*--next0]; span[head++] = node.aabb; } return head; } [MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.AggressiveInlining)] unsafe void Traverse(ref HitQuery query) { int* stack = stackalloc int[maxDepth]; float* hits = stackalloc float[maxDepth]; int* next = stack; *next++ = 1; //The root's first children is always at one *hits++ = 0f; //stackalloc does not guarantee data to be zero, we have to manually assign it while (next != stack) { int index = *--next; if (*--hits >= query.distance) continue; ref readonly Node child0 = ref nodes[index]; ref readonly Node child1 = ref nodes[index + 1]; float hit0 = child0.aabb.Intersect(query.ray); float hit1 = child1.aabb.Intersect(query.ray); //Orderly intersects the two children so that there is a higher chance of intersection on the first child. //Although the order of leaf intersection is wrong, the performance is actually better than reversing to correct it. if (hit0 < hit1) { if (hit1 < query.distance) { if (child1.IsLeaf) pack.GetIntersection(ref query, child1.token); else { *next++ = child1.children; *hits++ = hit1; } } if (hit0 < query.distance) { if (child0.IsLeaf) pack.GetIntersection(ref query, child0.token); else { *next++ = child0.children; *hits++ = hit0; } } } else { if (hit0 < query.distance) { if (child0.IsLeaf) pack.GetIntersection(ref query, child0.token); else { *next++ = child0.children; *hits++ = hit0; } } if (hit1 < query.distance) { if (child1.IsLeaf) pack.GetIntersection(ref query, child1.token); else { *next++ = child1.children; *hits++ = hit1; } } } } } int GetIntersectionCost(in Node node, in Ray ray, ref float distance) { if (node.IsLeaf) { //Now we finally calculate the intersection cost on the leaf return pack.GetIntersectionCost(ray, ref distance, node.token); } ref Node child0 = ref nodes[node.children]; ref Node child1 = ref nodes[node.children + 1]; float hit0 = child0.aabb.Intersect(ray); float hit1 = child1.aabb.Intersect(ray); int cost = 2; if (hit0 < hit1) //Orderly intersects the two children so that there is a higher chance of intersection on the first child { if (hit0 < distance) cost += GetIntersectionCost(in child0, ray, ref distance); if (hit1 < distance) cost += GetIntersectionCost(in child1, ray, ref distance); } else { if (hit1 < distance) cost += GetIntersectionCost(in child1, ray, ref distance); if (hit0 < distance) cost += GetIntersectionCost(in child0, ray, ref distance); } return cost; } [StructLayout(LayoutKind.Explicit, Size = 32)] //Size must be under 32 bytes to fit two nodes in one cache line (64 bytes) readonly struct Node { Node(in AxisAlignedBoundingBox aabb, uint token, int children) { this.aabb = aabb; //AABB is assigned before the last two fields this.token = token; this.children = children; } [FieldOffset(0)] public readonly AxisAlignedBoundingBox aabb; //NOTE: the AABB is 28 bytes large, but its last 4 bytes are not used and only occupied for SIMD loading //So we can overlap the next four bytes onto the AABB and pay extra attention when first assigning the fields [FieldOffset(24)] public readonly uint token; //Token will only be assigned if is leaf [FieldOffset(28)] public readonly int children; //Index of first child, second child is right after first public bool IsLeaf => children == 0; public static Node CreateLeaf(in AxisAlignedBoundingBox aabb, uint token) => new Node(aabb, token, 0); public static Node CreateNode(in AxisAlignedBoundingBox aabb, int children) => new Node(aabb, default, children); public override int GetHashCode() { unchecked { int hashCode = aabb.GetHashCode(); hashCode = (hashCode * 397) ^ (int)token; hashCode = (hashCode * 397) ^ children; return hashCode; } } } } }
27.537367
151
0.65314
[ "MIT" ]
MMXXX-VIII/ForceRenderer
EchoRenderer/Mathematics/Accelerators/BoundingVolumeHierarchy.cs
7,740
C#
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using LogicAndTrick.Oy; using Sledge.BspEditor.Documents; using Sledge.BspEditor.Modification; using Sledge.BspEditor.Modification.Operations; using Sledge.BspEditor.Modification.Operations.Selection; using Sledge.BspEditor.Primitives.MapData; using Sledge.BspEditor.Primitives.MapObjectData; using Sledge.BspEditor.Primitives.MapObjects; using Sledge.Common.Shell.Commands; using Sledge.Common.Shell.Components; using Sledge.Common.Shell.Context; using Sledge.Common.Shell.Documents; using Sledge.Common.Shell.Hooks; using Sledge.Common.Translations; using Sledge.Shell; namespace Sledge.BspEditor.Editing.Components.Visgroup { [AutoTranslate] [Export(typeof(ISidebarComponent))] [Export(typeof(IInitialiseHook))] [OrderHint("G")] public partial class VisgroupSidebarPanel : UserControl, ISidebarComponent, IInitialiseHook { [Import] private ITranslationStringProvider _translation; public Task OnInitialise() { Oy.Subscribe<IDocument>("Document:Activated", DocumentActivated); Oy.Subscribe<Change>("MapDocument:Changed", DocumentChanged); return Task.FromResult(0); } public string Title { get; set; } = "Visgroups"; public object Control => this; public string EditButton { set { this.InvokeLater(() => { btnEdit.Text = value; }); } } public string SelectButton { set { this.InvokeLater(() => { btnSelect.Text = value; }); } } public string ShowAllButton { set { this.InvokeLater(() => { btnShowAll.Text = value; }); } } public string NewButton { set { this.InvokeLater(() => { btnNew.Text = value; }); } } public string AutoVisgroups { get; set; } private WeakReference<MapDocument> _activeDocument = new WeakReference<MapDocument>(null); public VisgroupSidebarPanel() { InitializeComponent(); CreateHandle(); } public bool IsInContext(IContext context) { return context.TryGet("ActiveDocument", out MapDocument _); } private async Task DocumentActivated(IDocument doc) { var md = doc as MapDocument; _activeDocument = new WeakReference<MapDocument>(md); Update(md); } private async Task DocumentChanged(Change change) { if (_activeDocument.TryGetTarget(out MapDocument t) && change.Document == t) { if (change.HasObjectChanges || IsVisgroupDataChange(change)) { Update(change.Document); } } } private static bool IsVisgroupDataChange(Change change) { return change.HasDataChanges && change.AffectedData.Any(x => x is AutomaticVisgroup || x is Primitives.MapData.Visgroup); } private void Update(MapDocument document) { Task.Factory.StartNew(() => { if (document == null) { this.InvokeLater(() => VisgroupPanel.Clear()); } else { var tree = GetItemHierarchies(document); this.InvokeLater(() => VisgroupPanel.Update(tree)); } }); } private List<VisgroupItem> GetItemHierarchies(MapDocument document) { var list = new List<VisgroupItem>(); // add user visgroups var visgroups = document.Map.Data.Get<Primitives.MapData.Visgroup>().ToList(); foreach (var v in visgroups) { list.Add(new VisgroupItem(v.Name) { CheckState = GetVisibilityCheckState(v.Objects), Colour = v.Colour, Tag = v }); } var auto = new VisgroupItem(AutoVisgroups) { Disabled = true }; list.Insert(0, auto); // add auto visgroups var autoVisgroups = document.Map.Data.Get<AutomaticVisgroup>().ToList(); var parents = new Dictionary<string, VisgroupItem> {{"", auto}}; foreach (var av in autoVisgroups.OrderBy(x => x.Path.Length)) { VisgroupItem parent = auto; if (!parents.ContainsKey(av.Path)) { var path = new List<string>(); foreach (var spl in av.Path.Split('/')) { path.Add(spl); var seg = String.Join("/", path); if (!parents.ContainsKey(seg)) { var group = new VisgroupItem(_translation.GetString(spl)) { Parent = parent, Disabled = true }; list.Add(group); parents[seg] = group; } parent = parents[seg]; } } else { parent = parents[av.Path]; } list.Add(new VisgroupItem(_translation.GetString(av.Key)) { CheckState = GetVisibilityCheckState(av.Objects), Tag = av, Parent = parent }); } for (var i = list.Count - 1; i >= 0; i--) { var v = list[i]; if (v.Tag != null) continue; var children = list.Where(x => x.Parent == v).ToList(); if (children.All(x => x.CheckState == CheckState.Checked)) v.CheckState = CheckState.Checked; else if (children.All(x => x.CheckState == CheckState.Unchecked)) v.CheckState = CheckState.Unchecked; else v.CheckState = CheckState.Indeterminate; } return list; } private CheckState GetVisibilityCheckState(IEnumerable<IMapObject> objects) { var bools = objects.Select(x => x.Data.GetOne<VisgroupHidden>()?.IsHidden ?? false); return GetCheckState(bools); } private CheckState GetCheckState(IEnumerable<bool> bools) { var a = bools.Distinct().ToArray(); if (a.Length == 0) return CheckState.Checked; if (a.Length == 1) return a[0] ? CheckState.Unchecked : CheckState.Checked; return CheckState.Indeterminate; } private IEnumerable<IMapObject> GetVisgroupObjects(VisgroupItem item) { if (item?.Tag is Primitives.MapData.Visgroup v) return v.Objects; if (item?.Tag is AutomaticVisgroup av) return av.Objects; var children = VisgroupPanel.GetAllItems().Where(x => x.Parent == item).SelectMany(GetVisgroupObjects); return new HashSet<IMapObject>(children); } private void SelectButtonClicked(object sender, EventArgs e) { var sv = VisgroupPanel.SelectedVisgroup; if (sv != null && _activeDocument.TryGetTarget(out MapDocument md)) { MapDocumentOperation.Perform(md, new Transaction(new Deselect(md.Selection), new Select(GetVisgroupObjects(sv)))); } } private void EditButtonClicked(object sender, EventArgs e) { Oy.Publish("Command:Run", new CommandMessage("BspEditor:Map:Visgroups")); } private void ShowAllButtonClicked(object sender, EventArgs e) { if (_activeDocument.TryGetTarget(out MapDocument md)) { var objects = md.Map.Root.Find(x => x.Data.GetOne<VisgroupHidden>()?.IsHidden == true, true).ToList(); if (objects.Any()) { MapDocumentOperation.Perform(md, new TrivialOperation( d => objects.ToList().ForEach(x => x.Data.Replace(new VisgroupHidden(false))), c => c.AddRange(objects) )); } } } private void NewButtonClicked(object sender, EventArgs e) { } private void VisgroupToggled(object sender, VisgroupItem visgroup, CheckState state) { if (state == CheckState.Indeterminate) return; var visible = state == CheckState.Checked; var objects = GetVisgroupObjects(visgroup).SelectMany(x => x.FindAll()).ToList(); if (objects.Any() && _activeDocument.TryGetTarget(out MapDocument md)) { MapDocumentOperation.Perform(md, new TrivialOperation( d => objects.ForEach(x => x.Data.Replace(new VisgroupHidden(!visible))), c => c.AddRange(objects) )); } } private void VisgroupSelected(object sender, VisgroupItem visgroup) { } } }
36.732283
133
0.544802
[ "BSD-3-Clause" ]
LogicAndTrick/sledge
Sledge.BspEditor.Editing/Components/Visgroup/VisgroupSidebarPanel.cs
9,332
C#
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.ComponentModel.Design; namespace XenAdmin.Controls { [Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))] public partial class ToolTipContainer : Panel { /// <summary> /// If true, prevents the tooltip from appearing. /// </summary> public bool SuppressTooltip = false; EmptyPanel emptyPanel1; public ToolTipContainer() { InitializeComponent(); } public Control TheControl; protected override void OnControlAdded(ControlEventArgs e) { base.OnControlAdded(e); if (e.Control is EmptyPanel) return; TheControl = e.Control; e.Control.Dock = DockStyle.Fill; emptyPanel1 = new EmptyPanel(); emptyPanel1.Dock = DockStyle.Fill; Controls.Add(emptyPanel1); emptyPanel1.BringToFront(); emptyPanel1.Enabled = !TheControl.Enabled; TheControl.EnabledChanged += new EventHandler(TheControl_EnabledChanged); } private void TheControl_EnabledChanged(object sender, EventArgs e) { emptyPanel1.Enabled = !TheControl.Enabled; } public void SetToolTip(string text) { toolTip1.RemoveAll(); toolTip1.Popup += new PopupEventHandler(toolTip1_Popup); toolTip1.SetToolTip(emptyPanel1, text); } public void RemoveAll() { toolTip1.RemoveAll(); } private void toolTip1_Popup(object sender, PopupEventArgs e) { if (!e.AssociatedControl.ClientRectangle.Contains(e.AssociatedControl.PointToClient(MousePosition)) || SuppressTooltip) { e.Cancel = true; } } } }
34.386139
111
0.659084
[ "BSD-2-Clause" ]
wdxgy136/xenadmin-yeesan
XenAdmin/Controls/ToolTipContainer.cs
3,475
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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests related to binding (but not lowering) lock statements. /// </summary> public class UnsafeTests : CompilingTestBase { private static string GetEscapedNewLine() { if (Environment.NewLine == "\n") { return @"\n"; } else if (Environment.NewLine == "\r\n") { return @"\r\n"; } else { throw new Exception("Unrecognized new line"); } } #region Unsafe regions [Fact] public void FixedSizeBuffer() { var text1 = @" using System; using System.Runtime.InteropServices; public static class R { public unsafe struct S { public fixed byte Buffer[16]; } }"; var comp1 = CreateEmptyCompilation(text1, assemblyName: "assembly1", references: new[] { MscorlibRef_v20 }, options: TestOptions.UnsafeDebugDll); var ref1 = comp1.EmitToImageReference(); var text2 = @" using System; class C { unsafe void M(byte* p) { R.S* p2 = (R.S*)p; IntPtr p3 = M2((IntPtr)p2[0].Buffer); } unsafe IntPtr M2(IntPtr p) => p; }"; var comp2 = CreateCompilationWithMscorlib45(text2, references: new[] { ref1 }, options: TestOptions.UnsafeDebugDll); comp2.VerifyDiagnostics( // warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1), // warning CS1701: Assuming assembly reference 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' used by 'assembly1' matches identity 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' of 'mscorlib', you may need to supply runtime policy Diagnostic(ErrorCode.WRN_UnifyReferenceMajMin).WithArguments("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "assembly1", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mscorlib").WithLocation(1, 1)); } [Fact] public void CompilationNotUnsafe1() { var text = @" unsafe class C { } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false)).VerifyDiagnostics( // (2,14): error CS0227: Unsafe code may only appear if compiling with /unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "C")); CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void CompilationNotUnsafe2() { var text = @" class C { unsafe void Goo() { } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false)).VerifyDiagnostics( // (4,17): error CS0227: Unsafe code may only appear if compiling with /unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Goo")); CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void CompilationNotUnsafe3() { var text = @" class C { void Goo() { unsafe { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false)).VerifyDiagnostics( // (6,9): error CS0227: Unsafe code may only appear if compiling with /unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe")); CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void IteratorUnsafe1() { var text = @" unsafe class C { System.Collections.Generic.IEnumerator<int> Goo() { yield return 1; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void IteratorUnsafe2() { var text = @" class C { unsafe System.Collections.Generic.IEnumerator<int> Goo() { yield return 1; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,56): error CS1629: Unsafe code may not appear in iterators Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Goo")); } [Fact] public void IteratorUnsafe3() { var text = @" class C { System.Collections.Generic.IEnumerator<int> Goo() { unsafe { } yield return 1; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,9): error CS1629: Unsafe code may not appear in iterators Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe")); } [Fact] public void IteratorUnsafe4() { var text = @" unsafe class C { System.Collections.Generic.IEnumerator<int> Goo() { unsafe { } yield return 1; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,9): error CS1629: Unsafe code may not appear in iterators Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe")); } [WorkItem(546657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546657")] [Fact] public void IteratorUnsafe5() { var text = @" unsafe class C { System.Collections.Generic.IEnumerator<int> Goo() { System.Action a = () => { unsafe { } }; yield return 1; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,9): error CS1629: Unsafe code may not appear in iterators Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "unsafe")); } [Fact] public void UnsafeModifier() { var text = @" unsafe class C { unsafe C() { } unsafe ~C() { } unsafe static void Static() { } unsafe void Instance() { } unsafe struct Inner { } unsafe int field = 1; unsafe event System.Action Event; unsafe int Property { get; set; } unsafe int this[int x] { get { return field; } set { } } unsafe public static C operator +(C c1, C c2) { return c1; } unsafe public static implicit operator int(C c) { return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,32): warning CS0067: The event 'C.Event' is never used // unsafe event System.Action Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("C.Event")); } [Fact] public void TypeIsUnsafe() { var text = @" unsafe class C<T> { int* f0; int** f1; int*[] f2; int*[][] f3; C<int*> f4; C<int**> f5; C<int*[]> f6; C<int*[][]> f7; } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (8,7): error CS0306: The type 'int*' may not be used as a type argument Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*"), // (9,7): error CS0306: The type 'int**' may not be used as a type argument Diagnostic(ErrorCode.ERR_BadTypeArgument, "int**").WithArguments("int**"), // (4,10): warning CS0169: The field 'C<T>.f0' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f0").WithArguments("C<T>.f0"), // (5,11): warning CS0169: The field 'C<T>.f1' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f1").WithArguments("C<T>.f1"), // (6,12): warning CS0169: The field 'C<T>.f2' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f2").WithArguments("C<T>.f2"), // (7,14): warning CS0169: The field 'C<T>.f3' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f3").WithArguments("C<T>.f3"), // (8,13): warning CS0169: The field 'C<T>.f4' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f4").WithArguments("C<T>.f4"), // (9,14): warning CS0169: The field 'C<T>.f5' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f5").WithArguments("C<T>.f5"), // (10,15): warning CS0169: The field 'C<T>.f6' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f6").WithArguments("C<T>.f6"), // (11,17): warning CS0169: The field 'C<T>.f7' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f7").WithArguments("C<T>.f7")); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var fieldTypes = Enumerable.Range(0, 8).Select(i => type.GetMember<FieldSymbol>("f" + i).Type).ToArray(); Assert.True(fieldTypes[0].IsUnsafe()); Assert.True(fieldTypes[1].IsUnsafe()); Assert.True(fieldTypes[2].IsUnsafe()); Assert.True(fieldTypes[3].IsUnsafe()); Assert.False(fieldTypes[4].IsUnsafe()); Assert.False(fieldTypes[5].IsUnsafe()); Assert.False(fieldTypes[6].IsUnsafe()); Assert.False(fieldTypes[7].IsUnsafe()); } [Fact] public void UnsafeFieldTypes() { var template = @" {0} class C {{ public {1} int* f = null, g = null; }} "; CompareUnsafeDiagnostics(template, // (4,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public int* f = null, g = null; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*") ); } [Fact] public void UnsafeLocalTypes() { var template = @" {0} class C {{ void M() {{ {1} {{ int* f = null, g = null; }} }} }} "; CompareUnsafeDiagnostics(template, // (6,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")); } [Fact] public void UnsafeMethodSignatures() { var template = @" {0} interface I {{ {1} int* M(long* p, byte* q); }} {0} class C {{ {1} int* M(long* p, byte* q) {{ throw null; }} }} "; CompareUnsafeDiagnostics(template, // (4,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"), // (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"), // (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"), // (9,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"), // (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")); } [Fact] public void DelegateSignatures() { var template = @" {0} class C {{ {1} delegate int* M(long* p, byte* q); }} "; CompareUnsafeDiagnostics(template, // (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"), // (4,31): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"), // (4,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")); } [Fact] public void UnsafeConstructorSignatures() { var template = @" {0} class C {{ {1} C(long* p, byte* q) {{ throw null; }} }} "; CompareUnsafeDiagnostics(template, // (4,8): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"), // (4,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*")); } [Fact] public void UnsafeOperatorSignatures() { var template = @" {0} class C {{ public static {1} C operator +(C c, int* p) {{ throw null; }} }} "; CompareUnsafeDiagnostics(template, // (4,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")); } [Fact] public void UnsafeConversionSignatures() { var template = @" {0} class C {{ public static {1} explicit operator C(int* p) {{ throw null; }} public static {1} explicit operator byte*(C c) {{ throw null; }} public static {1} implicit operator C(short* p) {{ throw null; }} public static {1} implicit operator long*(C c) {{ throw null; }} }} "; CompareUnsafeDiagnostics(template, // (4,40): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (5,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"), // (6,40): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "short*"), // (7,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*")); } [Fact] public void UnsafePropertySignatures() { var template = @" {0} interface I {{ {1} int* P {{ get; set; }} }} {0} class C {{ {1} int* P {{ get; set; }} }} "; CompareUnsafeDiagnostics(template, // (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")); } [Fact] public void UnsafeIndexerSignatures() { var template = @" {0} interface I {{ {1} int* this[long* p, byte* q] {{ get; set; }} }} {0} class C {{ {1} int* this[long* p, byte* q] {{ get {{ throw null; }} set {{ throw null; }} }} }} "; CompareUnsafeDiagnostics(template, // (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (4,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"), // (4,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*"), // (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "long*"), // (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "byte*")); } [Fact] public void UnsafeEventSignatures() { var template = @" {0} interface I {{ {1} event int* E; }} {0} class C {{ {1} event int* E1; {1} event int* E2 {{ add {{ }} remove {{ }} }} }} "; DiagnosticDescription[] expected = { // (4,17): error CS0066: 'I.E': event must be of a delegate type Diagnostic(ErrorCode.ERR_EventNotDelegate, "E").WithArguments("I.E"), // (9,17): error CS0066: 'C.E1': event must be of a delegate type Diagnostic(ErrorCode.ERR_EventNotDelegate, "E1").WithArguments("C.E1"), // (10,17): error CS0066: 'C.E2': event must be of a delegate type Diagnostic(ErrorCode.ERR_EventNotDelegate, "E2").WithArguments("C.E2"), // (9,17): warning CS0067: The event 'C.E1' is never used Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("C.E1") }; CompareUnsafeDiagnostics(template, expected, expected); } [Fact] public void UnsafeTypeArguments() { var template = @" {0} interface I<T> {{ {1} void Test(I<int*> i); }} {0} class C<T> {{ {1} void Test(C<int*> c) {{ }} }} "; DiagnosticDescription[] expected = { // (4,24): error CS0306: The type 'int*' may not be used as a type argument Diagnostic(ErrorCode.ERR_BadTypeArgument, "i").WithArguments("int*"), // (9,24): error CS0306: The type 'int*' may not be used as a type argument Diagnostic(ErrorCode.ERR_BadTypeArgument, "c").WithArguments("int*") }; CompareUnsafeDiagnostics(template, expected, expected); } [Fact] public void UnsafeExpressions1() { var template = @" {0} class C {{ void Test() {{ {1} {{ Unsafe(); //CS0214 }} {1} {{ var x = Unsafe(); //CS0214 }} {1} {{ var x = Unsafe(); //CS0214 var y = Unsafe(); //CS0214 suppressed }} {1} {{ Unsafe(null); //CS0214 }} }} {1} int* Unsafe() {{ return null; }} //CS0214 {1} void Unsafe(int* p) {{ }} //CS0214 }} "; CompareUnsafeDiagnostics(template, // (28,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int* Unsafe() { return null; } //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (29,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // void Unsafe(int* p) { } //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (8,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Unsafe(); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (13,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x = Unsafe(); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (18,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x = Unsafe(); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (19,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var y = Unsafe(); //CS0214 suppressed Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (24,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Unsafe(null); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (24,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Unsafe(null); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe(null)") ); } [Fact] public void UnsafeExpressions2() { var template = @" {0} class C {{ {1} int* Field = Unsafe(); //CS0214 * 2 {1} C() {{ Unsafe(); //CS0214 }} {1} ~C() {{ Unsafe(); //CS0214 }} {1} void Test() {{ Unsafe(); //CS0214 }} {1} event System.Action E {{ add {{ Unsafe(); }} //CS0214 remove {{ Unsafe(); }} //CS0214 }} {1} int P {{ set {{ Unsafe(); }} //CS0214 }} {1} int this[int x] {{ set {{ Unsafe(); }} //CS0214 }} {1} public static implicit operator int(C c) {{ Unsafe(); //CS0214 return 0; }} {1} public static C operator +(C c) {{ Unsafe(); //CS0214 return c; }} {1} static int* Unsafe() {{ return null; }} //CS0214 }} "; CompareUnsafeDiagnostics(template, // (4,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int* Field = Unsafe(); //CS0214 * 2 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (4,19): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int* Field = Unsafe(); //CS0214 * 2 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (8,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Unsafe(); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (13,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Unsafe(); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (18,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Unsafe(); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (23,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // add { Unsafe(); } //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (24,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // remove { Unsafe(); } //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (29,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // set { Unsafe(); } //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (34,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // set { Unsafe(); } //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (39,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Unsafe(); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (45,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Unsafe(); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (49,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static int* Unsafe() { return null; } //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")); } [Fact] public void UnsafeExpressions3() { var template = @" {0} class C {{ {1} void Test(int* p = Unsafe()) //CS0214 * 2 {{ System.Action a1 = () => Unsafe(); //CS0214 System.Action a2 = () => {{ Unsafe(); //CS0214 }}; }} {1} static int* Unsafe() {{ return null; }} //CS0214 }} "; DiagnosticDescription[] expectedWithoutUnsafe = { // (4,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // void Test(int* p = Unsafe()) //CS0214 * 2 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (4,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // void Test(int* p = Unsafe()) //CS0214 * 2 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (4,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test(int* p = Unsafe()) //CS0214 * 2 Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Unsafe()").WithArguments("p"), // (6,34): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // System.Action a1 = () => Unsafe(); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (10,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Unsafe(); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Unsafe()"), // (14,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static int* Unsafe() { return null; } //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*") }; DiagnosticDescription[] expectedWithUnsafe = { // (4,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test(int* p = Unsafe()) //CS0214 * 2 Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Unsafe()").WithArguments("p") }; CompareUnsafeDiagnostics(template, expectedWithoutUnsafe, expectedWithUnsafe); } [Fact] public void UnsafeIteratorSignatures() { var template = @" {0} class C {{ {1} System.Collections.Generic.IEnumerable<int> Iterator(int* p) {{ yield return 1; }} }} "; var withoutUnsafe = string.Format(template, "", ""); CreateCompilation(withoutUnsafe, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // CONSIDER: We should probably suppress CS0214 (like Dev10 does) because it's // confusing, but we don't have a good way to do so, because we don't know that // the method is an iterator until we bind the body and we certainly don't want // to do that just to figure out the types of the parameters. // (4,59): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p")); var withUnsafeOnType = string.Format(template, "unsafe", ""); CreateCompilation(withUnsafeOnType, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p")); var withUnsafeOnMembers = string.Format(template, "", "unsafe"); CreateCompilation(withUnsafeOnMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p"), // (4,56): error CS1629: Unsafe code may not appear in iterators Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Iterator")); //this is for putting "unsafe" on an iterator, not for the parameter type var withUnsafeOnTypeAndMembers = string.Format(template, "unsafe", "unsafe"); CreateCompilation(withUnsafeOnTypeAndMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,64): error CS1637: Iterators cannot have unsafe parameters or yield types Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "p"), // (4,56): error CS1629: Unsafe code may not appear in iterators Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Iterator")); //this is for putting "unsafe" on an iterator, not for the parameter type } [Fact] public void UnsafeInAttribute1() { var text = @" unsafe class Attr : System.Attribute { [Attr(null)] // Dev10: doesn't matter that the type and member are both 'unsafe' public unsafe Attr(int* i) { } } "; // CONSIDER: Dev10 reports CS0214 (unsafe) and CS0182 (not a constant), but this makes // just as much sense. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,6): error CS0181: Attribute constructor parameter 'i' has type 'int*', which is not a valid attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("i", "int*")); } [Fact] public void UnsafeInAttribute2() { var text = @" unsafe class Attr : System.Attribute { [Attr(Unsafe() == null)] // Not a constant public unsafe Attr(bool b) { } static int* Unsafe() { return null; } } "; // CONSIDER: Dev10 reports both CS0214 (unsafe) and CS0182 (not a constant), but this makes // just as much sense. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type Diagnostic(ErrorCode.ERR_BadAttributeArgument, "Unsafe() == null")); } [Fact] public void TypeofNeverUnsafe() { var text = @" class C<T> { void Test() { System.Type t; t = typeof(int*); t = typeof(int**); t = typeof(int*[]); t = typeof(int*[][]); t = typeof(C<int*>); // CS0306 t = typeof(C<int**>); // CS0306 t = typeof(C<int*[]>); t = typeof(C<int*[][]>); } } "; CreateCompilation(text).VerifyDiagnostics( // (13,22): error CS0306: The type 'int*' may not be used as a type argument Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*"), // (14,22): error CS0306: The type 'int**' may not be used as a type argument Diagnostic(ErrorCode.ERR_BadTypeArgument, "int**").WithArguments("int**")); } [Fact] public void UnsafeOnEnum() { var text = @" unsafe enum E { A } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (2,13): error CS0106: The modifier 'unsafe' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "E").WithArguments("unsafe")); } [WorkItem(543834, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543834")] [Fact] public void UnsafeOnDelegates() { var text = @" public unsafe delegate void TestDelegate(); "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll.WithAllowUnsafe(false)).VerifyDiagnostics( // (2,29): error CS0227: Unsafe code may only appear if compiling with /unsafe Diagnostic(ErrorCode.ERR_IllegalUnsafe, "TestDelegate")); CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [WorkItem(543835, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543835")] [Fact] public void UnsafeOnConstField() { var text = @" public class Main { unsafe public const int number = 0; } "; CreateCompilation(text).VerifyDiagnostics( // (4,29): error CS0106: The modifier 'unsafe' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "number").WithArguments("unsafe")); CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,29): error CS0106: The modifier 'unsafe' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "number").WithArguments("unsafe")); } [Fact] public void UnsafeOnExplicitInterfaceImplementation() { var text = @" interface I { int P { get; set; } void M(); event System.Action E; } class C : I { unsafe int I.P { get; set; } unsafe void I.M() { } unsafe event System.Action I.E { add { } remove { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [WorkItem(544417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544417")] [Fact] public void UnsafeCallParamArrays() { var template = @" {0} class C {{ {1} static void Main() {{ {{ Goo(); }} {{ Goo(null); }} {{ Goo((int*)1); }} {{ Goo(new int*[2]); }} }} {1} static void Goo(params int*[] x) {{ }} }} "; CompareUnsafeDiagnostics(template, // (12,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static void Goo(params int*[] x) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (6,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo(); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo()"), // (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(null)"), // (8,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"), // (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo((int*)1)"), // (9,19): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo(new int*[2]); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo(new int*[2]); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]"), // (9,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo(new int*[2]); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(new int*[2])") ); } [WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")] [Fact] public void UnsafeCallOptionalParameters() { var template = @" {0} class C {{ {1} static void Main() {{ {{ Goo(); }} {{ Goo(null); }} {{ Goo((int*)1); }} }} {1} static void Goo(int* p = null) {{ }} }} "; CompareUnsafeDiagnostics(template, // (11,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static void Goo(int* p = null) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (6,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo(); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo()"), // (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(null)"), // (8,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"), // (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { Goo((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo((int*)1)") ); } [WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")] [Fact] public void UnsafeDelegateCallParamArrays() { var template = @" {0} class C {{ {1} static void Main() {{ D d = null; {{ d(); }} {{ d(null); }} {{ d((int*)1); }} {{ d(new int*[2]); }} }} {1} delegate void D(params int*[] x); }} "; CompareUnsafeDiagnostics(template, // (13,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // delegate void D(params int*[] x); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d(); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d()"), // (8,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d(null)"), // (9,14): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"), // (9,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d((int*)1)"), // (10,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d(new int*[2]); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (10,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d(new int*[2]); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]"), // (10,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d(new int*[2]); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d(new int*[2])") ); } [WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")] [Fact] public void UnsafeDelegateCallOptionalParameters() { var template = @" {0} class C {{ {1} static void Main() {{ D d = null; {{ d(); }} {{ d(null); }} {{ d((int*)1); }} }} {1} delegate void D(int* p = null); }} "; CompareUnsafeDiagnostics(template, // (12,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // delegate void D(int* p = null); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (7,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d(); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d()"), // (8,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (8,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d(null)"), // (9,14): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"), // (9,11): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "d((int*)1)") ); } [WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")] [Fact] public void UnsafeObjectCreationParamArrays() { var template = @" {0} class C {{ {1} static void Main() {{ C c; {{ c = new C(); }} {{ c = new C(null); }} {{ c = new C((int*)1); }} {{ c = new C(new int*[2]); }} }} {1} C(params int*[] x) {{ }} }} "; CompareUnsafeDiagnostics(template, // (13,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // C(params int*[] x) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C(); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C()"), // (8,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C(null)"), // (9,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"), // (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C((int*)1)"), // (10,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C(new int*[2]); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (10,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C(new int*[2]); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]"), // (10,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C(new int*[2]); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C(new int*[2])") ); } [WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")] [Fact] public void UnsafeObjectCreationOptionalParameters() { var template = @" {0} class C {{ {1} static void Main() {{ C c; {{ c = new C(); }} {{ c = new C(null); }} {{ c = new C((int*)1); }} }} {1} C(int* p = null) {{ }} }} "; CompareUnsafeDiagnostics(template, // (12,8): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // C(int* p = null) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (7,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C(); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C()"), // (8,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C(null); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C(null)"), // (9,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"), // (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { c = new C((int*)1); } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new C((int*)1)") ); } [WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")] [Fact] public void UnsafeIndexerParamArrays() { var template = @" {0} class C {{ {1} static void Main() {{ C c = new C(); {{ int x = c[1]; }} // NOTE: as in dev10, this does not produce an error (would for a call). {{ int x = c[1, null]; }} // NOTE: as in dev10, this does not produce an error (would for a call). {{ int x = c[1, (int*)1]; }} {{ int x = c[1, new int*[2]]; }} }} {1} int this[int x, params int*[] a] {{ get {{ return 0; }} set {{ }} }} }} "; CompareUnsafeDiagnostics(template, // (13,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int this[int x, params int*[] a] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { int x = c[1, (int*)1]; } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,24): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { int x = c[1, (int*)1]; } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1"), // (10,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { int x = c[1, new int*[2]]; } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (10,24): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { int x = c[1, new int*[2]]; } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "new int*[2]") ); } [WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")] [Fact] public void UnsafeIndexerOptionalParameters() { var template = @" {0} class C {{ {1} static void Main() {{ C c = new C(); {{ int x = c[1]; }} // NOTE: as in dev10, this does not produce an error (would for a call). {{ int x = c[1, null]; }} // NOTE: as in dev10, this does not produce an error (would for a call). {{ int x = c[1, (int*)1]; }} }} {1} int this[int x, int* p = null] {{ get {{ return 0; }} set {{ }} }} }} "; CompareUnsafeDiagnostics(template, // (12,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int this[int x, int* p = null] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { int x = c[1, (int*)1]; } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,24): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { int x = c[1, (int*)1]; } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(int*)1") ); } [WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")] [Fact] public void UnsafeAttributeParamArrays() { var template = @" [A] {0} class A : System.Attribute {{ {1} A(params int*[] a) {{ }} }} "; CompareUnsafeDiagnostics(template, new[] { // CONSIDER: this differs slightly from dev10, but is clearer. // (2,2): error CS0181: Attribute constructor parameter 'a' has type 'int*[]', which is not a valid attribute parameter type // [A] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("a", "int*[]"), // (5,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // A(params int*[] a) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*") }, new[] { // CONSIDER: this differs slightly from dev10, but is clearer. // (2,2): error CS0181: Attribute constructor parameter 'a' has type 'int*[]', which is not a valid attribute parameter type // [A] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("a", "int*[]") }); } [WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")] [Fact] public void UnsafeAttributeOptionalParameters() { var template = @" [A] {0} class A : System.Attribute {{ {1} A(int* p = null) {{ }} }} "; CompareUnsafeDiagnostics(template, new[] { // CONSIDER: this differs slightly from dev10, but is clearer. // (2,2): error CS0181: Attribute constructor parameter 'p' has type 'int*', which is not a valid attribute parameter type // [A] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("p", "int*"), // (5,8): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // A(int* p = null) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*") }, new[] { // CONSIDER: this differs slightly from dev10, but is clearer. // (2,2): error CS0181: Attribute constructor parameter 'p' has type 'int*', which is not a valid attribute parameter type // [A] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("p", "int*") }); } [WorkItem(544938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544938")] [Fact] public void UnsafeDelegateAssignment() { var template = @" {0} class C {{ {1} static void Main() {{ D d; {{ d = delegate {{ }}; }} {{ d = null; }} {{ d = Goo; }} }} {1} delegate void D(int* x = null); {1} static void Goo(int* x = null) {{ }} }} "; CompareUnsafeDiagnostics(template, // (9,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // { d = Goo; } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo"), // (12,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // delegate void D(int* x = null); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (13,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static void Goo(int* x = null) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")); } private static void CompareUnsafeDiagnostics(string template, params DiagnosticDescription[] expectedWithoutUnsafe) { CompareUnsafeDiagnostics(template, expectedWithoutUnsafe, new DiagnosticDescription[0]); } private static void CompareUnsafeDiagnostics(string template, DiagnosticDescription[] expectedWithoutUnsafe, DiagnosticDescription[] expectedWithUnsafe) { // NOTE: ERR_UnsafeNeeded is not affected by the presence/absence of the /unsafe flag. var withoutUnsafe = string.Format(template, "", ""); CreateCompilation(withoutUnsafe).VerifyDiagnostics(expectedWithoutUnsafe); CreateCompilation(withoutUnsafe, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithoutUnsafe); var withUnsafeOnType = string.Format(template, "unsafe", ""); CreateCompilation(withUnsafeOnType, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithUnsafe); var withUnsafeOnMembers = string.Format(template, "", "unsafe"); CreateCompilation(withUnsafeOnMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithUnsafe); var withUnsafeOnTypeAndMembers = string.Format(template, "unsafe", "unsafe"); CreateCompilation(withUnsafeOnTypeAndMembers, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expectedWithUnsafe); } [WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")] [Fact] public void MethodCallWithNullAsPointerArg() { var template = @" {0} class Test {{ {1} static void Goo(void* p) {{ }} {1} static void Main() {{ Goo(null); }} }} "; CompareUnsafeDiagnostics(template, // (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // static void Goo(void* p) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*"), // (7,13): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Goo(null); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (7,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // Goo(null); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "Goo(null)") ); } [WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")] [Fact] public void MethodCallWithUnsafeArgument() { var template = @" {0} class Test {{ {1} int M(params int*[] p) {{ return 0; }} {1} public static implicit operator int*(Test t) {{ return null; }} {1} void M() {{ {{ int x = M(null); //CS0214 }} {{ int x = M(null, null); //CS0214 }} {{ int x = M(this); //CS0214 }} }} }} "; CompareUnsafeDiagnostics(template, // (5,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public static implicit operator int*(Test t) { return null; } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (4,19): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int M(params int*[] p) { return 0; } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (10,23): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int x = M(null); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (10,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int x = M(null); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "M(null)"), // (13,23): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int x = M(null, null); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (13,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int x = M(null, null); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (13,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int x = M(null, null); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "M(null, null)"), // (16,23): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int x = M(this); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "this"), // (16,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int x = M(this); //CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "M(this)") ); } [WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")] [Fact] public void IndexerAccessWithUnsafeArgument() { var template = @" {0} class Test {{ {1} int this[params int*[] p] {{ get {{ return 0; }} set {{ }} }} {1} public static implicit operator int*(Test t) {{ return null; }} {1} void M() {{ {{ int x = this[null]; //CS0214 seems appropriate, but dev10 accepts }} {{ int x = this[null, null]; //CS0214 seems appropriate, but dev10 accepts }} {{ int x = this[this]; //CS0214 seems appropriate, but dev10 accepts }} }} }} "; CompareUnsafeDiagnostics(template, // (4,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int this[int* p] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (5,38): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public static implicit operator int*(Test t) { return null; } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*")); } [WorkItem(544097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544097")] [Fact] public void ConstructorInitializerWithUnsafeArgument() { var template = @" {0} class Base {{ {1} public Base(int* p) {{ }} }} {0} class Derived : Base {{ {1} public Derived() : base(null) {{ }} }} "; CompareUnsafeDiagnostics(template, // (4,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public Base(int* p) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,30): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public Derived() : base(null) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "null"), // (9,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public Derived() : base(null) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "base") ); } [WorkItem(544286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544286")] [Fact] public void UnsafeLambdaParameterType() { var template = @" {0} class Program {{ {1} delegate void F(int* x); {1} static void Main() {{ F e = x => {{ }}; }} }} "; CompareUnsafeDiagnostics(template, // (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // delegate void F(int* x); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (8,15): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // F e = x => { }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "x")); } #endregion Unsafe regions #region Non-moveable variables [Fact] public void NonMoveableVariables_Parameters() { var text = @" class C { void M(int x, ref int y, out int z, params int[] p) { M(x, ref y, out z, p); } } "; var expected = @" No, Call 'M(x, ref y, out z, p)' is not a non-moveable variable No, ThisReference 'M' is not a non-moveable variable Yes, Parameter 'x' is a non-moveable variable with underlying symbol 'x' No, Parameter 'y' is not a non-moveable variable No, Parameter 'z' is not a non-moveable variable Yes, Parameter 'p' is a non-moveable variable with underlying symbol 'p' ".Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_Locals() { var text = @" class C { void M(params object[] p) { C c = null; int x = 0; M(c, x); } } "; var expected = @" No, TypeExpression 'C' is not a non-moveable variable No, Conversion 'null' is not a non-moveable variable No, Literal 'null' is not a non-moveable variable No, TypeExpression 'int' is not a non-moveable variable No, Literal '0' is not a non-moveable variable No, Call 'M(c, x)' is not a non-moveable variable No, ThisReference 'M' is not a non-moveable variable No, Conversion 'c' is not a non-moveable variable Yes, Local 'c' is a non-moveable variable with underlying symbol 'c' No, Conversion 'x' is not a non-moveable variable Yes, Local 'x' is a non-moveable variable with underlying symbol 'x' ".Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_Fields1() { var text = @" class C { public S1 s; public C c; void M(params object[] p) { C c = new C(); S1 s = new S1(); M(this, this.s, this.s.s, this.s.c, this.c.s, this.c.c); M(c, c.s, c.s.s, c.s.c, c.c.s, c.c.c); M(s, s.s, s.s.i); } } struct S1 { public S2 s; public C c; } struct S2 { public int i; } "; var expected = @" No, TypeExpression 'C' is not a non-moveable variable No, ObjectCreationExpression 'new C()' is not a non-moveable variable No, TypeExpression 'S1' is not a non-moveable variable No, ObjectCreationExpression 'new S1()' is not a non-moveable variable No, Call 'M(this, this.s, this.s.s, this.s.c, this.c.s, this.c.c)' is not a non-moveable variable No, ThisReference 'M' is not a non-moveable variable No, Conversion 'this' is not a non-moveable variable No, ThisReference 'this' is not a non-moveable variable No, Conversion 'this.s' is not a non-moveable variable No, FieldAccess 'this.s' is not a non-moveable variable No, ThisReference 'this' is not a non-moveable variable No, Conversion 'this.s.s' is not a non-moveable variable No, FieldAccess 'this.s.s' is not a non-moveable variable No, FieldAccess 'this.s' is not a non-moveable variable No, ThisReference 'this' is not a non-moveable variable No, Conversion 'this.s.c' is not a non-moveable variable No, FieldAccess 'this.s.c' is not a non-moveable variable No, FieldAccess 'this.s' is not a non-moveable variable No, ThisReference 'this' is not a non-moveable variable No, Conversion 'this.c.s' is not a non-moveable variable No, FieldAccess 'this.c.s' is not a non-moveable variable No, FieldAccess 'this.c' is not a non-moveable variable No, ThisReference 'this' is not a non-moveable variable No, Conversion 'this.c.c' is not a non-moveable variable No, FieldAccess 'this.c.c' is not a non-moveable variable No, FieldAccess 'this.c' is not a non-moveable variable No, ThisReference 'this' is not a non-moveable variable No, Call 'M(c, c.s, c.s.s, c.s.c, c.c.s, c.c.c)' is not a non-moveable variable No, ThisReference 'M' is not a non-moveable variable No, Conversion 'c' is not a non-moveable variable Yes, Local 'c' is a non-moveable variable with underlying symbol 'c' No, Conversion 'c.s' is not a non-moveable variable No, FieldAccess 'c.s' is not a non-moveable variable Yes, Local 'c' is a non-moveable variable with underlying symbol 'c' No, Conversion 'c.s.s' is not a non-moveable variable No, FieldAccess 'c.s.s' is not a non-moveable variable No, FieldAccess 'c.s' is not a non-moveable variable Yes, Local 'c' is a non-moveable variable with underlying symbol 'c' No, Conversion 'c.s.c' is not a non-moveable variable No, FieldAccess 'c.s.c' is not a non-moveable variable No, FieldAccess 'c.s' is not a non-moveable variable Yes, Local 'c' is a non-moveable variable with underlying symbol 'c' No, Conversion 'c.c.s' is not a non-moveable variable No, FieldAccess 'c.c.s' is not a non-moveable variable No, FieldAccess 'c.c' is not a non-moveable variable Yes, Local 'c' is a non-moveable variable with underlying symbol 'c' No, Conversion 'c.c.c' is not a non-moveable variable No, FieldAccess 'c.c.c' is not a non-moveable variable No, FieldAccess 'c.c' is not a non-moveable variable Yes, Local 'c' is a non-moveable variable with underlying symbol 'c' No, Call 'M(s, s.s, s.s.i)' is not a non-moveable variable No, ThisReference 'M' is not a non-moveable variable No, Conversion 's' is not a non-moveable variable Yes, Local 's' is a non-moveable variable with underlying symbol 's' No, Conversion 's.s' is not a non-moveable variable Yes, FieldAccess 's.s' is a non-moveable variable with underlying symbol 's' Yes, Local 's' is a non-moveable variable with underlying symbol 's' No, Conversion 's.s.i' is not a non-moveable variable Yes, FieldAccess 's.s.i' is a non-moveable variable with underlying symbol 's' Yes, FieldAccess 's.s' is a non-moveable variable with underlying symbol 's' Yes, Local 's' is a non-moveable variable with underlying symbol 's' ".Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_Fields2() { var text = @" class Base { public int i; } class Derived : Base { void M() { base.i = 0; } } "; var expected = @" No, AssignmentOperator 'base.i = 0' is not a non-moveable variable No, FieldAccess 'base.i' is not a non-moveable variable No, BaseReference 'base' is not a non-moveable variable No, Literal '0' is not a non-moveable variable ".Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_Fields3() { var text = @" struct S { static int i; void M() { S.i = 0; } } "; var expected = @" No, AssignmentOperator 'S.i = 0' is not a non-moveable variable No, FieldAccess 'S.i' is not a non-moveable variable No, TypeExpression 'S' is not a non-moveable variable No, Literal '0' is not a non-moveable variable ".Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_Fields4() { var text = @" struct S { int i; void M(params object[] p) { // rvalues are never non-moveable. M(new S().i, default(S).i, MakeS().i, (new S[1])[0].i); } S MakeS() { return default(S); } } "; var expected = @" No, Call 'M(new S().i, default(S).i, MakeS().i, (new S[1])[0].i)' is not a non-moveable variable No, ThisReference 'M' is not a non-moveable variable No, Conversion 'new S().i' is not a non-moveable variable No, FieldAccess 'new S().i' is not a non-moveable variable No, ObjectCreationExpression 'new S()' is not a non-moveable variable No, Conversion 'default(S).i' is not a non-moveable variable No, FieldAccess 'default(S).i' is not a non-moveable variable No, DefaultExpression 'default(S)' is not a non-moveable variable No, Conversion 'MakeS().i' is not a non-moveable variable No, FieldAccess 'MakeS().i' is not a non-moveable variable No, Call 'MakeS()' is not a non-moveable variable No, ThisReference 'MakeS' is not a non-moveable variable No, Conversion '(new S[1])[0].i' is not a non-moveable variable No, FieldAccess '(new S[1])[0].i' is not a non-moveable variable No, ArrayAccess '(new S[1])[0]' is not a non-moveable variable No, ArrayCreation 'new S[1]' is not a non-moveable variable No, Literal '1' is not a non-moveable variable No, Literal '0' is not a non-moveable variable ".Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_Events() { var text = @" struct S { public event System.Action E; public event System.Action F { add { } remove { } } void M(params object[] p) { C c = new C(); S s = new S(); M(c.E, c.F); //note: note legal to pass F M(s.E, s.F); //note: note legal to pass F } } class C { public event System.Action E; public event System.Action F { add { } remove { } } } "; var expected = @" No, TypeExpression 'C' is not a non-moveable variable No, ObjectCreationExpression 'new C()' is not a non-moveable variable No, TypeExpression 'S' is not a non-moveable variable No, ObjectCreationExpression 'new S()' is not a non-moveable variable No, Call 'M(c.E, c.F)' is not a non-moveable variable No, ThisReference 'M' is not a non-moveable variable No, Conversion 'c.E' is not a non-moveable variable No, BadExpression 'c.E' is not a non-moveable variable No, EventAccess 'c.E' is not a non-moveable variable Yes, Local 'c' is a non-moveable variable with underlying symbol 'c' No, Conversion 'c.F' is not a non-moveable variable No, BadExpression 'c.F' is not a non-moveable variable No, EventAccess 'c.F' is not a non-moveable variable Yes, Local 'c' is a non-moveable variable with underlying symbol 'c' No, Call 'M(s.E, s.F)' is not a non-moveable variable No, ThisReference 'M' is not a non-moveable variable No, Conversion 's.E' is not a non-moveable variable Yes, EventAccess 's.E' is a non-moveable variable with underlying symbol 's' Yes, Local 's' is a non-moveable variable with underlying symbol 's' No, Conversion 's.F' is not a non-moveable variable No, BadExpression 's.F' is not a non-moveable variable No, EventAccess 's.F' is not a non-moveable variable Yes, Local 's' is a non-moveable variable with underlying symbol 's' ".Trim(); CheckNonMoveableVariables(text, expected, expectError: true); } [Fact] public void NonMoveableVariables_Lambda1() { var text = @" class C { void M(params object[] p) { int i = 0; // NOTE: considered non-moveable even though it will be hoisted - lambdas handled separately. i++; System.Action a = () => { int j = i; j++; }; } } "; var expected = string.Format(@" No, TypeExpression 'int' is not a non-moveable variable No, Literal '0' is not a non-moveable variable No, IncrementOperator 'i++' is not a non-moveable variable Yes, Local 'i' is a non-moveable variable with underlying symbol 'i' No, TypeExpression 'System.Action' is not a non-moveable variable No, Conversion '() =>{0} {{{0} int j = i;{0} j++;{0} }}' is not a non-moveable variable No, Lambda '() =>{0} {{{0} int j = i;{0} j++;{0} }}' is not a non-moveable variable No, TypeExpression 'int' is not a non-moveable variable Yes, Local 'i' is a non-moveable variable with underlying symbol 'i' No, IncrementOperator 'j++' is not a non-moveable variable Yes, Local 'j' is a non-moveable variable with underlying symbol 'j' ", GetEscapedNewLine()).Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_Lambda2() { var text = @" class C { void M() { int i = 0; // NOTE: considered non-moveable even though it will be hoisted - lambdas handled separately. i++; System.Func<int, System.Func<int, int>> a = p => q => p + q + i; } } "; var expected = @" No, TypeExpression 'int' is not a non-moveable variable No, Literal '0' is not a non-moveable variable No, IncrementOperator 'i++' is not a non-moveable variable Yes, Local 'i' is a non-moveable variable with underlying symbol 'i' No, TypeExpression 'System.Func<int, System.Func<int, int>>' is not a non-moveable variable No, Conversion 'p => q => p + q + i' is not a non-moveable variable No, Lambda 'p => q => p + q + i' is not a non-moveable variable No, Conversion 'q => p + q + i' is not a non-moveable variable No, Lambda 'q => p + q + i' is not a non-moveable variable No, BinaryOperator 'p + q + i' is not a non-moveable variable No, BinaryOperator 'p + q' is not a non-moveable variable Yes, Parameter 'p' is a non-moveable variable with underlying symbol 'p' Yes, Parameter 'q' is a non-moveable variable with underlying symbol 'q' Yes, Local 'i' is a non-moveable variable with underlying symbol 'i' ".Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_Dereference() { var text = @" struct S { int i; unsafe void Test(S* p) { S s; s = *p; s = p[0]; int j; j = (*p).i; j = p[0].i; j = p->i; } } "; var expected = @" No, TypeExpression 'S' is not a non-moveable variable No, AssignmentOperator 's = *p' is not a non-moveable variable Yes, Local 's' is a non-moveable variable with underlying symbol 's' Yes, PointerIndirectionOperator '*p' is a non-moveable variable Yes, Parameter 'p' is a non-moveable variable with underlying symbol 'p' No, AssignmentOperator 's = p[0]' is not a non-moveable variable Yes, Local 's' is a non-moveable variable with underlying symbol 's' Yes, PointerElementAccess 'p[0]' is a non-moveable variable Yes, Parameter 'p' is a non-moveable variable with underlying symbol 'p' No, Literal '0' is not a non-moveable variable No, TypeExpression 'int' is not a non-moveable variable No, AssignmentOperator 'j = (*p).i' is not a non-moveable variable Yes, Local 'j' is a non-moveable variable with underlying symbol 'j' Yes, FieldAccess '(*p).i' is a non-moveable variable Yes, PointerIndirectionOperator '*p' is a non-moveable variable Yes, Parameter 'p' is a non-moveable variable with underlying symbol 'p' No, AssignmentOperator 'j = p[0].i' is not a non-moveable variable Yes, Local 'j' is a non-moveable variable with underlying symbol 'j' Yes, FieldAccess 'p[0].i' is a non-moveable variable Yes, PointerElementAccess 'p[0]' is a non-moveable variable Yes, Parameter 'p' is a non-moveable variable with underlying symbol 'p' No, Literal '0' is not a non-moveable variable No, AssignmentOperator 'j = p->i' is not a non-moveable variable Yes, Local 'j' is a non-moveable variable with underlying symbol 'j' Yes, FieldAccess 'p->i' is a non-moveable variable Yes, PointerIndirectionOperator 'p' is a non-moveable variable Yes, Parameter 'p' is a non-moveable variable with underlying symbol 'p' ".Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_StackAlloc() { var text = @" struct S { unsafe void Test() { int* p = stackalloc int[1]; } } "; var expected = @" No, TypeExpression 'int*' is not a non-moveable variable Yes, ConvertedStackAllocExpression 'stackalloc int[1]' is a non-moveable variable No, Literal '1' is not a non-moveable variable ".Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_TypeParameters1() { var text = @" class C { public C c; void M<T>(T t, C c) where T : C { M(t, t.c); } } "; var expected = @" No, Call 'M(t, t.c)' is not a non-moveable variable No, ThisReference 'M' is not a non-moveable variable Yes, Parameter 't' is a non-moveable variable with underlying symbol 't' No, FieldAccess 't.c' is not a non-moveable variable Yes, Parameter 't' is a non-moveable variable with underlying symbol 't' ".Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_TypeParameters2() { var text = @" class D : C<S> { public override void M<U>(U u, int j) { M(u, u.i); // effective base type (System.ValueType) does not have a member 'i' } } abstract class C<T> { public abstract void M<U>(U u, int i) where U : T; } struct S { public int i; } "; var expected = @" No, Call 'M(u, u.i)' is not a non-moveable variable No, ThisReference 'M' is not a non-moveable variable Yes, Parameter 'u' is a non-moveable variable with underlying symbol 'u' No, BadExpression 'u.i' is not a non-moveable variable Yes, Parameter 'u' is a non-moveable variable with underlying symbol 'u' ".Trim(); CheckNonMoveableVariables(text, expected, expectError: true); } [Fact] public void NonMoveableVariables_RangeVariables1() { var text = @" using System.Linq; class C { void M(int[] array) { var result = from i in array from j in array select i + j; } } "; var expected = string.Format(@" No, TypeExpression 'var' is not a non-moveable variable No, QueryClause 'from i in array {0} from j in array {0} select i + j' is not a non-moveable variable No, QueryClause 'select i + j' is not a non-moveable variable No, QueryClause 'from j in array' is not a non-moveable variable No, Call 'from j in array' is not a non-moveable variable No, Conversion 'from i in array' is not a non-moveable variable No, QueryClause 'from i in array' is not a non-moveable variable Yes, Parameter 'array' is a non-moveable variable with underlying symbol 'array' No, QueryClause 'from j in array' is not a non-moveable variable No, Conversion 'array' is not a non-moveable variable No, Lambda 'array' is not a non-moveable variable No, Conversion 'array' is not a non-moveable variable Yes, Parameter 'array' is a non-moveable variable with underlying symbol 'array' No, Conversion 'i + j' is not a non-moveable variable No, Lambda 'i + j' is not a non-moveable variable No, BinaryOperator 'i + j' is not a non-moveable variable Yes, RangeVariable 'i' is a non-moveable variable with underlying symbol 'i' Yes, Parameter 'i' is a non-moveable variable with underlying symbol 'i' Yes, RangeVariable 'j' is a non-moveable variable with underlying symbol 'j' Yes, Parameter 'j' is a non-moveable variable with underlying symbol 'j' ", GetEscapedNewLine()).Trim(); CheckNonMoveableVariables(text, expected); } [Fact] public void NonMoveableVariables_RangeVariables2() { var text = @" using System; class Test { void M(C c) { var result = from x in c where x > 0 //int where x.Length < 2 //string select char.IsLetter(x); //char } } class C { public D Where(Func<int, bool> predicate) { return new D(); } } class D { public char[] Where(Func<string, bool> predicate) { return new char[10]; } } static class Extensions { public static object Select(this char[] array, Func<char, bool> func) { return null; } } "; var expected = string.Format(@" No, TypeExpression 'var' is not a non-moveable variable No, QueryClause 'from x in c{0} where x > 0 //int{0} where x.Length < 2 //string{0} select char.IsLetter(x)' is not a non-moveable variable No, QueryClause 'select char.IsLetter(x)' is not a non-moveable variable No, Call 'select char.IsLetter(x)' is not a non-moveable variable No, QueryClause 'where x.Length < 2' is not a non-moveable variable No, Call 'where x.Length < 2' is not a non-moveable variable No, QueryClause 'where x > 0' is not a non-moveable variable No, Call 'where x > 0' is not a non-moveable variable No, QueryClause 'from x in c' is not a non-moveable variable Yes, Parameter 'c' is a non-moveable variable with underlying symbol 'c' No, Conversion 'x > 0' is not a non-moveable variable No, Lambda 'x > 0' is not a non-moveable variable No, BinaryOperator 'x > 0' is not a non-moveable variable Yes, RangeVariable 'x' is a non-moveable variable with underlying symbol 'x' Yes, Parameter 'x' is a non-moveable variable with underlying symbol 'x' No, Literal '0' is not a non-moveable variable No, Conversion 'x.Length < 2' is not a non-moveable variable No, Lambda 'x.Length < 2' is not a non-moveable variable No, BinaryOperator 'x.Length < 2' is not a non-moveable variable No, PropertyAccess 'x.Length' is not a non-moveable variable Yes, RangeVariable 'x' is a non-moveable variable with underlying symbol 'x' Yes, Parameter 'x' is a non-moveable variable with underlying symbol 'x' No, Literal '2' is not a non-moveable variable No, Conversion 'char.IsLetter(x)' is not a non-moveable variable No, Lambda 'char.IsLetter(x)' is not a non-moveable variable No, Call 'char.IsLetter(x)' is not a non-moveable variable No, TypeExpression 'char' is not a non-moveable variable Yes, RangeVariable 'x' is a non-moveable variable with underlying symbol 'x' Yes, Parameter 'x' is a non-moveable variable with underlying symbol 'x' ", GetEscapedNewLine()).Trim(); CheckNonMoveableVariables(text, expected); } private static void CheckNonMoveableVariables(string text, string expected, bool expectError = false) { var compilation = CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll); var compilationDiagnostics = compilation.GetDiagnostics(); if (expectError != compilationDiagnostics.Any(diag => diag.Severity == DiagnosticSeverity.Error)) { compilationDiagnostics.Verify(); Assert.True(false); } var tree = compilation.SyntaxTrees.Single(); var methodDecl = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(); var methodBody = methodDecl.Body; var model = compilation.GetSemanticModel(tree); var binder = ((CSharpSemanticModel)model).GetEnclosingBinder(methodBody.SpanStart); Assert.NotNull(binder); Assert.Equal(SymbolKind.Method, binder.ContainingMemberOrLambda.Kind); var unusedDiagnostics = DiagnosticBag.GetInstance(); var block = binder.BindEmbeddedBlock(methodBody, unusedDiagnostics); unusedDiagnostics.Free(); var builder = ArrayBuilder<string>.GetInstance(); NonMoveableVariableVisitor.Process(block, binder, builder); var actual = string.Join(Environment.NewLine, builder); Assert.Equal(expected, actual); builder.Free(); } private class NonMoveableVariableVisitor : BoundTreeWalkerWithStackGuard { private readonly Binder _binder; private readonly ArrayBuilder<string> _builder; private NonMoveableVariableVisitor(Binder binder, ArrayBuilder<string> builder) { _binder = binder; _builder = builder; } public static void Process(BoundBlock block, Binder binder, ArrayBuilder<string> builder) { var visitor = new NonMoveableVariableVisitor(binder, builder); visitor.Visit(block); } public override BoundNode Visit(BoundNode node) { var expr = node as BoundExpression; if (expr != null) { var text = node.Syntax.ToString(); if (!string.IsNullOrEmpty(text)) { text = Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(text, quote: false); Symbol accessedLocalOrParameterOpt; bool isNonMoveableVariable = _binder.IsNonMoveableVariable(expr, out accessedLocalOrParameterOpt); if (isNonMoveableVariable) { _builder.Add(string.Format("Yes, {0} '{1}' is a non-moveable variable{2}", expr.Kind, text, accessedLocalOrParameterOpt == null ? "" : string.Format(" with underlying symbol '{0}'", accessedLocalOrParameterOpt.Name))); } else { _builder.Add(string.Format("No, {0} '{1}' is not a non-moveable variable", expr.Kind, text)); } } } return base.Visit(node); } protected override bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return false; } } #endregion Non-moveable variables #region IsManagedType [Fact] public void IsManagedType_Array() { var text = @" class C { int[] f1; int[,] f2; int[][] f3; } "; var compilation = CreateCompilation(text); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedType)); } [Fact] public void IsManagedType_Pointer() { var text = @" unsafe class C { int* f1; int** f2; void* f3; } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => !field.Type.IsManagedType)); } [Fact] public void IsManagedType_Dynamic() { var text = @" class C { dynamic f1; } "; var compilation = CreateCompilation(text); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedType)); } [Fact] public void IsManagedType_Error() { var text = @" class C<T> { C f1; C<int, int> f2; Garbage f3; } "; var compilation = CreateCompilation(text); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedType)); } [Fact] public void IsManagedType_TypeParameter() { var text = @" class C<T, U> where U : struct { T f1; U f2; } "; var compilation = CreateCompilation(text); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedType)); } [Fact] public void IsManagedType_AnonymousType() { var text = @" class C { void M() { var local1 = new { }; var local2 = new { F = 1 }; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.True(tree.GetCompilationUnitRoot().DescendantNodes().OfType<AnonymousObjectCreationExpressionSyntax>(). Select(syntax => model.GetTypeInfo(syntax).Type).All(type => ((TypeSymbol)type).IsManagedType)); } [Fact] public void IsManagedType_Class() { var text = @" class Outer { Outer f1; Outer.Inner f2; string f3; class Inner { } } "; var compilation = CreateCompilation(text); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Outer"); Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedType)); } [Fact] public void IsManagedType_GenericClass() { var text = @" class Outer<T> { Outer<T> f1; Outer<T>.Inner f2; Outer<int> f1; Outer<string>.Inner f2; class Inner { } } "; var compilation = CreateCompilation(text); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("Outer"); Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedType)); } [Fact] public void IsManagedType_ManagedSpecialTypes() { var text = @" class C { object f1; string f2; System.Collections.IEnumerable f3; int? f4; } "; var compilation = CreateCompilation(text); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedType)); } [Fact] public void IsManagedType_NonManagedSpecialTypes() { var text = @" class C { bool f1; char f2; sbyte f3; byte f4; short f5; ushort f6; int f7; uint f8; long f9; ulong f10; decimal f11; float f12; double f13; System.IntPtr f14; System.UIntPtr f14; } "; var compilation = CreateCompilation(text); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => !field.Type.IsManagedType)); } [Fact] public void IsManagedType_Void() { var text = @" class C { void M() { } } "; var compilation = CreateCompilation(text); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = type.GetMember<MethodSymbol>("M"); Assert.False(method.ReturnType.IsManagedType); } [Fact] public void IsManagedType_Enum() { var text = @" enum E { A } class C { enum E { A } } class D<T> { enum E { A } } struct S { enum E { A } } struct R<T> { enum E { A } } "; var compilation = CreateCompilation(text); var globalNamespace = compilation.GlobalNamespace; Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("E").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<NamedTypeSymbol>("E").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("D").GetMember<NamedTypeSymbol>("E").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").GetMember<NamedTypeSymbol>("E").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("R").GetMember<NamedTypeSymbol>("E").IsManagedType); } [Fact] public void IsManagedType_EmptyStruct() { var text = @" struct S { } struct P<T> { } class C { struct S { } } class D<T> { struct S { } } struct Q { struct S { } } struct R<T> { struct S { } } "; var compilation = CreateCompilation(text); var globalNamespace = compilation.GlobalNamespace; Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("P").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<NamedTypeSymbol>("S").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("D").GetMember<NamedTypeSymbol>("S").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("Q").GetMember<NamedTypeSymbol>("S").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("R").GetMember<NamedTypeSymbol>("S").IsManagedType); } [Fact] public void IsManagedType_SubstitutedStruct() { var text = @" class C<U> { S<U> f1; S<int> f2; S<U>.R f3; S<int>.R f4; } struct S<T> { struct R { } } "; var compilation = CreateCompilation(text); var type = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); Assert.True(type.GetMembers().OfType<FieldSymbol>().All(field => field.Type.IsManagedType)); } [Fact] public void IsManagedType_NonEmptyStruct() { var text = @" struct S1 { int f; } struct S2 { object f; } struct S3 { S1 s; } struct S4 { S2 s; } struct S5 { S1 s1; S2 s2; } "; var compilation = CreateCompilation(text); var globalNamespace = compilation.GlobalNamespace; Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedType); } [Fact] public void IsManagedType_StaticFieldStruct() { var text = @" struct S1 { static object o; int f; } struct S2 { static object o; object f; } struct S3 { static object o; S1 s; } struct S4 { static object o; S2 s; } struct S5 { static object o; S1 s1; S2 s2; } "; var compilation = CreateCompilation(text); var globalNamespace = compilation.GlobalNamespace; Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedType); } [Fact] public void IsManagedType_AutoPropertyStruct() { var text = @" struct S1 { int f { get; set; } } struct S2 { object f { get; set; } } struct S3 { S1 s { get; set; } } struct S4 { S2 s { get; set; } } struct S5 { S1 s1 { get; set; } S2 s2 { get; set; } } "; var compilation = CreateCompilation(text); var globalNamespace = compilation.GlobalNamespace; Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedType); } [Fact] public void IsManagedType_PropertyStruct() { var text = @" struct S1 { object o { get { return null; } set { } } int f { get; set; } } struct S2 { object o { get { return null; } set { } } object f { get; set; } } struct S3 { object o { get { return null; } set { } } S1 s { get; set; } } struct S4 { object o { get { return null; } set { } } S2 s { get; set; } } struct S5 { object o { get { return null; } set { } } S1 s1 { get; set; } S2 s2 { get; set; } } "; var compilation = CreateCompilation(text); var globalNamespace = compilation.GlobalNamespace; Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S3").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S4").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S5").IsManagedType); } [Fact] public void IsManagedType_EventStruct() { var text = @" struct S1 { event System.Action E; // has field } struct S2 { event System.Action E { add { } remove { } } // no field } "; var compilation = CreateCompilation(text); var globalNamespace = compilation.GlobalNamespace; Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("S1").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S2").IsManagedType); } [Fact] public void IsManagedType_ExpandingStruct() { var text = @" struct X<T> { public T t; } struct W<T> { X<W<W<T>>> x; } "; var compilation = CreateCompilation(text); var globalNamespace = compilation.GlobalNamespace; Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("X").IsManagedType); // because of X.t Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("W").IsManagedType); } [Fact] public void IsManagedType_CyclicStruct() { var text = @" struct S { S s; } struct R { object o; S s; } "; var compilation = CreateCompilation(text); var globalNamespace = compilation.GlobalNamespace; Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("R").IsManagedType); } [Fact] public void IsManagedType_CyclicStructChain() { var text = @" struct Q { R r; } struct R { A a; object o } struct S { A a; } //cycle struct A { B b; } struct B { C c; } struct C { D d; } struct D { A a; } "; var compilation = CreateCompilation(text); var globalNamespace = compilation.GlobalNamespace; Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("Q").IsManagedType); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("R").IsManagedType); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("S").IsManagedType); } [Fact] public void IsManagedType_SpecialClrTypes() { var text = @" class C { } "; var compilation = CreateCompilation(text); Assert.False(compilation.GetSpecialType(SpecialType.System_ArgIterator).IsManagedType); Assert.False(compilation.GetSpecialType(SpecialType.System_RuntimeArgumentHandle).IsManagedType); Assert.False(compilation.GetSpecialType(SpecialType.System_TypedReference).IsManagedType); } [Fact] public void ERR_ManagedAddr_ShallowRecursive() { var text = @" public unsafe struct S1 { public S1* s; //CS0208 public object o; } public unsafe struct S2 { public S2* s; //fine public int i; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S1') // public S1* s; //CS0523 Diagnostic(ErrorCode.ERR_ManagedAddr, "S1*").WithArguments("S1")); } [Fact] public void ERR_ManagedAddr_DeepRecursive() { var text = @" public unsafe struct A { public B** bb; //CS0208 public object o; public struct B { public C*[] cc; //CS0208 public struct C { public A*[,][] aa; //CS0208 } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('A') // public A*[,][] aa; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "A*").WithArguments("A"), // (9,16): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('A.B.C') // public C*[] cc; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "C*").WithArguments("A.B.C"), // (4,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('A.B') // public B** bb; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "B*").WithArguments("A.B")); } [Fact] public void ERR_ManagedAddr_Alias() { var text = @" using Alias = S; public unsafe struct S { public Alias* s; //CS0208 public object o; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // public Alias* s; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "Alias*").WithArguments("S")); } [Fact()] public void ERR_ManagedAddr_Members() { var text = @" public unsafe struct S { S* M() { return M(); } void M(S* p) { } S* P { get; set; } S* this[int x] { get { return M(); } set { } } int this[S* p] { get { return 0; } set { } } public S* s; //CS0208 public object o; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,5): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // S* M() { return M(); } Diagnostic(ErrorCode.ERR_ManagedAddr, "S*").WithArguments("S"), // (5,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // void M(S* p) { } Diagnostic(ErrorCode.ERR_ManagedAddr, "S*").WithArguments("S"), // (7,5): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // S* P { get; set; } Diagnostic(ErrorCode.ERR_ManagedAddr, "S*").WithArguments("S"), // (9,5): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // S* this[int x] { get { return M(); } set { } } Diagnostic(ErrorCode.ERR_ManagedAddr, "S*").WithArguments("S"), // (10,14): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // int this[S* p] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_ManagedAddr, "S*").WithArguments("S"), // (12,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // public S* s; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "S*").WithArguments("S")); } [WorkItem(10195, "https://github.com/dotnet/roslyn/issues/10195")] [Fact] public void PointerToStructInPartialMethodSignature() { string text = @"unsafe partial struct S { partial void M(S *p) { } partial void M(S *p); }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } #endregion IsManagedType #region AddressOf operand kinds [Fact] public void AddressOfExpressionKinds_Simple() { var text = @" unsafe class C { void M(int param) { int local; int* p; p = &param; p = &local; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void AddressOfExpressionKinds_Dereference() { var text = @" unsafe class C { void M() { int x; int* p = &x; p = &(*p); p = &p[0]; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void AddressOfExpressionKinds_Struct() { var text = @" unsafe class C { void M() { S1 s; S1* p1 = &s; S2* p2 = &s.s; S3* p3 = &s.s.s; int* p4 = &s.s.s.x; p2 = &(p1->s); p3 = &(p2->s); p4 = &(p3->x); p2 = &((*p1).s); p3 = &((*p2).s); p4 = &((*p3).x); } } struct S1 { public S2 s; } struct S2 { public S3 s; } struct S3 { public int x; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [WorkItem(529267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529267")] [Fact] public void AddressOfExpressionKinds_RangeVariable() { var text = @" using System.Linq; unsafe class C { int M(int param) { var z = from x in new int[2] select Goo(&x); return 0; } int Goo(int* p) { return 0; } } "; // NOTE: this is a breaking change - dev10 allows this. CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,50): error CS0211: Cannot take the address of the given expression // var z = from x in new int[2] select Goo(&x); Diagnostic(ErrorCode.ERR_InvalidAddrOp, "x").WithArguments("x")); } [WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")] [Fact] public void AddressOfExpressionKinds_ReadOnlyLocal() { var text = @" class Test { static void Main() { } } unsafe class C { int[] array; void M() { int* p; const int x = 1; p = &x; //CS0211 foreach (int y in new int[1]) { p = &y; } using (S s = new S()) { S* sp = &s; } fixed (int* a = &array[0]) { int** pp = &a; } } } struct S : System.IDisposable { public void Dispose() { } } "; CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,14): error CS0211: Cannot take the address of the given expression // p = &x; //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "x").WithLocation(13, 14), // (6,11): warning CS0649: Field 'C.array' is never assigned to, and will always have its default value null // int[] array; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "array").WithArguments("C.array", "null").WithLocation(6, 11) ); } [Fact] public void AddressOfExpressionKinds_Failure() { var text = @" class Base { public int f = 2; } unsafe class C : Base { event System.Action E; event System.Action F { add { } remove { } } int instanceField; int staticField; int this[int x] { get { return 0; } set { } } int P { get; set; } int M(int param) { int local; int[] array = new int[1]; System.Func<int> func = () => 1; int* p; p = &1; //CS0211 (can't addr) p = &array[0]; //CS0212 (need fixed) p = &(local = 1); //CS0211 p = &goo; //CS0103 (no goo) p = &base.f; //CS0212 p = &(local + local); //CS0211 p = &M(local); //CS0211 p = &func(); //CS0211 p = &(local += local); //CS0211 p = &(local == 0 ? local : param); //CS0211 p = &((int)param); //CS0211 p = &default(int); //CS0211 p = &delegate { return 1; }; //CS0211 p = &instanceField; //CS0212 p = &staticField; //CS0212 p = &(local++); //CS0211 p = &this[0]; //CS0211 p = &(() => 1); //CS0211 p = &M; //CS0211 p = &(new System.Int32()); //CS0211 p = &P; //CS0211 p = &sizeof(int); //CS0211 p = &this.instanceField; //CS0212 p = &(+local); //CS0211 int** pp; pp = &(&local); //CS0211 var q = &(new { }); //CS0208, CS0211 (managed) var r = &(new int[1]); //CS0208, CS0211 (managed) var s = &(array as object); //CS0208, CS0211 (managed) var t = &E; //CS0208 var u = &F; //CS0079 (can't use event like that) var v = &(E += null); //CS0211 var w = &(F += null); //CS0211 var x = &(array is object); //CS0211 var y = &(array ?? array); //CS0208, CS0211 (managed) var aa = &this; //CS0208 var bb = &typeof(int); //CS0208, CS0211 (managed) var cc = &Color.Red; //CS0211 return 0; } int Goo(int* p) { return 0; } static void Main() { } } unsafe struct S { S(int x) { var aa = &this; //CS0212 (need fixed) } } enum Color { Red, } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (76,18): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // var aa = &this; //CS0212 (need fixed) Diagnostic(ErrorCode.ERR_FixedNeeded, "&this").WithLocation(76, 18), // (23,14): error CS0211: Cannot take the address of the given expression // p = &1; //CS0211 (can't addr) Diagnostic(ErrorCode.ERR_InvalidAddrOp, "1").WithLocation(23, 14), // (24,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &array[0]; //CS0212 (need fixed) Diagnostic(ErrorCode.ERR_FixedNeeded, "&array[0]").WithLocation(24, 13), // (25,15): error CS0211: Cannot take the address of the given expression // p = &(local = 1); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local = 1").WithLocation(25, 15), // (26,14): error CS0103: The name 'goo' does not exist in the current context // p = &goo; //CS0103 (no goo) Diagnostic(ErrorCode.ERR_NameNotInContext, "goo").WithArguments("goo").WithLocation(26, 14), // (27,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &base.f; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&base.f").WithLocation(27, 13), // (28,15): error CS0211: Cannot take the address of the given expression // p = &(local + local); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local + local").WithLocation(28, 15), // (29,14): error CS0211: Cannot take the address of the given expression // p = &M(local); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "M(local)").WithLocation(29, 14), // (30,14): error CS0211: Cannot take the address of the given expression // p = &func(); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "func()").WithLocation(30, 14), // (31,15): error CS0211: Cannot take the address of the given expression // p = &(local += local); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local += local").WithLocation(31, 15), // (32,15): error CS0211: Cannot take the address of the given expression // p = &(local == 0 ? local : param); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local == 0 ? local : param").WithLocation(32, 15), // (33,15): error CS0211: Cannot take the address of the given expression // p = &((int)param); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "(int)param").WithLocation(33, 15), // (34,14): error CS0211: Cannot take the address of the given expression // p = &default(int); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "default(int)").WithLocation(34, 14), // (35,14): error CS0211: Cannot take the address of the given expression // p = &delegate { return 1; }; //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "delegate { return 1; }").WithLocation(35, 14), // (36,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &instanceField; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&instanceField").WithLocation(36, 13), // (37,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &staticField; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&staticField").WithLocation(37, 13), // (38,15): error CS0211: Cannot take the address of the given expression // p = &(local++); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "local++").WithLocation(38, 15), // (39,14): error CS0211: Cannot take the address of the given expression // p = &this[0]; //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "this[0]").WithArguments("C.this[int]").WithLocation(39, 14), // (40,15): error CS0211: Cannot take the address of the given expression // p = &(() => 1); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "() => 1").WithLocation(40, 15), // (41,14): error CS0211: Cannot take the address of the given expression // p = &M; //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "M").WithArguments("M", "method group").WithLocation(41, 14), // (42,15): error CS0211: Cannot take the address of the given expression // p = &(new System.Int32()); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "new System.Int32()").WithLocation(42, 15), // (43,14): error CS0211: Cannot take the address of the given expression // p = &P; //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "P").WithArguments("C.P").WithLocation(43, 14), // (44,14): error CS0211: Cannot take the address of the given expression // p = &sizeof(int); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "sizeof(int)").WithLocation(44, 14), // (45,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &this.instanceField; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&this.instanceField").WithLocation(45, 13), // (46,15): error CS0211: Cannot take the address of the given expression // p = &(+local); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "+local").WithLocation(46, 15), // (49,16): error CS0211: Cannot take the address of the given expression // pp = &(&local); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "&local").WithLocation(49, 16), // (51,19): error CS0211: Cannot take the address of the given expression // var q = &(new { }); //CS0208, CS0211 (managed) Diagnostic(ErrorCode.ERR_InvalidAddrOp, "new { }").WithLocation(51, 19), // (52,19): error CS0211: Cannot take the address of the given expression // var r = &(new int[1]); //CS0208, CS0211 (managed) Diagnostic(ErrorCode.ERR_InvalidAddrOp, "new int[1]").WithLocation(52, 19), // (53,19): error CS0211: Cannot take the address of the given expression // var s = &(array as object); //CS0208, CS0211 (managed) Diagnostic(ErrorCode.ERR_InvalidAddrOp, "array as object").WithLocation(53, 19), // (54,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Action') // var t = &E; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "&E").WithArguments("System.Action").WithLocation(54, 17), // (55,18): error CS0079: The event 'C.F' can only appear on the left hand side of += or -= // var u = &F; //CS0079 (can't use event like that) Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "F").WithArguments("C.F").WithLocation(55, 18), // (56,19): error CS0211: Cannot take the address of the given expression // var v = &(E += null); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "E += null").WithLocation(56, 19), // (57,19): error CS0211: Cannot take the address of the given expression // var w = &(F += null); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "F += null").WithLocation(57, 19), // (58,19): error CS0211: Cannot take the address of the given expression // var x = &(array is object); //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "array is object").WithLocation(58, 19), // (59,19): error CS0211: Cannot take the address of the given expression // var y = &(array ?? array); //CS0208, CS0211 (managed) Diagnostic(ErrorCode.ERR_InvalidAddrOp, "array ?? array").WithLocation(59, 19), // (60,19): error CS0211: Cannot take the address of the given expression // var aa = &this; //CS0208 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "this").WithArguments("this").WithLocation(60, 19), // (61,19): error CS0211: Cannot take the address of the given expression // var bb = &typeof(int); //CS0208, CS0211 (managed) Diagnostic(ErrorCode.ERR_InvalidAddrOp, "typeof(int)").WithLocation(61, 19), // (62,19): error CS0211: Cannot take the address of the given expression // var cc = &Color.Red; //CS0211 Diagnostic(ErrorCode.ERR_InvalidAddrOp, "Color.Red").WithLocation(62, 19) ); } #endregion AddressOf operand kinds #region AddressOf diagnostics [Fact] public void AddressOfManaged() { var text = @" unsafe class C { void M<T>(T t) { var p0 = &t; //CS0208 C c = new C(); var p1 = &c; //CS0208 S s = new S(); var p2 = &s; //CS0208 var anon = new { }; var p3 = &anon; //CS0208 } } public struct S { public string s; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T') // var p0 = &t; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "&t").WithArguments("T"), // (9,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C') // var p1 = &c; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "&c").WithArguments("C"), // (12,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // var p2 = &s; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("S"), // (15,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var p3 = &anon; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "&anon").WithArguments("<empty anonymous type>")); } [Fact] public void AddressOfManaged_Cycle() { var text = @" unsafe class C { void M() { S s = new S(); var p = &s; //CS0208 } } public struct S { public S s; //CS0523 public object o; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,14): error CS0523: Struct member 'S.s' of type 'S' causes a cycle in the struct layout // public S s; //CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "s").WithArguments("S.s", "S"), // (7,17): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // var p = &s; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("S")); } [Fact] public void AddressOfMoveableVariable() { var text = @" class Base { public int instanceField; public int staticField; } unsafe class Derived : Base { void M(ref int refParam, out int outParam) { Derived d = this; int[] array = new int[2]; int* p; p = &instanceField; //CS0212 p = &this.instanceField; //CS0212 p = &base.instanceField; //CS0212 p = &d.instanceField; //CS0212 p = &staticField; //CS0212 p = &this.staticField; //CS0212 p = &base.staticField; //CS0212 p = &d.staticField; //CS0212 p = &array[0]; //CS0212 p = &refParam; //CS0212 p = &outParam; //CS0212 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (17,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &instanceField; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&instanceField"), // (18,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &this.instanceField; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&this.instanceField"), // (19,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &base.instanceField; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&base.instanceField"), // (20,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &d.instanceField; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&d.instanceField"), // (22,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &staticField; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&staticField"), // (23,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &this.staticField; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&this.staticField"), // (24,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &base.staticField; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&base.staticField"), // (25,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &d.staticField; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&d.staticField"), // (27,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &array[0]; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&array[0]"), // (29,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &refParam; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&refParam"), // (30,13): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // p = &outParam; //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&outParam")); } [Fact] public void AddressOfInitializes() { var text = @" public struct S { public int x; public int y; } unsafe class C { void M() { S s; int* p = &s.x; int x = s.x; //fine int y = s.y; //cs0170 (uninitialized) } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (15,17): error CS0170: Use of possibly unassigned field 'y' // int y = s.y; //cs0170 (uninitialized) Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.y").WithArguments("y")); } [Fact] public void AddressOfCapturedLocal1() { var text = @" unsafe class C { void M(System.Action a) { int x; int* p = &x; //before capture M(() => { x++; }); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,11): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // M(&x, () => { x++; }); Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x")); } [Fact] public void AddressOfCapturedLocal2() { var text = @" unsafe class C { void M(System.Action a) { int x = 1; M(() => { x++; }); int* p = &x; //after capture } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,18): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // int* p = &x; Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x")); } [Fact] public void AddressOfCapturedLocal3() { var text = @" unsafe class C { void M(System.Action a) { int x; M(() => { int* p = &x; }); // in lambda } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,28): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // M(() => { int* p = &x; }); // in lambda Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x")); } [Fact] public void AddressOfCapturedLocal4() { var text = @" unsafe class C { void M(System.Action a) { int x; int* p = &x; //only report the first M(() => { p = &x; }); p = &x; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,28): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // M(() => { int* p = &x; }); // in lambda Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x")); } [Fact] public void AddressOfCapturedStructField1() { var text = @" unsafe struct S { int x; void M(System.Action a) { S s; int* p = &s.x; //before capture M(() => { s.x++; }); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,18): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // int* p = &s.x; //before capture Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s")); } [Fact] public void AddressOfCapturedStructField2() { var text = @" unsafe struct S { int x; void M(System.Action a) { S s; s.x = 1; M(() => { s.x++; }); int* p = &s.x; //after capture } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,18): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // int* p = &s.x; //after capture Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s")); } [Fact] public void AddressOfCapturedStructField3() { var text = @" unsafe struct S { int x; void M(System.Action a) { S s; M(() => { int* p = &s.x; }); // in lambda } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,28): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // M(() => { int* p = &s.x; }); // in lambda Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s")); } [Fact] public void AddressOfCapturedStructField4() { var text = @" unsafe struct S { int x; void M(System.Action a) { S s; int* p = &s.x; //only report the first M(() => { p = &s.x; }); p = &s.x; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,18): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // int* p = &s.x; //only report the first Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s")); } [Fact] public void AddressOfCapturedParameters() { var text = @" unsafe struct S { int x; void M(int x, S s, System.Action a) { M(x, s, () => { int* p1 = &x; int* p2 = &s.x; }); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,23): error CS1686: Local 'x' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // int* p1 = &x; Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&x").WithArguments("x"), // (11,23): error CS1686: Local 's' or its members cannot have their address taken and be used inside an anonymous method or lambda expression // int* p2 = &s.x; Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "&s.x").WithArguments("s") ); } [WorkItem(657083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/657083")] [Fact] public void CaptureStructWithFixedArray() { var text = @" unsafe public struct Test { private delegate int D(); public fixed int i[1]; public int goo() { Test t = this; t.i[0] = 5; D d = () => t.i[0]; return d(); } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_LocalCantBeFixedAndHoisted, "t.i").WithArguments("t") ); } [Fact] public void AddressOfCapturedMoveable1() { var text = @" unsafe class C { int x; void M(System.Action a) { fixed(int* p = &x) //fine - error only applies to non-moveable variables { M(() => x++); } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void AddressOfCapturedMoveable2() { var text = @" unsafe class C { void M(ref int x, System.Action a) { fixed (int* p = &x) //fine - error only applies to non-moveable variables { M(ref x, () => x++); } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,28): error CS1628: Cannot use ref or out parameter 'x' inside an anonymous method, lambda expression, or query expression // M(ref x, () => x++); Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "x").WithArguments("x")); } [WorkItem(543989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543989")] [Fact] public void AddressOfInsideAnonymousTypes() { var text = @" public class C { public static void Main() { int x = 10; unsafe { var t = new { p1 = &x }; } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( //(9,27): error CS0828: Cannot assign int* to anonymous type property // p1 = &x Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "p1 = &x").WithArguments("int*")); } [WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")] [WorkItem(544537, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544537")] [Fact] public void AddressOfStaticReadonlyFieldInsideFixed() { var text = @" public class Test { static readonly int R1 = 45; unsafe public static void Main() { fixed (int* v1 = &R1) { } } } "; CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } #endregion AddressOf diagnostics #region AddressOf SemanticModel tests [Fact] public void AddressOfSemanticModelAPIs() { var text = @" unsafe class C { void M() { int x; int* p = &x; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind()); var symbolInfo = model.GetSymbolInfo(syntax); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); var typeInfo = model.GetTypeInfo(syntax); var type = typeInfo.Type; var conv = model.GetConversion(syntax); Assert.NotNull(type); Assert.Same(type, typeInfo.ConvertedType); Assert.Equal(Conversion.Identity, conv); Assert.Equal(TypeKind.Pointer, type.TypeKind); Assert.Equal(SpecialType.System_Int32, ((PointerTypeSymbol)type).PointedAtType.SpecialType); var declaredSymbol = model.GetDeclaredSymbol(syntax.Ancestors().OfType<VariableDeclaratorSyntax>().First()); Assert.NotNull(declaredSymbol); Assert.Equal(SymbolKind.Local, declaredSymbol.Kind); Assert.Equal("p", declaredSymbol.Name); Assert.Equal(type, ((LocalSymbol)declaredSymbol).Type); } [Fact] public void SpeculativelyBindPointerToManagedType() { var text = @" unsafe struct S { public object o; } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single(); Assert.Equal(SyntaxKind.FieldDeclaration, syntax.Kind()); model.GetSpeculativeTypeInfo(syntax.SpanStart, SyntaxFactory.ParseTypeName("S*"), SpeculativeBindingOption.BindAsTypeOrNamespace); // Specifically don't see diagnostic from speculative binding. compilation.VerifyDiagnostics( // (4,19): warning CS0649: Field 'S.o' is never assigned to, and will always have its default value null // public object o; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "o").WithArguments("S.o", "null")); } [WorkItem(544346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544346")] [Fact] public void AddressOfLambdaExpr1() { var text = @" unsafe class C { void M() { var i1 = &()=>5; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind()); Assert.Equal("&()", syntax.ToString()); //NOTE: not actually lambda var symbolInfo = model.GetSymbolInfo(syntax); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); var typeInfo = model.GetTypeInfo(syntax); var type = typeInfo.Type; var conv = model.GetConversion(syntax); Assert.NotNull(type); Assert.Same(type, typeInfo.ConvertedType); Assert.Equal(Conversion.Identity, conv); Assert.Equal("?*", typeInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Pointer, typeInfo.Type.TypeKind); Assert.Equal(TypeKind.Error, ((PointerTypeSymbol)typeInfo.Type).PointedAtType.TypeKind); } [WorkItem(544346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544346")] [Fact] public void AddressOfLambdaExpr2() { var text = @" unsafe class C { void M() { var i1 = &(()=>5); } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind()); Assert.Equal("&(()=>5)", syntax.ToString()); var symbolInfo = model.GetSymbolInfo(syntax); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); var typeInfo = model.GetTypeInfo(syntax); var type = typeInfo.Type; var conv = model.GetConversion(syntax); Assert.NotNull(type); Assert.Same(type, typeInfo.ConvertedType); Assert.Equal(Conversion.Identity, conv); Assert.Equal("?*", typeInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Pointer, typeInfo.Type.TypeKind); Assert.Equal(TypeKind.Error, ((PointerTypeSymbol)typeInfo.Type).PointedAtType.TypeKind); } [WorkItem(544346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544346")] [Fact] public void AddressOfMethodGroup() { var text = @" unsafe class C { void M() { var i1 = &M; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.AddressOfExpression, syntax.Kind()); var symbolInfo = model.GetSymbolInfo(syntax); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); var typeInfo = model.GetTypeInfo(syntax); var type = typeInfo.Type; var conv = model.GetConversion(syntax); Assert.NotNull(type); Assert.Same(type, typeInfo.ConvertedType); Assert.Equal(Conversion.Identity, conv); Assert.Equal("?*", typeInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Pointer, typeInfo.Type.TypeKind); Assert.Equal(TypeKind.Error, ((PointerTypeSymbol)typeInfo.Type).PointedAtType.TypeKind); } #endregion AddressOf SemanticModel tests #region Dereference diagnostics [Fact] public void DereferenceSuccess() { var text = @" unsafe class C { int M(int* p) { return *p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void DereferenceNullLiteral() { var text = @" unsafe class C { void M() { int x = *null; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,17): error CS0193: The * or -> operator must be applied to a pointer // int x = *null; Diagnostic(ErrorCode.ERR_PtrExpected, "*null")); } [Fact] public void DereferenceNonPointer() { var text = @" unsafe class C { void M() { int p = 1; int x = *p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,17): error CS0193: The * or -> operator must be applied to a pointer // int x = *p; Diagnostic(ErrorCode.ERR_PtrExpected, "*p")); } [Fact] public void DereferenceVoidPointer() { var text = @" unsafe class C { void M(void* p) { var x = *p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,17): error CS0242: The operation in question is undefined on void pointers // var x = *p; Diagnostic(ErrorCode.ERR_VoidError, "*p")); } [Fact] public void DereferenceUninitialized() { var text = @" unsafe class C { void M() { int* p; int x = *p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,18): error CS0165: Use of unassigned local variable 'p' // int x = *p; Diagnostic(ErrorCode.ERR_UseDefViolation, "p").WithArguments("p")); } #endregion Dereference diagnostics #region Dereference SemanticModel tests [Fact] public void DereferenceSemanticModelAPIs() { var text = @" unsafe class C { void M() { int x; int* p = &x; x = *p; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<PrefixUnaryExpressionSyntax>().Last(); Assert.Equal(SyntaxKind.PointerIndirectionExpression, syntax.Kind()); var symbolInfo = model.GetSymbolInfo(syntax); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); var typeInfo = model.GetTypeInfo(syntax); var type = typeInfo.Type; var conv = model.GetConversion(syntax); Assert.NotNull(type); Assert.Same(type, typeInfo.ConvertedType); Assert.Equal(Conversion.Identity, conv); Assert.Equal(SpecialType.System_Int32, type.SpecialType); } #endregion Dereference SemanticModel tests #region PointerMemberAccess diagnostics [Fact] public void PointerMemberAccessSuccess() { var text = @" unsafe class C { string M(int* p) { return p->ToString(); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void PointerMemberAccessAddress() { var text = @" unsafe struct S { int x; void M(S* sp) { int* ip = &(sp->x); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void PointerMemberAccessNullLiteral() { var text = @" unsafe class C { void M() { string x = null->ToString(); //Roslyn: CS0193 / Dev10: CS0023 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS0193: The * or -> operator must be applied to a pointer // string x = null->ToString(); //Roslyn: CS0193 / Dev10: CS0023 Diagnostic(ErrorCode.ERR_PtrExpected, "null->ToString")); } [Fact] public void PointerMemberAccessMethodGroup() { var text = @" unsafe class C { void M() { string x = M->ToString(); //Roslyn: CS0193 / Dev10: CS0023 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS0193: The * or -> operator must be applied to a pointer // string x = M->ToString(); //Roslyn: CS0193 / Dev10: CS0023 Diagnostic(ErrorCode.ERR_PtrExpected, "M->ToString")); } [Fact] public void PointerMemberAccessLambda() { var text = @" unsafe class C { void M() { string x = (z => z)->ToString(); //Roslyn: CS0193 / Dev10: CS0023 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS0193: The * or -> operator must be applied to a pointer // string x = (z => z)->ToString(); //Roslyn: CS0193 / Dev10: CS0023 Diagnostic(ErrorCode.ERR_PtrExpected, "(z => z)->ToString")); } [Fact] public void PointerMemberAccessNonPointer() { var text = @" unsafe class C { void M() { int p = 1; int x = p->GetHashCode(); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,17): error CS0193: The * or -> operator must be applied to a pointer // int x = p->GetHashCode(); Diagnostic(ErrorCode.ERR_PtrExpected, "p->GetHashCode")); } [Fact] public void PointerMemberAccessVoidPointer() { var text = @" unsafe class C { void M(void* p) { var x = p->GetHashCode(); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,17): error CS0242: The operation in question is undefined on void pointers // var x = p->GetHashCode(); Diagnostic(ErrorCode.ERR_VoidError, "p->GetHashCode")); } [Fact] public void PointerMemberAccessUninitialized() { var text = @" unsafe class C { void M() { int* p; int x = p->GetHashCode(); } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,18): error CS0165: Use of unassigned local variable 'p' // int x = *p; Diagnostic(ErrorCode.ERR_UseDefViolation, "p").WithArguments("p")); } [Fact] public void PointerMemberAccessMemberKinds() { var text = @" unsafe struct S { int InstanceField; static int StaticField; int InstanceProperty { get; set; } static int StaticProperty { get; set; } // No syntax for indexer access. //int this[int x] { get { return 0; } set { } } void InstanceMethod() { } static void StaticMethod() { } // No syntax for type member access. //delegate void Delegate(); //struct Type { } static void Main() { S s; S* p = &s; p->InstanceField = 1; p->StaticField = 1; //CS0176 p->InstanceProperty = 2; p->StaticProperty = 2; //CS0176 p->InstanceMethod(); p->StaticMethod(); //CS0176 p->ExtensionMethod(); System.Action a; a = p->InstanceMethod; a = p->StaticMethod; //CS0176 a = p->ExtensionMethod; //CS1113 } } static class Extensions { public static void ExtensionMethod(this S s) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (26,9): error CS0176: Member 'S.StaticField' cannot be accessed with an instance reference; qualify it with a type name instead // p->StaticField = 1; //CS0176 Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticField").WithArguments("S.StaticField").WithLocation(26, 9), // (29,9): error CS0176: Member 'S.StaticProperty' cannot be accessed with an instance reference; qualify it with a type name instead // p->StaticProperty = 2; //CS0176 Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticProperty").WithArguments("S.StaticProperty").WithLocation(29, 9), // (32,9): error CS0176: Member 'S.StaticMethod()' cannot be accessed with an instance reference; qualify it with a type name instead // p->StaticMethod(); //CS0176 Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticMethod").WithArguments("S.StaticMethod()").WithLocation(32, 9), // (38,13): error CS0176: Member 'S.StaticMethod()' cannot be accessed with an instance reference; qualify it with a type name instead // a = p->StaticMethod; //CS0176 Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticMethod").WithArguments("S.StaticMethod()").WithLocation(38, 13), // (39,13): error CS1113: Extension method 'Extensions.ExtensionMethod(S)' defined on value type 'S' cannot be used to create delegates // a = p->ExtensionMethod; //CS1113 Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "p->ExtensionMethod").WithArguments("Extensions.ExtensionMethod(S)", "S").WithLocation(39, 13) ); } // NOTE: a type with events is managed, so this is always an error case. [Fact] public void PointerMemberAccessEvents() { var text = @" unsafe struct S { event System.Action InstanceFieldLikeEvent; static event System.Action StaticFieldLikeEvent; event System.Action InstanceCustomEvent { add { } remove { } } static event System.Action StaticCustomEvent { add { } remove { } } static void Main() { S s; S* p = &s; //CS0208 p->InstanceFieldLikeEvent += null; p->StaticFieldLikeEvent += null; //CS0176 p->InstanceCustomEvent += null; p->StaticCustomEvent += null; //CS0176 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // S* p = &s; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "S*").WithArguments("S"), // (13,16): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // S* p = &s; //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "&s").WithArguments("S"), // (16,9): error CS0176: Member 'S.StaticFieldLikeEvent' cannot be accessed with an instance reference; qualify it with a type name instead // p->StaticFieldLikeEvent += null; //CS0176 Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticFieldLikeEvent").WithArguments("S.StaticFieldLikeEvent"), // (19,9): error CS0176: Member 'S.StaticCustomEvent' cannot be accessed with an instance reference; qualify it with a type name instead // p->StaticCustomEvent += null; //CS0176 Diagnostic(ErrorCode.ERR_ObjectProhibited, "p->StaticCustomEvent").WithArguments("S.StaticCustomEvent"), // (5,32): warning CS0067: The event 'S.StaticFieldLikeEvent' is never used // static event System.Action StaticFieldLikeEvent; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "StaticFieldLikeEvent").WithArguments("S.StaticFieldLikeEvent"), // (4,25): warning CS0067: The event 'S.InstanceFieldLikeEvent' is never used // event System.Action InstanceFieldLikeEvent; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "InstanceFieldLikeEvent").WithArguments("S.InstanceFieldLikeEvent") ); } #endregion PointerMemberAccess diagnostics #region PointerMemberAccess SemanticModel tests [Fact] public void PointerMemberAccessSemanticModelAPIs() { var text = @" unsafe class C { void M() { S s; S* p = &s; p->M(); } } struct S { public void M() { } public void M(int x) { } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.PointerMemberAccessExpression, syntax.Kind()); var receiverSyntax = syntax.Expression; var methodGroupSyntax = syntax; var callSyntax = syntax.Parent; var structType = compilation.GlobalNamespace.GetMember<TypeSymbol>("S"); var structPointerType = new PointerTypeSymbol(structType); var structMethod1 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 0); var structMethod2 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 1); var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax); var receiverSymbol = receiverSummary.Symbol; Assert.Equal(SymbolKind.Local, receiverSymbol.Kind); Assert.Equal(structPointerType, ((LocalSymbol)receiverSymbol).Type); Assert.Equal("p", receiverSymbol.Name); Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason); Assert.Equal(0, receiverSummary.CandidateSymbols.Length); Assert.Equal(structPointerType, receiverSummary.Type); Assert.Equal(structPointerType, receiverSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind); Assert.Equal(0, receiverSummary.MethodGroup.Length); var methodGroupSummary = model.GetSemanticInfoSummary(methodGroupSyntax); Assert.Equal(structMethod1, methodGroupSummary.Symbol); Assert.Equal(CandidateReason.None, methodGroupSummary.CandidateReason); Assert.Equal(0, methodGroupSummary.CandidateSymbols.Length); Assert.Null(methodGroupSummary.Type); Assert.Null(methodGroupSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, methodGroupSummary.ImplicitConversion.Kind); Assert.True(methodGroupSummary.MethodGroup.SetEquals(ImmutableArray.Create<IMethodSymbol>(structMethod1, structMethod2), EqualityComparer<IMethodSymbol>.Default)); var callSummary = model.GetSemanticInfoSummary(callSyntax); Assert.Equal(structMethod1, callSummary.Symbol); Assert.Equal(CandidateReason.None, callSummary.CandidateReason); Assert.Equal(0, callSummary.CandidateSymbols.Length); Assert.Equal(SpecialType.System_Void, callSummary.Type.SpecialType); Assert.Equal(SpecialType.System_Void, callSummary.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, callSummary.ImplicitConversion.Kind); Assert.Equal(0, callSummary.MethodGroup.Length); } [Fact] public void PointerMemberAccessSemanticModelAPIs_ErrorScenario() { var text = @" unsafe class C { void M() { S s; S* p = &s; s->M(); //should be 'p' } } struct S { public void M() { } public void M(int x) { } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.PointerMemberAccessExpression, syntax.Kind()); var receiverSyntax = syntax.Expression; var methodGroupSyntax = syntax; var callSyntax = syntax.Parent; var structType = compilation.GlobalNamespace.GetMember<TypeSymbol>("S"); var structMethod1 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 0); var structMethod2 = structType.GetMembers("M").OfType<MethodSymbol>().Single(m => m.ParameterCount == 1); var structMethods = ImmutableArray.Create<MethodSymbol>(structMethod1, structMethod2); var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax); var receiverSymbol = receiverSummary.Symbol; Assert.Equal(SymbolKind.Local, receiverSymbol.Kind); Assert.Equal(structType, ((LocalSymbol)receiverSymbol).Type); Assert.Equal("s", receiverSymbol.Name); Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason); Assert.Equal(0, receiverSummary.CandidateSymbols.Length); Assert.Equal(structType, receiverSummary.Type); Assert.Equal(structType, receiverSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind); Assert.Equal(0, receiverSummary.MethodGroup.Length); var methodGroupSummary = model.GetSemanticInfoSummary(methodGroupSyntax); Assert.Equal(structMethod1, methodGroupSummary.Symbol); // Have enough info for overload resolution. Assert.Null(methodGroupSummary.Type); Assert.Null(methodGroupSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, methodGroupSummary.ImplicitConversion.Kind); Assert.True(methodGroupSummary.MethodGroup.SetEquals(StaticCast<IMethodSymbol>.From(structMethods), EqualityComparer<IMethodSymbol>.Default)); var callSummary = model.GetSemanticInfoSummary(callSyntax); Assert.Equal(structMethod1, callSummary.Symbol); // Have enough info for overload resolution. Assert.Equal(SpecialType.System_Void, callSummary.Type.SpecialType); Assert.Equal(callSummary.Type, callSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, callSummary.ImplicitConversion.Kind); Assert.Equal(0, callSummary.MethodGroup.Length); } #endregion PointerMemberAccess SemanticModel tests #region PointerElementAccess [Fact] public void PointerElementAccess_NoIndices() { var text = @" unsafe struct S { void M(S* p) { S s = p[]; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,17): error CS0443: Syntax error; value expected // S s = p[]; Diagnostic(ErrorCode.ERR_ValueExpected, "]")); } [Fact] public void PointerElementAccess_MultipleIndices() { var text = @" unsafe struct S { void M(S* p) { S s = p[1, 2]; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,15): error CS0196: A pointer must be indexed by only one value // S s = p[1, 2]; Diagnostic(ErrorCode.ERR_PtrIndexSingle, "p[1, 2]")); } [Fact] public void PointerElementAccess_RefIndex() { var text = @" unsafe struct S { void M(S* p) { int x = 1; S s = p[ref x]; } } "; // Dev10 gives an unhelpful syntax error. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,21): error CS1615: Argument 1 should not be passed with the 'ref' keyword // S s = p[ref x]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "ref")); } [Fact] public void PointerElementAccess_OutIndex() { var text = @" unsafe struct S { void M(S* p) { int x = 1; S s = p[out x]; } } "; // Dev10 gives an unhelpful syntax error. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,21): error CS1615: Argument 1 should not be passed with the 'out' keyword // S s = p[out x]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "out")); } [Fact] public void PointerElementAccess_NamedOffset() { var text = @" unsafe struct S { void M(S* p) { int x = 1; S s = p[index: x]; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,15): error CS1742: An array access may not have a named argument specifier // S s = p[index: x]; Diagnostic(ErrorCode.ERR_NamedArgumentForArray, "p[index: x]")); } [Fact] public void PointerElementAccess_VoidPointer() { var text = @" unsafe struct S { void M(void* p) { p[0] = null; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,9): error CS0242: The operation in question is undefined on void pointers // p[0] = null; Diagnostic(ErrorCode.ERR_VoidError, "p")); } #endregion PointerElementAccess diagnostics #region PointerElementAccess SemanticModel tests [Fact] public void PointerElementAccessSemanticModelAPIs() { var text = @" unsafe class C { void M() { const int size = 3; fixed(int* p = new int[size]) { for (int i = 0; i < size; i++) { p[i] = i * i; } } } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.ElementAccessExpression, syntax.Kind()); var receiverSyntax = syntax.Expression; var indexSyntax = syntax.ArgumentList.Arguments.Single().Expression; var accessSyntax = syntax; var intType = compilation.GetSpecialType(SpecialType.System_Int32); var intPointerType = new PointerTypeSymbol(intType); var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax); var receiverSymbol = receiverSummary.Symbol; Assert.Equal(SymbolKind.Local, receiverSymbol.Kind); Assert.Equal(intPointerType, ((LocalSymbol)receiverSymbol).Type); Assert.Equal("p", receiverSymbol.Name); Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason); Assert.Equal(0, receiverSummary.CandidateSymbols.Length); Assert.Equal(intPointerType, receiverSummary.Type); Assert.Equal(intPointerType, receiverSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind); Assert.Equal(0, receiverSummary.MethodGroup.Length); var indexSummary = model.GetSemanticInfoSummary(indexSyntax); var indexSymbol = indexSummary.Symbol; Assert.Equal(SymbolKind.Local, indexSymbol.Kind); Assert.Equal(intType, ((LocalSymbol)indexSymbol).Type); Assert.Equal("i", indexSymbol.Name); Assert.Equal(CandidateReason.None, indexSummary.CandidateReason); Assert.Equal(0, indexSummary.CandidateSymbols.Length); Assert.Equal(intType, indexSummary.Type); Assert.Equal(intType, indexSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, indexSummary.ImplicitConversion.Kind); Assert.Equal(0, indexSummary.MethodGroup.Length); var accessSummary = model.GetSemanticInfoSummary(accessSyntax); Assert.Null(accessSummary.Symbol); Assert.Equal(CandidateReason.None, accessSummary.CandidateReason); Assert.Equal(0, accessSummary.CandidateSymbols.Length); Assert.Equal(intType, accessSummary.Type); Assert.Equal(intType, accessSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, accessSummary.ImplicitConversion.Kind); Assert.Equal(0, accessSummary.MethodGroup.Length); } [Fact] public void PointerElementAccessSemanticModelAPIs_Fixed_Unmovable() { var text = @" unsafe class C { struct S1 { public fixed int f[10]; } void M() { S1 p = default; p.f[i] = 123; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.ElementAccessExpression, syntax.Kind()); var receiverSyntax = syntax.Expression; var indexSyntax = syntax.ArgumentList.Arguments.Single().Expression; var accessSyntax = syntax; var intType = compilation.GetSpecialType(SpecialType.System_Int32); var intPointerType = new PointerTypeSymbol(intType); var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax); var receiverSymbol = receiverSummary.Symbol; Assert.Equal(SymbolKind.Field, receiverSymbol.Kind); Assert.Equal(intPointerType, ((FieldSymbol)receiverSymbol).Type); Assert.Equal("f", receiverSymbol.Name); Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason); Assert.Equal(0, receiverSummary.CandidateSymbols.Length); Assert.Equal(intPointerType, receiverSummary.Type); Assert.Equal(intPointerType, receiverSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind); Assert.Equal(0, receiverSummary.MethodGroup.Length); var indexSummary = model.GetSemanticInfoSummary(indexSyntax); var indexSymbol = indexSummary.Symbol; Assert.Null(indexSymbol); var accessSummary = model.GetSemanticInfoSummary(accessSyntax); Assert.Null(accessSummary.Symbol); Assert.Equal(CandidateReason.None, accessSummary.CandidateReason); Assert.Equal(0, accessSummary.CandidateSymbols.Length); Assert.Equal(intType, accessSummary.Type); Assert.Equal(intType, accessSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, accessSummary.ImplicitConversion.Kind); Assert.Equal(0, accessSummary.MethodGroup.Length); } [Fact] public void PointerElementAccessSemanticModelAPIs_Fixed_Movable() { var text = @" unsafe class C { struct S1 { public fixed int f[10]; } S1 p = default; void M() { p.f[i] = 123; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().Single(); Assert.Equal(SyntaxKind.ElementAccessExpression, syntax.Kind()); var receiverSyntax = syntax.Expression; var indexSyntax = syntax.ArgumentList.Arguments.Single().Expression; var accessSyntax = syntax; var intType = compilation.GetSpecialType(SpecialType.System_Int32); var intPointerType = new PointerTypeSymbol(intType); var receiverSummary = model.GetSemanticInfoSummary(receiverSyntax); var receiverSymbol = receiverSummary.Symbol; Assert.Equal(SymbolKind.Field, receiverSymbol.Kind); Assert.Equal(intPointerType, ((FieldSymbol)receiverSymbol).Type); Assert.Equal("f", receiverSymbol.Name); Assert.Equal(CandidateReason.None, receiverSummary.CandidateReason); Assert.Equal(0, receiverSummary.CandidateSymbols.Length); Assert.Equal(intPointerType, receiverSummary.Type); Assert.Equal(intPointerType, receiverSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, receiverSummary.ImplicitConversion.Kind); Assert.Equal(0, receiverSummary.MethodGroup.Length); var indexSummary = model.GetSemanticInfoSummary(indexSyntax); var indexSymbol = indexSummary.Symbol; Assert.Null(indexSymbol); var accessSummary = model.GetSemanticInfoSummary(accessSyntax); Assert.Null(accessSummary.Symbol); Assert.Equal(CandidateReason.None, accessSummary.CandidateReason); Assert.Equal(0, accessSummary.CandidateSymbols.Length); Assert.Equal(intType, accessSummary.Type); Assert.Equal(intType, accessSummary.ConvertedType); Assert.Equal(ConversionKind.Identity, accessSummary.ImplicitConversion.Kind); Assert.Equal(0, accessSummary.MethodGroup.Length); } #endregion PointerElementAccess SemanticModel tests #region Pointer conversion tests [Fact] public void NullLiteralConversion() { var text = @" unsafe struct S { void M() { byte* b = null; int* i = null; S* s = null; void* v = null; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); foreach (var nullSyntax in tree.GetCompilationUnitRoot().DescendantTokens().Where(token => token.IsKind(SyntaxKind.NullKeyword))) { var node = (ExpressionSyntax)nullSyntax.Parent; var typeInfo = model.GetTypeInfo(node); var conv = model.GetConversion(node); Assert.Null(typeInfo.Type); Assert.Equal(TypeKind.Pointer, typeInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NullToPointer, conv.Kind); } } [Fact] public void VoidPointerConversion1() { var text = @" unsafe struct S { void M() { byte* b = null; int* i = null; S* s = null; void* v1 = b; void* v2 = i; void* v3 = s; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); foreach (var declarationSyntax in tree.GetCompilationUnitRoot().DescendantTokens().OfType<VariableDeclarationSyntax>().Where(syntax => syntax.GetFirstToken().IsKind(SyntaxKind.VoidKeyword))) { var value = declarationSyntax.Variables.Single().Initializer.Value; var typeInfo = model.GetTypeInfo(value); var type = typeInfo.Type; Assert.Equal(TypeKind.Pointer, type.TypeKind); Assert.NotEqual(SpecialType.System_Void, ((PointerTypeSymbol)type).PointedAtType.SpecialType); var convertedType = typeInfo.ConvertedType; Assert.Equal(TypeKind.Pointer, convertedType.TypeKind); Assert.Equal(SpecialType.System_Void, ((PointerTypeSymbol)convertedType).PointedAtType.SpecialType); var conv = model.GetConversion(value); Assert.Equal(ConversionKind.PointerToVoid, conv.Kind); } } [Fact] public void VoidPointerConversion2() { var text = @" unsafe struct S { void M() { void* v = null; void* vv1 = &v; void** vv2 = &v; void* vv3 = vv2; void** vv4 = vv3; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,22): error CS0266: Cannot implicitly convert type 'void*' to 'void**'. An explicit conversion exists (are you missing a cast?) // void** vv4 = vv3; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "vv3").WithArguments("void*", "void**")); } [Fact] public void ExplicitPointerConversion() { var text = @" unsafe struct S { void M(int* i, byte* b, void* v, int** ii, byte** bb, void** vv) { i = (int*)b; i = (int*)v; i = (int*)ii; i = (int*)bb; i = (int*)vv; b = (byte*)i; b = (byte*)v; b = (byte*)ii; b = (byte*)bb; b = (byte*)vv; v = (void*)i; v = (void*)b; v = (void*)ii; v = (void*)bb; v = (void*)vv; ii = (int**)i; ii = (int**)b; ii = (int**)v; ii = (int**)bb; ii = (int**)vv; bb = (byte**)i; bb = (byte**)b; bb = (byte**)v; bb = (byte**)ii; bb = (byte**)vv; vv = (void**)i; vv = (void**)b; vv = (void**)v; vv = (void**)ii; vv = (void**)bb; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ExplicitPointerNumericConversion() { var text = @" unsafe struct S { void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul) { sb = (sbyte)pi; b = (byte)pi; s = (short)pi; us = (ushort)pi; i = (int)pi; ui = (uint)pi; l = (long)pi; ul = (ulong)pi; sb = (sbyte)pv; b = (byte)pv; s = (short)pv; us = (ushort)pv; i = (int)pv; ui = (uint)pv; l = (long)pv; ul = (ulong)pv; pi = (int*)sb; pi = (int*)b; pi = (int*)s; pi = (int*)us; pi = (int*)i; pi = (int*)ui; pi = (int*)l; pi = (int*)ul; pv = (void*)sb; pv = (void*)b; pv = (void*)s; pv = (void*)us; pv = (void*)i; pv = (void*)ui; pv = (void*)l; pv = (void*)ul; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ExplicitPointerNumericConversion_Illegal() { var text = @" unsafe struct S { void M(int* pi, void* pv, bool b, char c, double d, decimal e, float f) { b = (bool)pi; c = (char)pi; d = (double)pi; e = (decimal)pi; f = (float)pi; b = (bool)pv; c = (char)pv; d = (double)pv; e = (decimal)pv; f = (float)pv; pi = (int*)b; pi = (int*)c; pi = (int*)d; pi = (int*)d; pi = (int*)f; pv = (void*)b; pv = (void*)c; pv = (void*)d; pv = (void*)e; pv = (void*)f; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,13): error CS0030: Cannot convert type 'int*' to 'bool' // b = (bool)pi; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(bool)pi").WithArguments("int*", "bool"), // (7,13): error CS0030: Cannot convert type 'int*' to 'char' // c = (char)pi; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(char)pi").WithArguments("int*", "char"), // (8,13): error CS0030: Cannot convert type 'int*' to 'double' // d = (double)pi; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(double)pi").WithArguments("int*", "double"), // (9,13): error CS0030: Cannot convert type 'int*' to 'decimal' // e = (decimal)pi; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(decimal)pi").WithArguments("int*", "decimal"), // (10,13): error CS0030: Cannot convert type 'int*' to 'float' // f = (float)pi; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(float)pi").WithArguments("int*", "float"), // (12,13): error CS0030: Cannot convert type 'void*' to 'bool' // b = (bool)pv; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(bool)pv").WithArguments("void*", "bool"), // (13,13): error CS0030: Cannot convert type 'void*' to 'char' // c = (char)pv; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(char)pv").WithArguments("void*", "char"), // (14,13): error CS0030: Cannot convert type 'void*' to 'double' // d = (double)pv; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(double)pv").WithArguments("void*", "double"), // (15,13): error CS0030: Cannot convert type 'void*' to 'decimal' // e = (decimal)pv; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(decimal)pv").WithArguments("void*", "decimal"), // (16,13): error CS0030: Cannot convert type 'void*' to 'float' // f = (float)pv; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(float)pv").WithArguments("void*", "float"), // (18,14): error CS0030: Cannot convert type 'bool' to 'int*' // pi = (int*)b; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)b").WithArguments("bool", "int*"), // (19,14): error CS0030: Cannot convert type 'char' to 'int*' // pi = (int*)c; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)c").WithArguments("char", "int*"), // (20,14): error CS0030: Cannot convert type 'double' to 'int*' // pi = (int*)d; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)d").WithArguments("double", "int*"), // (21,14): error CS0030: Cannot convert type 'double' to 'int*' // pi = (int*)d; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)d").WithArguments("double", "int*"), // (22,14): error CS0030: Cannot convert type 'float' to 'int*' // pi = (int*)f; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)f").WithArguments("float", "int*"), // (24,14): error CS0030: Cannot convert type 'bool' to 'void*' // pv = (void*)b; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)b").WithArguments("bool", "void*"), // (25,14): error CS0030: Cannot convert type 'char' to 'void*' // pv = (void*)c; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)c").WithArguments("char", "void*"), // (26,14): error CS0030: Cannot convert type 'double' to 'void*' // pv = (void*)d; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)d").WithArguments("double", "void*"), // (27,14): error CS0030: Cannot convert type 'decimal' to 'void*' // pv = (void*)e; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)e").WithArguments("decimal", "void*"), // (28,14): error CS0030: Cannot convert type 'float' to 'void*' // pv = (void*)f; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)f").WithArguments("float", "void*")); } [Fact] public void ExplicitPointerNumericConversion_Nullable() { var text = @" unsafe struct S { void M(int* pi, void* pv, sbyte? sb, byte? b, short? s, ushort? us, int? i, uint? ui, long? l, ulong? ul) { sb = (sbyte?)pi; b = (byte?)pi; s = (short?)pi; us = (ushort?)pi; i = (int?)pi; ui = (uint?)pi; l = (long?)pi; ul = (ulong?)pi; sb = (sbyte?)pv; b = (byte?)pv; s = (short?)pv; us = (ushort?)pv; i = (int?)pv; ui = (uint?)pv; l = (long?)pv; ul = (ulong?)pv; pi = (int*)sb; pi = (int*)b; pi = (int*)s; pi = (int*)us; pi = (int*)i; pi = (int*)ui; pi = (int*)l; pi = (int*)ul; pv = (void*)sb; pv = (void*)b; pv = (void*)s; pv = (void*)us; pv = (void*)i; pv = (void*)ui; pv = (void*)l; pv = (void*)ul; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (24,14): error CS0030: Cannot convert type 'sbyte?' to 'int*' // pi = (int*)sb; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)sb").WithArguments("sbyte?", "int*"), // (25,14): error CS0030: Cannot convert type 'byte?' to 'int*' // pi = (int*)b; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)b").WithArguments("byte?", "int*"), // (26,14): error CS0030: Cannot convert type 'short?' to 'int*' // pi = (int*)s; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)s").WithArguments("short?", "int*"), // (27,14): error CS0030: Cannot convert type 'ushort?' to 'int*' // pi = (int*)us; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)us").WithArguments("ushort?", "int*"), // (28,14): error CS0030: Cannot convert type 'int?' to 'int*' // pi = (int*)i; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)i").WithArguments("int?", "int*"), // (29,14): error CS0030: Cannot convert type 'uint?' to 'int*' // pi = (int*)ui; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)ui").WithArguments("uint?", "int*"), // (30,14): error CS0030: Cannot convert type 'long?' to 'int*' // pi = (int*)l; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)l").WithArguments("long?", "int*"), // (31,14): error CS0030: Cannot convert type 'ulong?' to 'int*' // pi = (int*)ul; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)ul").WithArguments("ulong?", "int*"), // (33,14): error CS0030: Cannot convert type 'sbyte?' to 'void*' // pv = (void*)sb; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)sb").WithArguments("sbyte?", "void*"), // (34,14): error CS0030: Cannot convert type 'byte?' to 'void*' // pv = (void*)b; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)b").WithArguments("byte?", "void*"), // (35,14): error CS0030: Cannot convert type 'short?' to 'void*' // pv = (void*)s; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)s").WithArguments("short?", "void*"), // (36,14): error CS0030: Cannot convert type 'ushort?' to 'void*' // pv = (void*)us; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)us").WithArguments("ushort?", "void*"), // (37,14): error CS0030: Cannot convert type 'int?' to 'void*' // pv = (void*)i; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)i").WithArguments("int?", "void*"), // (38,14): error CS0030: Cannot convert type 'uint?' to 'void*' // pv = (void*)ui; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)ui").WithArguments("uint?", "void*"), // (39,14): error CS0030: Cannot convert type 'long?' to 'void*' // pv = (void*)l; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)l").WithArguments("long?", "void*"), // (40,14): error CS0030: Cannot convert type 'ulong?' to 'void*' // pv = (void*)ul; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(void*)ul").WithArguments("ulong?", "void*")); } [Fact] public void PointerArrayConversion() { var text = @" using System; unsafe class C { void M(int*[] api, void*[] apv, Array a) { a = api; a.GetValue(0); //runtime error a = apv; a.GetValue(0); //runtime error api = a; //CS0266 apv = a; //CS0266 api = (int*[])a; apv = (void*[])a; apv = api; //CS0029 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (13,15): error CS0266: Cannot implicitly convert type 'System.Array' to 'int*[]'. An explicit conversion exists (are you missing a cast?) // api = a; //CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("System.Array", "int*[]"), // (14,15): error CS0266: Cannot implicitly convert type 'System.Array' to 'void*[]'. An explicit conversion exists (are you missing a cast?) // apv = a; //CS0266 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("System.Array", "void*[]"), // (19,15): error CS0029: Cannot implicitly convert type 'int*[]' to 'void*[]' // apv = api; //CS0029 Diagnostic(ErrorCode.ERR_NoImplicitConv, "api").WithArguments("int*[]", "void*[]")); } [Fact] public void PointerArrayToListConversion() { var text = @" using System.Collections.Generic; unsafe class C { void M(int*[] api, void*[] apv) { To(api); To(apv); api = From(api[0]); apv = From(apv[0]); } void To<T>(IList<T> list) { } IList<T> From<T>(T t) { return null; } } "; // NOTE: dev10 also reports some rather silly cascading CS0266s. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,9): error CS0306: The type 'int*' may not be used as a type argument // To(api); Diagnostic(ErrorCode.ERR_BadTypeArgument, "To").WithArguments("int*"), // (9,9): error CS0306: The type 'void*' may not be used as a type argument // To(apv); Diagnostic(ErrorCode.ERR_BadTypeArgument, "To").WithArguments("void*"), // (11,15): error CS0306: The type 'int*' may not be used as a type argument // api = From(api[0]); Diagnostic(ErrorCode.ERR_BadTypeArgument, "From").WithArguments("int*"), // (12,15): error CS0306: The type 'void*' may not be used as a type argument // apv = From(apv[0]); Diagnostic(ErrorCode.ERR_BadTypeArgument, "From").WithArguments("void*")); } [Fact] public void PointerArrayToEnumerableConversion() { var text = @" using System.Collections; unsafe class C { void M(int*[] api, void*[] apv) { IEnumerable e = api; e = apv; } } "; // NOTE: as in Dev10, there's a runtime error if you try to access an element. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } #endregion Pointer conversion tests #region Pointer arithmetic tests [Fact] public void PointerArithmetic_LegalNumeric() { var text = @" unsafe class C { void M(byte* p, int i, uint ui, long l, ulong ul) { p = p + i; p = i + p; p = p - i; p = p + ui; p = ui + p; p = p - ui; p = p + l; p = l + p; p = p - l; p = p + ul; p = ul + p; p = p - ul; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); var methodSymbol = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("M"); var pointerType = methodSymbol.Parameters[0].Type; Assert.Equal(TypeKind.Pointer, pointerType.TypeKind); foreach (var binOpSyntax in tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>()) { var summary = model.GetSemanticInfoSummary(binOpSyntax); if (binOpSyntax.Kind() == SyntaxKind.SimpleAssignmentExpression) { Assert.Null(summary.Symbol); } else { Assert.NotNull(summary.Symbol); Assert.Equal(MethodKind.BuiltinOperator, ((MethodSymbol)summary.Symbol).MethodKind); } Assert.Equal(0, summary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, summary.CandidateReason); Assert.Equal(pointerType, summary.Type); Assert.Equal(pointerType, summary.ConvertedType); Assert.Equal(Conversion.Identity, summary.ImplicitConversion); Assert.Equal(0, summary.MethodGroup.Length); Assert.Null(summary.Alias); Assert.False(summary.IsCompileTimeConstant); Assert.False(summary.ConstantValue.HasValue); } } [Fact] public void PointerArithmetic_LegalPointer() { var text = @" unsafe class C { void M(byte* p) { var diff = p - p; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); foreach (var binOpSyntax in tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>()) { var summary = model.GetSemanticInfoSummary(binOpSyntax); Assert.Equal("System.Int64 System.Byte*.op_Subtraction(System.Byte* left, System.Byte* right)", summary.Symbol.ToTestDisplayString()); Assert.Equal(0, summary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, summary.CandidateReason); Assert.Equal(SpecialType.System_Int64, summary.Type.SpecialType); Assert.Equal(SpecialType.System_Int64, summary.ConvertedType.SpecialType); Assert.Equal(Conversion.Identity, summary.ImplicitConversion); Assert.Equal(0, summary.MethodGroup.Length); Assert.Null(summary.Alias); Assert.False(summary.IsCompileTimeConstant); Assert.False(summary.ConstantValue.HasValue); } } [Fact] public void PointerArithmetic_IllegalNumericSubtraction() { var text = @" unsafe class C { void M(byte* p, int i, uint ui, long l, ulong ul) { p = i - p; p = ui - p; p = l - p; p = ul - p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,13): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'byte*' // p = i - p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - p").WithArguments("-", "int", "byte*"), // (7,13): error CS0019: Operator '-' cannot be applied to operands of type 'uint' and 'byte*' // p = ui - p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "ui - p").WithArguments("-", "uint", "byte*"), // (8,13): error CS0019: Operator '-' cannot be applied to operands of type 'long' and 'byte*' // p = l - p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "l - p").WithArguments("-", "long", "byte*"), // (9,13): error CS0019: Operator '-' cannot be applied to operands of type 'ulong' and 'byte*' // p = ul - p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "ul - p").WithArguments("-", "ulong", "byte*")); } [Fact] public void PointerArithmetic_IllegalPointerSubtraction() { var text = @" unsafe class C { void M(byte* b, int* i, byte** bb, int** ii) { long l; l = b - i; l = b - bb; l = b - ii; l = i - b; l = i - bb; l = i - ii; l = bb - b; l = bb - i; l = bb - ii; l = ii - b; l = ii - i; l = ii - bb; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte*' and 'int*' // l = b - i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "b - i").WithArguments("-", "byte*", "int*"), // (9,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte*' and 'byte**' // l = b - bb; Diagnostic(ErrorCode.ERR_BadBinaryOps, "b - bb").WithArguments("-", "byte*", "byte**"), // (10,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte*' and 'int**' // l = b - ii; Diagnostic(ErrorCode.ERR_BadBinaryOps, "b - ii").WithArguments("-", "byte*", "int**"), // (12,13): error CS0019: Operator '-' cannot be applied to operands of type 'int*' and 'byte*' // l = i - b; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - b").WithArguments("-", "int*", "byte*"), // (13,13): error CS0019: Operator '-' cannot be applied to operands of type 'int*' and 'byte**' // l = i - bb; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - bb").WithArguments("-", "int*", "byte**"), // (14,13): error CS0019: Operator '-' cannot be applied to operands of type 'int*' and 'int**' // l = i - ii; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i - ii").WithArguments("-", "int*", "int**"), // (16,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte**' and 'byte*' // l = bb - b; Diagnostic(ErrorCode.ERR_BadBinaryOps, "bb - b").WithArguments("-", "byte**", "byte*"), // (17,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte**' and 'int*' // l = bb - i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "bb - i").WithArguments("-", "byte**", "int*"), // (18,13): error CS0019: Operator '-' cannot be applied to operands of type 'byte**' and 'int**' // l = bb - ii; Diagnostic(ErrorCode.ERR_BadBinaryOps, "bb - ii").WithArguments("-", "byte**", "int**"), // (20,13): error CS0019: Operator '-' cannot be applied to operands of type 'int**' and 'byte*' // l = ii - b; Diagnostic(ErrorCode.ERR_BadBinaryOps, "ii - b").WithArguments("-", "int**", "byte*"), // (21,13): error CS0019: Operator '-' cannot be applied to operands of type 'int**' and 'int*' // l = ii - i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "ii - i").WithArguments("-", "int**", "int*"), // (22,13): error CS0019: Operator '-' cannot be applied to operands of type 'int**' and 'byte**' // l = ii - bb; Diagnostic(ErrorCode.ERR_BadBinaryOps, "ii - bb").WithArguments("-", "int**", "byte**")); } [Fact] public void PointerArithmetic_OtherOperators() { var text = @" unsafe class C { void M(byte* p, int i) { var r01 = p * i; var r02 = i * p; var r03 = p / i; var r04 = i / p; var r05 = p % i; var r06 = i % p; var r07 = p << i; var r08 = i << p; var r09 = p >> i; var r10 = i >> p; var r11 = p & i; var r12 = i & p; var r13 = p | i; var r14 = i | p; var r15 = p ^ i; var r16 = i ^ p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,19): error CS0019: Operator '*' cannot be applied to operands of type 'byte*' and 'int' // var r01 = p * i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p * i").WithArguments("*", "byte*", "int"), // (7,19): error CS0019: Operator '*' cannot be applied to operands of type 'int' and 'byte*' // var r02 = i * p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i * p").WithArguments("*", "int", "byte*"), // (8,19): error CS0019: Operator '/' cannot be applied to operands of type 'byte*' and 'int' // var r03 = p / i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p / i").WithArguments("/", "byte*", "int"), // (9,19): error CS0019: Operator '/' cannot be applied to operands of type 'int' and 'byte*' // var r04 = i / p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i / p").WithArguments("/", "int", "byte*"), // (10,19): error CS0019: Operator '%' cannot be applied to operands of type 'byte*' and 'int' // var r05 = p % i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p % i").WithArguments("%", "byte*", "int"), // (11,19): error CS0019: Operator '%' cannot be applied to operands of type 'int' and 'byte*' // var r06 = i % p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i % p").WithArguments("%", "int", "byte*"), // (12,19): error CS0019: Operator '<<' cannot be applied to operands of type 'byte*' and 'int' // var r07 = p << i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p << i").WithArguments("<<", "byte*", "int"), // (13,19): error CS0019: Operator '<<' cannot be applied to operands of type 'int' and 'byte*' // var r08 = i << p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i << p").WithArguments("<<", "int", "byte*"), // (14,19): error CS0019: Operator '>>' cannot be applied to operands of type 'byte*' and 'int' // var r09 = p >> i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >> i").WithArguments(">>", "byte*", "int"), // (15,19): error CS0019: Operator '>>' cannot be applied to operands of type 'int' and 'byte*' // var r10 = i >> p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i >> p").WithArguments(">>", "int", "byte*"), // (16,19): error CS0019: Operator '&' cannot be applied to operands of type 'byte*' and 'int' // var r11 = p & i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p & i").WithArguments("&", "byte*", "int"), // (17,19): error CS0019: Operator '&' cannot be applied to operands of type 'int' and 'byte*' // var r12 = i & p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i & p").WithArguments("&", "int", "byte*"), // (18,19): error CS0019: Operator '|' cannot be applied to operands of type 'byte*' and 'int' // var r13 = p | i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p | i").WithArguments("|", "byte*", "int"), // (19,19): error CS0019: Operator '|' cannot be applied to operands of type 'int' and 'byte*' // var r14 = i | p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i | p").WithArguments("|", "int", "byte*"), // (20,19): error CS0019: Operator '^' cannot be applied to operands of type 'byte*' and 'int' // var r15 = p ^ i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p ^ i").WithArguments("^", "byte*", "int"), // (21,19): error CS0019: Operator '^' cannot be applied to operands of type 'int' and 'byte*' // var r16 = i ^ p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "i ^ p").WithArguments("^", "int", "byte*")); } [Fact] public void PointerArithmetic_NumericWidening() { var text = @" unsafe class C { void M(int* p, sbyte sb, byte b, short s, ushort us) { p = p + sb; p = p + b; p = p + s; p = p + us; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void PointerArithmetic_NumericUDC() { var text = @" unsafe class C { void M(int* p) { p = p + this; } public static implicit operator int(C c) { return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void PointerArithmetic_Nullable() { var text = @" unsafe class C { void M(int* p, int? i) { p = p + i; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,13): error CS0019: Operator '+' cannot be applied to operands of type 'int*' and 'int?' // p = p + i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p + i").WithArguments("+", "int*", "int?")); } [Fact] public void PointerArithmetic_Compound() { var text = @" unsafe class C { void M(int* p, int i) { p++; ++p; p--; --p; p += i; p -= i; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void PointerArithmetic_VoidPointer() { var text = @" unsafe class C { void M(void* p) { var diff = p - p; p = p + 1; p = p - 1; p = 1 + p; p = 1 - p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS0242: The operation in question is undefined on void pointers // var diff = p - p; Diagnostic(ErrorCode.ERR_VoidError, "p - p"), // (7,13): error CS0242: The operation in question is undefined on void pointers // p = p + 1; Diagnostic(ErrorCode.ERR_VoidError, "p + 1"), // (8,13): error CS0242: The operation in question is undefined on void pointers // p = p - 1; Diagnostic(ErrorCode.ERR_VoidError, "p - 1"), // (9,13): error CS0242: The operation in question is undefined on void pointers // p = 1 + p; Diagnostic(ErrorCode.ERR_VoidError, "1 + p"), // (10,13): error CS0242: The operation in question is undefined on void pointers // p = 1 - p; Diagnostic(ErrorCode.ERR_VoidError, "1 - p"), // (10,13): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'void*' // p = 1 - p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 - p").WithArguments("-", "int", "void*")); } [Fact] public void PointerArithmetic_VoidPointerPointer() { var text = @" unsafe class C { void M(void** p) //void** is not a void pointer { var diff = p - p; p = p + 1; p = p - 1; p = 1 + p; p = 1 - p; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (10,13): error CS0019: Operator '-' cannot be applied to operands of type 'int' and 'void**' // p = 1 - p; Diagnostic(ErrorCode.ERR_BadBinaryOps, "1 - p").WithArguments("-", "int", "void**")); } #endregion Pointer arithmetic tests #region Pointer comparison tests [WorkItem(546712, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546712")] [Fact] public void PointerComparison_Null() { // We had a bug whereby overload resolution was failing if the null // was on the left. This test regresses the bug. var text = @" unsafe struct S { bool M(byte* pb, S* ps) { return null != pb && null == ps; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void PointerComparison_Pointer() { var text = @" unsafe class C { void M(byte* b, int* i, void* v) { bool result; byte* b2 = b; int* i2 = i; void* v2 = v; result = b == b2; result = b == i2; result = b == v2; result = i != i2; result = i != v2; result = i != b2; result = v <= v2; result = v <= b2; result = v <= i2; result = b >= b2; result = b >= i2; result = b >= v2; result = i < i2; result = i < v2; result = i < b2; result = v > v2; result = v > b2; result = v > i2; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); foreach (var binOpSyntax in tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>()) { var summary = model.GetSemanticInfoSummary(binOpSyntax); if (binOpSyntax.Kind() == SyntaxKind.SimpleAssignmentExpression) { Assert.Null(summary.Symbol); } else { Assert.NotNull(summary.Symbol); Assert.Equal(MethodKind.BuiltinOperator, ((MethodSymbol)summary.Symbol).MethodKind); } Assert.Equal(0, summary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, summary.CandidateReason); Assert.Equal(SpecialType.System_Boolean, summary.Type.SpecialType); Assert.Equal(SpecialType.System_Boolean, summary.ConvertedType.SpecialType); Assert.Equal(Conversion.Identity, summary.ImplicitConversion); Assert.Equal(0, summary.MethodGroup.Length); Assert.Null(summary.Alias); Assert.False(summary.IsCompileTimeConstant); Assert.False(summary.ConstantValue.HasValue); } } [Fact] public void PointerComparison_PointerPointer() { var text = @" unsafe class C { void M(byte* b, byte** bb) { bool result; result = b == bb; result = b != bb; result = b <= bb; result = b >= bb; result = b < bb; result = b > bb; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void PointerComparison_Numeric() { var text = @" unsafe class C { void M(char* p, int i, uint ui, long l, ulong ul) { bool result; result = p == i; result = p != i; result = p <= i; result = p >= i; result = p < i; result = p > i; result = p == ui; result = p != ui; result = p <= ui; result = p >= ui; result = p < ui; result = p > ui; result = p == l; result = p != l; result = p <= l; result = p >= l; result = p < l; result = p > l; result = p == ul; result = p != ul; result = p <= ul; result = p >= ul; result = p < ul; result = p > ul; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'int' // result = p == i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == i").WithArguments("==", "char*", "int"), // (9,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'int' // result = p != i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != i").WithArguments("!=", "char*", "int"), // (10,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'int' // result = p <= i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= i").WithArguments("<=", "char*", "int"), // (11,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'int' // result = p >= i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= i").WithArguments(">=", "char*", "int"), // (12,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'int' // result = p < i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < i").WithArguments("<", "char*", "int"), // (13,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'int' // result = p > i; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > i").WithArguments(">", "char*", "int"), // (15,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'uint' // result = p == ui; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == ui").WithArguments("==", "char*", "uint"), // (16,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'uint' // result = p != ui; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != ui").WithArguments("!=", "char*", "uint"), // (17,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'uint' // result = p <= ui; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= ui").WithArguments("<=", "char*", "uint"), // (18,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'uint' // result = p >= ui; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= ui").WithArguments(">=", "char*", "uint"), // (19,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'uint' // result = p < ui; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < ui").WithArguments("<", "char*", "uint"), // (20,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'uint' // result = p > ui; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > ui").WithArguments(">", "char*", "uint"), // (22,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'long' // result = p == l; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == l").WithArguments("==", "char*", "long"), // (23,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'long' // result = p != l; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != l").WithArguments("!=", "char*", "long"), // (24,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'long' // result = p <= l; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= l").WithArguments("<=", "char*", "long"), // (25,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'long' // result = p >= l; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= l").WithArguments(">=", "char*", "long"), // (26,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'long' // result = p < l; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < l").WithArguments("<", "char*", "long"), // (27,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'long' // result = p > l; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > l").WithArguments(">", "char*", "long"), // (29,18): error CS0019: Operator '==' cannot be applied to operands of type 'char*' and 'ulong' // result = p == ul; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p == ul").WithArguments("==", "char*", "ulong"), // (30,18): error CS0019: Operator '!=' cannot be applied to operands of type 'char*' and 'ulong' // result = p != ul; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p != ul").WithArguments("!=", "char*", "ulong"), // (31,18): error CS0019: Operator '<=' cannot be applied to operands of type 'char*' and 'ulong' // result = p <= ul; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p <= ul").WithArguments("<=", "char*", "ulong"), // (32,18): error CS0019: Operator '>=' cannot be applied to operands of type 'char*' and 'ulong' // result = p >= ul; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p >= ul").WithArguments(">=", "char*", "ulong"), // (33,18): error CS0019: Operator '<' cannot be applied to operands of type 'char*' and 'ulong' // result = p < ul; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p < ul").WithArguments("<", "char*", "ulong"), // (34,18): error CS0019: Operator '>' cannot be applied to operands of type 'char*' and 'ulong' // result = p > ul; Diagnostic(ErrorCode.ERR_BadBinaryOps, "p > ul").WithArguments(">", "char*", "ulong")); } #endregion Pointer comparison tests #region Fixed statement diagnostics [Fact] public void ERR_BadFixedInitType() { var text = @" unsafe class C { int x; void M() { fixed (int p = &x) //not a pointer { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,20): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int p = &x) //not a pointer Diagnostic(ErrorCode.ERR_BadFixedInitType, "p = &x")); } [Fact] public void ERR_FixedMustInit() { var text = @" unsafe class C { void M() { fixed (int* p) //missing initializer { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,21): error CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (int* p) //missing initializer Diagnostic(ErrorCode.ERR_FixedMustInit, "p")); } [Fact] public void ERR_ImplicitlyTypedLocalCannotBeFixed1() { var text = @" unsafe class C { int x; void M() { fixed (var p = &x) //implicitly typed { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,20): error CS0821: Implicitly-typed local variables cannot be fixed // fixed (var p = &x) //implicitly typed Diagnostic(ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, "p = &x")); } [Fact] public void ERR_ImplicitlyTypedLocalCannotBeFixed2() { var text = @" unsafe class C { int x; void M() { fixed (var p = &x) //not implicitly typed { } } } class var { } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,20): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (var p = &x) //not implicitly typed Diagnostic(ErrorCode.ERR_BadFixedInitType, "p = &x")); } [Fact] public void ERR_MultiTypeInDeclaration() { var text = @" unsafe class C { int x; void M() { fixed (int* p = &x, var q = p) //multiple declarations (vs declarators) { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,29): error CS1044: Cannot use more than one type in a for, using, fixed, or declaration statement // fixed (int* p = &x, var q = p) //multiple declarations (vs declarators) Diagnostic(ErrorCode.ERR_MultiTypeInDeclaration, "var"), // (8,33): error CS1026: ) expected // fixed (int* p = &x, var q = p) //multiple declarations (vs declarators) Diagnostic(ErrorCode.ERR_CloseParenExpected, "q"), // (8,38): error CS1002: ; expected // fixed (int* p = &x, var q = p) //multiple declarations (vs declarators) Diagnostic(ErrorCode.ERR_SemicolonExpected, ")"), // (8,38): error CS1513: } expected // fixed (int* p = &x, var q = p) //multiple declarations (vs declarators) Diagnostic(ErrorCode.ERR_RbraceExpected, ")"), // (8,29): error CS0210: You must provide an initializer in a fixed or using statement declaration // fixed (int* p = &x, var q = p) //multiple declarations (vs declarators) Diagnostic(ErrorCode.ERR_FixedMustInit, "var"), // (8,33): error CS0103: The name 'q' does not exist in the current context // fixed (int* p = &x, var q = p) //multiple declarations (vs declarators) Diagnostic(ErrorCode.ERR_NameNotInContext, "q").WithArguments("q")); } [Fact] public void ERR_BadCastInFixed_String() { var text = @" unsafe class C { public NotString n; void M() { fixed (char* p = (string)""hello"") { } fixed (char* p = (string)n) { } } } class NotString { unsafe public static implicit operator string(NotString n) { return null; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,22): warning CS0649: Field 'C.n' is never assigned to, and will always have its default value null // public NotString n; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "n").WithArguments("C.n", "null")); } [Fact] public void ERR_BadCastInFixed_Array() { var text = @" unsafe class C { public NotArray n; void M() { fixed (byte* p = (byte[])new byte[0]) { } fixed (int* p = (int[])n) { } } } class NotArray { unsafe public static implicit operator int[](NotArray n) { return null; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,21): warning CS0649: Field 'C.n' is never assigned to, and will always have its default value null // public NotArray n; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "n").WithArguments("C.n", "null")); } [Fact] public void ERR_BadCastInFixed_Pointer() { var text = @" unsafe class C { public byte x; public NotPointer n; void M() { fixed (byte* p = (byte*)&x) { } fixed (int* p = n) //CS0213 (confusing, but matches dev10) { } fixed (int* p = (int*)n) { } } } class NotPointer { unsafe public static implicit operator int*(NotPointer n) { return null; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (byte* p = (byte*)&x) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(byte*)&x").WithLocation(9, 26), // (13,25): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* p = n) //CS0213 (confusing, but matches dev10) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "n").WithLocation(13, 25), // (17,25): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* p = (int*)n) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(int*)n").WithLocation(17, 25), // (5,23): warning CS0649: Field 'C.n' is never assigned to, and will always have its default value null // public NotPointer n; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "n").WithArguments("C.n", "null").WithLocation(5, 23) ); } [Fact] public void ERR_FixedLocalInLambda() { var text = @" using System; unsafe class C { char c = 'a'; char[] a = new char[1]; static void Main() { C c = new C(); fixed (char* p = &c.c, q = c.a, r = ""hello"") { System.Action a; a = () => Console.WriteLine(*p); a = () => Console.WriteLine(*q); a = () => Console.WriteLine(*r); } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (15,42): error CS1764: Cannot use fixed local 'p' inside an anonymous method, lambda expression, or query expression // a = () => Console.WriteLine(*p); Diagnostic(ErrorCode.ERR_FixedLocalInLambda, "p").WithArguments("p"), // (16,42): error CS1764: Cannot use fixed local 'q' inside an anonymous method, lambda expression, or query expression // a = () => Console.WriteLine(*q); Diagnostic(ErrorCode.ERR_FixedLocalInLambda, "q").WithArguments("q"), // (17,42): error CS1764: Cannot use fixed local 'r' inside an anonymous method, lambda expression, or query expression // a = () => Console.WriteLine(*r); Diagnostic(ErrorCode.ERR_FixedLocalInLambda, "r").WithArguments("r")); } [Fact] public void NormalAddressOfInFixedStatement() { var text = @" class Program { int x; int[] a; unsafe static void Main() { Program p = new Program(); int q; fixed (int* px = (&(p.a[*(&q)]))) //fine { } fixed (int* px = &(p.a[*(&p.x)])) //CS0212 { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (15,34): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // fixed (int* px = &(p.a[*(&p.x)])) //CS0212 Diagnostic(ErrorCode.ERR_FixedNeeded, "&p.x"), // (5,11): warning CS0649: Field 'Program.a' is never assigned to, and will always have its default value null // int[] a; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "a").WithArguments("Program.a", "null")); } [Fact] public void StackAllocInFixedStatement() { var text = @" class Program { unsafe static void Main() { fixed (int* p = stackalloc int[2]) //CS0213 - already fixed { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,25): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* p = stackalloc int[2]) //CS0213 - already fixed Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int[2]").WithLocation(6, 25)); } [Fact] public void FixedInitializerRefersToPreviousVariable() { var text = @" unsafe class C { int f; int[] a; void Goo() { fixed (int* q = &f, r = &q[1]) //CS0213 { } fixed (int* q = &f, r = &a[*q]) //fine { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,33): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int* q = &f, r = &q[1]) //CS0213 Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&q[1]"), // (5,11): warning CS0649: Field 'C.a' is never assigned to, and will always have its default value null // int[] a; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "a").WithArguments("C.a", "null")); } [Fact] public void NormalInitializerType_Null() { var text = @" class Program { unsafe static void Main() { fixed (int* p = null) { } fixed (int* p = &null) { } fixed (int* p = _) { } fixed (int* p = &_) { } fixed (int* p = ()=>throw null) { } fixed (int* p = &(()=>throw null)) { } } } "; // Confusing, but matches Dev10. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,25): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* p = null) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "null").WithLocation(6, 25), // (10,26): error CS0211: Cannot take the address of the given expression // fixed (int* p = &null) Diagnostic(ErrorCode.ERR_InvalidAddrOp, "null").WithLocation(10, 26), // (14,25): error CS0103: The name '_' does not exist in the current context // fixed (int* p = _) Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(14, 25), // (18,26): error CS0103: The name '_' does not exist in the current context // fixed (int* p = &_) Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(18, 26), // (22,25): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* p = ()=>throw null) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "()=>throw null").WithLocation(22, 25), // (26,27): error CS0211: Cannot take the address of the given expression // fixed (int* p = &(()=>throw null)) Diagnostic(ErrorCode.ERR_InvalidAddrOp, "()=>throw null").WithLocation(26, 27) ); } [Fact] public void NormalInitializerType_Lambda() { var text = @" class Program { unsafe static void Main() { fixed (int* p = (x => x)) { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* p = (x => x)) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "x => x").WithLocation(6, 26)); } [Fact] public void NormalInitializerType_MethodGroup() { var text = @" class Program { unsafe static void Main() { fixed (int* p = Main) { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,25): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* p = Main) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "Main").WithLocation(6, 25)); } [Fact] public void NormalInitializerType_String() { var text = @" class Program { unsafe static void Main() { string s = ""hello""; fixed (char* p = s) //fine { } fixed (void* p = s) //fine { } fixed (int* p = s) //can't convert char* to int* { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (16,25): error CS0266: Cannot implicitly convert type 'char*' to 'int*'. An explicit conversion exists (are you missing a cast?) // fixed (int* p = s) //can't convert char* to int* Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "s").WithArguments("char*", "int*")); } [Fact] public void NormalInitializerType_ArrayOfManaged() { var text = @" class Program { unsafe static void Main() { string[] a = new string[2]; fixed (void* p = a) //string* is not a valid type { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // fixed (void* p = a) Diagnostic(ErrorCode.ERR_ManagedAddr, "a").WithArguments("string")); } [Fact] public void NormalInitializerType_Array() { var text = @" class Program { unsafe static void Main() { char[] a = new char[2]; fixed (char* p = a) //fine { } fixed (void* p = a) //fine { } fixed (int* p = a) //can't convert char* to int* { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (16,25): error CS0266: Cannot implicitly convert type 'char*' to 'int*'. An explicit conversion exists (are you missing a cast?) // fixed (int* p = a) //can't convert char* to int* Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("char*", "int*")); } [Fact] public void NormalInitializerType_MultiDimensionalArray() { var text = @" class Program { unsafe static void Main() { char[,] a = new char[2,2]; fixed (char* p = a) //fine { } fixed (void* p = a) //fine { } fixed (int* p = a) //can't convert char* to int* { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (16,25): error CS0266: Cannot implicitly convert type 'char*' to 'int*'. An explicit conversion exists (are you missing a cast?) // fixed (int* p = a) //can't convert char* to int* Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("char*", "int*")); } [Fact] public void NormalInitializerType_JaggedArray() { var text = @" class Program { unsafe static void Main() { char[][] a = new char[2][]; fixed (void* p = a) //char[]* is not a valid type { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('char[]') // fixed (void* p = a) //char[]* is not a valid type Diagnostic(ErrorCode.ERR_ManagedAddr, "a").WithArguments("char[]")); } #endregion Fixed statement diagnostics #region Fixed statement semantic model tests [Fact] public void FixedSemanticModelDeclaredSymbols() { var text = @" using System; unsafe class C { char c = 'a'; char[] a = new char[1]; static void Main() { C c = new C(); fixed (char* p = &c.c, q = c.a, r = ""hello"") { } } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var declarators = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Reverse().Take(3).Reverse().ToArray(); var declaredSymbols = declarators.Select(syntax => (LocalSymbol)model.GetDeclaredSymbol(syntax)).ToArray(); foreach (var symbol in declaredSymbols) { Assert.NotNull(symbol); Assert.Equal(LocalDeclarationKind.FixedVariable, symbol.DeclarationKind); Assert.True(((ILocalSymbol)symbol).IsFixed); TypeSymbol type = symbol.Type; Assert.Equal(TypeKind.Pointer, type.TypeKind); Assert.Equal(SpecialType.System_Char, ((PointerTypeSymbol)type).PointedAtType.SpecialType); } } [Fact] public void FixedSemanticModelSymbolInfo() { var text = @" using System; unsafe class C { char c = 'a'; char[] a = new char[1]; static void Main() { C c = new C(); fixed (char* p = &c.c, q = c.a, r = ""hello"") { Console.WriteLine(*p); Console.WriteLine(*q); Console.WriteLine(*r); } } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var stringSymbol = compilation.GetSpecialType(SpecialType.System_String); var charSymbol = compilation.GetSpecialType(SpecialType.System_Char); var charPointerSymbol = new PointerTypeSymbol(charSymbol); const int numSymbols = 3; var declarators = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Reverse().Take(numSymbols).Reverse().ToArray(); var dereferences = tree.GetCompilationUnitRoot().DescendantNodes().Where(syntax => syntax.IsKind(SyntaxKind.PointerIndirectionExpression)).ToArray(); Assert.Equal(numSymbols, dereferences.Length); var declaredSymbols = declarators.Select(syntax => (LocalSymbol)model.GetDeclaredSymbol(syntax)).ToArray(); var initializerSummaries = declarators.Select(syntax => model.GetSemanticInfoSummary(syntax.Initializer.Value)).ToArray(); for (int i = 0; i < numSymbols; i++) { var summary = initializerSummaries[i]; Assert.Equal(0, summary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, summary.CandidateReason); Assert.Equal(charPointerSymbol, summary.ConvertedType); Assert.Equal(Conversion.Identity, summary.ImplicitConversion); Assert.Equal(0, summary.MethodGroup.Length); Assert.Null(summary.Alias); } var summary0 = initializerSummaries[0]; Assert.Null(summary0.Symbol); Assert.Equal(charPointerSymbol, summary0.Type); var summary1 = initializerSummaries[1]; var arraySymbol = compilation.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<FieldSymbol>("a"); Assert.Equal(arraySymbol, summary1.Symbol); Assert.Equal(arraySymbol.Type, summary1.Type); var summary2 = initializerSummaries[2]; Assert.Null(summary2.Symbol); Assert.Equal(stringSymbol, summary2.Type); var accessSymbolInfos = dereferences.Select(syntax => model.GetSymbolInfo(((PrefixUnaryExpressionSyntax)syntax).Operand)).ToArray(); for (int i = 0; i < numSymbols; i++) { SymbolInfo info = accessSymbolInfos[i]; Assert.Equal(declaredSymbols[i], info.Symbol); Assert.Equal(0, info.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, info.CandidateReason); } } [Fact] public void FixedSemanticModelSymbolInfoConversions() { var text = @" using System; unsafe class C { char c = 'a'; char[] a = new char[1]; static void Main() { C c = new C(); fixed (void* p = &c.c, q = c.a, r = ""hello"") { } } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var stringSymbol = compilation.GetSpecialType(SpecialType.System_String); var charSymbol = compilation.GetSpecialType(SpecialType.System_Char); var charPointerSymbol = new PointerTypeSymbol(charSymbol); var voidSymbol = compilation.GetSpecialType(SpecialType.System_Void); var voidPointerSymbol = new PointerTypeSymbol(voidSymbol); const int numSymbols = 3; var declarators = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Reverse().Take(numSymbols).Reverse().ToArray(); var initializerSummaries = declarators.Select(syntax => model.GetSemanticInfoSummary(syntax.Initializer.Value)).ToArray(); for (int i = 0; i < numSymbols; i++) { var summary = initializerSummaries[i]; Assert.Equal(0, summary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, summary.CandidateReason); Assert.Equal(0, summary.MethodGroup.Length); Assert.Null(summary.Alias); } var summary0 = initializerSummaries[0]; Assert.Null(summary0.Symbol); Assert.Equal(charPointerSymbol, summary0.Type); Assert.Equal(voidPointerSymbol, summary0.ConvertedType); Assert.Equal(Conversion.PointerToVoid, summary0.ImplicitConversion); var summary1 = initializerSummaries[1]; var arraySymbol = compilation.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<FieldSymbol>("a"); Assert.Equal(arraySymbol, summary1.Symbol); Assert.Equal(arraySymbol.Type, summary1.Type); Assert.Equal(voidPointerSymbol, summary1.ConvertedType); Assert.Equal(Conversion.PointerToVoid, summary1.ImplicitConversion); var summary2 = initializerSummaries[2]; Assert.Null(summary2.Symbol); Assert.Equal(stringSymbol, summary2.Type); Assert.Equal(voidPointerSymbol, summary2.ConvertedType); Assert.Equal(Conversion.PointerToVoid, summary2.ImplicitConversion); } #endregion Fixed statement semantic model tests #region sizeof diagnostic tests [Fact] public void SizeOfManaged() { var text = @" unsafe class C { void M<T>(T t) { int x; x = sizeof(T); //CS0208 x = sizeof(C); //CS0208 x = sizeof(S); //CS0208 } } public struct S { public string s; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T') // x = sizeof(T); //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(T)").WithArguments("T"), // (8,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C') // x = sizeof(C); //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(C)").WithArguments("C"), // (9,13): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // x = sizeof(S); //CS0208 Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(S)").WithArguments("S")); } [Fact] public void SizeOfUnsafe1() { var template = @" {0} struct S {{ {1} void M() {{ int x; x = sizeof(S); // Type isn't unsafe, but expression is. }} }} "; CompareUnsafeDiagnostics(template, // (7,13): error CS0233: 'S' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // x = sizeof(S); Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(S)").WithArguments("S")); } [Fact] public void SizeOfUnsafe2() { var template = @" {0} class C {{ {1} void M() {{ int x; x = sizeof(int*); x = sizeof(int**); x = sizeof(void*); x = sizeof(void**); }} }} "; // CONSIDER: Dev10 reports ERR_SizeofUnsafe for each sizeof, but that seems redundant. CompareUnsafeDiagnostics(template, // (7,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // x = sizeof(int*); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (7,13): error CS0233: 'int*' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // x = sizeof(int*); Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(int*)").WithArguments("int*"), // (8,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // x = sizeof(int**); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (8,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // x = sizeof(int**); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int**"), // (8,13): error CS0233: 'int**' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // x = sizeof(int**); Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(int**)").WithArguments("int**"), // (9,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // x = sizeof(void*); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*"), // (9,13): error CS0233: 'void*' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // x = sizeof(void*); Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(void*)").WithArguments("void*"), // (10,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // x = sizeof(void**); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*"), // (10,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // x = sizeof(void**); Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void**"), // (10,13): error CS0233: 'void**' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // x = sizeof(void**); Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(void**)").WithArguments("void**") ); } [Fact] public void SizeOfUnsafeInIterator() { var text = @" struct S { System.Collections.Generic.IEnumerable<int> M() { yield return sizeof(S); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS1629: Unsafe code may not appear in iterators // yield return sizeof(S); Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "sizeof(S)")); } [Fact] public void SizeOfNonType1() { var text = @" unsafe struct S { void M() { S s = new S(); int i = 0; i = sizeof(s); i = sizeof(i); i = sizeof(M); } } "; // Not identical to Dev10, but same meaning. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,20): error CS0118: 's' is a variable but is used like a type // i = sizeof(s); Diagnostic(ErrorCode.ERR_BadSKknown, "s").WithArguments("s", "variable", "type"), // (10,20): error CS0118: 'i' is a variable but is used like a type // i = sizeof(i); Diagnostic(ErrorCode.ERR_BadSKknown, "i").WithArguments("i", "variable", "type"), // (11,20): error CS0246: The type or namespace name 'M' could not be found (are you missing a using directive or an assembly reference?) // i = sizeof(M); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "M").WithArguments("M"), // (6,11): warning CS0219: The variable 's' is assigned but its value is never used // S s = new S(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s")); } [Fact] public void SizeOfNonType2() { var text = @" unsafe struct S { void M() { int i; i = sizeof(void); i = sizeof(this); //parser error i = sizeof(x => x); //parser error } } "; // Not identical to Dev10, but same meaning. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,20): error CS1547: Keyword 'void' cannot be used in this context // i = sizeof(void); Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (8,20): error CS1031: Type expected // i = sizeof(this); //parser error Diagnostic(ErrorCode.ERR_TypeExpected, "this"), // (8,20): error CS1026: ) expected // i = sizeof(this); //parser error Diagnostic(ErrorCode.ERR_CloseParenExpected, "this"), // (8,20): error CS1002: ; expected // i = sizeof(this); //parser error Diagnostic(ErrorCode.ERR_SemicolonExpected, "this"), // (8,24): error CS1002: ; expected // i = sizeof(this); //parser error Diagnostic(ErrorCode.ERR_SemicolonExpected, ")"), // (8,24): error CS1513: } expected // i = sizeof(this); //parser error Diagnostic(ErrorCode.ERR_RbraceExpected, ")"), // (9,22): error CS1026: ) expected // i = sizeof(x => x); //parser error Diagnostic(ErrorCode.ERR_CloseParenExpected, "=>"), // (9,22): error CS1002: ; expected // i = sizeof(x => x); //parser error Diagnostic(ErrorCode.ERR_SemicolonExpected, "=>"), // (9,22): error CS1513: } expected // i = sizeof(x => x); //parser error Diagnostic(ErrorCode.ERR_RbraceExpected, "=>"), // (9,26): error CS1002: ; expected // i = sizeof(x => x); //parser error Diagnostic(ErrorCode.ERR_SemicolonExpected, ")"), // (9,26): error CS1513: } expected // i = sizeof(x => x); //parser error Diagnostic(ErrorCode.ERR_RbraceExpected, ")"), // (9,20): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?) // i = sizeof(x => x); //parser error Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x"), // (9,25): error CS0103: The name 'x' does not exist in the current context // i = sizeof(x => x); //parser error Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x")); } [Fact, WorkItem(529318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529318")] public void SizeOfNull() { string text = @" class Program { int F1 = sizeof(null); } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,21): error CS1031: Type expected // int F1 = sizeof(null); Diagnostic(ErrorCode.ERR_TypeExpected, "null"), // (4,21): error CS1026: ) expected // int F1 = sizeof(null); Diagnostic(ErrorCode.ERR_CloseParenExpected, "null"), // (4,21): error CS1003: Syntax error, ',' expected // int F1 = sizeof(null); Diagnostic(ErrorCode.ERR_SyntaxError, "null").WithArguments(",", "null"), // (4,14): error CS0233: '?' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // int F1 = sizeof(null); Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(").WithArguments("?")); } #endregion sizeof diagnostic tests #region sizeof semantic model tests private static readonly Dictionary<SpecialType, int> s_specialTypeSizeOfMap = new Dictionary<SpecialType, int> { { SpecialType.System_SByte, 1 }, { SpecialType.System_Byte, 1 }, { SpecialType.System_Int16, 2 }, { SpecialType.System_UInt16, 2 }, { SpecialType.System_Int32, 4 }, { SpecialType.System_UInt32, 4 }, { SpecialType.System_Int64, 8 }, { SpecialType.System_UInt64, 8 }, { SpecialType.System_Char, 2 }, { SpecialType.System_Single, 4 }, { SpecialType.System_Double, 8 }, { SpecialType.System_Boolean, 1 }, { SpecialType.System_Decimal, 16 }, }; [Fact] public void SizeOfSemanticModelSafe() { var text = @" class Program { static void Main() { int x; x = sizeof(sbyte); x = sizeof(byte); x = sizeof(short); x = sizeof(ushort); x = sizeof(int); x = sizeof(uint); x = sizeof(long); x = sizeof(ulong); x = sizeof(char); x = sizeof(float); x = sizeof(double); x = sizeof(bool); x = sizeof(decimal); //Supported by dev10, but not spec. } } "; // NB: not unsafe var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>(); foreach (var syntax in syntaxes) { var typeSummary = model.GetSemanticInfoSummary(syntax.Type); var type = typeSummary.Symbol as TypeSymbol; Assert.NotNull(type); Assert.Equal(0, typeSummary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, typeSummary.CandidateReason); Assert.NotEqual(SpecialType.None, type.SpecialType); Assert.Equal(type, typeSummary.Type); Assert.Equal(type, typeSummary.ConvertedType); Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion); Assert.Null(typeSummary.Alias); Assert.False(typeSummary.IsCompileTimeConstant); Assert.False(typeSummary.ConstantValue.HasValue); var sizeOfSummary = model.GetSemanticInfoSummary(syntax); Assert.Null(sizeOfSummary.Symbol); Assert.Equal(0, sizeOfSummary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, sizeOfSummary.CandidateReason); Assert.Equal(SpecialType.System_Int32, sizeOfSummary.Type.SpecialType); Assert.Equal(sizeOfSummary.Type, sizeOfSummary.ConvertedType); Assert.Equal(Conversion.Identity, sizeOfSummary.ImplicitConversion); Assert.Equal(0, sizeOfSummary.MethodGroup.Length); Assert.Null(sizeOfSummary.Alias); Assert.True(sizeOfSummary.IsCompileTimeConstant); Assert.Equal(s_specialTypeSizeOfMap[type.SpecialType], sizeOfSummary.ConstantValue); } } [Fact] public void SizeOfSemanticModelEnum() { var text = @" class Program { static void Main() { int x; x = sizeof(E1); x = sizeof(E2); } } enum E1 : short { A } enum E2 : long { A } "; // NB: not unsafe var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>(); foreach (var syntax in syntaxes) { var typeSummary = model.GetSemanticInfoSummary(syntax.Type); var type = typeSummary.Symbol as TypeSymbol; Assert.NotNull(type); Assert.Equal(0, typeSummary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, typeSummary.CandidateReason); Assert.Equal(TypeKind.Enum, type.TypeKind); Assert.Equal(type, typeSummary.Type); Assert.Equal(type, typeSummary.ConvertedType); Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion); Assert.Null(typeSummary.Alias); Assert.False(typeSummary.IsCompileTimeConstant); Assert.False(typeSummary.ConstantValue.HasValue); var sizeOfSummary = model.GetSemanticInfoSummary(syntax); Assert.Null(sizeOfSummary.Symbol); Assert.Equal(0, sizeOfSummary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, sizeOfSummary.CandidateReason); Assert.Equal(SpecialType.System_Int32, sizeOfSummary.Type.SpecialType); Assert.Equal(sizeOfSummary.Type, sizeOfSummary.ConvertedType); Assert.Equal(Conversion.Identity, sizeOfSummary.ImplicitConversion); Assert.Equal(0, sizeOfSummary.MethodGroup.Length); Assert.Null(sizeOfSummary.Alias); Assert.True(sizeOfSummary.IsCompileTimeConstant); Assert.Equal(s_specialTypeSizeOfMap[type.GetEnumUnderlyingType().SpecialType], sizeOfSummary.ConstantValue); } } [Fact] public void SizeOfSemanticModelUnsafe() { var text = @" struct Outer { unsafe static void Main() { int x; x = sizeof(Outer); x = sizeof(Inner); x = sizeof(Outer*); x = sizeof(Inner*); x = sizeof(Outer**); x = sizeof(Inner**); } struct Inner { } } "; // NB: not unsafe var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var syntaxes = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>(); foreach (var syntax in syntaxes) { var typeSummary = model.GetSemanticInfoSummary(syntax.Type); var type = typeSummary.Symbol as TypeSymbol; Assert.NotNull(type); Assert.Equal(0, typeSummary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, typeSummary.CandidateReason); Assert.Equal(SpecialType.None, type.SpecialType); Assert.Equal(type, typeSummary.Type); Assert.Equal(type, typeSummary.ConvertedType); Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion); Assert.Null(typeSummary.Alias); Assert.False(typeSummary.IsCompileTimeConstant); Assert.False(typeSummary.ConstantValue.HasValue); var sizeOfSummary = model.GetSemanticInfoSummary(syntax); Assert.Null(sizeOfSummary.Symbol); Assert.Equal(0, sizeOfSummary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, sizeOfSummary.CandidateReason); Assert.Equal(SpecialType.System_Int32, sizeOfSummary.Type.SpecialType); Assert.Equal(sizeOfSummary.Type, sizeOfSummary.ConvertedType); Assert.Equal(Conversion.Identity, sizeOfSummary.ImplicitConversion); Assert.Equal(0, sizeOfSummary.MethodGroup.Length); Assert.Null(sizeOfSummary.Alias); Assert.False(sizeOfSummary.IsCompileTimeConstant); Assert.False(sizeOfSummary.ConstantValue.HasValue); } } #endregion sizeof semantic model tests #region stackalloc diagnostic tests [Fact] public void StackAllocUnsafe() { var template = @" {0} struct S {{ {1} void M() {{ int* p = stackalloc int[1]; }} }} "; CompareUnsafeDiagnostics(template, // (6,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int* p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (6,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // int* p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[1]") ); } [Fact] public void StackAllocUnsafeInIterator() { var text = @" struct S { System.Collections.Generic.IEnumerable<int> M() { var p = stackalloc int[1]; yield return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,17): error CS1629: Unsafe code may not appear in iterators // var p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "stackalloc int[1]")); } [Fact] public void ERR_NegativeStackAllocSize() { var text = @" unsafe struct S { void M() { int* p = stackalloc int[-1]; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,33): error CS0247: Cannot use a negative size with stackalloc // int* p = stackalloc int[-1]; Diagnostic(ErrorCode.ERR_NegativeStackAllocSize, "-1")); } [Fact] public void ERR_StackallocInCatchFinally_Catch() { var text = @" unsafe class C { int x = M(() => { try { int* p = stackalloc int[1]; //fine System.Action a = () => { try { int* q = stackalloc int[1]; //fine } catch { int* q = stackalloc int[1]; //CS0255 } }; } catch { int* p = stackalloc int[1]; //CS0255 System.Action a = () => { try { int* q = stackalloc int[1]; //fine } catch { int* q = stackalloc int[1]; //CS0255 } }; } }); static int M(System.Action action) { try { int* p = stackalloc int[1]; //fine System.Action a = () => { try { int* q = stackalloc int[1]; //fine } catch { int* q = stackalloc int[1]; //CS0255 } }; } catch { int* p = stackalloc int[1]; //CS0255 System.Action a = () => { try { int* q = stackalloc int[1]; //fine } catch { int* q = stackalloc int[1]; //CS0255 } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (17,30): error CS0255: stackalloc may not be used in a catch or finally block // int* q = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"), // (23,22): error CS0255: stackalloc may not be used in a catch or finally block // int* p = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"), // (32,30): error CS0255: stackalloc may not be used in a catch or finally block // int* q = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"), // (51,30): error CS0255: stackalloc may not be used in a catch or finally block // int* q = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"), // (57,22): error CS0255: stackalloc may not be used in a catch or finally block // int* p = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"), // (66,30): error CS0255: stackalloc may not be used in a catch or finally block // int* q = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]")); } [Fact] public void ERR_StackallocInCatchFinally_Finally() { var text = @" unsafe class C { int x = M(() => { try { int* p = stackalloc int[1]; //fine System.Action a = () => { try { int* q = stackalloc int[1]; //fine } finally { int* q = stackalloc int[1]; //CS0255 } }; } finally { int* p = stackalloc int[1]; //CS0255 System.Action a = () => { try { int* q = stackalloc int[1]; //fine } finally { int* q = stackalloc int[1]; //CS0255 } }; } }); static int M(System.Action action) { try { int* p = stackalloc int[1]; //fine System.Action a = () => { try { int* q = stackalloc int[1]; //fine } finally { int* q = stackalloc int[1]; //CS0255 } }; } finally { int* p = stackalloc int[1]; //CS0255 System.Action a = () => { try { int* q = stackalloc int[1]; //fine } finally { int* q = stackalloc int[1]; //CS0255 } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (17,30): error CS0255: stackalloc may not be used in a catch or finally block // int* q = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"), // (23,22): error CS0255: stackalloc may not be used in a catch or finally block // int* p = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"), // (32,30): error CS0255: stackalloc may not be used in a catch or finally block // int* q = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"), // (51,30): error CS0255: stackalloc may not be used in a catch or finally block // int* q = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"), // (57,22): error CS0255: stackalloc may not be used in a catch or finally block // int* p = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]"), // (66,30): error CS0255: stackalloc may not be used in a catch or finally block // int* q = stackalloc int[1]; //CS0255 Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int[1]")); } [Fact] public void ERR_BadStackAllocExpr() { var text = @" unsafe class C { static void Main() { int* p = stackalloc int; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,29): error CS1575: A stackalloc expression requires [] after type // int* p = stackalloc int; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int")); } [Fact] public void StackAllocCountType() { var text = @" unsafe class C { static void Main() { { int* p = stackalloc int[1]; } //fine { int* p = stackalloc int[1L]; } //CS0266 (could cast), even though constant value is fine { int* p = stackalloc int['c']; } //fine { int* p = stackalloc int[""hello""]; } // CS0029 (no conversion) { int* p = stackalloc int[Main]; } //CS0428 (method group conversion) { int* p = stackalloc int[x => x]; } //CS1660 (lambda conversion) } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,35): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // { int* p = stackalloc int[1L]; } //CS0266 (could cast), even though constant value is fine Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int"), // (9,35): error CS0029: Cannot implicitly convert type 'string' to 'int' // { int* p = stackalloc int["hello"]; } // CS0029 (no conversion) Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""hello""").WithArguments("string", "int"), // (10,35): error CS0428: Cannot convert method group 'Main' to non-delegate type 'int'. Did you intend to invoke the method? // { int* p = stackalloc int[Main]; } //CS0428 (method group conversion) Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "int"), // (11,35): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // { int* p = stackalloc int[x => x]; } //CS1660 (lambda conversion) Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x => x").WithArguments("lambda expression", "int")); } [Fact] public void StackAllocCountQuantity() { // These all give unhelpful parser errors in Dev10. Let's see if we can do better. var text = @" unsafe class C { static void Main() { { int* p = stackalloc int[]; } { int* p = stackalloc int[1, 1]; } { int* p = stackalloc int[][]; } { int* p = stackalloc int[][1]; } { int* p = stackalloc int[1][]; } { int* p = stackalloc int[1][1]; } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,34): error CS1586: Array creation must have array size or array initializer // { int* p = stackalloc int[]; } Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 34), // (8,34): error CS1586: Array creation must have array size or array initializer // { int* p = stackalloc int[][]; } Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(8, 34), // (9,34): error CS1586: Array creation must have array size or array initializer // { int* p = stackalloc int[][1]; } Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(9, 34), // (9,37): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // { int* p = stackalloc int[][1]; } Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "1").WithLocation(9, 37), // (11,38): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // { int* p = stackalloc int[1][1]; } Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "1").WithLocation(11, 38), // (7,31): error CS1575: A stackalloc expression requires [] after type // { int* p = stackalloc int[1, 1]; } Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[1, 1]").WithLocation(7, 31), // (8,31): error CS1575: A stackalloc expression requires [] after type // { int* p = stackalloc int[][]; } Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][]").WithLocation(8, 31), // (9,31): error CS1575: A stackalloc expression requires [] after type // { int* p = stackalloc int[][1]; } Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][1]").WithLocation(9, 31), // (10,31): error CS1575: A stackalloc expression requires [] after type // { int* p = stackalloc int[1][]; } Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[1][]").WithLocation(10, 31), // (11,31): error CS1575: A stackalloc expression requires [] after type // { int* p = stackalloc int[1][1]; } Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[1][1]").WithLocation(11, 31) ); } [Fact] public void StackAllocExplicitConversion() { var text = @" unsafe class C { static void Main() { { var p = (int*)stackalloc int[1]; } { var p = (void*)stackalloc int[1]; } { var p = (C)stackalloc int[1]; } } public static implicit operator C(int* p) { return null; } } "; CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible. // { var p = (int*)stackalloc int[1]; } Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(int*)stackalloc int[1]").WithArguments("int", "int*").WithLocation(6, 19), // (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'void*' is not possible. // { var p = (void*)stackalloc int[1]; } Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(void*)stackalloc int[1]").WithArguments("int", "void*").WithLocation(7, 19), // (8,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'C' is not possible. // { var p = (C)stackalloc int[1]; } Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(C)stackalloc int[1]").WithArguments("int", "C").WithLocation(8, 19)); } [Fact] public void StackAllocNotExpression_FieldInitializer() { var text = @" unsafe class C { int* p = stackalloc int[1]; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,14): error CS1525: Invalid expression term 'stackalloc' // int* p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "stackalloc").WithArguments("stackalloc")); } [Fact] public void StackAllocNotExpression_DefaultParameterValue() { var text = @" unsafe class C { void M(int* p = stackalloc int[1]) { } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,21): error CS1525: Invalid expression term 'stackalloc' // void M(int* p = stackalloc int[1]) Diagnostic(ErrorCode.ERR_InvalidExprTerm, "stackalloc").WithArguments("stackalloc").WithLocation(4, 21) ); } [Fact] public void StackAllocNotExpression_ForLoop() { var text = @" unsafe class C { void M() { for (int* p = stackalloc int[1]; p != null; p++) //fine { } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void StackAllocNotExpression_GlobalDeclaration() { var text = @" unsafe int* p = stackalloc int[1]; "; CreateCompilationWithMscorlib45(text, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Script).VerifyDiagnostics( // (4,14): error CS1525: Invalid expression term 'stackalloc' // int* p = stackalloc int[1]; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "stackalloc").WithArguments("stackalloc")); } #endregion stackalloc diagnostic tests #region stackalloc semantic model tests [Fact] public void StackAllocSemanticModel() { var text = @" class C { unsafe static void Main() { const short count = 20; void* p = stackalloc char[count]; } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var stackAllocSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().Single(); var arrayTypeSyntax = (ArrayTypeSyntax)stackAllocSyntax.Type; var typeSyntax = arrayTypeSyntax.ElementType; var countSyntax = arrayTypeSyntax.RankSpecifiers.Single().Sizes.Single(); var stackAllocSummary = model.GetSemanticInfoSummary(stackAllocSyntax); Assert.Equal(SpecialType.System_Char, ((PointerTypeSymbol)stackAllocSummary.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Void, ((PointerTypeSymbol)stackAllocSummary.ConvertedType).PointedAtType.SpecialType); Assert.Equal(Conversion.PointerToVoid, stackAllocSummary.ImplicitConversion); Assert.Null(stackAllocSummary.Symbol); Assert.Equal(0, stackAllocSummary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, stackAllocSummary.CandidateReason); Assert.Equal(0, stackAllocSummary.MethodGroup.Length); Assert.Null(stackAllocSummary.Alias); Assert.False(stackAllocSummary.IsCompileTimeConstant); Assert.False(stackAllocSummary.ConstantValue.HasValue); var typeSummary = model.GetSemanticInfoSummary(typeSyntax); Assert.Equal(SpecialType.System_Char, typeSummary.Type.SpecialType); Assert.Equal(typeSummary.Type, typeSummary.ConvertedType); Assert.Equal(Conversion.Identity, typeSummary.ImplicitConversion); Assert.Equal(typeSummary.Symbol, typeSummary.Type); Assert.Equal(0, typeSummary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, typeSummary.CandidateReason); Assert.Equal(0, typeSummary.MethodGroup.Length); Assert.Null(typeSummary.Alias); Assert.False(typeSummary.IsCompileTimeConstant); Assert.False(typeSummary.ConstantValue.HasValue); var countSummary = model.GetSemanticInfoSummary(countSyntax); Assert.Equal(SpecialType.System_Int16, countSummary.Type.SpecialType); Assert.Equal(SpecialType.System_Int32, countSummary.ConvertedType.SpecialType); Assert.Equal(Conversion.ImplicitNumeric, countSummary.ImplicitConversion); var countSymbol = (LocalSymbol)countSummary.Symbol; Assert.Equal(countSummary.Type, countSymbol.Type); Assert.Equal("count", countSymbol.Name); Assert.Equal(0, countSummary.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, countSummary.CandidateReason); Assert.Equal(0, countSummary.MethodGroup.Length); Assert.Null(countSummary.Alias); Assert.True(countSummary.IsCompileTimeConstant); Assert.True(countSummary.ConstantValue.HasValue); Assert.Equal((short)20, countSummary.ConstantValue.Value); } #endregion stackalloc semantic model tests #region PointerTypes tests [WorkItem(5712, "https://github.com/dotnet/roslyn/issues/5712")] [Fact] public void PathologicalRefStructPtrMultiDimensionalArray() { var text = @" class C { class Goo3 { internal struct Struct1<U> {} } unsafe void NMethodCecilNameHelper_Parameter_AllTogether<U>(ref Goo3.Struct1<int>**[][,,] ppi) { } } "; CreateCompilation(text, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (8,67): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C.Goo3.Struct1<int>') // unsafe void NMethodCecilNameHelper_Parameter_AllTogether<U>(ref Goo3.Struct1<int>**[][,,] ppi) { } Diagnostic(ErrorCode.ERR_ManagedAddr, "Goo3.Struct1<int>*").WithArguments("C.Goo3.Struct1<int>").WithLocation(8, 67)); } [WorkItem(543990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543990")] [Fact] public void PointerTypeInVolatileField() { string text = @" unsafe class Test { static volatile int *px; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,23): warning CS0169: The field 'Test.px' is never used // static volatile int *px; Diagnostic(ErrorCode.WRN_UnreferencedField, "px").WithArguments("Test.px")); } [WorkItem(544003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544003")] [Fact] public void PointerTypesAsTypeArgs() { string text = @" class A { public class B{} } class C<T> : A { // BREAKING: Dev10 (incorrectly) does not report ERR_ManagedAddr here. private static C<T*[]>.B b; } "; var expected = new[] { // (8,22): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T') // private static C<T*[]>.B b; Diagnostic(ErrorCode.ERR_ManagedAddr, "T*").WithArguments("T"), // (8,30): warning CS0169: The field 'C<T>.b' is never used // private static C<T*[]>.B b; Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b") }; CreateCompilation(text).VerifyDiagnostics(expected); CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expected); } [WorkItem(544003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544003")] [WorkItem(544232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544232")] [Fact] public void PointerTypesAsTypeArgs2() { string text = @" class A { public class B{} } class C<T> : A { // BREAKING: Dev10 does not report an error here because it does not look for ERR_ManagedAddr until // late in the binding process - at which point the type has been resolved to A.B. private static C<T*[]>.B b; // Workarounds private static B b1; private static A.B b2; // Dev10 and Roslyn produce the same diagnostic here. private static C<T*[]> c; } "; var expected = new[] { // (10,22): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T') // private static C<T*[]>.B b; Diagnostic(ErrorCode.ERR_ManagedAddr, "T*").WithArguments("T"), // (17,22): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('T') // private static C<T*[]> c; Diagnostic(ErrorCode.ERR_ManagedAddr, "T*").WithArguments("T"), // (10,30): warning CS0169: The field 'C<T>.b' is never used // private static C<T*[]>.B b; Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b"), // (13,22): warning CS0169: The field 'C<T>.b1' is never used // private static B b1; Diagnostic(ErrorCode.WRN_UnreferencedField, "b1").WithArguments("C<T>.b1"), // (14,24): warning CS0169: The field 'C<T>.b2' is never used // private static A.B b2; Diagnostic(ErrorCode.WRN_UnreferencedField, "b2").WithArguments("C<T>.b2"), // (17,28): warning CS0169: The field 'C<T>.c' is never used // private static C<T*[]> c; Diagnostic(ErrorCode.WRN_UnreferencedField, "c").WithArguments("C<T>.c") }; CreateCompilation(text).VerifyDiagnostics(expected); CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expected); } [WorkItem(544003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544003")] [WorkItem(544232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544232")] [Fact] public void PointerTypesAsTypeArgs3() { string text = @" class A { public class B{} } class C<T> : A { // BREAKING: Dev10 does not report an error here because it does not look for ERR_ManagedAddr until // late in the binding process - at which point the type has been resolved to A.B. private static C<string*[]>.B b; // Dev10 and Roslyn produce the same diagnostic here. private static C<string*[]> c; } "; var expected = new[] { // (10,22): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // private static C<T*[]>.B b; Diagnostic(ErrorCode.ERR_ManagedAddr, "string*").WithArguments("string"), // (15,22): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // private static C<T*[]> c; Diagnostic(ErrorCode.ERR_ManagedAddr, "string*").WithArguments("string"), // (10,30): warning CS0169: The field 'C<T>.b' is never used // private static C<T*[]>.B b; Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b"), // (15,28): warning CS0169: The field 'C<T>.c' is never used // private static C<T*[]> c; Diagnostic(ErrorCode.WRN_UnreferencedField, "c").WithArguments("C<T>.c") }; CreateCompilation(text).VerifyDiagnostics(expected); CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(expected); } #endregion PointerTypes tests #region misc unsafe tests [Fact, WorkItem(543988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543988")] public void UnsafeFieldInitializerInStruct() { string sourceCode = @" public struct Test { static unsafe int*[] myArray = new int*[100]; } "; var tree = Parse(sourceCode); var comp = CreateCompilation(tree, options: TestOptions.UnsafeReleaseDll); var model = comp.GetSemanticModel(tree); model.GetDiagnostics().Verify(); } [Fact, WorkItem(544143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544143")] public void ConvertFromPointerToSelf() { string text = @" struct C { unsafe static public implicit operator long*(C* i) { return null; } unsafe static void Main() { C c = new C(); } } "; var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (4,44): error CS0556: User-defined conversion must convert to or from the enclosing type // unsafe static public implicit operator long*(C* i) Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "long*"), // (10,11): warning CS0219: The variable 'c' is assigned but its value is never used // C c = new C(); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c")); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); var info = model.GetSemanticInfoSummary(parameterSyntax.Type); } [Fact] public void PointerVolatileField() { string text = @" unsafe class C { volatile int* p; //Spec section 18.2 specifically allows this. } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,19): warning CS0169: The field 'C.p' is never used // volatile int* p; //Spec section 18.2 specifically allows this. Diagnostic(ErrorCode.WRN_UnreferencedField, "p").WithArguments("C.p")); } [Fact] public void SemanticModelPointerArrayForeachInfo() { var text = @" using System; unsafe class C { static void Main() { foreach(int* element in new int*[3]) { } } } "; var compilation = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var foreachSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); // Reports members of non-generic interfaces (pointers can't be type arguments). var info = model.GetForEachStatementInfo(foreachSyntax); Assert.Equal(default(ForEachStatementInfo), info); } [Fact, WorkItem(544336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544336")] public void PointerTypeAsDelegateParamInAnonMethod() { // It is legal to use a delegate with pointer types in a "safe" context // provided that you do not actually make a parameter of unsafe type! string sourceCode = @" unsafe delegate int D(int* p); class C { static void Main() { D d = delegate { return 1;}; } } "; var tree = Parse(sourceCode); var comp = CreateCompilation(tree, options: TestOptions.UnsafeReleaseDll); var model = comp.GetSemanticModel(tree); model.GetDiagnostics().Verify(); } [Fact(Skip = "529402"), WorkItem(529402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529402")] public void DotOperatorOnPointerTypes() { string text = @" unsafe class Program { static void Main(string[] args) { int* i1 = null; i1.ToString(); } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (7,9): error CS0023: Operator '.' cannot be applied to operand of type 'int*' // i1.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "i1.ToString").WithArguments(".", "int*")); } [Fact, WorkItem(545028, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545028")] public void PointerToEnumInGeneric() { string text = @" class C<T> { enum E { } unsafe E* ptr; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,15): warning CS0169: The field 'C<T>.ptr' is never used // unsafe E* ptr; Diagnostic(ErrorCode.WRN_UnreferencedField, "ptr").WithArguments("C<T>.ptr")); } [Fact] public void InvalidAsConversions() { string text = @" using System; public class Test { unsafe void M<T>(T t) { int* p = null; Console.WriteLine(t as int*); // CS0244 Console.WriteLine(p as T); // Dev10 reports CS0244 here as well, but CS0413 seems reasonable Console.WriteLine(null as int*); // CS0244 } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,27): error CS0244: Neither 'is' nor 'as' is valid on pointer types // Console.WriteLine(t as int*); // pointer Diagnostic(ErrorCode.ERR_PointerInAsOrIs, "t as int*"), // (10,27): error CS0413: The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint // Console.WriteLine(p as T); // pointer Diagnostic(ErrorCode.ERR_AsWithTypeVar, "p as T").WithArguments("T"), // (11,27): error CS0244: Neither 'is' nor 'as' is valid on pointer types // Console.WriteLine(null as int*); // pointer Diagnostic(ErrorCode.ERR_PointerInAsOrIs, "null as int*")); } [Fact] public void UnsafeConstructorInitializer() { string template = @" {0} class A {{ {1} public A(params int*[] x) {{ }} }} {0} class B : A {{ {1} B(int x) {{ }} {1} B(double x) : base() {{ }} }} "; CompareUnsafeDiagnostics(template, // (4,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public A(params int*[] x) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int*"), // (9,6): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // B(int x) { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "B"), // (10,20): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // B(double x) : base() { } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "base")); } [WorkItem(545985, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545985")] [Fact] public void UnboxPointer() { var text = @" class C { unsafe void Goo(object obj) { var x = (int*)obj; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,17): error CS0030: Cannot convert type 'object' to 'int*' // var x = (int*)obj; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int*)obj").WithArguments("object", "int*")); } [Fact] public void FixedBuffersNoDefiniteAssignmentCheck() { var text = @" unsafe struct struct_ForTestingDefiniteAssignmentChecking { //Definite Assignment Checking public fixed int FixedbuffInt[1024]; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void FixedBuffersNoErrorsOnValidTypes() { var text = @" unsafe struct struct_ForTestingDefiniteAssignmentChecking { public fixed bool _Type1[10]; public fixed byte _Type12[10]; public fixed int _Type2[10]; public fixed short _Type3[10]; public fixed long _Type4[10]; public fixed char _Type5[10]; public fixed sbyte _Type6[10]; public fixed ushort _Type7[10]; public fixed uint _Type8[10]; public fixed ulong _Type9[10]; public fixed float _Type10[10]; public fixed double _Type11[10]; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact()] [WorkItem(547030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547030")] public void FixedBuffersUsageScenarioInRange() { var text = @" using System; unsafe struct s { public fixed bool _buffer[5]; // This is a fixed buffer. } class Program { static s _fixedBufferExample = new s(); static void Main() { // Store values in the fixed buffer. // ... The load the values from the fixed buffer. Store(); Load(); } unsafe static void Store() { // Put the fixed buffer in unmovable memory. // ... Then assign some elements. fixed (bool* buffer = _fixedBufferExample._buffer) { buffer[0] = true; buffer[1] = false; buffer[2] = true; } } unsafe static void Load() { // Put in unmovable memory. // ... Then load some values from the memory. fixed (bool* buffer = _fixedBufferExample._buffer) { Console.Write(buffer[0]); Console.Write(buffer[1]); Console.Write(buffer[2]); } } } "; var compilation = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails); compilation.VerifyIL("Program.Store", @" { // Code size 34 (0x22) .maxstack 3 .locals init (pinned bool& V_0) IL_0000: ldsflda ""s Program._fixedBufferExample"" IL_0005: ldflda ""bool* s._buffer"" IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: conv.u IL_0012: dup IL_0013: ldc.i4.1 IL_0014: stind.i1 IL_0015: dup IL_0016: ldc.i4.1 IL_0017: add IL_0018: ldc.i4.0 IL_0019: stind.i1 IL_001a: ldc.i4.2 IL_001b: add IL_001c: ldc.i4.1 IL_001d: stind.i1 IL_001e: ldc.i4.0 IL_001f: conv.u IL_0020: stloc.0 IL_0021: ret } "); compilation.VerifyIL("Program.Load", @" { // Code size 46 (0x2e) .maxstack 3 .locals init (pinned bool& V_0) IL_0000: ldsflda ""s Program._fixedBufferExample"" IL_0005: ldflda ""bool* s._buffer"" IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: conv.u IL_0012: dup IL_0013: ldind.u1 IL_0014: call ""void System.Console.Write(bool)"" IL_0019: dup IL_001a: ldc.i4.1 IL_001b: add IL_001c: ldind.u1 IL_001d: call ""void System.Console.Write(bool)"" IL_0022: ldc.i4.2 IL_0023: add IL_0024: ldind.u1 IL_0025: call ""void System.Console.Write(bool)"" IL_002a: ldc.i4.0 IL_002b: conv.u IL_002c: stloc.0 IL_002d: ret } "); } [Fact()] [WorkItem(547030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547030")] public void FixedBuffersUsagescenarioOutOfRange() { // This should work as no range checking for unsafe code. //however the fact that we are writing bad unsafe code has potential for encountering problems var text = @" using System; unsafe struct s { public fixed bool _buffer[5]; // This is a fixed buffer. } class Program { static s _fixedBufferExample = new s(); static void Main() { // Store values in the fixed buffer. // ... The load the values from the fixed buffer. Store(); Load(); } unsafe static void Store() { // Put the fixed buffer in unmovable memory. // ... Then assign some elements. fixed (bool* buffer = _fixedBufferExample._buffer) { buffer[0] = true; buffer[8] = false; buffer[10] = true; } } unsafe static void Load() { // Put in unmovable memory. // ... Then load some values from the memory. fixed (bool* buffer = _fixedBufferExample._buffer) { Console.Write(buffer[0]); Console.Write(buffer[8]); Console.Write(buffer[10]); } } } "; //IL Baseline rather than execute because I'm intentionally writing outside of bounds of buffer // This will compile without warning but runtime behavior is unpredictable. var compilation = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails); compilation.VerifyIL("Program.Load", @" { // Code size 47 (0x2f) .maxstack 3 .locals init (pinned bool& V_0) IL_0000: ldsflda ""s Program._fixedBufferExample"" IL_0005: ldflda ""bool* s._buffer"" IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: conv.u IL_0012: dup IL_0013: ldind.u1 IL_0014: call ""void System.Console.Write(bool)"" IL_0019: dup IL_001a: ldc.i4.8 IL_001b: add IL_001c: ldind.u1 IL_001d: call ""void System.Console.Write(bool)"" IL_0022: ldc.i4.s 10 IL_0024: add IL_0025: ldind.u1 IL_0026: call ""void System.Console.Write(bool)"" IL_002b: ldc.i4.0 IL_002c: conv.u IL_002d: stloc.0 IL_002e: ret }"); compilation.VerifyIL("Program.Store", @" { // Code size 35 (0x23) .maxstack 3 .locals init (pinned bool& V_0) IL_0000: ldsflda ""s Program._fixedBufferExample"" IL_0005: ldflda ""bool* s._buffer"" IL_000a: ldflda ""bool s.<_buffer>e__FixedBuffer.FixedElementField"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: conv.u IL_0012: dup IL_0013: ldc.i4.1 IL_0014: stind.i1 IL_0015: dup IL_0016: ldc.i4.8 IL_0017: add IL_0018: ldc.i4.0 IL_0019: stind.i1 IL_001a: ldc.i4.s 10 IL_001c: add IL_001d: ldc.i4.1 IL_001e: stind.i1 IL_001f: ldc.i4.0 IL_0020: conv.u IL_0021: stloc.0 IL_0022: ret }"); } [Fact] public void FixedBufferUsageWith_this() { var text = @" using System; unsafe struct s { private fixed ushort _e_res[4]; void Error_UsingFixedBuffersWithThis() { fixed (ushort* abc = this._e_res) { abc[2] = 1; } } } "; CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails); } [Fact] [WorkItem(547074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547074")] public void FixedBufferWithNoSize() { var text = @" unsafe struct S { fixed[ } "; var s = CreateCompilation(text).GlobalNamespace.GetMember<TypeSymbol>("S"); foreach (var member in s.GetMembers()) { var field = member as FieldSymbol; if (field != null) { Assert.Equal(0, field.FixedSize); } } } [Fact()] [WorkItem(547030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547030")] public void FixedBufferUsageDifferentAssemblies() { // Ensure fixed buffers work as expected when fixed buffer is created in different assembly to where it is consumed. var s1 = @"using System; namespace ClassLibrary1 { public unsafe struct FixedBufferExampleForSizes { public fixed bool _buffer[5]; // This is a fixed buffer. } }"; var s2 = @"using System; using ClassLibrary1; namespace ConsoleApplication30 { class Program { static FixedBufferExampleForSizes _fixedBufferExample = new FixedBufferExampleForSizes(); static void Main() { // Store values in the fixed buffer. // ... The load the values from the fixed buffer. Store(); Load(); } unsafe static void Store() { // Put the fixed buffer in unmovable memory. // ... Then assign some elements. fixed (bool* buffer = _fixedBufferExample._buffer) { buffer[0] = true; buffer[10] = false; } } unsafe static void Load() { // Put in unmovable memory. // ... Then load some values from the memory. fixed (bool* buffer = _fixedBufferExample._buffer) { Console.Write(buffer[0]); Console.Write(buffer[10]); } } } }"; var comp1 = CompileAndVerify(s1, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).Compilation; var comp2 = CompileAndVerify(s2, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, references: new MetadataReference[] { MetadataReference.CreateFromImage(comp1.EmitToArray()) }, expectedOutput: "TrueFalse").Compilation; var s3 = @"using System; using ClassLibrary1; namespace ConsoleApplication30 { class Program { static FixedBufferExampleForSizes _fixedBufferExample = new FixedBufferExampleForSizes(); static void Main() { // Store values in the fixed buffer. // ... The load the values from the fixed buffer. Store(); Load(); } unsafe static void Store() { // Put the fixed buffer in unmovable memory. // ... Then assign some elements. fixed (bool* buffer = _fixedBufferExample._buffer) { buffer[0] = true; buffer[10] = false; buffer[1024] = true; //Intentionally outside range } } unsafe static void Load() { // Put in unmovable memory. // ... Then load some values from the memory. fixed (bool* buffer = _fixedBufferExample._buffer) { Console.Write(buffer[0]); Console.Write(buffer[10]); Console.Write(buffer[1024]); } } } }"; // Only compile this as its intentionally writing outside of fixed buffer boundaries and // this doesn't warn but causes flakiness when executed. var comp3 = CompileAndVerify(s3, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails, references: new MetadataReference[] { MetadataReference.CreateFromImage(comp1.EmitToArray()) }).Compilation; } [Fact] public void FixedBufferUsageSizeCheckChar() { //Determine the Correct size based upon expansion for different no of elements var text = @"using System; unsafe struct FixedBufferExampleForSizes1 { public fixed char _buffer[1]; // This is a fixed buffer. } unsafe struct FixedBufferExampleForSizes2 { public fixed char _buffer[2]; // This is a fixed buffer. } unsafe struct FixedBufferExampleForSizes3 { public fixed char _buffer[3]; // This is a fixed buffer. } class Program { // Reference to struct containing a fixed buffer static FixedBufferExampleForSizes1 _fixedBufferExample1 = new FixedBufferExampleForSizes1(); static FixedBufferExampleForSizes2 _fixedBufferExample2 = new FixedBufferExampleForSizes2(); static FixedBufferExampleForSizes3 _fixedBufferExample3 = new FixedBufferExampleForSizes3(); static unsafe void Main() { int x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample1); Console.Write(x.ToString()); x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample2); Console.Write(x.ToString()); x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample3); Console.Write(x.ToString()); } } "; CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"246"); } [Fact] public void FixedBufferUsageSizeCheckInt() { //Determine the Correct size based upon expansion for different no of elements var text = @"using System; unsafe struct FixedBufferExampleForSizes1 { public fixed int _buffer[1]; // This is a fixed buffer. } unsafe struct FixedBufferExampleForSizes2 { public fixed int _buffer[2]; // This is a fixed buffer. } unsafe struct FixedBufferExampleForSizes3 { public fixed int _buffer[3]; // This is a fixed buffer. } class Program { // Reference to struct containing a fixed buffer static FixedBufferExampleForSizes1 _fixedBufferExample1 = new FixedBufferExampleForSizes1(); static FixedBufferExampleForSizes2 _fixedBufferExample2 = new FixedBufferExampleForSizes2(); static FixedBufferExampleForSizes3 _fixedBufferExample3 = new FixedBufferExampleForSizes3(); static unsafe void Main() { int x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample1); Console.Write(x.ToString()); x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample2); Console.Write(x.ToString()); x = System.Runtime.InteropServices.Marshal.SizeOf(_fixedBufferExample3); Console.Write(x.ToString()); } } "; CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"4812"); } [Fact] public void CannotTakeAddressOfRefReadOnlyParameter() { CreateCompilation(@" public class Test { unsafe void M(in int p) { int* pointer = &p; } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,24): error CS0212: You can only take the address of an unfixed expression inside of a fixed statement initializer // int* pointer = &p; Diagnostic(ErrorCode.ERR_FixedNeeded, "&p").WithLocation(6, 24) ); } #endregion } }
37.347436
296
0.566647
[ "Apache-2.0" ]
ObsidianMinor/roslyn
src/Compilers/CSharp/Test/Semantic/Semantics/UnsafeTests.cs
324,850
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using Microsoft.EntityFrameworkCore.Diagnostics; namespace Microsoft.EntityFrameworkCore.Sqlite.Diagnostics.Internal { /// <summary> /// The <see cref="DiagnosticSource" /> event payload for /// <see cref="SqliteEventId.UnexpectedConnectionTypeWarning" />. /// </summary> public class UnexpectedConnectionTypeEventData : EventData { /// <summary> /// Constructs the event payload. /// </summary> /// <param name="eventDefinition"> The event definition. </param> /// <param name="messageGenerator"> A delegate that generates a log message for this event. </param> /// <param name="connectionType"> The connection type. </param> public UnexpectedConnectionTypeEventData( EventDefinitionBase eventDefinition, Func<EventDefinitionBase, EventData, string> messageGenerator, Type connectionType) : base(eventDefinition, messageGenerator) { ConnectionType = connectionType; } /// <summary> /// The connection type. /// </summary> public virtual Type ConnectionType { get; } } }
36.756757
108
0.648529
[ "MIT" ]
CameronAavik/efcore
src/EFCore.Sqlite.Core/Diagnostics/Internal/UnexpectedConnectionTypeEventData.cs
1,362
C#
interface ITextBox: IControl{ void SetText(string text); }
20.666667
30
0.741935
[ "MIT" ]
06012021-dotnet-uta/SekouDossoP0
classes/Interfacesss/ITextBox.cs
62
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using RubiksCubeTrainer.Puzzle3x3; namespace RubiksCubeTrainer.Solver3x3 { public class Solver { private Solver( ImmutableDictionary<string, IState> states, ImmutableDictionary<string, Algorithm> algorithms, ImmutableDictionary<string, Algorithm> algorithmTemplates) { this.States = states; this.Algorithms = algorithms; this.AlgorithmTemplates = algorithmTemplates; } public static Solver Empty { get; } = new Solver( ImmutableDictionary.Create<string, IState>(StringComparer.OrdinalIgnoreCase), ImmutableDictionary.Create<string, Algorithm>(StringComparer.OrdinalIgnoreCase), ImmutableDictionary.Create<string, Algorithm>(StringComparer.OrdinalIgnoreCase)); public ImmutableDictionary<string, Algorithm> Algorithms { get; } public ImmutableDictionary<string, Algorithm> AlgorithmTemplates { get; } public ImmutableDictionary<string, IState> States { get; } [DebuggerStepThrough] public IEnumerable<Algorithm> PossibleAlgorithms(Puzzle puzzle) => from algorithm in this.Algorithms.Values where algorithm.InitialState.Matches(puzzle) select algorithm; public Solver WithAlgorithm(Algorithm algorithm) => new Solver(this.States, this.Algorithms.Add(algorithm.Name, algorithm), this.AlgorithmTemplates); public Solver WithAlgorithmTemplate(Algorithm algorithm) => new Solver(this.States, this.Algorithms, this.AlgorithmTemplates.Add(algorithm.Name, algorithm)); public Solver WithState(string name, IState state) => new Solver(this.States.Add(name, state), this.Algorithms, this.AlgorithmTemplates); } }
40.291667
112
0.697518
[ "MIT" ]
JeffLeBert/RubiksCubeTrainer
Puzzle/Solver3x3/Solver.cs
1,936
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace App1 { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } } }
14.611111
44
0.741445
[ "MIT" ]
MACEL94/CityProblemGeoHelper
App1/App1/MainPage.xaml.cs
265
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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void Or_Vector128_SByte() { var test = new SimpleBinaryOpTest__Or_Vector128_SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.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 (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.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__Or_Vector128_SByte { 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(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 16 && alignment != 8) || (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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, 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 Vector128<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Or_Vector128_SByte testClass) { var result = AdvSimd.Or(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Or_Vector128_SByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.Or( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Or_Vector128_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__Or_Vector128_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Or( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_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 = AdvSimd.Or( AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_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(AdvSimd).GetMethod(nameof(AdvSimd.Or), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Or), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Or( AdvSimd.LoadVector128((SByte*)(pClsVar1)), AdvSimd.LoadVector128((SByte*)(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<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Or_Vector128_SByte(); var result = AdvSimd.Or(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__Or_Vector128_SByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.Or( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.Or( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(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 = AdvSimd.Or(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 = AdvSimd.Or( AdvSimd.LoadVector128((SByte*)(&test._fld1)), AdvSimd.LoadVector128((SByte*)(&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(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Or(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Or)}<SByte>(Vector128<SByte>, Vector128<SByte>): {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; } } } }
41.677966
187
0.580543
[ "MIT" ]
Davilink/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/Or.Vector128.SByte.cs
22,131
C#
// <auto-generated /> using System; using FriendsAdventure.WebApp.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace FriendsAdventure.WebApp.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
37.746377
125
0.469284
[ "MIT" ]
GeorgenaGeorgieva/Web
FriendsAdventure/WebApp/FriendsAdventure.WebApp/Data/Migrations/ApplicationDbContextModelSnapshot.cs
10,418
C#
using Dorisoy.Pan.Common.GenericRespository; using Dorisoy.Pan.Common.UnitOfWork; using Dorisoy.Pan.Data; using Dorisoy.Pan.Domain; namespace Dorisoy.Pan.Repository { public class DocumentReminderRepository : GenericRepository<DocumentReminder, DocumentContext>, IDocumentReminderRepository { public DocumentReminderRepository( IUnitOfWork<DocumentContext> uow ) : base(uow) { } } }
25.388889
99
0.698031
[ "MIT" ]
dorisoy/-Dorisoy.Pan
SourceCode/Src/Dorisoy.Pan.Repository/Document/DocumentReminder/DocumentReminderRepository.cs
459
C#
#pragma checksum "..\..\..\App.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "F9F387006E76106D0C3BB120D3BE3632F114F2D4" //------------------------------------------------------------------------------ // <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 SymApp; 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; namespace SymApp { /// <summary> /// App /// </summary> public partial class App : System.Windows.Application { /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.8.1.0")] public void InitializeComponent() { #line 5 "..\..\..\App.xaml" this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative); #line default #line hidden } /// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.8.1.0")] public static void Main() { SymApp.App app = new SymApp.App(); app.InitializeComponent(); app.Run(); } } }
31.611111
121
0.614675
[ "MIT" ]
Wowo51/Sym
SymApp/obj/Debug/netcoreapp3.1/App.g.cs
2,278
C#
using System.Linq; using Kiota.Builder.Writers; using Kiota.Builder.Writers.Go; using Kiota.Builder.Writers.Php; using Xunit; namespace Kiota.Builder.Refiners.Tests { public class PhpLanguageRefinerTests { private readonly CodeNamespace root = CodeNamespace.InitRootNamespace(); [Fact] public void ReplacesRequestBuilderPropertiesByMethods() { var model = root.AddClass(new CodeClass() { Name = "userRequestBuilder", Kind = CodeClassKind.RequestBuilder }).First(); var requestBuilder = model.AddProperty(new CodeProperty() { Name = "breaks", Kind = CodePropertyKind.RequestBuilder, Type = new CodeType() { Name = "string" } }).First(); ILanguageRefiner.Refine(new GenerationConfiguration {Language = GenerationLanguage.PHP}, root); Assert.Equal("breaks", requestBuilder.Name); Assert.Equal("userRequestBuilder", model.Name); } [Fact] public void PrefixReservedWordPropertyNamesWith() { var model = root.AddClass(new CodeClass() { Name = "userRequestBuilder", Kind = CodeClassKind.RequestBuilder }).First(); var property = model.AddProperty(new CodeProperty() { Name = "continue", Kind = CodePropertyKind.RequestBuilder, Type = new CodeType() { Name = "string" } }).First(); ILanguageRefiner.Refine(new GenerationConfiguration {Language = GenerationLanguage.PHP}, root); Assert.Equal("EscapedContinue",property.Name); } [Fact] public void ReplacesBinaryWithNativeType() { var model = root.AddClass(new CodeClass () { Name = "model", Kind = CodeClassKind.Model }).First(); var method = model.AddMethod(new CodeMethod() { Name = "method" }).First(); method.ReturnType = new CodeType() { Name = "binary" }; ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.PHP}, root); Assert.Equal("StreamInterface", method.ReturnType.Name); } [Fact] public void AddsDefaultImports() { var model = root.AddClass(new CodeClass () { Name = "model", Kind = CodeClassKind.Model }).First(); var requestBuilder = root.AddClass(new CodeClass() { Name = "rb", Kind = CodeClassKind.RequestBuilder, }).First(); ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.PHP }, root); Assert.NotEmpty(model.StartBlock.Usings); } [Fact] public void TestCanReturnCorrectAccess() { } } }
32.938144
109
0.52989
[ "MIT" ]
ehtick/kiota
tests/Kiota.Builder.Tests/Refiners/PhpLanguageRefinerTests.cs
3,197
C#
using NHibernate; using NHibernate.Cfg; namespace PersonalPlanung.Persistence.nh.Contracts { public interface IHibernateInitializationAware { void Initialized(Configuration configuration, ISessionFactory sessionFactory); } }
24.6
86
0.784553
[ "MIT" ]
Slesa/Godot
src/PersonalPlanung/PersonalPlanung.Persistence.nh/Contracts/IHibernateInitializationAware.cs
248
C#
using System; using System.Collections.Generic; using UnityEngine; namespace UI.Utils { public class RichStrings { public static string WithColor(string s, Color color) { return $"<color=#{ColorUtility.ToHtmlStringRGBA(color)}>{s}</color>"; } } public static class OnGuiUtil { static Texture2D _whiteTexture; public static Texture2D WhiteTexture { get { if (_whiteTexture == null) { _whiteTexture = new Texture2D(1, 1); _whiteTexture.SetPixel(0, 0, Color.white); _whiteTexture.Apply(); } return _whiteTexture; } } public static Bounds GetViewportBounds(Camera camera, Vector3 screenPosition1, Vector3 screenPosition2) { var v1 = Camera.main.ScreenToViewportPoint(screenPosition1); var v2 = Camera.main.ScreenToViewportPoint(screenPosition2); var min = Vector3.Min(v1, v2); var max = Vector3.Max(v1, v2); min.z = camera.nearClipPlane; max.z = camera.farClipPlane; var bounds = new Bounds(); bounds.SetMinMax(min, max); return bounds; } public static void DrawScreenRect(Rect rect, Color color) { GUI.color = color; GUI.DrawTexture(rect, WhiteTexture); GUI.color = Color.white; } public static void DrawScreenRectBorder(Rect rect, float thickness, Color color) { // Top DrawScreenRect(new Rect(rect.xMin, rect.yMin, rect.width, thickness), color); // Left DrawScreenRect(new Rect(rect.xMin, rect.yMin, thickness, rect.height), color); // Right DrawScreenRect(new Rect(rect.xMax - thickness, rect.yMin, thickness, rect.height), color); // Bottom DrawScreenRect(new Rect(rect.xMin, rect.yMax - thickness, rect.width, thickness), color); } public static Rect GetScreenRect(Vector3 screenPosition1, Vector3 screenPosition2) { // Move origin from bottom left to top left screenPosition1.y = Screen.height - screenPosition1.y; screenPosition2.y = Screen.height - screenPosition2.y; // Calculate corners var topLeft = Vector3.Min(screenPosition1, screenPosition2); var bottomRight = Vector3.Max(screenPosition1, screenPosition2); // Create Rect return Rect.MinMaxRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y); } } }
34.316456
111
0.576171
[ "Apache-2.0" ]
ch-andrei/SpaceColumbus
Assets/GameView/UI/Scripts/UiUtils.cs
2,713
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameOverManage : MonoBehaviour { public Text scoreText; void Start() { scoreText.text = GameManagerScript.score.ToString("F0"); } }
16.176471
64
0.712727
[ "MIT" ]
uguisu64/GameJam2020DinosaurGame
Assets/Scripts/GameOverScene/GameOverManage.cs
277
C#
namespace Ryujinx.HLE.HOS.Services.Spl.Types { enum HardwareType { Icosa, Copper, Hoag, Iowa, Calcio, Aula } }
14.25
45
0.48538
[ "MIT" ]
2579768776/Ryujinx
Ryujinx.HLE/HOS/Services/Spl/Types/HardwareType.cs
173
C#
using System; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace PixiEditor.Views { /// <summary> /// Interaction logic for NumerInput.xaml /// </summary> public partial class NumberInput : UserControl { // Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc... public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(float), typeof(NumberInput), new PropertyMetadata(0f, OnValueChanged)); // Using a DependencyProperty as the backing store for Min. This enables animation, styling, binding, etc... public static readonly DependencyProperty MinProperty = DependencyProperty.Register("Min", typeof(float), typeof(NumberInput), new PropertyMetadata(float.NegativeInfinity)); // Using a DependencyProperty as the backing store for Max. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxProperty = DependencyProperty.Register("Max", typeof(float), typeof(NumberInput), new PropertyMetadata(float.PositiveInfinity)); public NumberInput() { InitializeComponent(); } public float Value { get => (float) GetValue(ValueProperty); set => SetValue(ValueProperty, value); } public float Min { get => (float) GetValue(MinProperty); set => SetValue(MinProperty, value); } public float Max { get => (float) GetValue(MaxProperty); set => SetValue(MaxProperty, value); } private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { NumberInput input = (NumberInput) d; input.Value = Math.Clamp((float) e.NewValue, input.Min, input.Max); } private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e) { Regex regex = new Regex("^[.][0-9]+$|^[0-9]*[.]{0,1}[0-9]*$"); e.Handled = !regex.IsMatch((sender as TextBox).Text.Insert((sender as TextBox).SelectionStart, e.Text)); } } }
36.121212
119
0.627517
[ "MIT" ]
RobertsMaxwell/PixiEditor
PixiEditor/Views/NumberInput.xaml.cs
2,386
C#
using BotEngine; namespace Sanderling.Interface.MemoryStruct { public interface IWindowDroneView : IWindow, IContainer, IUIElement, IObjectIdInMemory, IObjectIdInt64 { IListViewAndControl ListView { get; } } }
17.153846
103
0.775785
[ "Apache-2.0" ]
Fulborg/A-Bot
src/Sanderling.Interface/Sanderling.Interface.MemoryStruct/IWindowDroneView.cs
223
C#
using System.Management.Automation; using System.Threading.Tasks; using Microsoft.Diagnostics.Runtime.Interop; namespace MS.Dbg.Commands { // TODO: This class is one reason why we need "cd" to set the proper // debugger context, because we want to be able to invoke straight // dbgeng commands and have them work according to the right context. [Cmdlet( VerbsLifecycle.Invoke, "DbgEng" )] public class InvokeDbgEngCommand : ExecutionBaseCommand { // ValueFromRemainingArguments is convenient, but it also requires that the param // type be an array. (In script, it doesn't; but the parameter binder won't // convert to a single string for a C# cmdlet.) [Parameter( Mandatory = true, Position = 0, ValueFromRemainingArguments = true, ValueFromPipeline = true )] [ValidateNotNullOrEmpty] public string[] Command { get; set; } [Parameter( Mandatory = false )] [AllowEmptyString] public string OutputPrefix { get; set; } private void _ConsumeLine( string line ) { SafeWriteObject( line, true ); // this will get sent to the pipeline thread } protected override bool TrySetDebuggerContext { get { return true; } } protected override void BeginProcessing() { base.BeginProcessing(); m_dontDisplayRegisters = true; if( null == OutputPrefix ) { if( HostSupportsColor ) OutputPrefix = "\u009b34;106mDbgEng>\u009bm "; else OutputPrefix = "DbgEng> "; } else if( (OutputPrefix.Length > 0) && HostSupportsColor ) { OutputPrefix = "\u009b34;106m" + OutputPrefix + "\u009bm "; } } // end BeginProcessing() protected override void ProcessRecord() { var inputCallbacks = Debugger.GetInputCallbacks() as DebugInputCallbacks; if( null != inputCallbacks ) inputCallbacks.UpdateCmdlet( this ); //var outputCallbacks = Debugger.GetOutputCallbacks() as DebugOutputCallbacks; //if( null != outputCallbacks ) // outputCallbacks.UpdateCmdlet( this ); using( var disposer = new ExceptionGuard() ) { disposer.Protect( Debugger.SetCurrentCmdlet( this ) ); disposer.Protect( InterceptCtrlC() ); MsgLoop.Prepare(); string actualCommand = string.Join( " ", Command ); Task t = Debugger.InvokeDbgEngCommandAsync( actualCommand, OutputPrefix, _ConsumeLine ); Task t2 = t.ContinueWith( async ( x ) => { DEBUG_STATUS execStatus = Debugger.GetExecutionStatus(); if( _StatusRequiresWait( execStatus ) ) { LogManager.Trace( "InvokeDbgExtensionCommand: Current execution status ({0}) indicates that we should enter a wait.", execStatus ); await WaitForBreakAsync(); } disposer.Dispose(); SignalDone(); } ).Unwrap(); MsgLoop.Run(); Host.UI.WriteLine(); Util.Await( t ); // in case it threw Util.Await( t2 ); // in case it threw } // end using( disposer ) } // end ProcessRecord() } // end class InvokeDbgEngCommand }
35.342857
141
0.54325
[ "MIT" ]
Bhaskers-Blu-Org2/DbgShell
DbgProvider/public/Commands/InvokeDbgEngCommand.cs
3,713
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using VOL.Core.Enums; using VOL.Core.Utilities; using VOL.Entity.DomainModels; namespace VOL.Core.Filters { public abstract class ServiceFunFilter<T> where T : class { /// <summary> /// 是否开启用户数据权限,true=用户只能操作自己(及下级角色)创建的数据,如:查询、删除、修改等操作 /// 注意:需要在代码生成器界面选择【是】及生成Model才会生效) /// </summary> protected bool LimitCurrentUserPermission { get; set; } = false; ///默认导出最大数量5K数据 protected int Limit { get; set; } = 5000; /// <summary> /// 默认上传文件大小限制3M /// </summary> protected int LimitUpFileSizee { get; set; } = 3; /// <summary> /// 查询前,对现在有的查询字符串条件增加或删除 /// </summary> protected Action<List<SearchParameters>> QueryRelativeList { get; set; } //查询前,在现有的查询条件上通过表达式修改查询条件 protected Func<IQueryable<T>, IQueryable<T>> QueryRelativeExpression { get; set; } /// <summary> /// 指定查询的列,格式:Expression<Func<T, object>> exp = x => new { x.字段1, x.字段2 } /// </summary> protected Expression<Func<T, object>> Columns { get; set; } /// <summary> /// 设置查询排序参数及方式,参数格式为: /// Expression<Func<T, Dictionary<object, bool>>> orderBy = x => new Dictionary<object, QueryOrderBy>() /// {{ x.ID, QueryOrderBy.Asc },{ x.DestWarehouseName, QueryOrderBy.Desc } }; /// 返回的是new Dictionary<object, bool>(){{}}key为排序字段,QueryOrderBy为排序方式 /// </summary> protected Expression<Func<T, Dictionary<object, QueryOrderBy>>> OrderByExpression; /// <summary> /// 设置查询的表名(已弃用) /// </summary> protected string TableName { get; set; } /// <summary> /// 页面查询或导出,从数据库查询出来的结果 /// </summary> protected Action<PageGridData<T>> GetPageDataOnExecuted; /// <summary> /// 调用新建处理前(SaveModel为传入的原生数据) /// </summary> protected Func<SaveModel, WebResponseContent> AddOnExecute; /// <summary> /// 调用新建保存数据库前处理(已将提交的原生数据转换成了对象) /// Func<T, object,ResponseData> T为主表数据,object为明细数据(如果需要使用明细对象,请用 object as List<T>转换) /// </summary> protected Func<T, object, WebResponseContent> AddOnExecuting; /// <summary> /// 调用新建保存数据库后处理。 /// **实现当前方法时,内部默认已经开启事务,如果实现的方法操作的是同一数据库,则不需要在AddOnExecuted中事务 /// Func<T, object,ResponseData> T为主表数据,object为明细数据(如果需要使用明细对象,请用 object as List<T>转换) /// 此处已开启了DbContext事务(重点),如果还有其他业务处事,直接在这里写EF代码,不需要再开启事务 /// 如果执行的是手写sql请用repository.DbContext.Database.ExecuteSqlCommand()或 repository.DbContext.Set<T>().FromSql执行具体sql语句 /// </summary> protected Func<T, object, WebResponseContent> AddOnExecuted; /// <summary> /// 调用更新方法前处理(SaveModel为传入的原生数据) /// </summary> protected Func<SaveModel, WebResponseContent> UpdateOnExecute; /// <summary> /// 调用更新方法保存数据库前处理 /// (已将提交的原生数据转换成了对象,将明细新增、修改、删除的数据分别用object1/2/3标识出来 ) /// T=更新的主表对象 /// object1=为新增明细的对象,使用时将object as List<T>转换一下 /// object2=为更新明细的对象 /// List<object>=为删除的细的对象Key /// </summary> protected Func<T, object, object, List<object>, WebResponseContent> UpdateOnExecuting; /// <summary> /// 调用更新方法保存数据库后处理 /// **实现当前方法时,内部默认已经开启事务,如果实现的方法操作的是同一数据库,则不需要在UpdateOnExecuted中事务 /// (已将提交的原生数据转换成了对象,将明细新增、修改、删除的数据分别用object1/2/3标识出来 ) /// T=更新的主表对象 /// object1=为新增明细的对象,使用时将object as List<T>转换一下 /// object2=为更新明细的对象 /// List<object>=为删除的细的对象Key /// 此处已开启了DbContext事务(重点),如果还有其他业务处事,直接在这里写EF代码,不需要再开启事务 /// 如果执行的是手写sql请用repository.DbContext.Database.ExecuteSqlCommand()或 repository.DbContext.Set<T>().FromSql执行具体sql语句 /// </summary> protected Func<T, object, object, List<object>, WebResponseContent> UpdateOnExecuted; /// <summary> /// 删除前处理,object[]准备删除的主键 /// </summary> protected Func<object[], WebResponseContent> DelOnExecuting; /// <summary> /// 删除后处理,object[]已删除的主键,此处已开启了DbContext事务(重点),如果还有其他业务处事,直接在这里写EF代码,不需要再开启事务 /// 如果执行的是手写sql请用repository.DbContext.Database.ExecuteSqlCommand()或 repository.DbContext.Set<T>().FromSql执行具体sql语句 /// </summary> protected Func<object[], WebResponseContent> DelOnExecuted; /// <summary> /// 审核前处理 /// </summary> protected Func<List<T>, WebResponseContent> AuditOnExecuting; /// <summary> /// 审核后处理 /// </summary> protected Func<List<T>, WebResponseContent> AuditOnExecuted; /// <summary> ///导出前处理,DataTable导出的表数据 ///List<T>导出的数据, List<string>忽略不需要导出的字段 /// </summary> protected Func<List<T>, List<string>, WebResponseContent> ExportOnExecuting; /// <summary> /// 导入保存后 /// </summary> protected Func<List<T>, WebResponseContent> ImportOnExecuted; /// <summary> /// 导入保存前 /// </summary> protected Func<List<T>, WebResponseContent> ImportOnExecuting; } }
36.809859
122
0.610293
[ "MIT" ]
h-alone/.NETCORE-VUE
Vue.Net/VOL.Core/Filters/ServiceFunFilter.cs
6,871
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; namespace ShaderTools.Utilities { // Helpers that are missing from Dev11 implementation: internal static class WeakReferenceExtensions { public static T GetTarget<T>(this WeakReference<T> reference) where T : class { reference.TryGetTarget(out var target); return target; } } }
31.529412
162
0.664179
[ "Apache-2.0" ]
BigHeadGift/HLSL
src/ShaderTools.Utilities/WeakReferenceExtensions.cs
522
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.12 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace Autodesk.Fbx { public class FbxImporter : FbxIOBase { internal FbxImporter(global::System.IntPtr cPtr, bool ignored) : base(cPtr, ignored) { } // override void Dispose() {base.Dispose();} public new static FbxImporter Create(FbxManager pManager, string pName) { global::System.IntPtr cPtr = NativeMethods.FbxImporter_Create__SWIG_0(FbxManager.getCPtr(pManager), pName); FbxImporter ret = (cPtr == global::System.IntPtr.Zero) ? null : new FbxImporter(cPtr, false); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } public new static FbxImporter Create(FbxObject pContainer, string pName) { global::System.IntPtr cPtr = NativeMethods.FbxImporter_Create__SWIG_1(FbxObject.getCPtr(pContainer), pName); FbxImporter ret = (cPtr == global::System.IntPtr.Zero) ? null : new FbxImporter(cPtr, false); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } public void GetFileVersion(out int pMajor, out int pMinor, out int pRevision) { NativeMethods.FbxImporter_GetFileVersion(swigCPtr, out pMajor, out pMinor, out pRevision); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); } public FbxIOFileHeaderInfo GetFileHeaderInfo() { global::System.IntPtr cPtr = NativeMethods.FbxImporter_GetFileHeaderInfo(swigCPtr); FbxIOFileHeaderInfo ret = (cPtr == global::System.IntPtr.Zero) ? null : new FbxIOFileHeaderInfo(cPtr, false); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } public bool Import(FbxDocument pDocument) { bool ret = NativeMethods.FbxImporter_Import(swigCPtr, FbxDocument.getCPtr(pDocument)); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } public int GetAnimStackCount() { int ret = NativeMethods.FbxImporter_GetAnimStackCount(swigCPtr); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } public string GetActiveAnimStackName() { string ret = NativeMethods.FbxImporter_GetActiveAnimStackName(swigCPtr); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } public bool IsFBX() { bool ret = NativeMethods.FbxImporter_IsFBX(swigCPtr); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); return ret; } public override int GetHashCode(){ return swigCPtr.Handle.GetHashCode(); } public bool Equals(FbxImporter other) { if (object.ReferenceEquals(other, null)) { return false; } return this.swigCPtr.Handle.Equals (other.swigCPtr.Handle); } public override bool Equals(object obj){ if (object.ReferenceEquals(obj, null)) { return false; } /* is obj a subclass of this type; if so use our Equals */ var typed = obj as FbxImporter; if (!object.ReferenceEquals(typed, null)) { return this.Equals(typed); } /* are we a subclass of the other type; if so use their Equals */ if (typeof(FbxImporter).IsSubclassOf(obj.GetType())) { return obj.Equals(this); } /* types are unrelated; can't be a match */ return false; } public static bool operator == (FbxImporter a, FbxImporter b) { if (object.ReferenceEquals(a, b)) { return true; } if (object.ReferenceEquals(a, null) || object.ReferenceEquals(b, null)) { return false; } return a.Equals(b); } public static bool operator != (FbxImporter a, FbxImporter b) { return !(a == b); } private void SetFbxSharpProgressCallback(FbxSharpProgressCallback callback) { NativeMethods.FbxImporter_SetFbxSharpProgressCallback(swigCPtr, FbxSharpProgressCallback.getCPtr(callback)); if (NativeMethods.SWIGPendingException.Pending) throw NativeMethods.SWIGPendingException.Retrieve(); } FbxSharpProgressCallback m_progressCallback; public void SetProgressCallback(Globals.FbxProgressCallback callback) { if (m_progressCallback != null) { m_progressCallback.Dispose(); } m_progressCallback = (callback == null) ? null : new FbxSharpProgressCallback.Wrapper(callback); SetFbxSharpProgressCallback(m_progressCallback); } } }
41.222222
113
0.720506
[ "Apache-2.0" ]
Ozker24/Improved
HDRP Improved/Library/PackageCache/com.autodesk.fbx@3.0.0-preview.1/Runtime/Scripts/FbxImporter.cs
4,823
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.5446 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Google.Apis.Audit.v1.Data { using System; using System.Collections; using System.Collections.Generic; public class Activities : Google.Apis.Requests.IDirectResponseSchema { private IList<Activity> items; private string kind; private string next; private Google.Apis.Requests.RequestError error; private string eTag; /// <summary>Each record in read response.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual IList<Activity> Items { get { return this.items; } set { this.items = value; } } /// <summary>Kind of list response this is.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get { return this.kind; } set { this.kind = value; } } /// <summary>Next page URL.</summary> [Newtonsoft.Json.JsonPropertyAttribute("next")] public virtual string Next { get { return this.next; } set { this.next = value; } } [Newtonsoft.Json.JsonPropertyAttribute("error")] public virtual Google.Apis.Requests.RequestError Error { get { return this.error; } set { this.error = value; } } public virtual string ETag { get { return this.eTag; } set { this.eTag = value; } } } public class Activity { private Activity.ActorData actor; private IList<Activity.EventsData> events; private Activity.IdData id; private string ipAddress; private string kind; private string ownerDomain; /// <summary>User doing the action.</summary> [Newtonsoft.Json.JsonPropertyAttribute("actor")] public virtual Activity.ActorData Actor { get { return this.actor; } set { this.actor = value; } } /// <summary>Activity events.</summary> [Newtonsoft.Json.JsonPropertyAttribute("events")] public virtual IList<Activity.EventsData> Events { get { return this.events; } set { this.events = value; } } /// <summary>Unique identifier for each activity record.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual Activity.IdData Id { get { return this.id; } set { this.id = value; } } /// <summary>IP Address of the user doing the action.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ipAddress")] public virtual string IpAddress { get { return this.ipAddress; } set { this.ipAddress = value; } } /// <summary>Kind of resource this is.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get { return this.kind; } set { this.kind = value; } } /// <summary>Domain of source customer.</summary> [Newtonsoft.Json.JsonPropertyAttribute("ownerDomain")] public virtual string OwnerDomain { get { return this.ownerDomain; } set { this.ownerDomain = value; } } /// <summary>User doing the action.</summary> public class ActorData { private string applicationId; private string callerType; private string email; private string key; /// <summary>ID of application which interacted on behalf of the user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("applicationId")] public virtual string ApplicationId { get { return this.applicationId; } set { this.applicationId = value; } } /// <summary>User or OAuth 2LO request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("callerType")] public virtual string CallerType { get { return this.callerType; } set { this.callerType = value; } } /// <summary>Email address of the user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("email")] public virtual string Email { get { return this.email; } set { this.email = value; } } /// <summary>For OAuth 2LO API requests, consumer_key of the requestor.</summary> [Newtonsoft.Json.JsonPropertyAttribute("key")] public virtual string Key { get { return this.key; } set { this.key = value; } } } public class EventsData { private string eventType; private string name; private IList<EventsData.ParametersData> parameters; /// <summary>Type of event.</summary> [Newtonsoft.Json.JsonPropertyAttribute("eventType")] public virtual string EventType { get { return this.eventType; } set { this.eventType = value; } } /// <summary>Name of event.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get { return this.name; } set { this.name = value; } } /// <summary>Event parameters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("parameters")] public virtual IList<EventsData.ParametersData> Parameters { get { return this.parameters; } set { this.parameters = value; } } public class ParametersData { private string name; private string value; /// <summary>Name of the parameter.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get { return this.name; } set { this.name = value; } } /// <summary>Value of the parameter.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual string Value { get { return this.value; } set { this.value = value; } } } } /// <summary>Unique identifier for each activity record.</summary> public class IdData { private string applicationId; private string customerId; private string time; private string uniqQualifier; /// <summary>Application ID of the source application.</summary> [Newtonsoft.Json.JsonPropertyAttribute("applicationId")] public virtual string ApplicationId { get { return this.applicationId; } set { this.applicationId = value; } } /// <summary>Obfuscated customer ID of the source customer.</summary> [Newtonsoft.Json.JsonPropertyAttribute("customerId")] public virtual string CustomerId { get { return this.customerId; } set { this.customerId = value; } } /// <summary>Time of occurrence of the activity.</summary> [Newtonsoft.Json.JsonPropertyAttribute("time")] public virtual string Time { get { return this.time; } set { this.time = value; } } /// <summary>Unique qualifier if multiple events have the same time.</summary> [Newtonsoft.Json.JsonPropertyAttribute("uniqQualifier")] public virtual string UniqQualifier { get { return this.uniqQualifier; } set { this.uniqQualifier = value; } } } } } namespace Google.Apis.Audit.v1 { using System; using System.IO; using System.Collections.Generic; using Google.Apis; using Google.Apis.Discovery; public partial class AuditService : Google.Apis.Discovery.IRequestProvider { private Google.Apis.Discovery.IService genericService; private Google.Apis.Authentication.IAuthenticator authenticator; private const string DiscoveryDocument = "{\"kind\":\"discovery#restDescription\",\"id\":\"audit:v1\",\"name\":\"audit\",\"version\":\"v1\"" + ",\"title\":\"Enterprise Audit API\",\"description\":\"Lets you access user activities i" + "n your enterprise made through various applications.\",\"icons\":{\"x16\":\"http://www" + ".google.com/images/icons/product/search-16.gif\",\"x32\":\"http://www.google.com/ima" + "ges/icons/product/search-32.gif\"},\"labels\":[\"labs\"],\"protocol\":\"rest\",\"basePath\"" + ":\"/apps/reporting/audit/v1/\",\"parameters\":{\"alt\":{\"type\":\"string\",\"description\":" + "\"Data format for the response.\",\"default\":\"json\",\"enum\":[\"atom\",\"json\"],\"enumDes" + "criptions\":[\"Responses with Content-Type of application/atom+xml\",\"Responses wit" + "h Content-Type of application/json\"],\"location\":\"query\"},\"fields\":{\"type\":\"strin" + "g\",\"description\":\"Selector specifying which fields to include in a partial respo" + "nse.\",\"location\":\"query\"},\"key\":{\"type\":\"string\",\"description\":\"API key. Your AP" + "I key identifies your project and provides you with API access, quota, and repor" + "ts. Required unless you provide an OAuth 2.0 token.\",\"location\":\"query\"},\"oauth_" + "token\":{\"type\":\"string\",\"description\":\"OAuth 2.0 token for the current user.\",\"l" + "ocation\":\"query\"},\"prettyPrint\":{\"type\":\"boolean\",\"description\":\"Returns respons" + "e with indentations and line breaks.\",\"default\":\"true\",\"location\":\"query\"},\"user" + "Ip\":{\"type\":\"string\",\"description\":\"IP address of the site where the request ori" + "ginates. Use this if you want to enforce per-user limits.\",\"location\":\"query\"}}," + "\"schemas\":{\"Activities\":{\"id\":\"Activities\",\"type\":\"object\",\"properties\":{\"items\"" + ":{\"type\":\"array\",\"description\":\"Each record in read response.\",\"items\":{\"$ref\":\"" + "Activity\"}},\"kind\":{\"type\":\"string\",\"description\":\"Kind of list response this is" + ".\",\"default\":\"audit#activities\"},\"next\":{\"type\":\"string\",\"description\":\"Next pag" + "e URL.\"}}},\"Activity\":{\"id\":\"Activity\",\"type\":\"object\",\"properties\":{\"actor\":{\"t" + "ype\":\"object\",\"description\":\"User doing the action.\",\"properties\":{\"applicationI" + "d\":{\"type\":\"string\",\"description\":\"ID of application which interacted on behalf " + "of the user.\",\"format\":\"int64\"},\"callerType\":{\"type\":\"string\",\"description\":\"Use" + "r or OAuth 2LO request.\"},\"email\":{\"type\":\"string\",\"description\":\"Email address " + "of the user.\"},\"key\":{\"type\":\"string\",\"description\":\"For OAuth 2LO API requests," + " consumer_key of the requestor.\"}}},\"events\":{\"type\":\"array\",\"description\":\"Acti" + "vity events.\",\"items\":{\"type\":\"object\",\"properties\":{\"eventType\":{\"type\":\"string" + "\",\"description\":\"Type of event.\"},\"name\":{\"type\":\"string\",\"description\":\"Name of" + " event.\"},\"parameters\":{\"type\":\"array\",\"description\":\"Event parameters.\",\"items\"" + ":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\",\"description\":\"Name of t" + "he parameter.\"},\"value\":{\"type\":\"string\",\"description\":\"Value of the parameter.\"" + "}}}}}}},\"id\":{\"type\":\"object\",\"description\":\"Unique identifier for each activity" + " record.\",\"properties\":{\"applicationId\":{\"type\":\"string\",\"description\":\"Applicat" + "ion ID of the source application.\",\"format\":\"int64\"},\"customerId\":{\"type\":\"strin" + "g\",\"description\":\"Obfuscated customer ID of the source customer.\"},\"time\":{\"type" + "\":\"string\",\"description\":\"Time of occurrence of the activity.\",\"format\":\"date-ti" + "me\"},\"uniqQualifier\":{\"type\":\"string\",\"description\":\"Unique qualifier if multipl" + "e events have the same time.\",\"format\":\"int64\"}}},\"ipAddress\":{\"type\":\"string\",\"" + "description\":\"IP Address of the user doing the action.\"},\"kind\":{\"type\":\"string\"" + ",\"description\":\"Kind of resource this is.\",\"default\":\"audit#activity\"},\"ownerDom" + "ain\":{\"type\":\"string\",\"description\":\"Domain of source customer.\"}}}},\"resources\"" + ":{\"activities\":{\"methods\":{\"list\":{\"id\":\"audit.activities.list\",\"path\":\"{custome" + "rId}/{applicationId}\",\"httpMethod\":\"GET\",\"description\":\"Retrieves a list of acti" + "vities for a specific customer and application.\",\"parameters\":{\"actorApplication" + "Id\":{\"type\":\"integer\",\"description\":\"Application ID of the application which int" + "eracted on behalf of the user while performing the event.\",\"minimum\":\"-922337203" + "6854775808\",\"maximum\":\"9223372036854775807\",\"location\":\"query\"},\"actorEmail\":{\"t" + "ype\":\"string\",\"description\":\"Email address of the user who performed the action." + "\",\"location\":\"query\"},\"applicationId\":{\"type\":\"integer\",\"description\":\"Applicati" + "on ID of the application on which the event was performed.\",\"required\":true,\"min" + "imum\":\"-9223372036854775808\",\"maximum\":\"9223372036854775807\",\"location\":\"path\"}," + "\"caller\":{\"type\":\"string\",\"description\":\"Type of the caller.\",\"enum\":[\"applicati" + "on_owner\",\"customer\"],\"enumDescriptions\":[\"Caller is an application owner.\",\"Cal" + "ler is a customer.\"],\"location\":\"query\"},\"continuationToken\":{\"type\":\"string\",\"d" + "escription\":\"Next page URL.\",\"location\":\"query\"},\"customerId\":{\"type\":\"string\",\"" + "description\":\"Represents the customer who is the owner of target object on which" + " action was performed.\",\"required\":true,\"pattern\":\"C.+\",\"location\":\"path\"},\"endT" + "ime\":{\"type\":\"string\",\"description\":\"Return events which occured at or before th" + "is time.\",\"location\":\"query\"},\"eventName\":{\"type\":\"string\",\"description\":\"Name o" + "f the event being queried.\",\"location\":\"query\"},\"maxResults\":{\"type\":\"integer\",\"" + "description\":\"Number of activity records to be shown in each page.\",\"minimum\":\"1" + "\",\"maximum\":\"1000\",\"location\":\"query\"},\"parameters\":{\"type\":\"string\",\"descriptio" + "n\":\"Event parameters in the form\\n:\\n.\",\"location\":\"query\"},\"startTime\":{\"type\":" + "\"string\",\"description\":\"Return events which occured at or after this time.\",\"loc" + "ation\":\"query\"}},\"parameterOrder\":[\"customerId\",\"applicationId\"],\"response\":{\"$r" + "ef\":\"Activities\"}}}}}}"; private const string Version = "v1"; private const string Name = "audit"; private const string BaseUri = "https://www.googleapis.com/apps/reporting/audit/v1/"; private const Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; private string key; protected AuditService(Google.Apis.Discovery.IService genericService, Google.Apis.Authentication.IAuthenticator authenticator) { this.genericService = genericService; this.authenticator = authenticator; this.activities = new ActivitiesResource(this); } public AuditService() : this(Google.Apis.Authentication.NullAuthenticator.Instance) { } public AuditService(Google.Apis.Authentication.IAuthenticator authenticator) : this(new Google.Apis.Discovery.DiscoveryService(new Google.Apis.Discovery.StringDiscoveryDevice(DiscoveryDocument)).GetService(AuditService.DiscoveryVersionUsed, new Google.Apis.Discovery.FactoryParameterV1_0(new System.Uri(AuditService.BaseUri))), authenticator) { } /// <summary>Sets the API-Key (or DeveloperKey) which this service uses for all requests</summary> public virtual string Key { get { return this.key; } set { this.key = value; } } public virtual Google.Apis.Requests.IRequest CreateRequest(string resource, string method) { Google.Apis.Requests.IRequest request = this.genericService.CreateRequest(resource, method); if (!string.IsNullOrEmpty(Key)) { request = request.WithKey(this.Key); } return request.WithAuthentication(authenticator); } public virtual void RegisterSerializer(Google.Apis.ISerializer serializer) { genericService.Serializer = serializer; } public virtual string SerializeObject(object obj) { return genericService.SerializeRequest(obj); } public virtual T DeserializeResponse<T>(Google.Apis.Requests.IResponse response) { return genericService.DeserializeResponse<T>(response); } } public class ActivitiesResource { private Google.Apis.Discovery.IRequestProvider service; private const string Resource = "activities"; public ActivitiesResource(AuditService service) { this.service = service; } /// <summary>Retrieves a list of activities for a specific customer and application.</summary> /// <param name="customerId">Required - Must match pattern C.+ - Represents the customer who is the owner of target object on which action was performed.</param> /// <param name="applicationId">Required - Minimum value of -9223372036854775808 - Maximum value of 9223372036854775807 - Application ID of the application on which the event was performed.</param> public virtual ListRequest List(string customerId, long applicationId) { return new ListRequest(service, customerId, applicationId); } /// <summary>Retrieves a list of activities for a specific customer and application.</summary> /// <param name="customerId">Required - Must match pattern C.+ - Represents the customer who is the owner of target object on which action was performed.</param> /// <param name="applicationId">Required - Minimum value of -9223372036854775808 - Maximum value of 9223372036854775807 - Application ID of the application on which the event was performed.</param> /// <param name="actorApplicationId">Optional - Minimum value of -9223372036854775808 - Maximum value of 9223372036854775807 - Application ID of the application which interacted on behalf of the user while performing the event.</param> /// <param name="actorEmail">Optional - Email address of the user who performed the action.</param> /// <param name="caller">Optional - Must be one of the following values [application_owner, customer] - Type of the caller.</param> /// <param name="continuationToken">Optional - Next page URL.</param> /// <param name="endTime">Optional - Return events which occured at or before this time.</param> /// <param name="eventName">Optional - Name of the event being queried.</param> /// <param name="maxResults">Optional - Minimum value of 1 - Maximum value of 1000 - Number of activity records to be shown in each page.</param> /// <param name="parameters">Optional - Event parameters in the form ///: ///.</param> /// <param name="startTime">Optional - Return events which occured at or after this time.</param> public virtual ListRequest List(string customerId, long applicationId, [System.Runtime.InteropServices.OptionalAttribute()] System.Int64? actorApplicationId, [System.Runtime.InteropServices.OptionalAttribute()] string actorEmail, [System.Runtime.InteropServices.OptionalAttribute()] Caller? caller, [System.Runtime.InteropServices.OptionalAttribute()] string continuationToken, [System.Runtime.InteropServices.OptionalAttribute()] string endTime, [System.Runtime.InteropServices.OptionalAttribute()] string eventName, [System.Runtime.InteropServices.OptionalAttribute()] System.Int64? maxResults, [System.Runtime.InteropServices.OptionalAttribute()] string parameters, [System.Runtime.InteropServices.OptionalAttribute()] string startTime) { return new ListRequest(service, customerId, applicationId, actorApplicationId, actorEmail, caller, continuationToken, endTime, eventName, maxResults, parameters, startTime); } /// <summary>Type of the caller.</summary> [System.ComponentModel.TypeConverterAttribute(typeof(Google.Apis.Util.EnumStringValueTypeConverter))] public enum Caller { /// <summary>Caller is an application owner.</summary> [Google.Apis.Util.StringValueAttribute("application_owner")] Application_owner, /// <summary>Caller is a customer.</summary> [Google.Apis.Util.StringValueAttribute("customer")] Customer, } public class ListRequest : Google.Apis.Requests.ServiceRequest<Google.Apis.Audit.v1.Data.Activities> { private System.Int64? actorApplicationId; private string actorEmail; private long applicationId; private Caller? caller; private string continuationToken; private string customerId; private string endTime; private string eventName; private System.Int64? maxResults; private string parameters; private string startTime; public ListRequest(Google.Apis.Discovery.IRequestProvider service, string customerId, long applicationId) : base(service) { this.customerId = customerId; this.applicationId = applicationId; } public ListRequest(Google.Apis.Discovery.IRequestProvider service, string customerId, long applicationId, [System.Runtime.InteropServices.OptionalAttribute()] System.Int64? actorApplicationId, [System.Runtime.InteropServices.OptionalAttribute()] string actorEmail, [System.Runtime.InteropServices.OptionalAttribute()] Caller? caller, [System.Runtime.InteropServices.OptionalAttribute()] string continuationToken, [System.Runtime.InteropServices.OptionalAttribute()] string endTime, [System.Runtime.InteropServices.OptionalAttribute()] string eventName, [System.Runtime.InteropServices.OptionalAttribute()] System.Int64? maxResults, [System.Runtime.InteropServices.OptionalAttribute()] string parameters, [System.Runtime.InteropServices.OptionalAttribute()] string startTime) : base(service) { this.customerId = customerId; this.applicationId = applicationId; this.actorApplicationId = actorApplicationId; this.actorEmail = actorEmail; this.caller = caller; this.continuationToken = continuationToken; this.endTime = endTime; this.eventName = eventName; this.maxResults = maxResults; this.parameters = parameters; this.startTime = startTime; } /// <summary>Application ID of the application which interacted on behalf of the user while performing the event.</summary> [Google.Apis.Util.RequestParameterAttribute("actorApplicationId")] public virtual System.Int64? ActorApplicationId { get { return this.actorApplicationId; } set { this.actorApplicationId = value; } } /// <summary>Email address of the user who performed the action.</summary> [Google.Apis.Util.RequestParameterAttribute("actorEmail")] public virtual string ActorEmail { get { return this.actorEmail; } set { this.actorEmail = value; } } /// <summary>Application ID of the application on which the event was performed.</summary> [Google.Apis.Util.RequestParameterAttribute("applicationId")] public virtual long ApplicationId { get { return this.applicationId; } } /// <summary>Type of the caller.</summary> [Google.Apis.Util.RequestParameterAttribute("caller")] public virtual Caller? Caller { get { return this.caller; } set { this.caller = value; } } /// <summary>Next page URL.</summary> [Google.Apis.Util.RequestParameterAttribute("continuationToken")] public virtual string ContinuationToken { get { return this.continuationToken; } set { this.continuationToken = value; } } /// <summary>Represents the customer who is the owner of target object on which action was performed.</summary> [Google.Apis.Util.RequestParameterAttribute("customerId")] public virtual string CustomerId { get { return this.customerId; } } /// <summary>Return events which occured at or before this time.</summary> [Google.Apis.Util.RequestParameterAttribute("endTime")] public virtual string EndTime { get { return this.endTime; } set { this.endTime = value; } } /// <summary>Name of the event being queried.</summary> [Google.Apis.Util.RequestParameterAttribute("eventName")] public virtual string EventName { get { return this.eventName; } set { this.eventName = value; } } /// <summary>Number of activity records to be shown in each page.</summary> [Google.Apis.Util.RequestParameterAttribute("maxResults")] public virtual System.Int64? MaxResults { get { return this.maxResults; } set { this.maxResults = value; } } /// <summary>Event parameters in the form ///: ///.</summary> [Google.Apis.Util.RequestParameterAttribute("parameters")] public virtual string Parameters { get { return this.parameters; } set { this.parameters = value; } } /// <summary>Return events which occured at or after this time.</summary> [Google.Apis.Util.RequestParameterAttribute("startTime")] public virtual string StartTime { get { return this.startTime; } set { this.startTime = value; } } protected override string ResourcePath { get { return "activities"; } } protected override string MethodName { get { return "list"; } } } } public partial class AuditService { private const string Resource = ""; private ActivitiesResource activities; private Google.Apis.Discovery.IRequestProvider service { get { return this; } } public virtual ActivitiesResource Activities { get { return this.activities; } } } }
45.093278
790
0.513278
[ "Apache-2.0" ]
Victhor94/loggencsg
vendors/gapi/Src/google-api-dotnet-client.contrib/20110811-0.9.3/Generated/Source/Google.Apis.Audit.v1.cs
32,873
C#
/* * Generated code file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty */ using System; using System.Diagnostics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Xml; using System.Xml.XPath; // Image 3: System.Xml.dll - Assembly: System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e - Types 1759-2427 namespace MS.Internal.Xml.Cache { internal sealed class XPathDocumentNavigator : XPathNavigator, IXmlLineInfo // TypeDefIndex: 1780 { // Fields private XPathNode[] pageCurrent; // 0x10 private XPathNode[] pageParent; // 0x18 private int idxCurrent; // 0x20 private int idxParent; // 0x24 // Properties public override string Value { get; } // 0x0000000180E892F0-0x0000000180E89590 public override XPathNodeType NodeType { get; } // 0x0000000180E89240-0x0000000180E89280 public override string LocalName { get; } // 0x0000000180E89150-0x0000000180E891A0 public override string NamespaceURI { get; } // 0x0000000180E891F0-0x0000000180E89240 public override string Prefix { get; } // 0x0000000180E89280-0x0000000180E892D0 public override XmlNameTable NameTable { get; } // 0x0000000180E891A0-0x0000000180E891F0 public override object UnderlyingObject { get; } // 0x0000000180E892D0-0x0000000180E892F0 public int LineNumber { get; } // 0x0000000180E88FF0-0x0000000180E89090 public int LinePosition { get; } // 0x0000000180E89090-0x0000000180E89150 // Constructors public XPathDocumentNavigator(XPathNode[] pageCurrent, int idxCurrent, XPathNode[] pageParent, int idxParent); // 0x0000000180E88F60-0x0000000180E88FF0 // Methods public override XPathNavigator Clone(); // 0x0000000180E88940-0x0000000180E88A10 public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope); // 0x0000000180E88B00-0x0000000180E88D20 public override bool MoveToNextNamespace(XPathNamespaceScope scope); // 0x0000000180E88D20-0x0000000180E88ED0 public override bool MoveToParent(); // 0x0000000180E88ED0-0x0000000180E88F60 public override bool IsSamePosition(XPathNavigator other); // 0x0000000180E88A70-0x0000000180E88B00 public bool HasLineInfo(); // 0x0000000180E88A20-0x0000000180E88A70 public int GetPositionHashCode(); // 0x0000000180E88A10-0x0000000180E88A20 } }
47.5
153
0.793263
[ "MIT" ]
TotalJTM/PrimitierModdingFramework
Dumps/PrimitierDumpV1.0.1/MS/Internal/Xml/Cache/XPathDocumentNavigator.cs
2,377
C#
using System.Runtime.InteropServices; namespace Vulkan { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] [return: NativeTypeName( "uint64_t")] public unsafe delegate ulong PFN_vkGetDeviceMemoryOpaqueCaptureAddress([NativeTypeName("VkDevice")] VkDevice device, [NativeTypeName("const VkDeviceMemoryOpaqueCaptureAddressInfo *")] in VkDeviceMemoryOpaqueCaptureAddressInfo pInfo); }
55.272727
141
0.536184
[ "BSD-3-Clause" ]
trmcnealy/Vulkan
Vulkan/Delegates/PFN_vkGetDeviceMemoryOpaqueCaptureAddress.cs
608
C#
namespace Kartverket.Register.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddDocumentTranslation : DbMigration { public override void Up() { CreateTable( "dbo.DocumentTranslations", c => new { Id = c.Guid(nullable: false), RegisterItemId = c.Guid(nullable: false), Name = c.String(), Description = c.String(), CultureName = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.RegisterItems", t => t.RegisterItemId, cascadeDelete: true) .Index(t => t.RegisterItemId); } public override void Down() { DropForeignKey("dbo.DocumentTranslations", "RegisterItemId", "dbo.RegisterItems"); DropIndex("dbo.DocumentTranslations", new[] { "RegisterItemId" }); DropTable("dbo.DocumentTranslations"); } } }
32.970588
94
0.491525
[ "MIT" ]
kartverket/Geonorge.Register
Kartverket.Register/Migrations/201710090833469_AddDocumentTranslation.cs
1,121
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the appmesh-2019-01-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AppMesh.Model { /// <summary> /// Container for the parameters to the ListTagsForResource operation. /// List the tags for an App Mesh resource. /// </summary> public partial class ListTagsForResourceRequest : AmazonAppMeshRequest { private int? _limit; private string _nextToken; private string _resourceArn; /// <summary> /// Gets and sets the property Limit. /// <para> /// The maximum number of tag results returned by <code>ListTagsForResource</code> in /// paginated output. When this parameter is used, <code>ListTagsForResource</code> returns /// only <code>limit</code> results in a single page along with a <code>nextToken</code> /// response element. You can see the remaining results of the initial request by sending /// another <code>ListTagsForResource</code> request with the returned <code>nextToken</code> /// value. This value can be between 1 and 100. If you don't use this parameter, <code>ListTagsForResource</code> /// returns up to 100 results and a <code>nextToken</code> value if applicable. /// </para> /// </summary> [AWSProperty(Min=1, Max=50)] public int Limit { get { return this._limit.GetValueOrDefault(); } set { this._limit = value; } } // Check to see if Limit property is set internal bool IsSetLimit() { return this._limit.HasValue; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// The <code>nextToken</code> value returned from a previous paginated <code>ListTagsForResource</code> /// request where <code>limit</code> was used and the results exceeded the value of that /// parameter. Pagination continues from the end of the previous results that returned /// the <code>nextToken</code> value. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } /// <summary> /// Gets and sets the property ResourceArn. /// <para> /// The Amazon Resource Name (ARN) that identifies the resource to list the tags for. /// </para> /// </summary> [AWSProperty(Required=true)] public string ResourceArn { get { return this._resourceArn; } set { this._resourceArn = value; } } // Check to see if ResourceArn property is set internal bool IsSetResourceArn() { return this._resourceArn != null; } } }
36.420561
122
0.60816
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/AppMesh/Generated/Model/ListTagsForResourceRequest.cs
3,897
C#
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alex Kofman // Created: 2009.06.25 using System; using NUnit.Framework; using Xtensive.Orm.Configuration; using Xtensive.Orm.Tests.Model.StringKeyTestModel; namespace Xtensive.Orm.Tests.Model.StringKeyTestModel { [Serializable] [HierarchyRoot] [KeyGenerator(KeyGeneratorKind.None)] public class Product : Entity { [Key, Field(Length = 100)] public string Code { get; private set; } [Field(Length = 100)] public string Name { get; set; } public Product(string code) : base(code) { } } } namespace Xtensive.Orm.Tests.Model { public class StringKeyTest : AutoBuildTest { protected override DomainConfiguration BuildConfiguration() { var config = base.BuildConfiguration(); config.Types.Register(typeof (Product)); return config; } [Test] public void MainTest() { } } }
23.066667
64
0.660886
[ "MIT" ]
SergeiPavlov/dataobjects-net
Orm/Xtensive.Orm.Tests/Model/StringKeyTest.cs
1,038
C#
using System; using UnityEngine; using UnityEditor; using System.Linq; using System.IO; using System.Collections.Generic; using System.Reflection; namespace AssetBundleGraph { /** * IModifier is an interface which modifies incoming assets. * Subclass of IModifier must have CustomModifier attribute. */ public interface IModifier { /** * Test if incoming assset is different from this IModifier's setting. * asset is always type of object defined */ bool IsModified (object asset); /** * Modifies incoming asset. */ void Modify (object asset); /** * Draw Inspector GUI for this Modifier. */ void OnInspectorGUI (Action onValueChanged); /** * Serialize this Modifier to JSON using JsonUtility. */ string Serialize(); } /** * Used to declare the class is used as a IModifier. * Classes with CustomModifier attribute must implement IModifier interface. */ [AttributeUsage(AttributeTargets.Class)] public class CustomModifier : Attribute { private string m_name; private Type m_modifyFor; /** * Name of Modifier appears on GUI. */ public string Name { get { return m_name; } } /** * Type of asset Modifier modifies. */ public Type For { get { return m_modifyFor; } } /** * CustomModifier declares the class is used as a IModifier. * @param [in] name Name of Modifier appears on GUI. * @param [in] modifyFor Type of asset Modifier modifies. */ public CustomModifier (string name, Type modifyFor) { m_name = name; m_modifyFor = modifyFor; } } public class ModifierUtility { private static Dictionary<Type, Dictionary<string, string>> s_attributeClassNameMap; public static Dictionary<string, string> GetAttributeClassNameMap (Type targetType) { UnityEngine.Assertions.Assert.IsNotNull(targetType); if(s_attributeClassNameMap == null) { s_attributeClassNameMap = new Dictionary<Type, Dictionary<string, string>>(); } if(!s_attributeClassNameMap.Keys.Contains(targetType)) { var map = new Dictionary<string, string>(); var builders = Assembly .GetExecutingAssembly() .GetTypes() .Where(t => t != typeof(IModifier)) .Where(t => typeof(IModifier).IsAssignableFrom(t)); foreach (var type in builders) { CustomModifier attr = type.GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; if (attr != null && attr.For == targetType) { if (!map.ContainsKey(attr.Name)) { map[attr.Name] = type.FullName; } else { Debug.LogWarning("Multiple CustomModifier class with the same name/type found. Ignoring " + type.Name); } } } s_attributeClassNameMap[targetType] = map; } return s_attributeClassNameMap[targetType]; } public static string GetModifierGUIName(IModifier m) { CustomModifier attr = m.GetType().GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; return attr.Name; } public static string GetModifierGUIName(string className) { var type = Type.GetType(className); if(type != null) { CustomModifier attr = Type.GetType(className).GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; if(attr != null) { return attr.Name; } } return string.Empty; } public static string GUINameToClassName(string guiName, Type targetType) { var map = GetAttributeClassNameMap(targetType); if(map.ContainsKey(guiName)) { return map[guiName]; } return null; } public static Type GetModifierTargetType(IModifier m) { CustomModifier attr = m.GetType().GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; UnityEngine.Assertions.Assert.IsNotNull(attr); return attr.For; } public static Type GetModifierTargetType(string className) { var type = Type.GetType(className); if(type != null) { CustomModifier attr = Type.GetType(className).GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; if(attr != null) { return attr.For; } } return null; } public static bool HasValidCustomModifierAttribute(Type t) { CustomModifier attr = t.GetCustomAttributes(typeof(CustomModifier), false).FirstOrDefault() as CustomModifier; if(attr != null) { return !string.IsNullOrEmpty(attr.Name) && attr.For != null; } return false; } public static IModifier CreateModifier(NodeData node, BuildTarget target) { return CreateModifier(node, BuildTargetUtility.TargetToGroup(target)); } public static IModifier CreateModifier(NodeData node, BuildTargetGroup targetGroup) { var data = node.InstanceData[targetGroup]; var className = node.ScriptClassName; Type dataType = null; if(!string.IsNullOrEmpty(className)) { dataType = Type.GetType(className); } if(data != null && dataType != null) { return JsonUtility.FromJson(data, dataType) as IModifier; } return null; } public static IModifier CreateModifier(string guiName, Type targetType) { var className = GUINameToClassName(guiName, targetType); if(className != null) { return (IModifier) Assembly.GetExecutingAssembly().CreateInstance(className); } return null; } public static IModifier CreateModifier(string className) { if(className == null) { return null; } Type t = Type.GetType(className); if(t == null) { return null; } if(!HasValidCustomModifierAttribute(t)) { return null; } return (IModifier) Assembly.GetExecutingAssembly().CreateInstance(className); } } }
26.142202
115
0.696964
[ "MIT" ]
sassembla/Advent2016_AssetBundleGraph
Assets/AssetBundleGraph/Editor/System/Modifiers/IModifier.cs
5,699
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Linq.Expressions; using System.Reflection; namespace Microsoft.AspNetCore.Mvc.ViewFeatures; public class MemberExpressionCacheKeyTest { [Fact] public void GetEnumerator_ReturnsMembers() { // Arrange var expected = new[] { typeof(TestModel3).GetProperty(nameof(TestModel3.Value)), typeof(TestModel2).GetProperty(nameof(TestModel2.TestModel3)), typeof(TestModel).GetProperty(nameof(TestModel.TestModel2)), }; var key = GetKey(m => m.TestModel2.TestModel3.Value); // Act var actual = GetMembers(key); // Assert Assert.Equal(expected, actual); } [Fact] public void GetEnumerator_WithNullableType_ReturnsMembers() { // Arrange var expected = new[] { typeof(DateTime).GetProperty(nameof(DateTime.Ticks)), typeof(DateTime?).GetProperty(nameof(Nullable<DateTime>.Value)), typeof(TestModel).GetProperty(nameof(TestModel.NullableDateTime)), }; var key = GetKey(m => m.NullableDateTime.Value.Ticks); // Act var actual = GetMembers(key); // Assert Assert.Equal(expected, actual); } [Fact] public void GetEnumerator_WithValueType_ReturnsMembers() { // Arrange var expected = new[] { typeof(DateTime).GetProperty(nameof(DateTime.Ticks)), typeof(TestModel).GetProperty(nameof(TestModel.DateTime)), }; var key = GetKey(m => m.DateTime.Ticks); // Act var actual = GetMembers(key); // Assert Assert.Equal(expected, actual); } private static MemberExpressionCacheKey GetKey<TResult>(Expression<Func<TestModel, TResult>> expression) { var memberExpression = Assert.IsAssignableFrom<MemberExpression>(expression.Body); return new MemberExpressionCacheKey(typeof(TestModel), memberExpression); } private static IList<MemberInfo> GetMembers(MemberExpressionCacheKey key) { var members = new List<MemberInfo>(); foreach (var member in key) { members.Add(member); } return members; } public class TestModel { public TestModel2 TestModel2 { get; set; } public DateTime DateTime { get; set; } public DateTime? NullableDateTime { get; set; } } public class TestModel2 { public string Name { get; set; } public TestModel3 TestModel3 { get; set; } } public class TestModel3 { public string Value { get; set; } } }
26.277778
108
0.608879
[ "MIT" ]
3ejki/aspnetcore
src/Mvc/Mvc.ViewFeatures/test/MemberExpressionCacheKeyTest.cs
2,840
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("MindsquallsNXT")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MindsquallsNXT")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("98ff11f4-d725-4a52-a019-b362e73aebcd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.864865
84
0.745896
[ "BSD-2-Clause" ]
DomenicP/NXTKinectDriverStation
NXTKinectConsole/Properties/AssemblyInfo.cs
1,404
C#
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/Beef using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Beef.CodeGen.Config { /// <summary> /// Represents a temporary capability to translate XML and YAML property names and values. For the most part the names will not change other than PascalCase versus camelCase. /// </summary> internal static class XmlYamlTranslate { private static readonly List<(ConfigType ConvertType, ConfigurationEntity Entity, string XmlName, string YamlName)> _config = new List<(ConfigType, ConfigurationEntity, string, string)>(new (ConfigType, ConfigurationEntity, string, string)[] { // Entity oriented configuration. (ConfigType.Entity, ConfigurationEntity.CodeGen, "AppendToNamespace", "refDataAppendToNamespace"), (ConfigType.Entity, ConfigurationEntity.CodeGen, "MapperDefaultRefDataConverter", "refDataDefaultMapperConverter"), (ConfigType.Entity, ConfigurationEntity.Entity, "AutoInferImplements", "implementsAutoInfer"), (ConfigType.Entity, ConfigurationEntity.Entity, "EntityFrameworkEntity", "entityFrameworkModel"), (ConfigType.Entity, ConfigurationEntity.Entity, "CosmosEntity", "cosmosModel"), (ConfigType.Entity, ConfigurationEntity.Entity, "ODataEntity", "odataModel"), (ConfigType.Entity, ConfigurationEntity.Entity, "ManagerConstructor", "managerCtor"), (ConfigType.Entity, ConfigurationEntity.Entity, "DataSvcConstructor", "dataSvcCtor"), (ConfigType.Entity, ConfigurationEntity.Entity, "DataConstructor", "dataCtor"), (ConfigType.Entity, ConfigurationEntity.Entity, "DataDatabaseMapperInheritsFrom", "databaseMapperInheritsFrom"), (ConfigType.Entity, ConfigurationEntity.Entity, "DataDatabaseCustomMapper", "databaseCustomMapper"), (ConfigType.Entity, ConfigurationEntity.Entity, "DataEntityFrameworkMapperInheritsFrom", "entityFrameworkMapperInheritsFrom"), (ConfigType.Entity, ConfigurationEntity.Entity, "DataEntityFrameworkCustomMapper", "entityFrameworkCustomMapper"), (ConfigType.Entity, ConfigurationEntity.Entity, "DataCosmosValueContainer", "cosmosValueContainer"), (ConfigType.Entity, ConfigurationEntity.Entity, "DataCosmosMapperInheritsFrom", "cosmosMapperInheritsFrom"), (ConfigType.Entity, ConfigurationEntity.Entity, "DataCosmosCustomMapper", "cosmosCustomMapper"), (ConfigType.Entity, ConfigurationEntity.Entity, "DataODataMapperInheritsFrom", "odataMapperInheritsFrom"), (ConfigType.Entity, ConfigurationEntity.Entity, "DataODataCustomMapper", "odataCustomMapper"), (ConfigType.Entity, ConfigurationEntity.Property, "IgnoreSerialization", "serializationIgnore"), (ConfigType.Entity, ConfigurationEntity.Property, "EmitDefaultValue", "serializationEmitDefault"), (ConfigType.Entity, ConfigurationEntity.Property, "IsDataConverterGeneric", "dataConverterIsGeneric"), (ConfigType.Entity, ConfigurationEntity.Property, "DataDatabaseMapper", "databaseMapper"), (ConfigType.Entity, ConfigurationEntity.Property, "DataDatabaseIgnore", "databaseIgnore"), (ConfigType.Entity, ConfigurationEntity.Operation, "OperationType", "type"), (ConfigType.Entity, ConfigurationEntity.Operation, "PagingArgs", "paging"), (ConfigType.Entity, ConfigurationEntity.Operation, "DataCosmosContainerId", "cosmosContainerId"), (ConfigType.Entity, ConfigurationEntity.Operation, "DataCosmosPartitionKey", "cosmosPartitionKey"), (ConfigType.Entity, ConfigurationEntity.Parameter, "IsDataConverterGeneric", "dataConverterIsGeneric"), (ConfigType.Entity, ConfigurationEntity.Parameter, "ValidatorFluent", "validatorCode"), // Database oriented configuration. (ConfigType.Database, ConfigurationEntity.StoredProcedure, "OrderBy", "orderby"), (ConfigType.Database, ConfigurationEntity.Parameter, "IsNullable", "nullable"), (ConfigType.Database, ConfigurationEntity.Parameter, "IsCollection", "collection") }); private static readonly List<(ConfigType ConvertType, ConfigurationEntity Entity, string XmlName, bool IsArray, Func<string?, string?>? Converter)> _xmlToYamlConvert = new List<(ConfigType, ConfigurationEntity, string, bool, Func<string?, string?>?)>(new (ConfigType, ConfigurationEntity, string, bool, Func<string?, string?>?)[] { (ConfigType.Entity, ConfigurationEntity.CodeGen, "xmlns", false, (xml) => NullValue()), (ConfigType.Entity, ConfigurationEntity.CodeGen, "xsi", false, (xml) => NullValue()), (ConfigType.Entity, ConfigurationEntity.CodeGen, "noNamespaceSchemaLocation", false, (xml) => NullValue()), (ConfigType.Entity, ConfigurationEntity.CodeGen, "WebApiAuthorize", false, (xml) => string.IsNullOrEmpty(xml) ? null : (xml == "true" ? "Authorize" : (xml == "false" ? "AllowAnonymous" : xml))), (ConfigType.Entity, ConfigurationEntity.CodeGen, "EventPublish", false, (xml) => ConvertEventPublish(xml)), (ConfigType.Entity, ConfigurationEntity.CodeGen, "EntityUsing", false, (xml) => throw new CodeGenException("CodeGeneration.EntityUsing has been deprecated; is replaced by CodeGeneration.EntityScope, Entity.EntityScope and Entity.EntityUsing.")), (ConfigType.Entity, ConfigurationEntity.Entity, "ManagerCtorParams", true, null), (ConfigType.Entity, ConfigurationEntity.Entity, "DataSvcCtorParams", true, null), (ConfigType.Entity, ConfigurationEntity.Entity, "DataCtorParams", true, null), (ConfigType.Entity, ConfigurationEntity.Entity, "WebApiCtorParams", true, null), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeData", false, (xml) => string.IsNullOrEmpty(xml) ? null : (xml == "true" ? "Exclude" : "RequiresMapper")), (ConfigType.Entity, ConfigurationEntity.Entity, "WebApiAuthorize", false, (xml) => string.IsNullOrEmpty(xml) ? null : (xml == "true" ? "Authorize" : (xml == "false" ? "AllowAnonymous" : xml))), (ConfigType.Entity, ConfigurationEntity.Entity, "EventPublish", false, (xml) => ConvertEventPublish(xml)), (ConfigType.Entity, ConfigurationEntity.Operation, "WebApiAuthorize", false, (xml) => string.IsNullOrEmpty(xml) ? null : (xml == "true" ? "Authorize" : (xml == "false" ? "AllowAnonymous" : xml))), (ConfigType.Entity, ConfigurationEntity.Operation, "WebApiOperationType", false, (xml) => throw new CodeGenException("Operation.WebApiOperationType has been renamed; please change to Operation.ManagerOperationType.")), (ConfigType.Entity, ConfigurationEntity.Operation, "EventPublish", false, (xml) => ConvertEventPublish(xml)), (ConfigType.Entity, ConfigurationEntity.Property, "Type", false, (xml) => xml != null && xml.StartsWith("RefDataNamespace.", StringComparison.InvariantCulture) ? $"^{xml[17..]}" : xml), (ConfigType.Entity, ConfigurationEntity.Parameter, "Type", false, (xml) => xml != null && xml.StartsWith("RefDataNamespace.", StringComparison.InvariantCulture) ? $"^{xml[17..]}" : xml), (ConfigType.Database, ConfigurationEntity.CodeGen, "xmlns", false, (xml) => NullValue()), (ConfigType.Database, ConfigurationEntity.CodeGen, "xsi", false, (xml) => NullValue()), (ConfigType.Database, ConfigurationEntity.CodeGen, "noNamespaceSchemaLocation", false, (xml) => NullValue()), (ConfigType.Database, ConfigurationEntity.CodeGen, "CdcExcludeColumnsFromETag", true, null), (ConfigType.Database, ConfigurationEntity.Query, "IncludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.Query, "ExcludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.Query, "AliasColumns", true, null), (ConfigType.Database, ConfigurationEntity.QueryJoin, "IncludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.QueryJoin, "ExcludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.QueryJoin, "AliasColumns", true, null), (ConfigType.Database, ConfigurationEntity.Table, "IncludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.Table, "ExcludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.Table, "GetAllOrderBy", true, null), (ConfigType.Database, ConfigurationEntity.Table, "UdtExcludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.Table, "View", false, (xml) => throw new CodeGenException("Table.View property is no longer supported; please use the new Query capability (more advanced).")), (ConfigType.Database, ConfigurationEntity.Table, "ViewName", false, (xml) => throw new CodeGenException("Table.View property is no longer supported; please use the new Query capability (more advanced).")), (ConfigType.Database, ConfigurationEntity.Table, "ViewSchema", false, (xml) => throw new CodeGenException("Table.View property is no longer supported; please use the new Query capability (more advanced).")), (ConfigType.Database, ConfigurationEntity.StoredProcedure, "Type", false, (xml) => string.IsNullOrEmpty(xml) ? null : (xml == "GetAll" ? "GetColl" : xml)), (ConfigType.Database, ConfigurationEntity.StoredProcedure, "IncludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.StoredProcedure, "ExcludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.StoredProcedure, "MergeOverrideIdentityColumns", true, null), (ConfigType.Database, ConfigurationEntity.OrderBy, "Order", false, (xml) => string.IsNullOrEmpty(xml) ? null : (xml.StartsWith("Des", StringComparison.OrdinalIgnoreCase) ? "Descending" : "Ascending")), (ConfigType.Database, ConfigurationEntity.Cdc, "IncludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.Cdc, "ExcludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.Cdc, "AliasColumns", true, null), (ConfigType.Database, ConfigurationEntity.Cdc, "DataCtorParams", true, null), (ConfigType.Database, ConfigurationEntity.Cdc, "IdentifierMappingColumns", true, null), (ConfigType.Database, ConfigurationEntity.Cdc, "IncludeColumnsOnDelete", true, null), (ConfigType.Database, ConfigurationEntity.Cdc, "ExcludeColumnsFromETag", true, null), (ConfigType.Database, ConfigurationEntity.CdcJoin, "IncludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.CdcJoin, "ExcludeColumns", true, null), (ConfigType.Database, ConfigurationEntity.CdcJoin, "AliasColumns", true, null), (ConfigType.Database, ConfigurationEntity.CdcJoin, "IdentifierMappingColumns", true, null), (ConfigType.Database, ConfigurationEntity.CdcJoin, "IncludeColumnsOnDelete", true, null), (ConfigType.Database, ConfigurationEntity.CdcJoin, "ExcludeColumnsFromETag", true, null) }); private static string? NullValue() => (string?)null!; private static string? ConvertEventPublish(string? xml) { if (string.IsNullOrEmpty(xml)) return null; if (string.Compare(xml, "true", StringComparison.InvariantCultureIgnoreCase) == 0) return "DataSvc"; if (string.Compare(xml, "false", StringComparison.InvariantCultureIgnoreCase) == 0) return "None"; return xml; } private static readonly List<(ConfigType ConvertType, ConfigurationEntity Entity, string XmlName, Type OverrideType, PropertySchemaAttribute Attribute)> _xmlSpecificPropertySchema = new List<(ConfigType, ConfigurationEntity, string, Type, PropertySchemaAttribute)>(new (ConfigType, ConfigurationEntity, string, Type, PropertySchemaAttribute)[] { (ConfigType.Entity, ConfigurationEntity.CodeGen, "WebApiAuthorize", typeof(string), new PropertySchemaAttribute("WebApi") { Title = "The authorize attribute value to be used for the corresponding entity Web API controller; generally `Authorize` (or `true`), otherwise `AllowAnonymous` (or `false`).", Description = "Defaults to `AllowAnonymous`. This can be overridden within the `Entity`(s) and/or their corresponding `Operation`(s)." }), (ConfigType.Entity, ConfigurationEntity.CodeGen, "EventPublish", typeof(string), new PropertySchemaAttribute("Events") { Title = "The layer to add logic to publish an event for a `Create`, `Update` or `Delete` operation.", Options = new string[] { "None", "false", "DataSvc", "true", "Data" }, Description = "Defaults to `DataSvc` (`true`); unless the `EventOutbox` is not `None` where it will default to `Data`. Used to enable the sending of messages to the likes of EventHub, Service Broker, SignalR, etc. This can be overridden within the `Entity`(s)." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ManagerCtorParams", typeof(string), new PropertySchemaAttribute("Manager") { Title = "The comma seperated list of additional (non-inferred) Dependency Injection (DI) parameters for the generated `Manager` constructor.", IsImportant = true, Description = "Each constructor parameter should be formatted as `Type` + `^` + `Name`; e.g. `IConfiguration^Config`. Where the `Name` portion is not specified it will be inferred. " + "Where the `Type` matches an already inferred value it will be ignored." }), (ConfigType.Entity, ConfigurationEntity.Entity, "DataSvcCtorParams", typeof(string), new PropertySchemaAttribute("DataSvc") { Title = "The comma seperated list of additional (non-inferred) Dependency Injection (DI) parameters for the generated `DataSvc` constructor.", IsImportant = true, Description = "Each constructor parameter should be formatted as `Type` + `^` + `Name`; e.g. `IConfiguration^Config`. Where the `Name` portion is not specified it will be inferred. " + "Where the `Type` matches an already inferred value it will be ignored." }), (ConfigType.Entity, ConfigurationEntity.Entity, "DataCtorParams", typeof(string), new PropertySchemaAttribute("Data") { Title = "The comma seperated list of additional (non-inferred) Dependency Injection (DI) parameters for the generated `Data` constructor.", IsImportant = true, Description = "Each constructor parameter should be formatted as `Type` + `^` + `Name`; e.g. `IConfiguration^Config`. Where the `Name` portion is not specified it will be inferred. " + "Where the `Type` matches an already inferred value it will be ignored." }), (ConfigType.Entity, ConfigurationEntity.Entity, "WebApiCtorParams", typeof(string), new PropertySchemaAttribute("WebApi") { Title = "The comma seperated list of additional (non-inferred) Dependency Injection (DI) parameters for the generated `WebApi` constructor.", IsImportant = true, Description = "Each constructor parameter should be formatted as `Type` + `^` + `Name`; e.g. `IConfiguration^Config`. Where the `Name` portion is not specified it will be inferred. " + "Where the `Type` matches an already inferred value it will be ignored." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeEntity", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `Entity` class (`Xxx.cs`)." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeAll", typeof(bool?), new PropertySchemaAttribute("ExcludeAll") { Title = "The option to exclude the generation of all `Operation` related artefacts; excluding the `Entity` class.", Description = "Is a shorthand means for setting all of the other `Exclude*` properties (with the exception of `ExcludeEntity`) to `true`." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeIData", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `IData` interface (`IXxxData.cs`)." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeData", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `Data` class (`XxxData.cs`).", Description = "An unspecified (null) value indicates _not_ to exclude. A value of `true` indicates to exclude all output; alternatively, where `false` is specifically specified it indicates to at least output the corresponding `Mapper` class." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeIDataSvc", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `IDataSvc` interface (`IXxxDataSvc.cs`)." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeDataSvc", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `DataSvc` class (`IXxxDataSvc.cs`)." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeIManager", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `IManager` interface (`IXxxManager.cs`)." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeManager", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `Manager` class (`XxxManager.cs`)." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeWebApi", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `XxxController` class (`IXxxController.cs`)." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeWebApiAgent", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `XxxAgent` class (`XxxAgent.cs`)." }), (ConfigType.Entity, ConfigurationEntity.Entity, "ExcludeGrpcAgent", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `XxxAgent` class (`XxxAgent.cs`)." }), (ConfigType.Entity, ConfigurationEntity.Entity, "WebApiAuthorize", typeof(string), new PropertySchemaAttribute("WebApi") { Title = "The authorize attribute value to be used for the corresponding entity Web API controller; generally `Authorize` (or `true`), otherwise `AllowAnonymous` (or `false`).", Description = "Defaults to the `CodeGeneration.WebApiAuthorize` configuration property (inherits) where not specified; can be overridden at the `Operation` level also." }), (ConfigType.Entity, ConfigurationEntity.Entity, "EventPublish", typeof(string), new PropertySchemaAttribute("Events") { Title = "The layer to add logic to publish an event for a `Create`, `Update` or `Delete` operation.", Options = new string[] { "None", "false", "DataSvc", "true", "Data" }, Description = "Defaults to the `CodeGeneration.EventPublish` configuration property (inherits) where not specified. Used to enable the sending of messages to the likes of EventHub, Service Broker, SignalR, etc. This can be overridden within the `Entity`(s)." }), (ConfigType.Entity, ConfigurationEntity.Operation, "ExcludeAll", typeof(bool?), new PropertySchemaAttribute("ExcludeAll") { Title = "The option to exclude the generation of all `Operation` related output; excluding the `Entity` class.", Description = "Is a shorthand means for setting all of the other `Exclude*` properties (with the exception of `ExcludeEntity`) to `true`." }), (ConfigType.Entity, ConfigurationEntity.Operation, "ExcludeIData", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `IData` interface (`IXxxData.cs`) output." }), (ConfigType.Entity, ConfigurationEntity.Operation, "ExcludeData", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `Data` class (`XxxData.cs`) output." }), (ConfigType.Entity, ConfigurationEntity.Operation, "ExcludeIDataSvc", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `IDataSvc` interface (`IXxxDataSvc.cs`) output." }), (ConfigType.Entity, ConfigurationEntity.Operation, "ExcludeDataSvc", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `DataSvc` class (`IXxxDataSvc.cs`) output." }), (ConfigType.Entity, ConfigurationEntity.Operation, "ExcludeIManager", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `IManager` interface (`IXxxManager.cs`) output." }), (ConfigType.Entity, ConfigurationEntity.Operation, "ExcludeManager", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `Manager` class (`XxxManager.cs`) output." }), (ConfigType.Entity, ConfigurationEntity.Operation, "ExcludeWebApi", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `XxxController` class (`IXxxController.cs`) output." }), (ConfigType.Entity, ConfigurationEntity.Operation, "ExcludeWebApiAgent", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `XxxAgent` class (`XxxAgent.cs`) output." }), (ConfigType.Entity, ConfigurationEntity.Operation, "ExcludeGrpcAgent", typeof(bool?), new PropertySchemaAttribute("Exclude") { Title = "Indicates whether to exclude the generation of the `XxxAgent` class (`XxxAgent.cs`) output." }), (ConfigType.Entity, ConfigurationEntity.Operation, "WebApiAuthorize", typeof(string), new PropertySchemaAttribute("WebApi") { Title = "The authorize attribute value to be used for the corresponding entity Web API controller; generally `Authorize` (or `true`), otherwise `AllowAnonymous` (or `false`).", Description = "Defaults to the `Entity.WebApiAuthorize` configuration property (inherits) where not specified." }), (ConfigType.Entity, ConfigurationEntity.Operation, "EventPublish", typeof(string), new PropertySchemaAttribute("Events") { Title = "The layer to add logic to publish an event for a `Create`, `Update` or `Delete` operation.", Options = new string[] { "None", "false", "DataSvc", "true", "Data" }, Description = "Defaults to the `Entity.EventPublish` configuration property (inherits) where not specified. Used to enable the sending of messages to the likes of EventHub, Service Broker, SignalR, etc. This can be overridden within the `Entity`(s)." }), (ConfigType.Database, ConfigurationEntity.Table, "IncludeColumns", typeof(string), new PropertySchemaAttribute("Columns") { Title = "The comma separated list of `Column` names to be included in the underlying generated output.", IsImportant = true, Description = "Where not specified this indicates that all `Columns` are to be included." }), (ConfigType.Database, ConfigurationEntity.Table, "ExcludeColumns", typeof(string), new PropertySchemaAttribute("Columns") { Title = "The comma seperated list of `Column` names to be excluded from the underlying generated output.", IsImportant = true, Description = "Where not specified this indicates no `Columns` are to be excluded." }), (ConfigType.Database, ConfigurationEntity.Table, "GetAllOrderBy", typeof(string), new PropertySchemaAttribute("CodeGen") { Title = "The comma seperated list of `Column` names (including sort order ASC/DESC) to be used as the `GetAll` query sort order." }), (ConfigType.Database, ConfigurationEntity.Table, "UdtExcludeColumns", typeof(string), new PropertySchemaAttribute("UDT") { Title = "The comma seperated list of `Column` names to be excluded from the `User Defined Table (UDT)`.", Description = "Where not specified this indicates that no `Columns` are to be excluded." }), (ConfigType.Database, ConfigurationEntity.StoredProcedure, "Type", typeof(string), new PropertySchemaAttribute("Key") { Title = "The stored procedure operation type.", Options = new string[] { "Get", "GetAll", "Create", "Update", "Upsert", "Delete", "Merge" }, Description = "Defaults to `GetAll`." }), (ConfigType.Database, ConfigurationEntity.StoredProcedure, "MergeOverrideIdentityColumns", typeof(string), new PropertySchemaAttribute("Merge") { Title = "The comma seperated list of `Column` names to be used in the `Merge` statement to determine whether to _insert_, _update_ or _delete_.", Description = "This is used to override the default behaviour of using the primary key column(s)." }), (ConfigType.Database, ConfigurationEntity.OrderBy, "Order", typeof(string), new PropertySchemaAttribute("Key") { Title = "The corresponding sort order.", Options = new string[] { "Asc", "Desc" }, Description = "Defaults to `Asc`." }), (ConfigType.Database, ConfigurationEntity.Query, "IncludeColumns", typeof(string), new PropertySchemaAttribute("Columns") { Title = "The comma separated list of `Column` names to be included in the underlying generated output.", IsImportant = true, Description = "Where not specified this indicates that all `Columns` are to be included." }), (ConfigType.Database, ConfigurationEntity.Query, "ExcludeColumns", typeof(string), new PropertySchemaAttribute("Columns") { Title = "The comma seperated list of `Column` names to be excluded from the underlying generated output.", IsImportant = true, Description = "Where not specified this indicates no `Columns` are to be excluded." }), (ConfigType.Database, ConfigurationEntity.Query, "AliasColumns", typeof(string), new PropertySchemaAttribute("Columns") { Title = "The comma seperated list of `Column` and `Alias` pairs (split by a `^` lookup character) to enable column aliasing/renaming.", IsImportant = true, Description = "Each alias value should be formatted as `Column` + `^` + `Alias`; e.g. `PCODE^ProductCode`" }), (ConfigType.Database, ConfigurationEntity.QueryJoin, "IncludeColumns", typeof(string), new PropertySchemaAttribute("Columns") { Title = "The comma separated list of `Column` names to be included in the underlying generated output.", IsImportant = true, Description = "Where not specified this indicates that all `Columns` are to be included." }), (ConfigType.Database, ConfigurationEntity.QueryJoin, "ExcludeColumns", typeof(string), new PropertySchemaAttribute("Columns") { Title = "The comma seperated list of `Column` names to be excluded from the underlying generated output.", IsImportant = true, Description = "Where not specified this indicates no `Columns` are to be excluded." }), (ConfigType.Database, ConfigurationEntity.QueryJoin, "AliasColumns", typeof(string), new PropertySchemaAttribute("Columns") { Title = "The comma seperated list of `Column` and `Alias` pairs (split by a `^` lookup character) to enable column aliasing/renaming.", IsImportant = true, Description = "Each alias value should be formatted as `Column` + `^` + `Alias`; e.g. `PCODE^ProductCode`" }) }); /// <summary> /// Gets the YAML name from the XML name. /// </summary> internal static string GetYamlName(ConfigType convertType, ConfigurationEntity entity, string xmlName) { var item = _config.FirstOrDefault(x => x.ConvertType == convertType && x.Entity == entity && x.XmlName == xmlName); return item.YamlName ?? (StringConversion.ToCamelCase(xmlName)!); } /// <summary> /// Gets the XML name from the YAML name. /// </summary> internal static string GetXmlName(ConfigType convertType, ConfigurationEntity entity, string jsonName) { var item = _config.FirstOrDefault(x => x.ConvertType == convertType && x.Entity == entity && x.YamlName == jsonName); return item.XmlName ?? (StringConversion.ToPascalCase(jsonName)!); } /// <summary> /// Gets the YAML value from the XML value. /// </summary> internal static string? GetYamlValue(ConfigType convertType, ConfigurationEntity entity, string xmlName, string? xmlValue) { var item = _xmlToYamlConvert.FirstOrDefault(x => x.ConvertType == convertType && x.Entity == entity && x.XmlName == xmlName); var yaml = item.Converter == null ? xmlValue : item.Converter(xmlValue); return item.IsArray ? FormatYamlArray(yaml) : FormatYamlValue(yaml); } /// <summary> /// Check YAML for special characters and format accordingly. /// </summary> internal static string? FormatYamlValue(string? value) { if (string.IsNullOrEmpty(value)) return null; if (value.IndexOfAny(new char[] { ':', '{', '}', '[', ']', ',', '&', '*', '#', '?', '|', '-', '<', '>', '=', '!', '%', '@', '\\', '\"', '\'' }) >= 0) value = $"'{value.Replace("'", "''", StringComparison.InvariantCultureIgnoreCase)}'"; if (string.Compare(value, "NULL", StringComparison.InvariantCultureIgnoreCase) == 0) value = $"'{value}'"; return value; } /// <summary> /// Splits the string on a comma, and then formats each part and then bookends with square brackets. /// </summary> /// <param name="value"></param> /// <returns></returns> internal static string? FormatYamlArray(string? value) { if (string.IsNullOrEmpty(value)) return null; var sb = new StringBuilder(); foreach (var part in value.Split(',', StringSplitOptions.RemoveEmptyEntries)) { sb.Append(sb.Length == 0 ? "[ " : ", "); var yaml = FormatYamlValue(part); if (!string.IsNullOrEmpty(yaml)) sb.Append(FormatYamlValue(part)); } sb.Append(" ]"); return sb.ToString(); } /// <summary> /// Gets the <see cref="PropertySchemaAttribute"/> for the specified XML name. /// </summary> internal static (Type Type, PropertySchemaAttribute Attribute) GetXmlPropertySchemaAttribute(ConfigType convertType, ConfigurationEntity entity, string xmlName) { var item = _xmlSpecificPropertySchema.FirstOrDefault(x => x.ConvertType == convertType && x.Entity == entity && x.XmlName == xmlName); return (item.OverrideType, item.Attribute); } } /// <summary> /// The code-generation configuration entity. /// </summary> public enum ConfigurationEntity { /// <summary>Not specified.</summary> None, /// <summary>Code-generation root configuration.</summary> CodeGen, /// <summary>Entity configuration.</summary> Entity, /// <summary>Const configuration.</summary> Const, /// <summary>Property configuration.</summary> Property, /// <summary>Operation configuration.</summary> Operation, /// <summary>Table configuration.</summary> Table, /// <summary>Query configuration.</summary> Query, /// <summary>Query Join configuration.</summary> QueryJoin, /// <summary>Query Join On configuration.</summary> QueryJoinOn, /// <summary>Query Order configuration.</summary> QueryOrder, /// <summary>Query Where configuration.</summary> QueryWhere, /// <summary>Cdc configuration.</summary> Cdc, /// <summary>Cdc Join configuration.</summary> CdcJoin, /// <summary>Cdc Join On configuration.</summary> CdcJoinOn, /// <summary>Stored procedure configuration.</summary> StoredProcedure, /// <summary>Parameter configuration.</summary> Parameter, /// <summary>OrderBy configuration.</summary> OrderBy, /// <summary>Where configuration.</summary> Where, /// <summary>Execute configuration.</summary> Execute } }
80.069284
351
0.660542
[ "MIT" ]
Avanade/Beef
tools/Beef.CodeGen.Core/Config/XmlYamlTranslate.cs
34,672
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using ProjetoAgoraVai.Data; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ProjetoAgoraVai { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDbContext<Contexto>(options => options.UseSqlServer(Configuration.GetConnectionString("Contexto"))); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
31.078125
143
0.621418
[ "MIT" ]
beatrizrufis/Avalia-oDS2
ProjetoAgoraVai/ProjetoAgoraVai/Startup.cs
1,989
C#
/* Copyright (C) 2016 Alexey Lavrenchenko (http://prosecuritiestrading.com/) 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 ProSecuritiesTrading.MOEX.FIX.Base.Group; using ProSecuritiesTrading.MOEX.FIX.Base.Group.Data; namespace ProSecuritiesTrading.MOEX.FIX.Base.Message.ASTS { public class TradeCaptureReportData { public byte[] MessageBytes; public HeaderData Header; public string TradeReportID = null; public byte[] TradeReportIDBytes = null; /// <summary> /// Null: -1. /// </summary> public int TrdType = -1; /// <summary> /// Null: -1. /// </summary> public int TrdSubType = -1; public string SecondaryTradeReportID = null; public byte[] SecondaryTradeReportIDBytes = null; /// <summary> /// Null: 0. /// </summary> public byte ExecType = 0; public string ExecID = null; public byte[] ExecIDBytes = null; /// <summary> /// Null: 0. /// </summary> public byte PreviouslyReported = 0; // <Instrument> public string Symbol = null; public byte[] SymbolBytes = null; /// <summary> /// Null: -1. /// </summary> public int Product = -1; public string CFICode = null; public byte[] CFICodeBytes = null; public string SecurityType = null; public byte[] SecurityTypeBytes = null; // </Instrument> public FinancingDetails FinancingDetails = null; // <YieldData> /// <summary> /// Null: -1.0. /// </summary> public double Yield = -1.0; // </YieldData> public UnderlyingInstrumentData[] UnderlyingInstruments = null; public int LastQty = 0; public double LastPx = 0.0; /// <summary> /// Null: -1.0. /// </summary> public double CalculatedCcyLastQty = -1.0; /// <summary> /// Null: DateTime.MinValue. /// </summary> public DateTime TradeDate = DateTime.MinValue; /// <summary> /// Null: DateTime.MinValue. /// </summary> public DateTime TransactTime = DateTime.MinValue; public string SettlType = null; public byte[] SettlTypeBytes = null; /// <summary> /// Null: DateTime.MinValue. /// </summary> public DateTime SettlDate = DateTime.MinValue; public string OptionSettlType = null; public byte[] OptionSettlTypeBytes = null; public SideData[] Sides = null; /// <summary> /// Null: -1.0. /// </summary> public double Price2 = -1.0; /// <summary> /// Null: -1.0. /// </summary> public double Price = -1.0; /// <summary> /// Null: 0. /// </summary> public byte PriceType = 0; public string InstitutionID = null; public byte[] InstitutionIDBytes = null; /// <summary> /// Null: 0. /// </summary> public byte TradeThruTime = 0; public string ClearingStatus = null; public byte[] ClearingStatusBytes = null; public string ClearingRefNo = null; public byte[] ClearingRefNoBytes = null; public string CurrencyCode = null; public byte[] CurrencyCodeBytes = null; public string ClientAccID = null; public byte[] ClientAccIDBytes = null; public string ParentID = null; public byte[] ParentIDBytes = null; public string ClearingHandlingType = null; public byte[] ClearingHandlingTypeBytes = null; /// <summary> /// Null: -1. /// </summary> public int OperationType = -1; /// <summary> /// Null: -1.0. /// </summary> public double Price1 = -1.0; /// <summary> /// Null: double.MinValue. /// </summary> public double CurrentRepoValue = double.MinValue; /// <summary> /// Null: double.MinValue. /// </summary> public double CurrentRepoBackValue = double.MinValue; /// <summary> /// Null: -1. /// </summary> public int TradeBalance = -1; /// <summary> /// Null: double.MinValue. /// </summary> public double TotalAmount = double.MinValue; /// <summary> /// Null: double.MinValue. /// </summary> public double LastCouponPaymentValue = double.MinValue; /// <summary> /// Null: DateTime.MinValue. /// </summary> public DateTime LastCouponPaymentDate = DateTime.MinValue; /// <summary> /// Null: double.MinValue. /// </summary> public double LastPrincipalPaymentValue = double.MinValue; /// <summary> /// Null: DateTime.MinValue. /// </summary> public DateTime LastPrincipalPaymentDate = DateTime.MinValue; /// <summary> /// Null: double.MinValue. /// </summary> public double ExpectedDiscount = double.MinValue; /// <summary> /// Null: -1. /// </summary> public int ExpectedQty = -1; /// <summary> /// Null: double.MinValue. /// </summary> public double ExpectedRepoValue = double.MinValue; /// <summary> /// Null: double.MinValue. /// </summary> public double ExpectedRepoBackValue = double.MinValue; /// <summary> /// Null: double.MinValue. /// </summary> public double ExpectedReturnValue = double.MinValue; /// <summary> /// Null: -1. /// </summary> public int PreciseBalance = -1; // <Trailer> public int CheckSum = -1; // </Trailer> /// <summary> /// NoError = 0, Sides = 1. /// </summary> public byte Error = 0; public TradeCaptureReportData(byte[] buffer, HeaderData header) { this.MessageBytes = buffer; this.Header = header; } } }
31.448113
76
0.553622
[ "Apache-2.0" ]
AlexeyLA0509/PSTTrader
src/ProSecuritiesTrading.MOEX.FIX/Base/Message/ASTS/TradeCaptureReportData.cs
6,669
C#
using AutoMapper; using Microsoft.EntityFrameworkCore; using RPG.Data.Context; using RPG.Data.Models; using RPG.Domain.Dto.Character; using RPG.Domain.Response; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace RPG.Services.CharacterServices { public class CharacterService : ICharacterService { private static readonly List<Character> CharacterList = new List<Character> { new Character(), new Character{Id=1, Name="Omar"} }; private readonly IMapper _mapper; private readonly DataContext _dataContext; public CharacterService(IMapper mapper, DataContext dataContext) { _mapper = mapper; _dataContext = dataContext; } public async Task<ServiceResponse<List<GetCharacterDto>>> AddCharacter(AddCharacterDto newCharacter) { Character character = _mapper.Map<Character>(newCharacter); await _dataContext.Character.AddAsync(character); await _dataContext.SaveChangesAsync(); ServiceResponse<List<GetCharacterDto>> serviceResponse = new ServiceResponse<List<GetCharacterDto>>(); serviceResponse.Data = _mapper.Map<List<GetCharacterDto>>(_dataContext.Character.ToList()); return serviceResponse; } public async Task<ServiceResponse<List<GetCharacterDto>>> DeleteCharacters(int id) { ServiceResponse<List<GetCharacterDto>> serviceResponse = new ServiceResponse<List<GetCharacterDto>>(); Character character = await _dataContext.Character.FirstOrDefaultAsync(c=>c.Id==id); if (character != null) { _dataContext.Character.Remove(character); if (await SaveChangesAsync()) { serviceResponse.Data = _mapper.Map<List<GetCharacterDto>>(await _dataContext.Character.ToListAsync()); serviceResponse.Message = "Character :" + character.Name + ", deleted successfully"; } else{ serviceResponse.Success = false; serviceResponse.Message = "No Such Character"; } } if (character == null) { serviceResponse.Success = false; serviceResponse.Message = "No Such Character"; } return serviceResponse; } public async Task<ServiceResponse<List<GetCharacterDto>>> GetAllCharacters() { ServiceResponse<List<GetCharacterDto>> serviceResponse = new ServiceResponse<List<GetCharacterDto>>(); serviceResponse.Data = _mapper.Map<List<GetCharacterDto>>(await _dataContext.Character.ToListAsync()); return serviceResponse; } public async Task<ServiceResponse<GetCharacterDto>> GetCharacterById(int id) { ServiceResponse<GetCharacterDto> serviceResponse = new ServiceResponse<GetCharacterDto>(); serviceResponse.Data = _mapper.Map<GetCharacterDto>(await _dataContext.Character.FirstOrDefaultAsync(c => c.Id == id)); return serviceResponse; } public async Task<ServiceResponse<GetCharacterDto>> UpdateCharacter(UpdateCharacterDto updateCharacter) { ServiceResponse<GetCharacterDto> serviceResponse = new ServiceResponse<GetCharacterDto>(); var character = _mapper.Map<Character>(updateCharacter); _dataContext.Character.Update(character); var success = await SaveChangesAsync(); if (success) { serviceResponse.Data = _mapper.Map<GetCharacterDto>(character); serviceResponse.Message = "All changes saved"; } if (!success) { serviceResponse.Success = false; serviceResponse.Message = "No Such Character"; } return serviceResponse; } public async Task<bool> SaveChangesAsync() { return await _dataContext.SaveChangesAsync() > 0; } } }
40.038462
131
0.629203
[ "MIT" ]
HusseinShukri/DotNET-RPG
RPG/RPG.Services/CharacterService/.vshistory/CharacterService.cs/2021-08-09_19_08_39_846.cs
4,166
C#
using System; using EloquentObjects.Channels; namespace EloquentObjects { /// <summary> /// This is a custom implementation of the FaultException since the Mono version used in Unity3D of the FaultException /// throws a NotImplementedException when serialized. /// </summary> public sealed class FaultException : Exception { private readonly FaultException _innerException; /// <summary> /// Creates the FaultException with provided message. /// </summary> /// <param name="message">Reason of the fault.</param> /// <param name="stackTrace">Stack stackTrace</param> /// <param name="exceptionType">Exception type as a string</param> private FaultException(string message, string stackTrace, string exceptionType) : base(message) { StackTrace = stackTrace; ExceptionType = exceptionType; } /// <summary> /// Creates the FaultException with provided message. /// </summary> /// <param name="message">Reason of the fault.</param> /// <param name="stackTrace">Stack stackTrace</param> /// <param name="exceptionType">Exception type as a string</param> /// <param name="innerException">Inner exception</param> private FaultException(string message, string stackTrace, string exceptionType, FaultException innerException) : base( message, Create(innerException)) { _innerException = innerException; StackTrace = stackTrace; ExceptionType = exceptionType; } public string ExceptionType { get; } #region Overrides of Exception public override string StackTrace { get; } #endregion internal void Write(IFrameBuilder builder) { builder.WriteString(Message); builder.WriteString(StackTrace); builder.WriteString(ExceptionType); if (InnerException != null) { builder.WriteBool(true); _innerException.Write(builder); } else { builder.WriteBool(false); } } internal static FaultException Read(IFrame frame) { var message = frame.TakeString(); var stackTrace = frame.TakeString(); var exceptionType = frame.TakeString(); var hasException = frame.TakeBool(); FaultException innerException = null; if (hasException) { innerException = Read(frame); } return innerException == null ? new FaultException(message, stackTrace, exceptionType) : new FaultException(message, stackTrace, exceptionType, innerException); } internal static FaultException Create(Exception exception) { return exception.InnerException == null ? new FaultException(exception.Message, exception.StackTrace, exception.GetType().FullName) : new FaultException(exception.Message, exception.StackTrace, exception.GetType().FullName, Create(exception.InnerException)); } } }
36.142857
126
0.598358
[ "MIT" ]
ni28/EloquentObjects
src/EloquentObjects/FaultException.cs
3,289
C#
namespace State.Application.Models.Responses { public class GenericResponse { public GenericResponse(string message) { Message = message; } public string Message { get; set; } } }
19.75
46
0.586498
[ "MIT" ]
dsrodolfo/State.Api
State.Application/Models/Responses/GenericResponse.cs
239
C#
using DoctorXamarinMrBlazorApp.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DoctorXamarinMrBlazorApp.Event { public class MyDeviceEventArgs : System.EventArgs { public MyDevice Device { get; set; } public MyDeviceEventArgs(MyDevice device) { Device = device; } } }
20.55
53
0.690998
[ "Apache-2.0" ]
CodearoundHub/DoctorXamarinMrBlazorApp
src/DoctorXamarinMrBlazorApp/DoctorXamarinMrBlazorApp/Event/MyDeviceEventArgs.cs
413
C#
using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.OpenApi.Models; namespace EasyRpc.AspNetCore.Documentation { /// <summary> /// Document filter context /// </summary> public class DocumentFilterContext { /// <summary> /// Default constructor /// </summary> /// <param name="document"></param> /// <param name="httpContext"></param> public DocumentFilterContext(OpenApiDocument document, HttpContext httpContext) { Document = document; HttpContext = httpContext; } /// <summary> /// Http context /// </summary> public HttpContext HttpContext { get; } /// <summary> /// Open api document /// </summary> public OpenApiDocument Document { get; } } /// <summary> /// Document filter /// </summary> public interface IDocumentFilter { /// <summary> /// Apply logic to document /// </summary> /// <param name="context"></param> void Apply(DocumentFilterContext context); } }
24.5625
87
0.569975
[ "MIT" ]
ipjohnson/EasyRpc
src/EasyRpc.AspNetCore/Documentation/IDocumentFilter.cs
1,181
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Security.Cryptography; namespace cn.vimfung.luascriptcore.modules.crypto { /// <summary> /// 加密模块 /// </summary> public class Crypto : object, LuaExportType { public static byte[] md5(object data) { if (data is byte[] || data is string) { byte[] rawData = null; if (data is string) { rawData = System.Text.Encoding.UTF8.GetBytes (data as string); } else { rawData = data as byte[]; } MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); return md5Hasher.ComputeHash(rawData); } return null; } public static byte[] sha1(object data) { if (data is byte[] || data is string) { byte[] rawData = null; if (data is string) { rawData = System.Text.Encoding.UTF8.GetBytes (data as string); } else { rawData = data as byte[]; } SHA1CryptoServiceProvider shaHasher = new SHA1CryptoServiceProvider(); return shaHasher.ComputeHash(rawData); } return null; } public static byte[] hmacMD5(object data, object key) { byte[] rawKey = null; byte[] rawData = null; if (data is byte[] || data is string) { if (data is string) { rawData = System.Text.Encoding.UTF8.GetBytes (data as string); } else { rawData = data as byte[]; } } if (key is byte[] || key is string) { if (key is string) { rawKey = System.Text.Encoding.UTF8.GetBytes (key as string); } else { rawKey = key as byte[]; } } if (data != null && key != null) { HMACMD5 hmac = new HMACMD5 (rawKey); return hmac.ComputeHash (rawData); } return null; } public static byte[] hmacSHA1(object data, object key) { byte[] rawKey = null; byte[] rawData = null; if (data is byte[] || data is string) { if (data is string) { rawData = System.Text.Encoding.UTF8.GetBytes (data as string); } else { rawData = data as byte[]; } } if (key is byte[] || key is string) { if (key is string) { rawKey = System.Text.Encoding.UTF8.GetBytes (key as string); } else { rawKey = key as byte[]; } } if (data != null && key != null) { HMACSHA1 hmac = new HMACSHA1 (rawKey); return hmac.ComputeHash (rawData); } return null; } } }
18.268657
74
0.586601
[ "Apache-2.0" ]
vimfung/LuaScriptCore-Modules
Crypto/Unity3D/Crypto.cs
2,458
C#
namespace PluginCore.BBCode { public class PairTag : IPairTag { public PairTag(IPairTagMatch openerMatch, IPairTagMatch closerMatch) { _openerMatch = openerMatch; _closerMatch = closerMatch; } readonly IPairTagMatch _openerMatch; readonly IPairTagMatch _closerMatch; public IPairTagMatch openerMatch => _openerMatch; public IPairTagMatch closerMatch => _closerMatch; public override string ToString() { return "[pairTag" + " openerMatch='" + (_openerMatch is null ? "null" : _openerMatch.ToString()) + "'" + " closerMatch='" + (_closerMatch is null ? "null" : _closerMatch.ToString()) + "'" + "]"; } } public class VoidCloserTagMatch : IPairTagMatch { public VoidCloserTagMatch() { _init(-1); } public VoidCloserTagMatch(int tagIndex) { _init(tagIndex); } void _init(int tagIndex) { _tagIndex = tagIndex; } int _tagIndex; public bool isTagOpener => false; public int tagIndex => _tagIndex; public uint tagLength => 0; public string tagValue => ""; public string tagName => null; } }
22.822581
104
0.522261
[ "MIT" ]
Klug76/flashdevelop
PluginCore/BBCode/PairTag.cs
1,354
C#
namespace Pyro.Common.Interfaces.Repositories { public interface IBaseRepository { void Save(); } }
14.75
46
0.669492
[ "BSD-3-Clause" ]
angusmillar/Pyro
Pyro.Common/Interfaces/Repositories/IBaseRepository.cs
120
C#
using System; namespace Reflex { internal class Binding { internal Type Contract; internal Type Concrete; internal BindingScope Scope; internal Func<object> Method; } }
17.833333
37
0.630841
[ "MIT" ]
gustavopsantos/Reflex
Reflex/Assets/Reflex/Scripts/Definitions/Binding.cs
216
C#
//******************************************************************************************************************************************************************************************// // Copyright (c) 2020 abergs (https://github.com/abergs/fido2-net-lib) // // // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, // // and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // //******************************************************************************************************************************************************************************************// using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Neos.IdentityServer.MultiFactor.WebAuthN.AttestationFormat; using Newtonsoft.Json; namespace Neos.IdentityServer.MultiFactor.WebAuthN.Metadata { public class StaticMetadataRepository : IMetadataRepository { protected readonly IDictionary<Guid, MetadataTOCPayloadEntry> _entries; protected MetadataTOCPayload _toc; protected readonly HttpClient _httpClient; protected readonly DateTime? _cacheUntil; // from https://developers.yubico.com/U2F/yubico-u2f-ca-certs.txt protected const string YUBICO_ROOT = "MIIDHjCCAgagAwIBAgIEG0BT9zANBgkqhkiG9w0BAQsFADAuMSwwKgYDVQQDEyNZ" + "dWJpY28gVTJGIFJvb3QgQ0EgU2VyaWFsIDQ1NzIwMDYzMTAgFw0xNDA4MDEwMDAw" + "MDBaGA8yMDUwMDkwNDAwMDAwMFowLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290" + "IENBIFNlcmlhbCA0NTcyMDA2MzEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK" + "AoIBAQC/jwYuhBVlqaiYWEMsrWFisgJ+PtM91eSrpI4TK7U53mwCIawSDHy8vUmk" + "5N2KAj9abvT9NP5SMS1hQi3usxoYGonXQgfO6ZXyUA9a+KAkqdFnBnlyugSeCOep" + "8EdZFfsaRFtMjkwz5Gcz2Py4vIYvCdMHPtwaz0bVuzneueIEz6TnQjE63Rdt2zbw" + "nebwTG5ZybeWSwbzy+BJ34ZHcUhPAY89yJQXuE0IzMZFcEBbPNRbWECRKgjq//qT" + "9nmDOFVlSRCt2wiqPSzluwn+v+suQEBsUjTGMEd25tKXXTkNW21wIWbxeSyUoTXw" + "LvGS6xlwQSgNpk2qXYwf8iXg7VWZAgMBAAGjQjBAMB0GA1UdDgQWBBQgIvz0bNGJ" + "hjgpToksyKpP9xv9oDAPBgNVHRMECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBBjAN" + "BgkqhkiG9w0BAQsFAAOCAQEAjvjuOMDSa+JXFCLyBKsycXtBVZsJ4Ue3LbaEsPY4" + "MYN/hIQ5ZM5p7EjfcnMG4CtYkNsfNHc0AhBLdq45rnT87q/6O3vUEtNMafbhU6kt" + "hX7Y+9XFN9NpmYxr+ekVY5xOxi8h9JDIgoMP4VB1uS0aunL1IGqrNooL9mmFnL2k" + "LVVee6/VR6C5+KSTCMCWppMuJIZII2v9o4dkoZ8Y7QRjQlLfYzd3qGtKbw7xaF1U" + "sG/5xUb/Btwb2X2g4InpiB/yt/3CpQXpiWX/K4mBvUKiGn05ZsqeY1gx4g0xLBqc" + "U9psmyPzK+Vsgw2jeRQ5JlKDyqE0hebfC1tvFu0CCrJFcw=="; public StaticMetadataRepository(DateTime? cacheUntil = null) { _httpClient = new HttpClient(); _entries = new Dictionary<Guid, MetadataTOCPayloadEntry>(); _cacheUntil = cacheUntil; } public async Task<MetadataStatement> GetMetadataStatement(MetadataTOCPayloadEntry entry) { if (_toc == null) await GetToc(); if (!string.IsNullOrEmpty(entry.AaGuid) && Guid.TryParse(entry.AaGuid, out Guid parsedAaGuid)) { if (_entries.ContainsKey(parsedAaGuid)) return _entries[parsedAaGuid].MetadataStatement; } return null; } protected async Task<string> DownloadStringAsync(string url) { return await _httpClient.GetStringAsync(url); } public async Task<MetadataTOCPayload> GetToc() { var yubico = new MetadataTOCPayloadEntry { AaGuid = "f8a011f3-8c0a-4d15-8006-17111f9edc7d", Hash = "", StatusReports = new StatusReport[] { new StatusReport() { Status = AuthenticatorStatus.NOT_FIDO_CERTIFIED } }, MetadataStatement = new MetadataStatement { AttestationTypes = new ushort[] { (ushort)MetadataAttestationType.ATTESTATION_BASIC_FULL }, Hash = "", Description = "Yubico YubiKey FIDO2", AttestationRootCertificates = new string[] { YUBICO_ROOT } } }; _entries.Add(new Guid(yubico.AaGuid), yubico); // YubiKey 5 USB and NFC AAGUID values from https://support.yubico.com/support/solutions/articles/15000014219-yubikey-5-series-technical-manual#AAGUID_Valuesxf002do var yubikey5usb = new MetadataTOCPayloadEntry { AaGuid = "cb69481e-8ff7-4039-93ec-0a2729a154a8", Hash = "", StatusReports = new StatusReport[] { new StatusReport { Status = AuthenticatorStatus.NOT_FIDO_CERTIFIED } }, MetadataStatement = new MetadataStatement { AttestationTypes = new ushort[] { (ushort)MetadataAttestationType.ATTESTATION_BASIC_FULL }, Hash = "", Description = "Yubico YubiKey 5 USB", AttestationRootCertificates = new string[] { YUBICO_ROOT } } }; _entries.Add(new Guid(yubikey5usb.AaGuid), yubikey5usb); var yubikey5nfc = new MetadataTOCPayloadEntry { AaGuid = "fa2b99dc-9e39-4257-8f92-4a30d23c4118", Hash = "", StatusReports = new StatusReport[] { new StatusReport { Status = AuthenticatorStatus.NOT_FIDO_CERTIFIED } }, MetadataStatement = new MetadataStatement { AttestationTypes = new ushort[] { (ushort)MetadataAttestationType.ATTESTATION_BASIC_FULL }, Hash = "", Description = "Yubico YubiKey 5 NFC", AttestationRootCertificates = new string[] { YUBICO_ROOT } } }; _entries.Add(new Guid(yubikey5nfc.AaGuid), yubikey5nfc); var yubicoSecuriyKeyNfc = new MetadataTOCPayloadEntry { AaGuid = "6d44ba9b-f6ec-2e49-b930-0c8fe920cb73", Hash = "", StatusReports = new StatusReport[] { new StatusReport() { Status = AuthenticatorStatus.NOT_FIDO_CERTIFIED } }, MetadataStatement = new MetadataStatement { Description = "Yubico Security Key NFC", Icon = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDIzLjAuMSwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9Ill1YmljbyIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgdmlld0JveD0iMCAwIDc2OCA3NjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDc2OCA3Njg7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4KPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCS5zdDB7ZmlsbDojOUFDQTNDO30KPC9zdHlsZT4KPHBvbHlnb24gaWQ9IlkiIGNsYXNzPSJzdDAiIHBvaW50cz0iMjE4LjQzLDIxMS44MSAzMTYuNDksMjExLjgxIDM4Ni41Miw0MDAuMDcgNDUzLjIsMjExLjgxIDU0OS41NywyMTEuODEgMzg3LjA4LDYxMS44NiAKCTI4Ni4yMyw2MTEuODYgMzMyLjE3LDUwMi4wNCAiLz4KPHBhdGggaWQ9IkNpcmNsZV8xXyIgY2xhc3M9InN0MCIgZD0iTTM4NCwwQzE3MS45MiwwLDAsMTcxLjkyLDAsMzg0czE3MS45MiwzODQsMzg0LDM4NHMzODQtMTcxLjkyLDM4NC0zODRTNTk2LjA4LDAsMzg0LDB6CgkgTTM4NCw2OTMuNThDMjEzLjAyLDY5My41OCw3NC40Miw1NTQuOTgsNzQuNDIsMzg0UzIxMy4wMiw3NC40MiwzODQsNzQuNDJTNjkzLjU4LDIxMy4wMiw2OTMuNTgsMzg0UzU1NC45OCw2OTMuNTgsMzg0LDY5My41OHoiLz4KPC9zdmc+Cg==", AttachmentHint = 6, AttestationTypes = new ushort[] { (ushort)MetadataAttestationType.ATTESTATION_BASIC_FULL }, Hash = "", AttestationRootCertificates = new string[] { YUBICO_ROOT } } }; _entries.Add(new Guid(yubicoSecuriyKeyNfc.AaGuid), yubicoSecuriyKeyNfc); var msftWhfbSoftware = new MetadataTOCPayloadEntry { AaGuid = "6028B017-B1D4-4C02-B4B3-AFCDAFC96BB2", Hash = "", StatusReports = new StatusReport[] { new StatusReport { Status = AuthenticatorStatus.NOT_FIDO_CERTIFIED } }, MetadataStatement = new MetadataStatement { AttestationTypes = new ushort[] { (ushort)MetadataAttestationType.ATTESTATION_BASIC_FULL }, Hash = "", Description = "Windows Hello software authenticator" } }; _entries.Add(new Guid(msftWhfbSoftware.AaGuid), msftWhfbSoftware); var msftWhfbSoftwareVbs = new MetadataTOCPayloadEntry { AaGuid = "6E96969E-A5CF-4AAD-9B56-305FE6C82795", Hash = "", StatusReports = new StatusReport[] { new StatusReport { Status = AuthenticatorStatus.NOT_FIDO_CERTIFIED } }, MetadataStatement = new MetadataStatement { AttestationTypes = new ushort[] { (ushort)MetadataAttestationType.ATTESTATION_BASIC_FULL }, Hash = "", Description = "Windows Hello VBS software authenticator" } }; _entries.Add(new Guid(msftWhfbSoftwareVbs.AaGuid), msftWhfbSoftwareVbs); var msftWhfbHardware = new MetadataTOCPayloadEntry { AaGuid = "08987058-CADC-4B81-B6E1-30DE50DCBE96", Hash = "", StatusReports = new StatusReport[] { new StatusReport { Status = AuthenticatorStatus.NOT_FIDO_CERTIFIED } }, MetadataStatement = new MetadataStatement { AttestationTypes = new ushort[] { (ushort)MetadataAttestationType.ATTESTATION_BASIC_FULL }, Hash = "", Description = "Windows Hello hardware authenticator" } }; _entries.Add(new Guid(msftWhfbHardware.AaGuid), msftWhfbHardware); var msftWhfbHardwareVbs = new MetadataTOCPayloadEntry { AaGuid = "9DDD1817-AF5A-4672-A2B9-3E3DD95000A9", Hash = "", StatusReports = new StatusReport[] { new StatusReport { Status = AuthenticatorStatus.NOT_FIDO_CERTIFIED } }, MetadataStatement = new MetadataStatement { AttestationTypes = new ushort[] { (ushort)MetadataAttestationType.ATTESTATION_BASIC_FULL }, Hash = "", Description = "Windows Hello VBS hardware authenticator" } }; _entries.Add(new Guid(msftWhfbHardwareVbs.AaGuid), msftWhfbHardwareVbs); var solostatement = await DownloadStringAsync("https://raw.githubusercontent.com/solokeys/solo/master/metadata/Solo-FIDO2-CTAP2-Authenticator.json"); var soloMetadataStatement = JsonConvert.DeserializeObject<MetadataStatement>(solostatement); var soloKeysSolo = new MetadataTOCPayloadEntry { AaGuid = soloMetadataStatement.AaGuid, Url = "https://raw.githubusercontent.com/solokeys/solo/master/metadata/Solo-FIDO2-CTAP2-Authenticator.json", StatusReports = new StatusReport[] { new StatusReport { Status = AuthenticatorStatus.NOT_FIDO_CERTIFIED } }, MetadataStatement = soloMetadataStatement }; _entries.Add(new Guid(soloKeysSolo.AaGuid), soloKeysSolo); var soloTapStatement = await DownloadStringAsync("https://raw.githubusercontent.com/solokeys/solo/master/metadata/SoloTap-FIDO2-CTAP2-Authenticator.json"); var soloTapMetadataStatement = JsonConvert.DeserializeObject<MetadataStatement>(soloTapStatement); var soloTapMetadata = new MetadataTOCPayloadEntry { AaGuid = soloTapMetadataStatement.AaGuid, Url = "https://raw.githubusercontent.com/solokeys/solo/master/metadata/SoloTap-FIDO2-CTAP2-Authenticator.json", StatusReports = new StatusReport[] { new StatusReport { Status = AuthenticatorStatus.NOT_FIDO_CERTIFIED } }, MetadataStatement = soloTapMetadataStatement }; _entries.Add(new Guid(soloTapMetadata.AaGuid), soloTapMetadata); var soloSomuStatement = await DownloadStringAsync("https://raw.githubusercontent.com/solokeys/solo/master/metadata/Somu-FIDO2-CTAP2-Authenticator.json"); var soloSomuMetadataStatement = JsonConvert.DeserializeObject<MetadataStatement>(soloSomuStatement); var soloSomuMetadata = new MetadataTOCPayloadEntry { AaGuid = soloSomuMetadataStatement.AaGuid, Url = "https://raw.githubusercontent.com/solokeys/solo/master/metadata/Somu-FIDO2-CTAP2-Authenticator.json", StatusReports = new StatusReport[] { new StatusReport { Status = AuthenticatorStatus.NOT_FIDO_CERTIFIED } }, MetadataStatement = soloSomuMetadataStatement }; _entries.Add(new Guid(soloSomuMetadata.AaGuid), soloSomuMetadata); foreach (var entry in _entries) { entry.Value.MetadataStatement.AaGuid = entry.Value.AaGuid; } _toc = new MetadataTOCPayload() { Entries = _entries.Select(o => o.Value).ToArray(), NextUpdate = _cacheUntil?.ToString("yyyy-MM-dd") ?? "", //Results in no caching LegalHeader = "Static FAKE", Number = 1 }; return _toc; } } }
53.41791
1,140
0.524448
[ "MIT" ]
k-korn/adfsmfa
Neos.IdentityServer 3.0/Neos.IdentityServer.MultiFactor.WebAuthN.Core/Metadata/StaticMetadataRepository.cs
17,897
C#
using System; using System.Collections.Generic; using Compliance.EarlyBound; using Compliance.Plugins; using FakeXrmEasy; using FluentAssertions; using Microsoft.Xrm.Sdk; using Xunit; namespace Compliance.Plugins.Tests { public class CompliancePrefixPluginTests { public class when_creating_complaint { public static IEnumerable<object[]> Legislations { get { return new[] { new object[] { new opc_legislation { Id = Guid.NewGuid(), opc_acronym = "PA", opc_name = "Privacy Act" } }, new object[] { new opc_legislation { Id = Guid.NewGuid(), opc_acronym = "PIPEDA", opc_name = "Personal Information Protection and Electronic Documents Act" } } }; } } [Theory(DisplayName = "complaint number should change"), MemberData(nameof(Legislations))] public void complaint_number_should_change(opc_legislation legislation) { // Arrange var context = new XrmFakedContext(); var complaintNumber = "0000100"; var complaint = new opc_complaint { Id = Guid.NewGuid(), opc_number = complaintNumber, opc_legislation = legislation.ToEntityReference() }; context.Initialize(new List<Entity> { complaint, legislation }); // Act context.ExecutePluginWithTarget<ComplaintPrefixPlugin>(complaint); // Assert complaint.opc_number.Should().NotBe(complaintNumber); } [Theory(DisplayName = "complaint number should be prefixed with legislation"), MemberData(nameof(Legislations))] public void complaint_number_should_be_prefixed_with_legislation(opc_legislation legislation) { // Arrange var context = new XrmFakedContext(); var complaintNumber = "0000100"; var complaint = new opc_complaint { Id = Guid.NewGuid(), opc_number = complaintNumber, opc_legislation = legislation.ToEntityReference() }; context.Initialize(new List<Entity> { complaint, legislation }); // Act context.ExecutePluginWithTarget<ComplaintPrefixPlugin>(complaint); // Assert complaint.opc_number.Should().Be($"{legislation.opc_acronym}-{complaintNumber}"); } } } }
34.871795
183
0.552206
[ "MIT" ]
opc-cpvp/OPC.PowerApps
src/Compliance.Plugins.Tests/CompliancePrefixPluginTests.cs
2,722
C#
namespace VAdvantage.Model { /** Generated Model - DO NOT CHANGE */ using System; using System.Text; using VAdvantage.DataBase; using VAdvantage.Common; using VAdvantage.Classes; using VAdvantage.Process; using VAdvantage.Model; using VAdvantage.Utility; using System.Data; /** Generated Model for AD_WorkflowProcessorLog * @author Jagmohan Bhatt (generated) * @version Vienna Framework 1.1.1 - $Id$ */ public class X_AD_WorkflowProcessorLog : PO { public X_AD_WorkflowProcessorLog (Context ctx, int AD_WorkflowProcessorLog_ID, Trx trxName) : base (ctx, AD_WorkflowProcessorLog_ID, trxName) { /** if (AD_WorkflowProcessorLog_ID == 0) { SetAD_WorkflowProcessorLog_ID (0); SetAD_WorkflowProcessor_ID (0); SetIsError (false); } */ } public X_AD_WorkflowProcessorLog (Ctx ctx, int AD_WorkflowProcessorLog_ID, Trx trxName) : base (ctx, AD_WorkflowProcessorLog_ID, trxName) { /** if (AD_WorkflowProcessorLog_ID == 0) { SetAD_WorkflowProcessorLog_ID (0); SetAD_WorkflowProcessor_ID (0); SetIsError (false); } */ } /** Load Constructor @param ctx context @param rs result set @param trxName transaction */ public X_AD_WorkflowProcessorLog (Context ctx, DataRow rs, Trx trxName) : base(ctx, rs, trxName) { } /** Load Constructor @param ctx context @param rs result set @param trxName transaction */ public X_AD_WorkflowProcessorLog (Ctx ctx, DataRow rs, Trx trxName) : base(ctx, rs, trxName) { } /** Load Constructor @param ctx context @param rs result set @param trxName transaction */ public X_AD_WorkflowProcessorLog (Ctx ctx, IDataReader dr, Trx trxName) : base(ctx, dr, trxName) { } /** Static Constructor Set Table ID By Table Name added by ->Harwinder */ static X_AD_WorkflowProcessorLog() { Table_ID = Get_Table_ID(Table_Name); model = new KeyNamePair(Table_ID,Table_Name); } /** Serial Version No */ //static long serialVersionUID 27562514366921L; /** Last Updated Timestamp 7/29/2010 1:07:30 PM */ public static long updatedMS = 1280389050132L; /** AD_Table_ID=696 */ public static int Table_ID; // =696; /** TableName=AD_WorkflowProcessorLog */ public static String Table_Name="AD_WorkflowProcessorLog"; protected static KeyNamePair model; protected Decimal accessLevel = new Decimal(4); /** AccessLevel @return 4 - System */ protected override int Get_AccessLevel() { return Convert.ToInt32(accessLevel.ToString()); } /** Load Meta Data @param ctx context @return PO Info */ protected override POInfo InitPO (Ctx ctx) { POInfo poi = POInfo.GetPOInfo (ctx, Table_ID); return poi; } /** Load Meta Data @param ctx context @return PO Info */ protected override POInfo InitPO(Context ctx) { POInfo poi = POInfo.GetPOInfo (ctx, Table_ID); return poi; } /** Info @return info */ public override String ToString() { StringBuilder sb = new StringBuilder ("X_AD_WorkflowProcessorLog[").Append(Get_ID()).Append("]"); return sb.ToString(); } /** Set Workflow Processorl Log. @param AD_WorkflowProcessorLog_ID Result of the execution of the Workflow Processor */ public void SetAD_WorkflowProcessorLog_ID (int AD_WorkflowProcessorLog_ID) { if (AD_WorkflowProcessorLog_ID < 1) throw new ArgumentException ("AD_WorkflowProcessorLog_ID is mandatory."); Set_ValueNoCheck ("AD_WorkflowProcessorLog_ID", AD_WorkflowProcessorLog_ID); } /** Get Workflow Processorl Log. @return Result of the execution of the Workflow Processor */ public int GetAD_WorkflowProcessorLog_ID() { Object ii = Get_Value("AD_WorkflowProcessorLog_ID"); if (ii == null) return 0; return Convert.ToInt32(ii); } /** Set Workflow Processor. @param AD_WorkflowProcessor_ID Workflow Processor Server */ public void SetAD_WorkflowProcessor_ID (int AD_WorkflowProcessor_ID) { if (AD_WorkflowProcessor_ID < 1) throw new ArgumentException ("AD_WorkflowProcessor_ID is mandatory."); Set_ValueNoCheck ("AD_WorkflowProcessor_ID", AD_WorkflowProcessor_ID); } /** Get Workflow Processor. @return Workflow Processor Server */ public int GetAD_WorkflowProcessor_ID() { Object ii = Get_Value("AD_WorkflowProcessor_ID"); if (ii == null) return 0; return Convert.ToInt32(ii); } /** Set BinaryData. @param BinaryData Binary Data */ public void SetBinaryData (Byte[] BinaryData) { Set_Value ("BinaryData", BinaryData); } /** Get BinaryData. @return Binary Data */ public Byte[] GetBinaryData() { return (Byte[])Get_Value("BinaryData"); } /** Set Description. @param Description Optional short description of the record */ public void SetDescription (String Description) { if (Description != null && Description.Length > 255) { log.Warning("Length > 255 - truncated"); Description = Description.Substring(0,255); } Set_Value ("Description", Description); } /** Get Description. @return Optional short description of the record */ public String GetDescription() { return (String)Get_Value("Description"); } /** Set Error. @param IsError An Error occured in the execution */ public void SetIsError (Boolean IsError) { Set_Value ("IsError", IsError); } /** Get Error. @return An Error occured in the execution */ public Boolean IsError() { Object oo = Get_Value("IsError"); if (oo != null) { if (oo.GetType() == typeof(bool)) return Convert.ToBoolean(oo); return "Y".Equals(oo); } return false; } /** Set Reference. @param Reference Reference for this record */ public void SetReference (String Reference) { if (Reference != null && Reference.Length > 60) { log.Warning("Length > 60 - truncated"); Reference = Reference.Substring(0,60); } Set_Value ("Reference", Reference); } /** Get Reference. @return Reference for this record */ public String GetReference() { return (String)Get_Value("Reference"); } /** Set Summary. @param Summary Textual summary of this request */ public void SetSummary (String Summary) { if (Summary != null && Summary.Length > 2000) { log.Warning("Length > 2000 - truncated"); Summary = Summary.Substring(0,2000); } Set_Value ("Summary", Summary); } /** Get Summary. @return Textual summary of this request */ public String GetSummary() { return (String)Get_Value("Summary"); } /** Set Text Message. @param TextMsg Text Message */ public void SetTextMsg (String TextMsg) { if (TextMsg != null && TextMsg.Length > 2000) { log.Warning("Length > 2000 - truncated"); TextMsg = TextMsg.Substring(0,2000); } Set_Value ("TextMsg", TextMsg); } /** Get Text Message. @return Text Message */ public String GetTextMsg() { return (String)Get_Value("TextMsg"); } } }
25.596774
141
0.750788
[ "Apache-2.0" ]
AsimKhan2019/ERP-CMR-DMS
ViennaAdvantageWeb/ModelLibrary/ModelAD/X_AD_WorkflowProcessorLog.cs
6,348
C#
using System; namespace Apprenda.EFPlugin { /// <summary> /// Helper class to load the guest app's EF Configuration /// </summary> public interface ITypeLoader { Type Load(string className); } }
17.615385
61
0.624454
[ "MIT" ]
apprenda/ApplicationSamples
datatierplugin/src/efplugin/ITypeLoader.cs
231
C#
using System; using Convey.MessageBrokers.RabbitMQ; using Trill.Services.Stories.Application.Events; using Trill.Services.Stories.Application.Exceptions; using Trill.Services.Stories.Core.Exceptions; namespace Trill.Services.Stories.Infrastructure.Exceptions { internal sealed class ExceptionToMessageMapper : IExceptionToMessageMapper { public object Map(Exception exception, object message) => exception switch { AppException ex => new StoryActionRejected(ex.Message, ex.GetExceptionCode()), DomainException ex => new StoryActionRejected(ex.Message, ex.GetExceptionCode()), _ => new StoryActionRejected("There was an error", "story_error") }; } }
35.952381
97
0.703311
[ "MIT" ]
devmentors/Trill.Services.Stories
src/Trill.Services.Stories.Infrastructure/Exceptions/ExceptionToMessageMapper.cs
755
C#
// Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using JetBrains.Annotations; using Nuke.Common.Tooling; using Nuke.Common.Utilities; namespace Nuke.Common.CI.AppVeyor { // [PublicAPI] // [Headers("Accept: application/json")] // public interface IAppVeyorRestClient // { // [Post("/api/build/messages")] // Task WriteMessage(AppVeyorMessageCategory category, string message, string details = ""); // } // [PublicAPI] public enum AppVeyorMessageCategory { Information, Warning, Error } /// <summary> /// Interface according to the <a href="https://www.appveyor.com/docs/environment-variables/">official website</a>. /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] public partial class AppVeyor : Host, IBuildServer { public new static AppVeyor Instance => Host.Instance as AppVeyor; public static int MessageLimit = 500; internal static bool IsRunningAppVeyor => !Environment.GetEnvironmentVariable("APPVEYOR").IsNullOrEmpty(); private readonly Lazy<Tool> _cli = Lazy.Create(() => IsRunningAppVeyor ? ToolResolver.GetPathTool("appveyor") : null); private int _messageCount; internal AppVeyor() { } string IBuildServer.Branch => RepositoryBranch; string IBuildServer.Commit => RepositoryCommitSha; public Tool Cli => _cli.Value; public string Url => EnvironmentInfo.GetVariable<string>("APPVEYOR_URL"); public string ApiUrl => EnvironmentInfo.GetVariable<string>("APPVEYOR_API_URL"); public string AccountName => EnvironmentInfo.GetVariable<string>("APPVEYOR_ACCOUNT_NAME"); public int ProjectId => EnvironmentInfo.GetVariable<int>("APPVEYOR_PROJECT_ID"); public string ProjectName => EnvironmentInfo.GetVariable<string>("APPVEYOR_PROJECT_NAME"); public string ProjectSlug => EnvironmentInfo.GetVariable<string>("APPVEYOR_PROJECT_SLUG"); public string BuildFolder => EnvironmentInfo.GetVariable<string>("APPVEYOR_BUILD_FOLDER"); public int BuildId => EnvironmentInfo.GetVariable<int>("APPVEYOR_BUILD_ID"); public int BuildNumber => EnvironmentInfo.GetVariable<int>("APPVEYOR_BUILD_NUMBER"); public string BuildVersion => EnvironmentInfo.GetVariable<string>("APPVEYOR_BUILD_VERSION"); public string BuildWorkerImage => EnvironmentInfo.GetVariable<string>("APPVEYOR_BUILD_WORKER_IMAGE"); [CanBeNull] public int? PullRequestNumber => EnvironmentInfo.GetVariable<int?>("APPVEYOR_PULL_REQUEST_NUMBER"); [CanBeNull] public string PullRequestTitle => EnvironmentInfo.GetVariable<string>("APPVEYOR_PULL_REQUEST_TITLE"); public string JobId => EnvironmentInfo.GetVariable<string>("APPVEYOR_JOB_ID"); [CanBeNull] public string JobName => EnvironmentInfo.GetVariable<string>("APPVEYOR_JOB_NAME"); public int JobNumber => EnvironmentInfo.GetVariable<int>("APPVEYOR_JOB_NUMBER"); public string RepositoryProvider => EnvironmentInfo.GetVariable<string>("APPVEYOR_REPO_PROVIDER"); public string RepositoryScm => EnvironmentInfo.GetVariable<string>("APPVEYOR_REPO_SCM"); public string RepositoryName => EnvironmentInfo.GetVariable<string>("APPVEYOR_REPO_NAME"); public string RepositoryBranch => EnvironmentInfo.GetVariable<string>("APPVEYOR_REPO_BRANCH"); public bool RepositoryTag => EnvironmentInfo.GetVariable<bool>("APPVEYOR_REPO_TAG"); [CanBeNull] public string RepositoryTagName => EnvironmentInfo.GetVariable<string>("APPVEYOR_REPO_TAG_NAME"); public string RepositoryCommitSha => EnvironmentInfo.GetVariable<string>("APPVEYOR_REPO_COMMIT"); public string RepositoryCommitAuthor => EnvironmentInfo.GetVariable<string>("APPVEYOR_REPO_COMMIT_AUTHOR"); public string RepositoryCommitAuthorEmail => EnvironmentInfo.GetVariable<string>("APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL"); public DateTime RepositoryCommitTimestamp => EnvironmentInfo.GetVariable<DateTime>("APPVEYOR_REPO_COMMIT_TIMESTAMP"); public string RepositoryCommitMessage => EnvironmentInfo.GetVariable<string>("APPVEYOR_REPO_COMMIT_MESSAGE"); [CanBeNull] public string RepositoryCommitMessageExtended => EnvironmentInfo.GetVariable<string>("APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED"); public bool ScheduledBuild => EnvironmentInfo.GetVariable<bool>("APPVEYOR_SCHEDULED_BUILD"); public bool ForcedBuild => EnvironmentInfo.GetVariable<bool>("APPVEYOR_FORCED_BUILD"); public bool Rebuild => EnvironmentInfo.GetVariable<bool>("APPVEYOR_RE_BUILD"); [CanBeNull] public string Platform => EnvironmentInfo.GetVariable<string>("PLATFORM"); [CanBeNull] public string Configuration => EnvironmentInfo.GetVariable<string>("CONFIGURATION"); public void UpdateBuildVersion(string version) { Cli?.Invoke($"UpdateBuild -Version {version.DoubleQuote()}"); EnvironmentInfo.SetVariable("APPVEYOR_BUILD_VERSION", version); } public void PushArtifact(string path, string name = null) { name ??= Path.GetFileName(path); Cli?.Invoke($"PushArtifact {path} -FileName {name}"); } public void WriteInformation(string message, string details = null) { WriteMessage(AppVeyorMessageCategory.Information, message, details); } public void WriteWarning(string message, string details = null) { WriteMessage(AppVeyorMessageCategory.Warning, message, details); } public void WriteError(string message, string details = null) { WriteMessage(AppVeyorMessageCategory.Error, message, details); } private void WriteMessage(AppVeyorMessageCategory category, string message, string details) { if (_messageCount == MessageLimit) { Theme.WriteWarning( $"AppVeyor has a default limit of {MessageLimit} messages. " + "If you're getting an exception from 'appveyor.exe' after this message, " + "contact https://appveyor.com/support to resolve this issue for your account."); } _messageCount++; Cli?.Invoke($"AddMessage {message.DoubleQuote()} -Category {category} -Details {details.DoubleQuote()}", logInvocation: false, logOutput: false); } } }
49.614815
146
0.700956
[ "MIT" ]
ChaseFlorell/nuke
source/Nuke.Common/CI/AppVeyor/AppVeyor.cs
6,698
C#
using System; using System.Collections.Generic; using System.Text; using TechCatalogAdminPanel.Models.Enums; namespace TechCatalogAdminPanel.Common.ViewModels { public class TvEditViewModel : BaseDeviceEditViewModel { public Resolution Resolution { get; set; } public ScreenTechnology ScreenTechnology { get; set; } public decimal DisplaySizeInch { get; set; } public bool IsVoiceControl { get; set; } public bool IsSmartTv { get; set; } } }
23.809524
62
0.704
[ "MIT" ]
Valentinles/TechCatalog-AdminPanel
src/TechCatalogAdminPanel.Common/ViewModels/TvEditViewModel.cs
502
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Devices.PointOfService.Provider { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class BarcodeScannerSetActiveSymbologiesRequest { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::System.Collections.Generic.IReadOnlyList<uint> Symbologies { get { throw new global::System.NotImplementedException("The member IReadOnlyList<uint> BarcodeScannerSetActiveSymbologiesRequest.Symbologies is not implemented in Uno."); } } #endif // Forced skipping of method Windows.Devices.PointOfService.Provider.BarcodeScannerSetActiveSymbologiesRequest.Symbologies.get #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.Foundation.IAsyncAction ReportCompletedAsync() { throw new global::System.NotImplementedException("The member IAsyncAction BarcodeScannerSetActiveSymbologiesRequest.ReportCompletedAsync() is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.Foundation.IAsyncAction ReportFailedAsync() { throw new global::System.NotImplementedException("The member IAsyncAction BarcodeScannerSetActiveSymbologiesRequest.ReportFailedAsync() is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.Foundation.IAsyncAction ReportFailedAsync( int reason) { throw new global::System.NotImplementedException("The member IAsyncAction BarcodeScannerSetActiveSymbologiesRequest.ReportFailedAsync(int reason) is not implemented in Uno."); } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.Foundation.IAsyncAction ReportFailedAsync( int reason, string failedReasonDescription) { throw new global::System.NotImplementedException("The member IAsyncAction BarcodeScannerSetActiveSymbologiesRequest.ReportFailedAsync(int reason, string failedReasonDescription) is not implemented in Uno."); } #endif } }
46.039216
210
0.78109
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.PointOfService.Provider/BarcodeScannerSetActiveSymbologiesRequest.cs
2,348
C#
// ------------------------------------------------------------------------------ // <copyright file="LoopStatementFactory.cs" company="Drake53"> // Licensed under the MIT license. // See the LICENSE file in the project root for more information. // </copyright> // ------------------------------------------------------------------------------ using War3Net.CodeAnalysis.Jass.Syntax; namespace War3Net.CodeAnalysis.Jass { public static partial class JassSyntaxFactory { public static JassLoopStatementSyntax LoopStatement(JassStatementListSyntax body) { return new JassLoopStatementSyntax(body); } public static JassLoopStatementSyntax LoopStatement(params IStatementSyntax[] body) { return new JassLoopStatementSyntax(StatementList(body)); } } }
34.791667
91
0.57006
[ "MIT" ]
Bia10/War3Net
src/War3Net.CodeAnalysis.Jass/SyntaxFactory/LoopStatementFactory.cs
837
C#
using System; namespace NQuery.Iterators { internal sealed class IndirectedRowBuffer : RowBuffer { public IndirectedRowBuffer(int count) { Count = count; } public RowBuffer ActiveRowBuffer { get; set; } public override int Count { get; } public override object this[int index] { get { return ActiveRowBuffer[index]; } } public override void CopyTo(object[] array, int destinationIndex) { ActiveRowBuffer.CopyTo(array, destinationIndex); } } }
22.461538
73
0.587329
[ "MIT" ]
dallmair/nquery-vnext
src/NQuery/Iterators/IndirectedRowBuffer.cs
586
C#
using DataAccessLayer.Repositories; using EntityLayer.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccessLayer.EntityFramework { public class EfContactRepository : GenericRepository<Contact>, IContactDal { } }
21.266667
78
0.799373
[ "MIT" ]
elifkuus/Blog-WebSite
BlogWebSite/DataAccessLayer/EntityFramework/EfContactRepository.cs
321
C#
/******************************************************************************** * RequestContext.cs * * * * Author: Denes Solti * ********************************************************************************/ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Threading; namespace Solti.Utils.Rpc.Internals { using Interfaces; using Properties; internal class RequestContext : IRequestContext { internal RequestContext(string? sessionId, string module, string method, Stream payload, CancellationToken cancellation) { SessionId = sessionId; Module = module; Method = method; Payload = payload; Cancellation = cancellation; Headers = new Dictionary<string, string>(); RequestParameters = new Dictionary<string, string>(); } public RequestContext(HttpListenerRequest request, CancellationToken cancellation) { NameValueCollection paramz = request.QueryString; RequestParameters = paramz.AllKeys.ToDictionary(key => key, key => paramz[key]); // // Ne a RequestParameters-bol kerjuk le mert az kivetelt dob ha nincs elem adott kulccsal // SessionId = paramz["sessionid"]; Module = paramz["module"] ?? throw new InvalidOperationException(Errors.NO_MODULE); Method = paramz["method"] ?? throw new InvalidOperationException(Errors.NO_METHOD); Payload = request.InputStream; Headers = request.Headers.AllKeys.ToDictionary(key => key, key => request.Headers[key]); Cancellation = cancellation; } public string? SessionId { get; } public string Module { get; } public string Method { get; } public Stream Payload { get; } public CancellationToken Cancellation { get; } public IReadOnlyDictionary<string, string> Headers { get; } public IReadOnlyDictionary<string, string> RequestParameters { get; } } }
35.641791
128
0.535176
[ "MIT" ]
Sholtee/rpc
SRC/RPC.Server/Private/RequestContext.cs
2,390
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// NetworkInterfacesOperations operations. /// </summary> internal partial class NetworkInterfacesOperations : IServiceOperations<NetworkManagementClient>, INetworkInterfacesOperations { /// <summary> /// Initializes a new instance of the NetworkInterfacesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal NetworkInterfacesOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets information about the specified network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NetworkInterface>> GetWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkInterfaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkInterfaceName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkInterfaceName", networkInterfaceName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkInterfaceName}", System.Uri.EscapeDataString(networkInterfaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NetworkInterface>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkInterface>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network interface operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<NetworkInterface>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<NetworkInterface> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all network interfaces in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/networkInterfaces").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterface>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterface>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all network interfaces in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterface>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterface>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all route tables applied to a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<EffectiveRouteListResult>> GetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<EffectiveRouteListResult> _response = await BeginGetEffectiveRouteTableWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all network security groups applied to a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> ListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<EffectiveNetworkSecurityGroupListResult> _response = await BeginListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets information about all network interfaces in a virtual machine in a /// virtual machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetVMNetworkInterfacesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualMachineScaleSetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualMachineScaleSetName"); } if (virtualmachineIndex == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualmachineIndex"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualMachineScaleSetName", virtualMachineScaleSetName); tracingParameters.Add("virtualmachineIndex", virtualmachineIndex); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListVirtualMachineScaleSetVMNetworkInterfaces", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualMachineScaleSetName}", System.Uri.EscapeDataString(virtualMachineScaleSetName)); _url = _url.Replace("{virtualmachineIndex}", System.Uri.EscapeDataString(virtualmachineIndex)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterface>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterface>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all network interfaces in a virtual machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetNetworkInterfacesWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualMachineScaleSetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualMachineScaleSetName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualMachineScaleSetName", virtualMachineScaleSetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListVirtualMachineScaleSetNetworkInterfaces", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/networkInterfaces").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualMachineScaleSetName}", System.Uri.EscapeDataString(virtualMachineScaleSetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterface>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterface>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get the specified network interface in a virtual machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NetworkInterface>> GetVirtualMachineScaleSetNetworkInterfaceWithHttpMessagesAsync(string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualMachineScaleSetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualMachineScaleSetName"); } if (virtualmachineIndex == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualmachineIndex"); } if (networkInterfaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkInterfaceName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualMachineScaleSetName", virtualMachineScaleSetName); tracingParameters.Add("virtualmachineIndex", virtualmachineIndex); tracingParameters.Add("networkInterfaceName", networkInterfaceName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetVirtualMachineScaleSetNetworkInterface", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.Compute/virtualMachineScaleSets/{virtualMachineScaleSetName}/virtualMachines/{virtualmachineIndex}/networkInterfaces/{networkInterfaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualMachineScaleSetName}", System.Uri.EscapeDataString(virtualMachineScaleSetName)); _url = _url.Replace("{virtualmachineIndex}", System.Uri.EscapeDataString(virtualmachineIndex)); _url = _url.Replace("{networkInterfaceName}", System.Uri.EscapeDataString(networkInterfaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NetworkInterface>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkInterface>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkInterfaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkInterfaceName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkInterfaceName", networkInterfaceName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkInterfaceName}", System.Uri.EscapeDataString(networkInterfaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network interface operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<NetworkInterface>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkInterfaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkInterfaceName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkInterfaceName", networkInterfaceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkInterfaceName}", System.Uri.EscapeDataString(networkInterfaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<NetworkInterface>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkInterface>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<NetworkInterface>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all route tables applied to a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<EffectiveRouteListResult>> BeginGetEffectiveRouteTableWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkInterfaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkInterfaceName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkInterfaceName", networkInterfaceName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginGetEffectiveRouteTable", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/effectiveRouteTable").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkInterfaceName}", System.Uri.EscapeDataString(networkInterfaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<EffectiveRouteListResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<EffectiveRouteListResult>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all network security groups applied to a network interface. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>> BeginListEffectiveNetworkSecurityGroupsWithHttpMessagesAsync(string resourceGroupName, string networkInterfaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkInterfaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkInterfaceName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkInterfaceName", networkInterfaceName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginListEffectiveNetworkSecurityGroups", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkInterfaces/{networkInterfaceName}/effectiveNetworkSecurityGroups").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkInterfaceName}", System.Uri.EscapeDataString(networkInterfaceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<EffectiveNetworkSecurityGroupListResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<EffectiveNetworkSecurityGroupListResult>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all network interfaces in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterface>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterface>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all network interfaces in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterface>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterface>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets information about all network interfaces in a virtual machine in a /// virtual machine scale set. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetVMNetworkInterfacesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListVirtualMachineScaleSetVMNetworkInterfacesNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterface>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterface>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all network interfaces in a virtual machine scale set. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListVirtualMachineScaleSetNetworkInterfacesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListVirtualMachineScaleSetNetworkInterfacesNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterface>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterface>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
48.092713
402
0.571107
[ "MIT" ]
samtoubia/azure-sdk-for-net
src/ResourceManagement/Network/Microsoft.Azure.Management.Network/Generated/NetworkInterfacesOperations.cs
133,313
C#
using System; using UnityEngine; public class MinMaxSliderAttribute : PropertyAttribute { public readonly float max; public readonly float min; public MinMaxSliderAttribute( float min_, float max_ ) { min = min_; max = max_; } }
17.142857
55
0.745833
[ "MIT" ]
theADAMJR/PROJECT-2D
Assets/Asset Packs/FoliageWaver/MinMaxSliderAttribute.cs
242
C#
using UnityEngine; public class ExitToMenu : MonoBehaviour { [SerializeField] private KeyCode key; public void Update() { if (Input.GetKeyDown(key)) { G.Instance.Scene.Load("MainMenu"); } } }
18.384615
46
0.598326
[ "MIT" ]
doc97/Neon-Domination
Assets/Scripts/Management/ExitToMenu.cs
241
C#
using System; using System.Collections; namespace DataMining.Data { /// <summary> /// same as VSSearcher, but takes as an argument a docId /// </summary> public class DocVSSearcher { private DocsLoader dLoader; private CatsLoader cLoader; private Index index; private const int TRAININGSET = 5000; public DocVSSearcher(Index index, DocsLoader dLoader, CatsLoader cLoader) { this.dLoader = dLoader; this.cLoader = cLoader; this.index = index; } public ResultDocument[] Search(int docId, int topResults) { //make a hashtable for terms in the doc which is being compared to all the rest Hashtable termIds = new Hashtable(); DocTermItem[] docTerms = index.DocTerms(docId); foreach (DocTermItem dti in docTerms) termIds.Add(dti.TermId, dti.TermCount); ResultDocument[] allResults = new ResultDocument[TRAININGSET]; float docNorm = index.GetDocNorm(docId); float doc2norm; float similarity; for (int doc2id = 0; doc2id < allResults.Length; doc2id++) { doc2norm = index.GetDocNorm(doc2id); similarity = getDotProduct(docId, doc2id, termIds) / (docNorm * doc2norm); allResults[doc2id] = new ResultDocument(doc2id, similarity); } Array.Sort(allResults); ResultDocument[] results = new ResultDocument[topResults]; int j = 0; for (int i = 0; i < topResults; i++) { if (allResults[j].DocId == docId) //do not return the doc itself! j++; results[i] = allResults[j++]; } return results; } private float getDotProduct(int doc1id, int doc2id, Hashtable termIds) { DocTermItem[] docTerms; docTerms = index.DocTerms(doc2id); float dotProduct = 0; float idf; int termCount; foreach (DocTermItem dti in docTerms) { if (termIds.Contains(dti.TermId)) { termCount = Convert.ToInt32(termIds[dti.TermId]); idf = index.GetTermIDF(dti.TermId); dotProduct += (termCount * idf * dti.TermCount * idf); //dot =+ (t1f * idf)(t2f * idf) } } return dotProduct; } } }
32.75641
106
0.536204
[ "Unlicense" ]
ic4f/oldcode
2007-knn-wikipedia-classifier/Data/DocVSSearcher.cs
2,555
C#
using System; using System.Linq; namespace Amg.Extensions { internal static class ObjectExtensions { /// <summary> /// Writes instance properties /// </summary> /// <param name="x"></param> /// <returns></returns> public static IWritable Destructure(this object x) => TextFormatExtensions.GetWritable(_ => _.Dump(x)); /// <summary> /// object properties as table /// </summary> /// <param name="x"></param> /// <returns></returns> public static IWritable PropertiesTable(this object x) { return x.GetType() .GetProperties() .Select(p => new { p.Name, Value = p.GetValue(x, new object[] { }) }) .ToTable(header: false); } /// <summary> /// like ToString, but never throws. x can also be null. /// </summary> /// <param name="x"></param> /// <returns></returns> public static string SafeToString(this object? x) { if (x == null) { return String.Empty; } try { return x.ToString(); } catch { return String.Empty; } } } }
26.019608
111
0.464205
[ "MIT" ]
sidiandi/Amg.GetOpt
Amg.GetOpt/Extensions/ObjectExtensions.cs
1,329
C#
using HelloExtensions.Auth.Interfaces; namespace HelloExtensions.ProjectA.Auth.Interfaces { public interface IUserCredentials : ICredentialInfo, IXmlSupport { } }
19.666667
68
0.774011
[ "MIT" ]
andreigit/CompositionAndInterfaces-Sample
HelloExtensions.ProjectA.Auth/Interfaces/IUserCredentials.cs
179
C#
namespace LeetCode.Naive.Problems; /// <summary> /// Problem: https://leetcode.com/problems/parsing-a-boolean-expression/ /// Submission: https://leetcode.com/submissions/detail/419973463/ /// </summary> internal class P1106 { public class Solution { public bool ParseBoolExpr(string expression) { if (expression == "t") return true; if (expression == "f") return false; if (expression[0] == '!') return ParseNot(1, expression).value; if (expression[0] == '&') return ParseAnd(1, expression).value; else return ParseOr(1, expression).value; } private (bool value, int lastpos) ParseNot(int start, string expression) { var parts = GetParts(start, expression); return (!parts.parts[0], parts.lastpos); } private (bool value, int lastpos) ParseAnd(int start, string expression) { var parts = GetParts(start, expression); return (parts.parts.Aggregate(true, (a, b) => a & b), parts.lastpos); } private (bool value, int lastpos) ParseOr(int start, string expression) { var parts = GetParts(start, expression); return (parts.parts.Aggregate(false, (a, b) => a | b), parts.lastpos); } private (List<bool> parts, int lastpos) GetParts(int start, string expression) { var parts = new List<bool>(); while (expression[start] != ')') { switch (expression[start + 1]) { case 't': parts.Add(true); start += 2; break; case 'f': parts.Add(false); start += 2; break; case '!': var not = ParseNot(start + 2, expression); parts.Add(not.value); start = not.lastpos; break; case '&': var and = ParseAnd(start + 2, expression); parts.Add(and.value); start = and.lastpos; break; case '|': var or = ParseOr(start + 2, expression); parts.Add(or.value); start = or.lastpos; break; } } return (parts, start + 1); } } }
27.095238
83
0.519772
[ "MIT" ]
viacheslave/algo
leetcode/c#/Problems/P1106.cs
2,276
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.SecretsManager; using Amazon.SecretsManager.Model; namespace Amazon.PowerShell.Cmdlets.SEC { /// <summary> /// Cancels the scheduled deletion of a secret by removing the <code>DeletedDate</code> /// time stamp. This makes the secret accessible to query once again. /// /// /// <para><b>Minimum permissions</b></para><para> /// To run this command, you must have the following permissions: /// </para><ul><li><para> /// secretsmanager:RestoreSecret /// </para></li></ul><para><b>Related operations</b></para><ul><li><para> /// To delete a secret, use <a>DeleteSecret</a>. /// </para></li></ul> /// </summary> [Cmdlet("Restore", "SECSecret", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("Amazon.SecretsManager.Model.RestoreSecretResponse")] [AWSCmdlet("Calls the AWS Secrets Manager RestoreSecret API operation.", Operation = new[] {"RestoreSecret"}, SelectReturnType = typeof(Amazon.SecretsManager.Model.RestoreSecretResponse))] [AWSCmdletOutput("Amazon.SecretsManager.Model.RestoreSecretResponse", "This cmdlet returns an Amazon.SecretsManager.Model.RestoreSecretResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class RestoreSECSecretCmdlet : AmazonSecretsManagerClientCmdlet, IExecutor { #region Parameter SecretId /// <summary> /// <para> /// <para>Specifies the secret that you want to restore from a previously scheduled deletion. /// You can specify either the Amazon Resource Name (ARN) or the friendly name of the /// secret.</para><note><para>If you specify an ARN, we generally recommend that you specify a complete ARN. You /// can specify a partial ARN too—for example, if you don’t include the final hyphen and /// six random characters that Secrets Manager adds at the end of the ARN when you created /// the secret. A partial ARN match can work as long as it uniquely matches only one secret. /// However, if your secret has a name that ends in a hyphen followed by six characters /// (before Secrets Manager adds the hyphen and six characters to the ARN) and you try /// to use that as a partial ARN, then those characters cause Secrets Manager to assume /// that you’re specifying a complete ARN. This confusion can cause unexpected results. /// To avoid this situation, we recommend that you don’t create secret names ending with /// a hyphen followed by six characters.</para><para>If you specify an incomplete ARN without the random suffix, and instead provide the /// 'friendly name', you <i>must</i> not include the random suffix. If you do include /// the random suffix added by Secrets Manager, you receive either a <i>ResourceNotFoundException</i> /// or an <i>AccessDeniedException</i> error, depending on your permissions.</para></note> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String SecretId { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is '*'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.SecretsManager.Model.RestoreSecretResponse). /// Specifying the name of a property of type Amazon.SecretsManager.Model.RestoreSecretResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the SecretId parameter. /// The -PassThru parameter is deprecated, use -Select '^SecretId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^SecretId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.SecretId), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Restore-SECSecret (RestoreSecret)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.SecretsManager.Model.RestoreSecretResponse, RestoreSECSecretCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.SecretId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.SecretId = this.SecretId; #if MODULAR if (this.SecretId == null && ParameterWasBound(nameof(this.SecretId))) { WriteWarning("You are passing $null as a value for parameter SecretId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.SecretsManager.Model.RestoreSecretRequest(); if (cmdletContext.SecretId != null) { request.SecretId = cmdletContext.SecretId; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.SecretsManager.Model.RestoreSecretResponse CallAWSServiceOperation(IAmazonSecretsManager client, Amazon.SecretsManager.Model.RestoreSecretRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Secrets Manager", "RestoreSecret"); try { #if DESKTOP return client.RestoreSecret(request); #elif CORECLR return client.RestoreSecretAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String SecretId { get; set; } public System.Func<Amazon.SecretsManager.Model.RestoreSecretResponse, RestoreSECSecretCmdlet, object> Select { get; set; } = (response, cmdlet) => response; } } }
48.51046
279
0.62403
[ "Apache-2.0" ]
QPC-database/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/SecretsManager/Basic/Restore-SECSecret-Cmdlet.cs
11,602
C#
// CivOne // // To the extent possible under law, the person who associated CC0 with // CivOne has waived all copyright and related or neighboring rights // to CivOne. // // You should have received a copy of the CC0 legalcode along with this // work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. using CivOne.Enums; using CivOne.Leaders; namespace CivOne.Civilizations { internal class English : BaseCivilization<Elizabeth> { public English() : base(Civilization.English, "English", "English", "eliz") { StartX = 31; StartY = 14; CityNames = new[] { "London", "Coventry", "Birmingham", "Dover", "Nottingham", "York", "Liverpool", "Brighton", "Oxford", "Reading", "Exeter", "Cambridge", "Hastings", "Canterbury", "Banbury", "Newcastle" }; } } }
20.357143
77
0.637427
[ "CC0-1.0" ]
Andersw88/CivOne
src/Civilizations/English.cs
857
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("SendToRabbitMQ")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("SendToRabbitMQ")] [assembly: System.Reflection.AssemblyTitleAttribute("SendToRabbitMQ")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.333333
80
0.65121
[ "MIT" ]
CamiKaze/MessageQueue
SendToRabbitMQ/SendToRabbitMQ/obj/Debug/netcoreapp2.2/SendToRabbitMQ.AssemblyInfo.cs
992
C#
using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyTitle("GitVersionCore")] [assembly: AssemblyProduct("GitVersion")] [assembly: AssemblyVersion("4.0.0.0")] [assembly: AssemblyFileVersion("4.0.0.0")] [assembly: InternalsVisibleTo("GitVersionTask.Tests")] [assembly: InternalsVisibleTo("GitVersion")] [assembly: InternalsVisibleTo("GitVersionCore.Tests")] [assembly: InternalsVisibleTo("GitVersionExe.Tests")] [assembly: AssemblyInformationalVersion("4.0.0-netstandard.1+1538.Branch.feature/netstandard.Sha.91536c107ba91f755f14904fc69965a9ad70fcb0")]
42.785714
141
0.789649
[ "MIT" ]
yohanb/GitVersion
src/GitVersionCore/AssemblyInfo.cs
590
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace LordJZ.WinAPI.Native { [StructLayout(LayoutKind.Explicit)] internal struct IMAGE_NT_HEADERS { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public char[] Signature; [FieldOffset(4)] public IMAGE_FILE_HEADER FileHeader; [FieldOffset(24)] public IMAGE_OPTIONAL_HEADER32 OptionalHeader32; [FieldOffset(24)] public IMAGE_OPTIONAL_HEADER64 OptionalHeader64; public bool Is64 { get { switch (OptionalHeader32.Magic) { case MagicType.IMAGE_NT_OPTIONAL_HDR32_MAGIC: return false; case MagicType.IMAGE_NT_OPTIONAL_HDR64_MAGIC: return true; default: throw new InvalidOperationException(); } } } public bool IsValid { get { return Signature[0] == 'P' && Signature[1] == 'E' && Signature[2] == 0 && Signature[3] == 0 && FileHeader.SizeOfOptionalHeader >= 200 && (OptionalHeader32.Magic == MagicType.IMAGE_NT_OPTIONAL_HDR32_MAGIC || OptionalHeader32.Magic == MagicType.IMAGE_NT_OPTIONAL_HDR64_MAGIC); } } } }
28.981481
110
0.548882
[ "MIT" ]
LordJZ/LordJZ
LordJZ.WinAPI/Native/IMAGE_NT_HEADERS.cs
1,567
C#
using NCop.Aspects.Aspects; namespace NCop.Aspects.Weaving.Expressions { internal class BindingRaiseEventAspectDecoratorExpression : IAspectExpression { private readonly IEventAspectDefinition aspectDefinition = null; internal BindingRaiseEventAspectDecoratorExpression(IEventAspectDefinition aspectDefinition) { this.aspectDefinition = aspectDefinition; } public IAspectWeaver Reduce(IAspectWeavingSettings aspectWeavingSettings) { return new BindingRaiseEventAspectDecoratorWeaver(aspectDefinition.Member, aspectWeavingSettings); } } }
34.333333
110
0.763754
[ "MIT" ]
sagifogel/NCop
NCop.Aspects/Weaving/Expressions/BindingRaiseEventAspectDecoratorExpression.cs
620
C#