content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Windows.Forms; namespace SpotifyKeys { public class HotKey : IMessageFilter, IDisposable { private bool disposed = false; private readonly IntPtr handle; private readonly int id; private readonly Keys key; private readonly KeyModifier[] modifier; private event EventHandler hotKeyPressed; public HotKey(IntPtr handle, int id, Keys key, KeyModifier[] modifier, EventHandler hotKeyPressed) { if(modifier == null) throw new System.ComponentModel.InvalidEnumArgumentException("Modifiers should not be null."); if (key == Keys.None || modifier.Length == 0) throw new System.ComponentModel.InvalidEnumArgumentException("The key or modifiers should not be none."); if(hotKeyPressed == null) throw new System.ComponentModel.InvalidEnumArgumentException("The HotKeyPressedEvent cannot be null."); this.handle = handle; this.id = id; this.key = key; this.modifier = modifier; this.hotKeyPressed += hotKeyPressed; } public void RegisterHotKey() { // convert from enum to numeric value int mod = 0; foreach(KeyModifier _modifier in modifier) mod += (int)_modifier; // register hotkey bool isKeyRegisterd = NativeMethods.RegisterHotKey(handle, id, mod, key); // check if function failed if (!isKeyRegisterd) { NativeMethods.UnregisterHotKey(IntPtr.Zero, id); // retry, if failed again throw exception isKeyRegisterd = NativeMethods.RegisterHotKey(handle, id, mod, key); if (!isKeyRegisterd) throw new InvalidOperationException("The hotkey is in use."); else Application.AddMessageFilter(this); } else { Application.AddMessageFilter(this); } } public bool PreFilterMessage(ref Message m) { const int WM_HOTKEY = 0x0312; if (m.Msg == WM_HOTKEY && m.HWnd == handle && m.WParam == (IntPtr) id && hotKeyPressed != null) { hotKeyPressed(this, EventArgs.Empty); return true; } return false; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { Application.RemoveMessageFilter(this); NativeMethods.UnregisterHotKey(handle, id); } disposed = true; } } }
31.956522
121
0.543197
[ "MIT" ]
nobbyfix/SpotifyKeys
SpotifyKeys/HotKey.cs
2,942
C#
using Content.Server.DoAfter; using Content.Server.Popups; using Content.Server.Sticky.Components; using Content.Server.Sticky.Events; using Content.Shared.Hands.EntitySystems; using Content.Shared.Interaction; using Content.Shared.Sticky.Components; using Content.Shared.Verbs; using Robust.Shared.Containers; using Robust.Shared.Player; namespace Content.Server.Sticky.Systems; public sealed class StickySystem : EntitySystem { [Dependency] private readonly DoAfterSystem _doAfterSystem = default!; [Dependency] private readonly PopupSystem _popupSystem = default!; [Dependency] private readonly SharedContainerSystem _containerSystem = default!; [Dependency] private readonly SharedHandsSystem _handsSystem = default!; [Dependency] private readonly SharedInteractionSystem _interactionSystem = default!; private const string StickerSlotId = "stickers_container"; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<StickSuccessfulEvent>(OnStickSuccessful); SubscribeLocalEvent<UnstickSuccessfulEvent>(OnUnstickSuccessful); SubscribeLocalEvent<StickyComponent, AfterInteractEvent>(OnAfterInteract); SubscribeLocalEvent<StickyComponent, GetVerbsEvent<Verb>>(AddUnstickVerb); } private void OnAfterInteract(EntityUid uid, StickyComponent component, AfterInteractEvent args) { if (args.Handled || !args.CanReach || args.Target == null) return; // try stick object to a clicked target entity args.Handled = StartSticking(uid, args.User, args.Target.Value, component); } private void AddUnstickVerb(EntityUid uid, StickyComponent component, GetVerbsEvent<Verb> args) { if (component.StuckTo == null || !component.CanUnstick || !args.CanInteract || args.Hands == null) return; // we can't use args.CanAccess, because it stuck in another container // we also need to ignore entity that it stuck to var inRange = _interactionSystem.InRangeUnobstructed(uid, args.User, predicate: entity => component.StuckTo == entity); if (!inRange) return; args.Verbs.Add(new Verb { Text = Loc.GetString("comp-sticky-unstick-verb-text"), IconTexture = "/Textures/Interface/VerbIcons/eject.svg.192dpi.png", Act = () => StartUnsticking(uid, args.User, component) }); } private bool StartSticking(EntityUid uid, EntityUid user, EntityUid target, StickyComponent? component = null) { if (!Resolve(uid, ref component)) return false; // check whitelist and blacklist if (component.Whitelist != null && !component.Whitelist.IsValid(target)) return false; if (component.Blacklist != null && component.Blacklist.IsValid(target)) return false; // check if delay is not zero to start do after var delay = (float) component.StickDelay.TotalSeconds; if (delay > 0) { // show message to user if (component.StickPopupStart != null) { var msg = Loc.GetString(component.StickPopupStart); _popupSystem.PopupEntity(msg, user, Filter.Entities(user)); } // start sticking object to target _doAfterSystem.DoAfter(new DoAfterEventArgs(user, delay, target: target) { BroadcastFinishedEvent = new StickSuccessfulEvent(uid, user, target), BreakOnStun = true, BreakOnTargetMove = true, BreakOnUserMove = true, NeedHand = true }); } else { // if delay is zero - stick entity immediately StickToEntity(uid, target, user, component); } return true; } private void OnStickSuccessful(StickSuccessfulEvent ev) { // check if entity still has sticky component if (!TryComp(ev.Uid, out StickyComponent? component)) return; StickToEntity(ev.Uid, ev.Target, ev.User, component); } private void StartUnsticking(EntityUid uid, EntityUid user, StickyComponent? component = null) { if (!Resolve(uid, ref component)) return; var delay = (float) component.UnstickDelay.TotalSeconds; if (delay > 0) { // show message to user if (component.UnstickPopupStart != null) { var msg = Loc.GetString(component.UnstickPopupStart); _popupSystem.PopupEntity(msg, user, Filter.Entities(user)); } // start unsticking object _doAfterSystem.DoAfter(new DoAfterEventArgs(user, delay, target: uid) { BroadcastFinishedEvent = new UnstickSuccessfulEvent(uid, user), BreakOnStun = true, BreakOnTargetMove = true, BreakOnUserMove = true, NeedHand = true }); } else { // if delay is zero - unstick entity immediately UnstickFromEntity(uid, user, component); } } private void OnUnstickSuccessful(UnstickSuccessfulEvent ev) { // check if entity still has sticky component if (!TryComp(ev.Uid, out StickyComponent? component)) return; UnstickFromEntity(ev.Uid, ev.User, component); } public void StickToEntity(EntityUid uid, EntityUid target, EntityUid user, StickyComponent? component = null) { if (!Resolve(uid, ref component)) return; // add container to entity and insert sticker into it var container = _containerSystem.EnsureContainer<Container>(target, StickerSlotId); container.ShowContents = true; if (!container.Insert(uid)) return; // show message to user if (component.StickPopupSuccess != null) { var msg = Loc.GetString(component.StickPopupSuccess); _popupSystem.PopupEntity(msg, user, Filter.Entities(user)); } // send information to appearance that entity is stuck if (TryComp(uid, out AppearanceComponent? appearance)) { appearance.SetData(StickyVisuals.IsStuck, true); } component.StuckTo = target; RaiseLocalEvent(uid, new EntityStuckEvent(target, user), true); } public void UnstickFromEntity(EntityUid uid, EntityUid user, StickyComponent? component = null) { if (!Resolve(uid, ref component)) return; if (component.StuckTo == null) return; // try to remove sticky item from target container var target = component.StuckTo.Value; if (!_containerSystem.TryGetContainer(target, StickerSlotId, out var container) || !container.Remove(uid)) return; // delete container if it's now empty if (container.ContainedEntities.Count == 0) container.Shutdown(); // try place dropped entity into user hands _handsSystem.PickupOrDrop(user, uid); // send information to appearance that entity isn't stuck if (TryComp(uid, out AppearanceComponent? appearance)) { appearance.SetData(StickyVisuals.IsStuck, false); } // show message to user if (component.UnstickPopupSuccess != null) { var msg = Loc.GetString(component.UnstickPopupSuccess); _popupSystem.PopupEntity(msg, user, Filter.Entities(user)); } component.StuckTo = null; RaiseLocalEvent(uid, new EntityUnstuckEvent(target, user), true); } private sealed class StickSuccessfulEvent : EntityEventArgs { public readonly EntityUid Uid; public readonly EntityUid User; public readonly EntityUid Target; public StickSuccessfulEvent(EntityUid uid, EntityUid user, EntityUid target) { Uid = uid; User = user; Target = target; } } private sealed class UnstickSuccessfulEvent : EntityEventArgs { public readonly EntityUid Uid; public readonly EntityUid User; public UnstickSuccessfulEvent(EntityUid uid, EntityUid user) { Uid = uid; User = user; } } }
34.938017
114
0.627558
[ "MIT" ]
EmoGarbage404/space-station-14
Content.Server/Sticky/Systems/StickySystem.cs
8,457
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nucleus.ConsoleEngine { public enum CommandFeedback { Success, WrongNumberOfArguments, Error } }
18.25
40
0.721461
[ "MIT" ]
lucasassislar/nucleusdotnet
Nucleus.Gaming/Nucleus.Gaming/ConsoleEngine/CommandFeedback.cs
221
C#
using System; using System.Linq; using System.Reflection; using FluentAssertions; using Nest; using Newtonsoft.Json; using Tests.Framework; namespace Tests.CodeStandards { [ProjectReferenceOnly] public class QueriesStandards { protected static PropertyInfo[] QueryProperties = typeof(IQueryContainer).GetProperties(); protected static PropertyInfo[] QueryPlaceHolderProperties = typeof(IQueryContainer).GetProperties() .Where(a=>!a.GetCustomAttributes<JsonIgnoreAttribute>().Any()).ToArray(); /* * All properties must be either marked with JsonIgnore or JsonProperty */ [U] public void InterfacePropertiesMustBeMarkedExplicitly() { var properties = from p in QueryProperties let a = p.GetCustomAttributes<JsonIgnoreAttribute>().Concat<Attribute>(p.GetCustomAttributes<JsonPropertyAttribute>()) where a.Count() != 1 select p; properties.Should().BeEmpty(); } [U] public void StaticQueryExposesAll() { var staticProperties = from p in typeof(Query<>).GetMethods() let name = p.Name.StartsWith("GeoShape") ? "GeoShape" : p.Name select name; var placeHolders = QueryPlaceHolderProperties.Select(p => p.Name.StartsWith("GeoShape") ? "GeoShape" : p.Name); staticProperties.Distinct().Should().Contain(placeHolders.Distinct()); } [U] public void FluentDescriptorExposesAll() { var fluentMethods = from p in typeof(QueryContainerDescriptor<>).GetMethods() let name = p.Name.StartsWith("GeoShape") ? "GeoShape" : p.Name select name; var placeHolders = QueryPlaceHolderProperties.Select(p => p.Name.StartsWith("GeoShape") ? "GeoShape" : p.Name); fluentMethods.Distinct().Should().Contain(placeHolders.Distinct()); } [U] public void VisitorVisitsAll() { var skipQueryImplementations = new[] { typeof(IFieldNameQuery), typeof(IFuzzyQuery<,>), typeof(IConditionlessQuery) }; var queries = typeof(IQuery).Assembly().ExportedTypes .Where(t => t.IsInterface() && typeof(IQuery).IsAssignableFrom(t)) .Where(t => !skipQueryImplementations.Contains(t)) .ToList(); queries.Should().NotBeEmpty(); var visitMethods = typeof(IQueryVisitor).GetMethods().Where(m => m.Name == "Visit"); visitMethods.Should().NotBeEmpty(); var missingTypes = from q in queries let visitMethod = visitMethods.FirstOrDefault(m => m.GetParameters().First().ParameterType == q) where visitMethod == null select q; missingTypes.Should().BeEmpty(); } } }
37.376812
127
0.689802
[ "Apache-2.0" ]
jslicer/elasticsearch-net
src/Tests/CodeStandards/Queries.doc.cs
2,581
C#
 using NUnit.Framework; namespace System.IO.Abstractions.Tests { [TestFixture] public class FileSystemTests { [Test] public void Is_Serializable() { var fileSystem = new FileSystem(); var memoryStream = new MemoryStream(); var serializer = new Runtime.Serialization.Formatters.Binary.BinaryFormatter(); #pragma warning disable SYSLIB0011 serializer.Serialize(memoryStream, fileSystem); #pragma warning restore SYSLIB0011 Assert.That(memoryStream.Length > 0, "Length didn't increase after serialization task."); } [Test] public void Mock_File_Succeeds() { var fileSystemMock = new Moq.Mock<IFileSystem>(); Assert.DoesNotThrow(() => fileSystemMock.Setup(x => x.File.ToString()).Returns("") ); } [Test] public void Mock_Directory_Succeeds() { var fileSystemMock = new Moq.Mock<IFileSystem>(); Assert.DoesNotThrow(() => fileSystemMock.Setup(x => x.Directory.ToString()).Returns("") ); } [Test] public void Mock_FileInfo_Succeeds() { var fileSystemMock = new Moq.Mock<IFileSystem>(); Assert.DoesNotThrow(() => fileSystemMock.Setup(x => x.FileInfo.ToString()).Returns("") ); } [Test] public void Mock_FileStream_Succeeds() { var fileSystemMock = new Moq.Mock<IFileSystem>(); Assert.DoesNotThrow(() => fileSystemMock.Setup(x => x.FileStream.ToString()).Returns("") ); } [Test] public void Mock_Path_Succeeds() { var fileSystemMock = new Moq.Mock<IFileSystem>(); Assert.DoesNotThrow(() => fileSystemMock.Setup(x => x.Path.ToString()).Returns("") ); } [Test] public void Mock_DirectoryInfo_Succeeds() { var fileSystemMock = new Moq.Mock<IFileSystem>(); Assert.DoesNotThrow(() => fileSystemMock.Setup(x => x.DirectoryInfo.ToString()).Returns("") ); } [Test] public void Mock_DriveInfo_Succeeds() { var fileSystemMock = new Moq.Mock<IFileSystem>(); Assert.DoesNotThrow(() => fileSystemMock.Setup(x => x.DirectoryInfo.ToString()).Returns("") ); } [Test] public void Mock_FileSystemWatcher_Succeeds() { var fileSystemMock = new Moq.Mock<IFileSystem>(); Assert.DoesNotThrow(() => fileSystemMock.Setup(x => x.FileSystemWatcher.ToString()).Returns("") ); } } }
27.104762
101
0.53584
[ "MIT" ]
BrianMcBrayer/System.IO.Abstractions
tests/System.IO.Abstractions.Tests/FileSystemTests.cs
2,848
C#
using UnityEngine; using UnityGameEvents; using UnityGameEventUnityEngineExtensions.Objects; namespace UnityGameEventUnityEngineExtensions { public interface IUnityEngineRayGameEventListenerController : IGameEventWithParameterListenerController<UnityEngineRayGameEventListenerObjectScript, Ray> { // ... } }
27.416667
157
0.823708
[ "MIT" ]
BigETI/UnityGameEventUnityEngineExtensions
Runtime/Interfaces/IUnityEngineRayGameEventListenerController.cs
329
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the storagegateway-2013-06-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.StorageGateway.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.StorageGateway.Model.Internal.MarshallTransformations { /// <summary> /// ResetCache Request Marshaller /// </summary> public class ResetCacheRequestMarshaller : IMarshaller<IRequest, ResetCacheRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ResetCacheRequest)input); } public IRequest Marshall(ResetCacheRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.StorageGateway"); string target = "StorageGateway_20130630.ResetCache"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetGatewayARN()) { context.Writer.WritePropertyName("GatewayARN"); context.Writer.Write(publicRequest.GatewayARN); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } } }
35.371795
135
0.665821
[ "Apache-2.0" ]
samritchie/aws-sdk-net
AWSSDK_DotNet35/Amazon.StorageGateway/Model/Internal/MarshallTransformations/ResetCacheRequestMarshaller.cs
2,759
C#
namespace TicketingSystem.Web.ViewModels.Comments { using System; using AutoMapper; using TicketSystem.Web.Infrastructure.Mapping; using Models; public class CommentViewModel : IMapFrom<Comment>, IHaveCustomMappings { public int Id { get; set; } public string AuthorName { get; set; } public string Content { get; set; } public void CreateMappings(IConfiguration configuration) { configuration.CreateMap<Comment, CommentViewModel>() .ForMember(c => c.AuthorName, opt => opt.MapFrom(c => c.Author.UserName)); } } }
32.578947
90
0.646204
[ "MIT" ]
crDahaka/Ticketing-System-ASP.NET-MVC-5
TicketingSystem.Web/ViewModels/Comments/CommentViewModel.cs
621
C#
using Esquire.Models; namespace Esquire.Data.Repositories { public interface ICodedQuestionBaseRepository : IRepository<CodedQuestionBase> { } }
18.555556
82
0.724551
[ "Apache-2.0" ]
CDCgov/phlip-backend
Data/Repositories/ICodedQuestionBaseRepository.cs
169
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/WebServices.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="WS_HTTP_HEADER_AUTH_POLICY_DESCRIPTION" /> struct.</summary> public static unsafe class WS_HTTP_HEADER_AUTH_POLICY_DESCRIPTIONTests { /// <summary>Validates that the <see cref="WS_HTTP_HEADER_AUTH_POLICY_DESCRIPTION" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<WS_HTTP_HEADER_AUTH_POLICY_DESCRIPTION>(), Is.EqualTo(sizeof(WS_HTTP_HEADER_AUTH_POLICY_DESCRIPTION))); } /// <summary>Validates that the <see cref="WS_HTTP_HEADER_AUTH_POLICY_DESCRIPTION" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(WS_HTTP_HEADER_AUTH_POLICY_DESCRIPTION).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="WS_HTTP_HEADER_AUTH_POLICY_DESCRIPTION" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(WS_HTTP_HEADER_AUTH_POLICY_DESCRIPTION), Is.EqualTo(48)); } else { Assert.That(sizeof(WS_HTTP_HEADER_AUTH_POLICY_DESCRIPTION), Is.EqualTo(24)); } } } }
41.136364
151
0.680663
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/WebServices/WS_HTTP_HEADER_AUTH_POLICY_DESCRIPTIONTests.cs
1,812
C#
using System; using TicTacToe.Server.Core.Packets.Handlers.Handler; using TicTacToe.Shared.Packet.Types; namespace TicTacToe.Core.Game.Packets.Handlers.Types { public class GameMovePacketHandler : PacketHandler<MovePacket> { public override void Handle(MovePacket instance, object state, object sender) { Console.WriteLine("MOVE"); } } }
25.071429
79
0.780627
[ "MIT" ]
PerfectlyFineCode/tictactoe-server
src/Tic Tac Toe/TicTacToe.Core/Game/Packets/Handlers/Types/GameMovePacketHandler.cs
353
C#
using PG.Commons.Xml.Values; namespace PG.StarWarsGame.Commons.Xml.Tags.Engine.FoC { public sealed class MPDefaultFreeStartingUnitsXmlTagDefinition : AXmlTagDefinition { private const string KEY_ID = "MP_Default_Free_Starting_Units"; private const XmlValueType PG_TYPE = XmlValueType.Boolean; private const XmlValueTypeInternal INTERNAL_TYPE = XmlValueTypeInternal.Undefined; private const bool IS_SINGLETON = true; public override string Id => KEY_ID; public override XmlValueType Type => PG_TYPE; public override XmlValueTypeInternal TypeInternal => INTERNAL_TYPE; public override bool IsSingleton => IS_SINGLETON; } }
41.058824
90
0.744986
[ "MIT" ]
AlamoEngine-Tools/PetroglyphTools
PG.StarWarsGame/PG.StarWarsGame/Commons/Xml/Tags/Engine/FoC/MPDefaultFreeStartingUnitsXmlTagDefinition.cs
698
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR.Hubs; using Microsoft.AspNet.SignalR; namespace SignalRChat { public class ChatHub : Hub { public void Send(string name, string message) { // Call the broadcastMessage method to update clients. //Clients.All.broadcastMessage(name, message); Clients.All.broadcastMessage(name, message); } } }
25.315789
66
0.671518
[ "Apache-2.0" ]
abayaz61/NCache
Samples/dotnet/SignalRChat/SignalRChat/ChatHub.cs
483
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Idfy.Infrastructure; namespace Idfy.Signature { /// <summary> /// Sign contracts, declarations, forms and other documents using digital signatures. /// </summary> public class SignatureService : IdfyBaseService, ISignatureService { public SignatureService() { } public SignatureService(string clientId, string clientSecret, IEnumerable<string> scopes) : base(clientId, clientSecret, scopes) { } public SignatureService(string clientId, string clientSecret, IEnumerable<OAuthScope> scopes) : base(clientId, clientSecret, scopes) { } /// <summary> /// Retrieves details of a single document. /// </summary> /// <param name="documentId"></param> /// <returns></returns> public Document GetDocument(Guid documentId) { return Get<Document>($"{Urls.SignatureDocuments}/{documentId}"); } /// <summary> /// Retrieves details of a single document. /// </summary> /// <param name="documentId"></param> /// <returns></returns> public async Task<Document> GetDocumentAsync(Guid documentId) { return await GetAsync<Document>($"{Urls.SignatureDocuments}/{documentId}"); } /// <summary> /// Creates a new document. /// </summary> /// <param name="documentCreateOptions"></param> /// <returns></returns> public Document CreateDocument(DocumentCreateOptions documentCreateOptions) { return Post<Document>($"{Urls.SignatureDocuments}", documentCreateOptions); } /// <summary> /// Creates a new document. /// </summary> /// <param name="documentCreateOptions"></param> /// <returns></returns> public async Task<Document> CreateDocumentAsync(DocumentCreateOptions documentCreateOptions) { return await PostAsync<Document>($"{Urls.SignatureDocuments}", documentCreateOptions); } /// <summary> /// Updates a document. /// </summary> /// <param name="documentId"></param> /// <param name="documentUpdateOptions"></param> /// <returns></returns> public Document UpdateDocument(Guid documentId, DocumentUpdateOptions documentUpdateOptions) { return Patch<Document>($"{Urls.SignatureDocuments}/{documentId}", documentUpdateOptions); } /// <summary> /// Updates a document. /// </summary> /// <param name="documentId"></param> /// <param name="documentUpdateOptions"></param> /// <returns></returns> public async Task<Document> UpdateDocumentAsync(Guid documentId, DocumentUpdateOptions documentUpdateOptions) { return await PatchAsync<Document>($"{Urls.SignatureDocuments}/{documentId}", documentUpdateOptions); } /// <summary> /// Cancels a document. /// </summary> /// <param name="documentId"></param> /// <param name="reason"></param> /// <returns></returns> public void CancelDocument(Guid documentId, string reason = null) { var url = APIHelper.AppendQueryParams($"{Urls.SignatureDocuments}/{documentId}/cancel", new Dictionary<string, object>() { {"reason", reason} }); Post(url); } /// <summary> /// Cancels a document. /// </summary> /// <param name="documentId"></param> /// <param name="reason"></param> /// <returns></returns> public async Task CancelDocumentAsync(Guid documentId, string reason = null) { var url = APIHelper.AppendQueryParams($"{Urls.SignatureDocuments}/{documentId}/cancel", new Dictionary<string, object>() { {"reason", reason} }); await PostAsync(url); } /// <summary> /// Retrieves the status of a document. /// </summary> /// <param name="documentId"></param> /// <returns></returns> public DocumentStatusSummary GetDocumentStatus(Guid documentId) { return Get<DocumentStatusSummary>($"{Urls.SignatureDocuments}/{documentId}/status"); } /// <summary> /// Retrieves the status of a document. /// </summary> /// <param name="documentId"></param> /// <returns></returns> public async Task<DocumentStatusSummary> GetDocumentStatusAsync(Guid documentId) { return await GetAsync<DocumentStatusSummary>($"{Urls.SignatureDocuments}/{documentId}/status"); } /// <summary> /// Retrieves information about a document. /// </summary> /// <param name="documentId"></param> public DocumentSummary GetDocumentSummary(Guid documentId) { return Get<DocumentSummary>($"{Urls.SignatureDocuments}/{documentId}/summary"); } /// <summary> /// Retrieves information about a document. /// </summary> /// <param name="documentId"></param> public async Task<DocumentSummary> GetDocumentSummaryAsync(Guid documentId) { return await GetAsync<DocumentSummary>($"{Urls.SignatureDocuments}/{documentId}/summary"); } /// <summary> /// Queries your documents using the provided parameters. /// </summary> /// <param name="externalId"></param> /// <param name="signerId"></param> /// <param name="externalSignerId"></param> /// <param name="fromDate"></param> /// <param name="toDate"></param> /// <param name="lastUpdated"></param> /// <param name="signedDate"></param> /// <param name="nameOfSigner"></param> /// <param name="title"></param> /// <param name="status"></param> /// <param name="tags"></param> /// <param name="offset"></param> /// <param name="limit"></param> /// <returns></returns> public CollectionWithPaging<DocumentSummary> ListDocumentSummaries( string externalId = null, Guid? signerId = null, string externalSignerId = null, DateTime? fromDate = null, DateTime? toDate = null, DateTime? lastUpdated = null, DateTime? signedDate = null, string nameOfSigner = null, string title = null, DocumentStatus? status = null, string tags = null, int? offset = null, int? limit = null) { var url = APIHelper.AppendQueryParams($"{Urls.SignatureDocuments}/summary", new Dictionary<string, object>() { {"externalId", externalId}, {"signerId", signerId}, {"externalSignerId", externalSignerId}, {"fromDate", fromDate}, {"toDate", toDate}, {"lastUpdated", lastUpdated}, {"signedDate", signedDate}, {"nameOfSigner", nameOfSigner}, {"title", title}, {"status", status}, {"tags", tags}, {"offset", offset}, {"limit", limit} }); return Get<CollectionWithPaging<DocumentSummary>>(url); } /// <summary> /// Queries your documents using the provided parameters. /// </summary> /// <param name="externalId"></param> /// <param name="signerId"></param> /// <param name="externalSignerId"></param> /// <param name="fromDate"></param> /// <param name="toDate"></param> /// <param name="lastUpdated"></param> /// <param name="signedDate"></param> /// <param name="nameOfSigner"></param> /// <param name="title"></param> /// <param name="status"></param> /// <param name="tags"></param> /// <param name="offset"></param> /// <param name="limit"></param> /// <returns></returns> public async Task<CollectionWithPaging<DocumentSummary>> ListDocumentSummariesAsync( string externalId = null, Guid? signerId = null, string externalSignerId = null, DateTime? fromDate = null, DateTime? toDate = null, DateTime? lastUpdated = null, DateTime? signedDate = null, string nameOfSigner = null, string title = null, DocumentStatus? status = null, string tags = null, int? offset = null, int? limit = null) { var url = APIHelper.AppendQueryParams($"{Urls.SignatureDocuments}/summary", new Dictionary<string, object>() { {"externalId", externalId}, {"signerId", signerId}, {"externalSignerId", externalSignerId}, {"fromDate", fromDate}, {"toDate", toDate}, {"lastUpdated", lastUpdated}, {"signedDate", signedDate}, {"nameOfSigner", nameOfSigner}, {"title", title}, {"status", status}, {"tags", tags}, {"offset", offset}, {"limit", limit} }); return await GetAsync<CollectionWithPaging<DocumentSummary>>(url); } /// <summary> /// Retrieves the details of a single signer. /// </summary> /// <param name="documentId"></param> /// <param name="signerId"></param> /// <returns></returns> public Signer GetSigner(Guid documentId, Guid signerId) { return Get<Signer>($"{Urls.SignatureDocuments}/{documentId}/signers/{signerId}"); } /// <summary> /// Retrieves the details of a single signer. /// </summary> /// <param name="documentId"></param> /// <param name="signerId"></param> /// <returns></returns> public async Task<Signer> GetSignerAsync(Guid documentId, Guid signerId) { return await GetAsync<Signer>($"{Urls.SignatureDocuments}/{documentId}/signers/{signerId}"); } /// <summary> /// Creates a new signer. /// </summary> /// <param name="documentId"></param> /// <param name="signerOptions"></param> /// <returns></returns> public Signer CreateSigner(Guid documentId, SignerOptions signerOptions) { return Post<Signer>($"{Urls.SignatureDocuments}/{documentId}/signers", signerOptions); } /// <summary> /// Creates a new signer. /// </summary> /// <param name="documentId"></param> /// <param name="signerOptions"></param> /// <returns></returns> public async Task<Signer> CreateSignerAsync(Guid documentId, SignerOptions signerOptions) { return await PostAsync<Signer>($"{Urls.SignatureDocuments}/{documentId}/signers", signerOptions); } /// <summary> /// Updates a signer. /// </summary> /// <param name="documentId"></param> /// <param name="signerId"></param> /// <param name="signerOptions"></param> /// <returns></returns> public Signer UpdateSigner(Guid documentId, Guid signerId, SignerOptions signerOptions) { return Patch<Signer>($"{Urls.SignatureDocuments}/{documentId}/signers/{signerId}", signerOptions); } /// <summary> /// Updates a signer. /// </summary> /// <param name="documentId"></param> /// <param name="signerId"></param> /// <param name="signerOptions"></param> /// <returns></returns> public Task<Signer> UpdateSignerAsync(Guid documentId, Guid signerId, SignerOptions signerOptions) { return PatchAsync<Signer>($"{Urls.SignatureDocuments}/{documentId}/signers/{signerId}", signerOptions); } /// <summary> /// Deletes a signer. /// </summary> /// <param name="documentId"></param> /// <param name="signerId"></param> public void DeleteSigner(Guid documentId, Guid signerId) { Delete($"{Urls.SignatureDocuments}/{documentId}/signers/{signerId}"); } /// <summary> /// Deletes a signer. /// </summary> /// <param name="documentId"></param> /// <param name="signerId"></param> public async Task DeleteSignerAsync(Guid documentId, Guid signerId) { await DeleteAsync($"{Urls.SignatureDocuments}/{documentId}/signers/{signerId}"); } /// <summary> /// Lists all signers of a document. /// </summary> /// <param name="documentId"></param> /// <returns></returns> public List<Signer> ListSigners(Guid documentId) { return Get<List<Signer>>($"{Urls.SignatureDocuments}/{documentId}/signers"); } /// <summary> /// Lists all signers of a document. /// </summary> /// <param name="documentId"></param> /// <returns></returns> public async Task<List<Signer>> ListSignersAsync(Guid documentId) { return await GetAsync<List<Signer>>($"{Urls.SignatureDocuments}/{documentId}/signers"); } /// <summary> /// Retrieves the details of a single attachment. /// </summary> /// <param name="documentId"></param> /// <param name="attachmentId"></param> /// <returns></returns> public Attachment GetAttachment(Guid documentId, Guid attachmentId) { return Get<Attachment>($"{Urls.SignatureDocuments}/{documentId}/attachments/{attachmentId}"); } /// <summary> /// Retrieves the details of a single attachment. /// </summary> /// <param name="documentId"></param> /// <param name="attachmentId"></param> /// <returns></returns> public async Task<Attachment> GetAttachmentAsync(Guid documentId, Guid attachmentId) { return await GetAsync<Attachment>($"{Urls.SignatureDocuments}/{documentId}/attachments/{attachmentId}"); } /// <summary> /// Adds an attachment to the specified document. /// </summary> /// <param name="documentId"></param> /// <param name="attachmentOptions"></param> /// <returns></returns> public Attachment CreateAttachment(Guid documentId, AttachmentOptions attachmentOptions) { return Post<Attachment>($"{Urls.SignatureDocuments}/{documentId}/attachments", attachmentOptions); } /// <summary> /// Adds an attachment to the specified document. /// </summary> /// <param name="documentId"></param> /// <param name="attachmentOptions"></param> /// <returns></returns> public async Task<Attachment> CreateAttachmentAsync(Guid documentId, AttachmentOptions attachmentOptions) { return await PostAsync<Attachment>($"{Urls.SignatureDocuments}/{documentId}/attachments", attachmentOptions); } /// <summary> /// Updates the specified attachment (Will only take affect if no one has signed the document yet). /// </summary> /// <param name="documentId"></param> /// <param name="attachmentId"></param> /// <param name="attachmentOptions"></param> /// <returns></returns> public Attachment UpdateAttachment(Guid documentId, Guid attachmentId, AttachmentOptions attachmentOptions) { return Patch<Attachment>($"{Urls.SignatureDocuments}/{documentId}/attachments/{attachmentId}", attachmentOptions); } /// <summary> /// Updates the specified attachment (Will only take affect if no one has signed the document yet). /// </summary> /// <param name="documentId"></param> /// <param name="attachmentId"></param> /// <param name="attachmentOptions"></param> /// <returns></returns> public async Task<Attachment> UpdateAttachmentAsync(Guid documentId, Guid attachmentId, AttachmentOptions attachmentOptions) { return await PatchAsync<Attachment>($"{Urls.SignatureDocuments}/{documentId}/attachments/{attachmentId}", attachmentOptions); } /// <summary> /// Deletes the specified attachment (Will only take affect if no one has signed the document yet). /// </summary> /// <param name="documentId"></param> /// <param name="attachmentId"></param> public void DeleteAttachment(Guid documentId, Guid attachmentId) { Delete($"{Urls.SignatureDocuments}/{documentId}/attachments/{attachmentId}"); } /// <summary> /// Deletes the specified attachment (Will only take affect if no one has signed the document yet). /// </summary> /// <param name="documentId"></param> /// <param name="attachmentId"></param> public async Task DeleteAttachmentAsync(Guid documentId, Guid attachmentId) { await DeleteAsync($"{Urls.SignatureDocuments}/{documentId}/attachments/{attachmentId}"); } /// <summary> /// Returns a list of all attachments for the specified document. /// </summary> /// <param name="documentId"></param> /// <returns></returns> public List<Attachment> ListAttachments(Guid documentId) { return Get<List<Attachment>>($"{Urls.SignatureDocuments}/{documentId}/attachments"); } /// <summary> /// Returns a list of all attachments for the specified document. /// </summary> /// <param name="documentId"></param> /// <returns></returns> public async Task<List<Attachment>> ListAttachmentsAsync(Guid documentId) { return await GetAsync<List<Attachment>>($"{Urls.SignatureDocuments}/{documentId}/attachments"); } /// <summary> /// Retrieves the signed document file. /// </summary> /// <param name="documentId"></param> /// <param name="fileFormat"></param> /// <returns></returns> public Stream GetFile(Guid documentId, FileFormat fileFormat) { var url = APIHelper.AppendQueryParams($"{Urls.SignatureDocuments}/{documentId}/files", new Dictionary<string, object>() { {"fileFormat", fileFormat} }); return GetFile(url); } /// <summary> /// Retrieves the signed document file. /// </summary> /// <param name="documentId"></param> /// <param name="fileFormat"></param> /// <returns></returns> public async Task<Stream> GetFileAsync(Guid documentId, FileFormat fileFormat) { var url = APIHelper.AppendQueryParams($"{Urls.SignatureDocuments}/{documentId}/files", new Dictionary<string, object>() { {"fileFormat", fileFormat} }); return await GetFileAsync(url); } /// <summary> /// Retrieves the signed document file for the specified signer. /// </summary> /// <param name="documentId"></param> /// <param name="signerId"></param> /// <param name="fileFormat"></param> /// <returns></returns> public Stream GetFileForSigner(Guid documentId, Guid signerId, FileFormat fileFormat) { var url = APIHelper.AppendQueryParams($"{Urls.SignatureDocuments}/{documentId}/files/signers/{signerId}", new Dictionary<string, object>() { {"fileFormat", fileFormat} }); return GetFile(url); } /// <summary> /// Retrieves the signed document file for the specified signer. /// </summary> /// <param name="documentId"></param> /// <param name="signerId"></param> /// <param name="fileFormat"></param> /// <returns></returns> public async Task<Stream> GetFileForSignerAsync(Guid documentId, Guid signerId, FileFormat fileFormat) { var url = APIHelper.AppendQueryParams($"{Urls.SignatureDocuments}/{documentId}/files/signers/{signerId}", new Dictionary<string, object>() { {"fileFormat", fileFormat} }); return await GetFileAsync(url); } /// <summary> /// Retrieves the attachment file. /// </summary> /// <param name="documentId"></param> /// <param name="attachmentId"></param> /// <param name="fileFormat"></param> /// <returns></returns> public Stream GetAttachmentFile(Guid documentId, Guid attachmentId, FileFormat fileFormat) { var url = APIHelper.AppendQueryParams($"{Urls.SignatureDocuments}/{documentId}/files/attachments/{attachmentId}", new Dictionary<string, object>() { {"fileFormat", fileFormat} }); return GetFile(url); } /// <summary> /// Retrieves the attachment file. /// </summary> /// <param name="documentId"></param> /// <param name="attachmentId"></param> /// <param name="fileFormat"></param> /// <returns></returns> public async Task<Stream> GetAttachmentFileAsync(Guid documentId, Guid attachmentId, FileFormat fileFormat) { var url = APIHelper.AppendQueryParams($"{Urls.SignatureDocuments}/{documentId}/files/attachments/{attachmentId}", new Dictionary<string, object>() { {"fileFormat", fileFormat} }); return await GetFileAsync(url); } /// <summary> /// Retrieves the attachment file for the specified signer. /// </summary> /// <param name="documentId"></param> /// <param name="attachmentId"></param> /// <param name="signerId"></param> /// <param name="fileFormat"></param> /// <returns></returns> public Stream GetAttachmentFileForSigner(Guid documentId, Guid attachmentId, Guid signerId, FileFormat fileFormat) { var url = APIHelper.AppendQueryParams( $"{Urls.SignatureDocuments}/{documentId}/files/attachments/{attachmentId}/signers/{signerId}", new Dictionary<string, object>() { {"fileFormat", fileFormat} }); return GetFile(url); } /// <summary> /// Retrieves the attachment file for the specified signer. /// </summary> /// <param name="documentId"></param> /// <param name="attachmentId"></param> /// <param name="signerId"></param> /// <param name="fileFormat"></param> /// <returns></returns> public async Task<Stream> GetAttachmentFileForSignerAsync(Guid documentId, Guid attachmentId, Guid signerId, FileFormat fileFormat) { var url = APIHelper.AppendQueryParams( $"{Urls.SignatureDocuments}/{documentId}/files/attachments/{attachmentId}/signers/{signerId}", new Dictionary<string, object>() { {"fileFormat", fileFormat} }); return await GetFileAsync(url); } /// <summary> /// Returns a list of all notifications that has been sent / attempted sent for a document. /// </summary> /// <param name="documentId"></param> /// <returns></returns> public List<NotificationLogItem> ListNotifications(Guid documentId) { return Get<List<NotificationLogItem>>($"{Urls.SignatureDocuments}/{documentId}/notifications"); } /// <summary> /// Returns a list of all notifications that has been sent / attempted sent for a document. /// </summary> /// <param name="documentId"></param> /// <returns></returns> public async Task<List<NotificationLogItem>> ListNotificationsAsync(Guid documentId) { return await GetAsync<List<NotificationLogItem>>($"{Urls.SignatureDocuments}/{documentId}/notifications"); } /// <summary> /// Sends a reminder to the specified signers. /// </summary> /// <param name="documentId"></param> /// <param name="manualReminder"></param> /// <returns></returns> public ManualReminder SendReminders(Guid documentId, ManualReminder manualReminder) { return Post<ManualReminder>($"{Urls.SignatureDocuments}/{documentId}/notifications/reminder", manualReminder); } /// <summary> /// Sends a reminder to the specified signers. /// </summary> /// <param name="documentId"></param> /// <param name="manualReminder"></param> /// <returns></returns> public async Task<ManualReminder> SendRemindersAsync(Guid documentId, ManualReminder manualReminder) { return await PostAsync<ManualReminder>($"{Urls.SignatureDocuments}/{documentId}/notifications/reminder", manualReminder); } /// <summary> /// Returns a list of all color themes that can be used in the signature application. /// </summary> /// <returns></returns> public List<ColorTheme> ListThemes() { return Get<List<ColorTheme>>($"{Urls.Signature}/themes/list/themes"); } /// <summary> /// Returns a list of all color themes that can be used in the signature application. /// </summary> /// <returns></returns> public async Task<List<ColorTheme>> ListThemesAsync() { return await GetAsync<List<ColorTheme>>($"{Urls.Signature}/themes/list/themes"); } /// <summary> /// Returns a list of all spinners that can be used in the signature application. /// </summary> /// <returns></returns> public List<Spinner> ListSpinners() { return Get<List<Spinner>>($"{Urls.Signature}/themes/list/spinners"); } /// <summary> /// Returns a list of all spinners that can be used in the signature application. /// </summary> /// <returns></returns> public async Task<List<Spinner>> ListSpinnersAsync() { return await GetAsync<List<Spinner>>($"{Urls.Signature}/themes/list/spinners"); } public List<AppSignatureMethod> ListSignatureMethods(SignatureMechanism mechanism, FileType fileType, Language language, bool signableAttachments) { var url = ListSignMethodsUrlWithParams($"{Urls.Signature}/signature-methods", mechanism, fileType, language, signableAttachments); return Get<List<AppSignatureMethod>>(url); } public Task<List<AppSignatureMethod>> ListSignatureMethodsAsync(SignatureMechanism mechanism, FileType fileType, Language language, bool signableAttachments) { var url = ListSignMethodsUrlWithParams($"{Urls.Signature}/signature-methods", mechanism, fileType, language, signableAttachments); return GetAsync<List<AppSignatureMethod>>(url); } public List<AppSignatureMethod> ListSignatureMethodsForAccount(SignatureMechanism mechanism, FileType fileType, Language language, bool signableAttachments) { var url = ListSignMethodsUrlWithParams($"{Urls.Signature}/signature-methods/account", mechanism, fileType, language, signableAttachments); return Get<List<AppSignatureMethod>>(url); } public Task<List<AppSignatureMethod>> ListSignatureMethodsForAccountAsync(SignatureMechanism mechanism, FileType fileType, Language language, bool signableAttachments) { var url = ListSignMethodsUrlWithParams($"{Urls.Signature}/signature-methods/account", mechanism, fileType, language, signableAttachments); return GetAsync<List<AppSignatureMethod>>(url); } private static string ListSignMethodsUrlWithParams(string url, SignatureMechanism mechanism, FileType fileType, Language language, bool signableAttachments) { url = APIHelper.AppendQueryParams(url, new Dictionary<string, object>() { {"mechanism", mechanism}, {"fileType", fileType}, {"language", language}, {"signableAttachments", signableAttachments} }); return url; } } }
39.549407
154
0.557166
[ "Apache-2.0" ]
JTOne123/idfy-sdk-net
src/Idfy.SDK/Services/Signature/SignatureService.cs
30,020
C#
//////////////////////////////// // // Copyright 2019 Battelle Energy Alliance, LLC // // //////////////////////////////// using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace CSET_Main.Framework { public class ProfileFunction { private string functionName; public string FunctionName { get { return functionName; } set { functionName = value; } } private ObservableCollection<ProfileCategory> profileCategories; public ObservableCollection<ProfileCategory> ProfileCategories { get { return profileCategories; } set { profileCategories = value; } } public String Function_ID { get; set; } public int FunctionID { get; set; } private Dictionary<String, ProfileCategory> dictionaryCategoriesBySubLabel = new Dictionary<string, ProfileCategory>(); private RankingManager RankingManger; public ProfileFunction(RankingManager rankingManager) { this.ProfileCategories = new ObservableCollection<ProfileCategory>(); this.RankingManger = rankingManager; } public void SetCategories(IEnumerable<ProfileCategory> profileCategories) { List<ProfileCategory> defaultCategories = new List<ProfileCategory>(); List<ProfileCategory> customCategories = new List<ProfileCategory>(); foreach (ProfileCategory category in profileCategories) { if (category.IsCustomCategory) customCategories.Add(category); else defaultCategories.Add(category); } //THIS WAS COMMENTED OUT in the move to the web on May 29, 2018 //this.ProfileCategories.AddRange(defaultCategories.OrderBy(x => x.DefaultCategoryID)); //this.ProfileCategories.AddRange(customCategories.OrderBy(x => x.Heading)); foreach (ProfileCategory category in profileCategories) { dictionaryCategoriesBySubLabel[category.SubLabel] = category; } } internal void RemoveCategory(ProfileCategory profileCategory) { ProfileCategories.Remove(profileCategory); if(profileCategory.SubLabel != null) dictionaryCategoriesBySubLabel.Remove(profileCategory.SubLabel); } internal void AddCategory(ProfileCategory profileCategory) { ProfileCategories.Add(profileCategory); dictionaryCategoriesBySubLabel[profileCategory.SubLabel] = profileCategory; } internal Tuple<bool,ProfileQuestion> AddImportQuestion(ProfileImportQuestion importQuestion) { ProfileCategory category; if (!dictionaryCategoriesBySubLabel.TryGetValue(importQuestion.CategorySubLabel, out category)) { category = new ProfileCategory(this); category.SubLabel = importQuestion.CategorySubLabel; category.Heading = importQuestion.Category; category.IsSelect = true; AddCategory(category); } if (!category.ContainsImportQuestion(importQuestion)) { ProfileQuestion question = new ProfileQuestion(category, RankingManger, importQuestion); category.AddQuestion(question); return Tuple.Create(true, question); } else { return Tuple.Create<bool,ProfileQuestion>(false, null); } } internal bool IsSame(ProfileFunction function) { if (function.ProfileCategories.Count != this.ProfileCategories.Count) return false; foreach (ProfileCategory profileCategory in function.ProfileCategories) { ProfileCategory thisCategory; if (dictionaryCategoriesBySubLabel.TryGetValue(profileCategory.SubLabel, out thisCategory)) { if (!thisCategory.IsSame(profileCategory)) { return false; } } else return false; } return true; } } }
33.985401
127
0.563789
[ "MIT" ]
Harshilpatel134/cisagovdocker
CSETWebApi/CSETWeb_Api/BusinessLogic/Framework/ProfileFunction.cs
4,656
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace ProjectTracker.Model.Migrations { public partial class StatusChangedToString : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "StatusInt", table: "Projects"); migrationBuilder.AddColumn<string>( name: "Status", table: "Projects", type: "TEXT", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Status", table: "Projects"); migrationBuilder.AddColumn<int>( name: "StatusInt", table: "Projects", type: "INTEGER", nullable: false, defaultValue: 0); } } }
27.6
71
0.524845
[ "MIT" ]
TarunBola/ProjectTracker
Model/Migrations/20210327181338_StatusChangedToString.cs
968
C#
using System; using System.IO; using System.Linq; using System.Reflection; using System.Security.Claims; using System.Threading.Tasks; using System.Transactions; using BlazorAppQA.Infrastructure.ApplicationContext; using BlazorAppQA.Infrastructure.BaseCommandHandler; using BlazorAppQA.Infrastructure.Common; using BlazorAppQA.Infrastructure.Domain; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace BlazorAppQA.Infrastructure.CommandHandlers.InsertNewQuestionHandler { public class InsertNewQuestionCommandHandler : BaseCommandHandler<InsertNewQuestionCommand> { private readonly IWebHostEnvironment _hostingEnvironment; private readonly IDataProtector _dataProtector; private readonly HttpContext _httpContext; public InsertNewQuestionCommandHandler(IServiceProvider provider) : base(provider) { _hostingEnvironment = provider.GetService<IWebHostEnvironment>(); _dataProtector = provider.GetService<IDataProtectionProvider>().CreateProtector(Assembly.GetExecutingAssembly().FullName); _httpContext = provider.GetService<IHttpContextAccessor>().HttpContext; } protected override async Task<dynamic> ExecuteAsync(InsertNewQuestionCommand command) { using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { using var scope = _serviceScopeFactory.CreateScope(); using var applicationDbContext = scope.ServiceProvider.GetService<ApplicationDbContext>(); var tagsArray = command.Tags.Split("\u0020", StringSplitOptions.RemoveEmptyEntries) .Select(t => t.Trim().ToLowerInvariant()).Distinct(); var newQuestion = new Question() { Title = command.Title.Trim(), TagsArray = string.Join(";", tagsArray), CategoryId = int.Parse(_dataProtector.Unprotect(command.ProtectedCategoryId)), Description = command.Description.Trim(), UserId = int.Parse(_httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier)), Date = DateTime.Now }; applicationDbContext.Questions.Add(newQuestion); if (command.Files != null) { await command.Files.AsEnumerable().ForEachAsync(async file => { var fileName = Guid.NewGuid(); var absolutePath = Path.Combine(_hostingEnvironment.WebRootPath, $"qimages\\{fileName}.jpg"); var fileInfo = new FileInfo(absolutePath); fileInfo.Directory.Create(); using var fileSteam = new FileStream(absolutePath, FileMode.Create); await file.Data.CopyToAsync(fileSteam); newQuestion.QuestionImages.Add(new QuestionImage() { FileName = fileName }); }); } await applicationDbContext.SaveChangesAsync(); transactionScope.Complete(); } return default; } public override void Dispose() { } } }
42.938272
134
0.628235
[ "MIT" ]
fcapellino/net-core-blazor-qa
BlazorAppQA.Infrastructure/CommandHandlers/InsertNewQuestionHandler/InsertNewQuestionCommandHandler.cs
3,480
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.ServiceModel; namespace Workday.Staffing { [GeneratedCode("System.ServiceModel", "4.0.0.0"), EditorBrowsable(EditorBrowsableState.Advanced), DebuggerStepThrough, MessageContract(IsWrapped = false)] public class Put_DependentOutput { [MessageBodyMember(Namespace = "urn:com.workday/bsvc", Order = 0)] public Put_Dependent_ResponseType Put_Dependent_Response; public Put_DependentOutput() { } public Put_DependentOutput(Put_Dependent_ResponseType Put_Dependent_Response) { this.Put_Dependent_Response = Put_Dependent_Response; } } }
26.8
155
0.8
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.Staffing/Put_DependentOutput.cs
670
C#
/* * ISO standards can be purchased through the ANSI webstore at https://webstore.ansi.org */ using AgGateway.ADAPT.ISOv4Plugin.ExtensionMethods; using AgGateway.ADAPT.ISOv4Plugin.ISOModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AgGateway.ADAPT.ApplicationDataModel.Logistics; using AgGateway.ADAPT.ApplicationDataModel.Shapes; using AgGateway.ADAPT.ISOv4Plugin.ISOEnumerations; using AgGateway.ADAPT.ApplicationDataModel.Guidance; using AgGateway.ADAPT.ApplicationDataModel.Products; using AgGateway.ADAPT.ApplicationDataModel.LoggedData; using AgGateway.ADAPT.ISOv4Plugin.ObjectModel; using AgGateway.ADAPT.ISOv4Plugin.Representation; using AgGateway.ADAPT.ApplicationDataModel.Equipment; using System.IO; using AgGateway.ADAPT.ApplicationDataModel.Common; using AgGateway.ADAPT.Representation.RepresentationSystem; using AgGateway.ADAPT.Representation.RepresentationSystem.ExtensionMethods; namespace AgGateway.ADAPT.ISOv4Plugin.Mappers { public interface ITimeLogMapper { IEnumerable<ISOTimeLog> ExportTimeLogs(IEnumerable<OperationData> operationDatas, string dataPath); IEnumerable<OperationData> ImportTimeLogs(ISOTask loggedTask, int? prescriptionID); } public class TimeLogMapper : BaseMapper, ITimeLogMapper { public TimeLogMapper(TaskDataMapper taskDataMapper) : base(taskDataMapper, "TLG") { } #region Export private Dictionary<int, int> _dataLogValueOrdersByWorkingDataID; public IEnumerable<ISOTimeLog> ExportTimeLogs(IEnumerable<OperationData> operationDatas, string dataPath) { _dataLogValueOrdersByWorkingDataID = new Dictionary<int, int>(); List<ISOTimeLog> timeLogs = new List<ISOTimeLog>(); foreach (OperationData operation in operationDatas) { IEnumerable<SpatialRecord> spatialRecords = operation.GetSpatialRecords != null ? operation.GetSpatialRecords() : null; if (spatialRecords != null && spatialRecords.Any()) //No need to export a timelog if no data { ISOTimeLog timeLog = ExportTimeLog(operation, spatialRecords, dataPath); timeLogs.Add(timeLog); } } return timeLogs; } private ISOTimeLog ExportTimeLog(OperationData operation, IEnumerable<SpatialRecord> spatialRecords, string dataPath) { ISOTimeLog isoTimeLog = new ISOTimeLog(); //ID string id = operation.Id.FindIsoId() ?? GenerateId(5); isoTimeLog.Filename = id; isoTimeLog.TimeLogType = 1; // TimeLogType TLG.C is a required attribute. Currently only the value "1" is defined. ExportIDs(operation.Id, id); List<DeviceElementUse> deviceElementUses = operation.GetAllSections(); List<WorkingData> workingDatas = deviceElementUses.SelectMany(x => x.GetWorkingDatas()).ToList(); ISOTime isoTime = new ISOTime(); isoTime.HasStart = true; isoTime.Type = ISOTimeType.Effective; isoTime.DataLogValues = ExportDataLogValues(workingDatas, deviceElementUses).ToList(); //Set the timelog data definition for PTN ISOPosition position = new ISOPosition(); position.HasPositionNorth = true; position.HasPositionEast = true; position.HasPositionUp = true; position.HasPositionStatus = true; position.HasPDOP = false; position.HasHDOP = false; position.HasNumberOfSatellites = false; position.HasGpsUtcTime = false; position.HasGpsUtcTime = false; isoTime.Positions.Add(position); //Write XML TaskDocumentWriter xmlWriter = new TaskDocumentWriter(); xmlWriter.WriteTimeLog(dataPath, isoTimeLog, isoTime); //Write BIN var binFilePath = Path.Combine(dataPath, isoTimeLog.Filename + ".bin"); BinaryWriter writer = new BinaryWriter(_dataLogValueOrdersByWorkingDataID); writer.Write(binFilePath, workingDatas.ToList(), spatialRecords); return isoTimeLog; } public IEnumerable<ISODataLogValue> ExportDataLogValues(List<WorkingData> workingDatas, List<DeviceElementUse> deviceElementUses) { if (workingDatas == null) { return null; } List<ISODataLogValue> dlvs = new List<ISODataLogValue>(); for(int i = 0; i < workingDatas.Count(); i++) { WorkingData workingData = workingDatas[i]; //DDI int? mappedDDI = RepresentationMapper.Map(workingData.Representation); var dlv = new ISODataLogValue(); if (mappedDDI != null) { if (workingData.Representation != null && workingData.Representation.Code == "dtRecordingStatus" && workingData.DeviceElementUseId != 0) { dlv.ProcessDataDDI = 141.AsHexDDI(); //No support for exporting CondensedWorkState at this time } else { dlv.ProcessDataDDI = mappedDDI.Value.AsHexDDI(); } } else if (workingData.Representation.CodeSource == ApplicationDataModel.Representations.RepresentationCodeSourceEnum.ISO11783_DDI) { dlv.ProcessDataDDI = workingData.Representation.Code; } //DeviceElementIdRef DeviceElementUse use = deviceElementUses.FirstOrDefault(d => d.Id.ReferenceId == workingData.DeviceElementUseId); if (use != null) { DeviceElementConfiguration deviceElementConfiguration = DataModel.Catalog.DeviceElementConfigurations.FirstOrDefault(d => d.Id.ReferenceId == use.DeviceConfigurationId); if (deviceElementConfiguration != null) { //This requires the Devices will have been mapped prior to the LoggedData dlv.DeviceElementIdRef = TaskDataMapper.InstanceIDMap.GetISOID(deviceElementConfiguration.DeviceElementId); } } dlvs.Add(dlv); _dataLogValueOrdersByWorkingDataID.Add(workingData.Id.ReferenceId, i); } return dlvs; } private class BinaryWriter { // ATTENTION: CoordinateMultiplier and ZMultiplier also exist in Import\SpatialRecordMapper.cs! private const double CoordinateMultiplier = 0.0000001; private const double ZMultiplier = 0.001; // In ISO the PositionUp value is specified in mm. private readonly DateTime _januaryFirst1980 = new DateTime(1980, 1, 1); private readonly IEnumeratedValueMapper _enumeratedValueMapper; private readonly INumericValueMapper _numericValueMapper; private Dictionary<int, int> _dlvOrdersByWorkingDataID; public BinaryWriter(Dictionary<int, int> dlvOrdersByWorkingDataID) : this(new EnumeratedValueMapper(), new NumericValueMapper(), dlvOrdersByWorkingDataID) { } public BinaryWriter(IEnumeratedValueMapper enumeratedValueMapper, INumericValueMapper numericValueMapper, Dictionary<int, int> dlvOrdersByWorkingDataID) { _enumeratedValueMapper = enumeratedValueMapper; _numericValueMapper = numericValueMapper; _dlvOrdersByWorkingDataID = dlvOrdersByWorkingDataID; } public IEnumerable<ISOSpatialRow> Write(string fileName, List<WorkingData> meters, IEnumerable<SpatialRecord> spatialRecords) { if (spatialRecords == null) return null; using (var memoryStream = new MemoryStream()) { foreach (var spatialRecord in spatialRecords) { WriteSpatialRecord(spatialRecord, meters, memoryStream); } var binaryWriter = new System.IO.BinaryWriter(File.Create(fileName)); binaryWriter.Write(memoryStream.ToArray()); binaryWriter.Flush(); binaryWriter.Close(); } return null; } private void WriteSpatialRecord(SpatialRecord spatialRecord, List<WorkingData> meters, MemoryStream memoryStream) { //Start Time var millisecondsSinceMidnight = (UInt32)new TimeSpan(0, spatialRecord.Timestamp.Hour, spatialRecord.Timestamp.Minute, spatialRecord.Timestamp.Second, spatialRecord.Timestamp.Millisecond).TotalMilliseconds; memoryStream.Write(BitConverter.GetBytes(millisecondsSinceMidnight), 0, 4); var daysSinceJanOne1980 = (UInt16)(spatialRecord.Timestamp - (_januaryFirst1980)).TotalDays; memoryStream.Write(BitConverter.GetBytes(daysSinceJanOne1980), 0, 2); //Position var north = Int32.MaxValue; //"Not available" value for the Timelog var east = Int32.MaxValue; var up = Int32.MaxValue; if (spatialRecord.Geometry != null) { Point location = spatialRecord.Geometry as Point; if (location != null) { north = (Int32)(location.Y / CoordinateMultiplier); east = (Int32)(location.X / CoordinateMultiplier); up = (Int32)(location.Z.GetValueOrDefault() / ZMultiplier); } } memoryStream.Write(BitConverter.GetBytes(north), 0, 4); memoryStream.Write(BitConverter.GetBytes(east), 0, 4); memoryStream.Write(BitConverter.GetBytes(up), 0, 4); memoryStream.WriteByte((byte)ISOPositionStatus.NotAvailable); //Values Dictionary<int, uint> dlvsToWrite = GetMeterValues(spatialRecord, meters); byte numberOfMeters = (byte)dlvsToWrite.Count; memoryStream.WriteByte(numberOfMeters); foreach (var key in dlvsToWrite.Keys) { byte order = (byte)key; uint value = dlvsToWrite[key]; memoryStream.WriteByte(order); memoryStream.Write(BitConverter.GetBytes(value), 0, 4); } } private Dictionary<int, uint> GetMeterValues(SpatialRecord spatialRecord, List<WorkingData> workingDatas) { var dlvsToWrite = new Dictionary<int, uint>(); var workingDatasWithValues = workingDatas.Where(x => spatialRecord.GetMeterValue(x) != null); foreach (WorkingData workingData in workingDatasWithValues) { int order = _dlvOrdersByWorkingDataID[workingData.Id.ReferenceId]; UInt32? value = null; if (workingData is NumericWorkingData) { NumericWorkingData numericMeter = workingData as NumericWorkingData; if (numericMeter != null && spatialRecord.GetMeterValue(numericMeter) != null) { value = _numericValueMapper.Map(numericMeter, spatialRecord); } } else if (workingData is EnumeratedWorkingData) { EnumeratedWorkingData enumeratedMeter = workingData as EnumeratedWorkingData; if (enumeratedMeter != null && spatialRecord.GetMeterValue(enumeratedMeter) != null) { value = _enumeratedValueMapper.Map(enumeratedMeter, new List<WorkingData>() { workingData }, spatialRecord); } } if (value == null) { continue; } else { dlvsToWrite.Add(order, value.Value); } } return dlvsToWrite; } } #endregion Export #region Import public IEnumerable<OperationData> ImportTimeLogs(ISOTask loggedTask, int? prescriptionID) { List<OperationData> operations = new List<OperationData>(); foreach (ISOTimeLog isoTimeLog in loggedTask.TimeLogs) { IEnumerable<OperationData> operationData = ImportTimeLog(loggedTask, isoTimeLog, prescriptionID); if (operationData != null) { operations.AddRange(operationData); } } return operations; } private IEnumerable<OperationData> ImportTimeLog(ISOTask loggedTask, ISOTimeLog isoTimeLog, int? prescriptionID) { WorkingDataMapper workingDataMapper = new WorkingDataMapper(new EnumeratedMeterFactory(), TaskDataMapper); SectionMapper sectionMapper = new SectionMapper(workingDataMapper, TaskDataMapper); SpatialRecordMapper spatialMapper = new SpatialRecordMapper(new RepresentationValueInterpolator(), sectionMapper, workingDataMapper, TaskDataMapper); IEnumerable<ISOSpatialRow> isoRecords = ReadTimeLog(isoTimeLog, this.TaskDataPath); if (isoRecords != null) { isoRecords = isoRecords.ToList(); //Avoids multiple reads ISOTime time = isoTimeLog.GetTimeElement(this.TaskDataPath); //Identify unique devices represented in this TimeLog data IEnumerable<string> deviceElementIDs = time.DataLogValues.Where(d => d.ProcessDataDDI != "DFFF" && d.ProcessDataDDI != "DFFE").Select(d => d.DeviceElementIdRef); Dictionary<ISODevice, HashSet<string>> loggedDeviceElementsByDevice = new Dictionary<ISODevice, HashSet<string>>(); foreach (string deviceElementID in deviceElementIDs) { ISODeviceElement isoDeviceElement = TaskDataMapper.DeviceElementHierarchies.GetISODeviceElementFromID(deviceElementID); if (isoDeviceElement != null) { ISODevice device = isoDeviceElement.Device; if (!loggedDeviceElementsByDevice.ContainsKey(device)) { loggedDeviceElementsByDevice.Add(device, new HashSet<string>()); } loggedDeviceElementsByDevice[device].Add(deviceElementID); } } //Split all devices in the same TimeLog into separate OperationData objects to handle multi-implement scenarios //This will ensure implement geometries/DeviceElementUse Depths & Orders do not get confused between implements List<OperationData> operationDatas = new List<OperationData>(); foreach (ISODevice dvc in loggedDeviceElementsByDevice.Keys) { OperationData operationData = new OperationData(); //Determine products Dictionary<string, List<ISOProductAllocation>> productAllocations = GetProductAllocationsByDeviceElement(loggedTask, dvc); List<int> productIDs = GetDistinctProductIDs(TaskDataMapper, productAllocations); //This line will necessarily invoke a spatial read in order to find //1)The correct number of CondensedWorkState working datas to create //2)Any Widths and Offsets stored in the spatial data IEnumerable<DeviceElementUse> sections = sectionMapper.Map(time, isoRecords, operationData.Id.ReferenceId, loggedDeviceElementsByDevice[dvc], productAllocations); var workingDatas = sections != null ? sections.SelectMany(x => x.GetWorkingDatas()).ToList() : new List<WorkingData>(); operationData.GetSpatialRecords = () => spatialMapper.Map(isoRecords, workingDatas, productAllocations); operationData.MaxDepth = sections.Count() > 0 ? sections.Select(s => s.Depth).Max() : 0; operationData.GetDeviceElementUses = x => sectionMapper.ConvertToBaseTypes(sections.Where(s => s.Depth == x).ToList()); operationData.PrescriptionId = prescriptionID; operationData.OperationType = GetOperationTypeFromLoggingDevices(time); operationData.ProductIds = productIDs; operationData.SpatialRecordCount = isoRecords.Count(); operationDatas.Add(operationData); } //Set the CoincidentOperationDataIds property identifying Operation Datas from the same TimeLog. operationDatas.ForEach(o => o.CoincidentOperationDataIds = operationDatas.Where(o2 => o2.Id.ReferenceId != o.Id.ReferenceId).Select(o3 => o3.Id.ReferenceId).ToList()); return operationDatas; } return null; } internal static List<int> GetDistinctProductIDs(TaskDataMapper taskDataMapper, Dictionary<string, List<ISOProductAllocation>> productAllocations) { HashSet<int> productIDs = new HashSet<int>(); foreach (string detID in productAllocations.Keys) { foreach (ISOProductAllocation pan in productAllocations[detID]) { int? id = taskDataMapper.InstanceIDMap.GetADAPTID(pan.ProductIdRef); if (id.HasValue) { productIDs.Add(id.Value); } } } return productIDs.ToList(); } private Dictionary<string, List<ISOProductAllocation>> GetProductAllocationsByDeviceElement(ISOTask loggedTask, ISODevice dvc) { Dictionary<string, List<ISOProductAllocation>> output = new Dictionary<string, List<ISOProductAllocation>>(); foreach (ISOProductAllocation pan in loggedTask.ProductAllocations.Where(p => !string.IsNullOrEmpty(p.DeviceElementIdRef))) { if (dvc.DeviceElements.Select(d => d.DeviceElementId).Contains(pan.DeviceElementIdRef)) //Filter PANs by this DVC { if (!output.ContainsKey(pan.DeviceElementIdRef)) { output.Add(pan.DeviceElementIdRef, new List<ISOProductAllocation>()); } output[pan.DeviceElementIdRef].Add(pan); } } return output; } private OperationTypeEnum GetOperationTypeFromLoggingDevices(ISOTime time) { HashSet<DeviceOperationType> representedTypes = new HashSet<DeviceOperationType>(); IEnumerable<string> distinctDeviceElementIDs = time.DataLogValues.Select(d => d.DeviceElementIdRef).Distinct(); foreach (string isoDeviceElementID in distinctDeviceElementIDs) { int? deviceElementID = TaskDataMapper.InstanceIDMap.GetADAPTID(isoDeviceElementID); if (deviceElementID.HasValue) { DeviceElement deviceElement = DataModel.Catalog.DeviceElements.FirstOrDefault(d => d.Id.ReferenceId == deviceElementID.Value); if (deviceElement != null && deviceElement.DeviceClassification != null) { DeviceOperationType deviceOperationType = DeviceOperationTypes.FirstOrDefault(d => d.MachineEnumerationMember.ToModelEnumMember().Value == deviceElement.DeviceClassification.Value.Value); if (deviceOperationType != null) { representedTypes.Add(deviceOperationType); } } } } DeviceOperationType deviceType = representedTypes.FirstOrDefault(t => t.ClientNAMEMachineType >= 2 && t.ClientNAMEMachineType <= 11); if (deviceType != null) { //2-11 represent known types of operations //These will map to implement devices and will govern the actual operation type. //Return the first such device type return deviceType.OperationType; } return OperationTypeEnum.Unknown; } private IEnumerable<ISOSpatialRow> ReadTimeLog(ISOTimeLog timeLog, string dataPath) { ISOTime templateTime = timeLog.GetTimeElement(dataPath); string binName = string.Concat(timeLog.Filename, ".bin"); string filePath = dataPath.GetDirectoryFiles(binName, SearchOption.TopDirectoryOnly).FirstOrDefault(); if (templateTime != null && filePath != null) { BinaryReader reader = new BinaryReader(); return reader.Read(filePath, templateTime); } return null; } private class BinaryReader { private DateTime _firstDayOf1980 = new DateTime(1980, 01, 01); public IEnumerable<ISOSpatialRow> Read(string fileName, ISOTime templateTime) { if (templateTime == null) yield break; if (!File.Exists(fileName)) yield break; using (var binaryReader = new System.IO.BinaryReader(File.Open(fileName, FileMode.Open))) { while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length) { ISOPosition templatePosition = templateTime.Positions.FirstOrDefault(); var record = new ISOSpatialRow { TimeStart = GetStartTime(templateTime, binaryReader) }; if (templatePosition != null) { //North and East are required binary data record.NorthPosition = ReadInt32((double?)templatePosition.PositionNorth, templatePosition.HasPositionNorth, binaryReader).GetValueOrDefault(0); record.EastPosition = ReadInt32((double?)templatePosition.PositionEast, templatePosition.HasPositionEast, binaryReader).GetValueOrDefault(0); if (templatePosition.HasPositionUp) //Optional position attributes will be included in the binary only if a corresponding attribute is present in the PTN element { record.Elevation = ReadInt32(templatePosition.PositionUp, templatePosition.HasPositionUp, binaryReader); } //Position status is required record.PositionStatus = ReadByte((byte?)templatePosition.PositionStatus, templatePosition.HasPositionStatus, binaryReader); if (templatePosition.HasPDOP) { record.PDOP = ReadUShort((double?)templatePosition.PDOP, templatePosition.HasPDOP, binaryReader); } if (templatePosition.HasHDOP) { record.HDOP = ReadUShort((double?)templatePosition.HDOP, templatePosition.HasHDOP, binaryReader); } if (templatePosition.HasNumberOfSatellites) { record.NumberOfSatellites = ReadByte(templatePosition.NumberOfSatellites, templatePosition.HasNumberOfSatellites, binaryReader); } if (templatePosition.HasGpsUtcTime) { if (templatePosition.GpsUtcTime.HasValue) { record.GpsUtcTime = Convert.ToUInt32(templatePosition.GpsUtcTime.Value); } else { record.GpsUtcTime = binaryReader.ReadUInt32(); } } if (templatePosition.HasGpsUtcDate) { if (templatePosition.GpsUtcDate.HasValue) { record.GpsUtcDate = (ushort)templatePosition.GpsUtcDate.Value; } else { record.GpsUtcDate = binaryReader.ReadUInt16(); } } if (record.GpsUtcDate != null && record.GpsUtcTime != null) { record.GpsUtcDateTime = _firstDayOf1980.AddDays((double)record.GpsUtcDate).AddMilliseconds((double)record.GpsUtcTime); } } var numberOfDLVs = binaryReader.ReadByte(); record.SpatialValues = new List<SpatialValue>(); //Read DLVs out of the TLG.bin for (int i = 0; i < numberOfDLVs; i++) { var order = binaryReader.ReadByte(); var value = binaryReader.ReadInt32(); SpatialValue spatialValue = CreateSpatialValue(templateTime, order, value); if(spatialValue != null) record.SpatialValues.Add(spatialValue); } //Add any fixed values from the TLG.xml foreach (ISODataLogValue fixedValue in templateTime.DataLogValues.Where(dlv => dlv.ProcessDataValue.HasValue && !EnumeratedMeterFactory.IsCondensedMeter(dlv.ProcessDataDDI.AsInt32DDI()))) { byte order = (byte)templateTime.DataLogValues.IndexOf(fixedValue); if (record.SpatialValues.Any(s => s.Id == order)) //Check to ensure the binary data didn't already write this value { //Per the spec, any fixed value in the XML applies to all rows; as such, replace what was read from the binary SpatialValue matchingValue = record.SpatialValues.Single(s => s.Id == order); matchingValue.DataLogValue = fixedValue; } } yield return record; } } } private static ushort? ReadUShort(double? value, bool specified, System.IO.BinaryReader binaryReader) { if (specified) { if (value.HasValue) return (ushort)value.Value; return binaryReader.ReadUInt16(); } return null; } private static byte? ReadByte(byte? byteValue, bool specified, System.IO.BinaryReader binaryReader) { if (specified) { if (byteValue.HasValue) return byteValue; return binaryReader.ReadByte(); } return null; } private static int? ReadInt32(double? d, bool specified, System.IO.BinaryReader binaryReader) { if (specified) { if (d.HasValue) return (int)d.Value; return binaryReader.ReadInt32(); } return null; } private DateTime GetStartTime(ISOTime templateTime, System.IO.BinaryReader binaryReader) { if (templateTime.HasStart && templateTime.Start == null) { var milliseconds = (double)binaryReader.ReadInt32(); var daysFrom1980 = binaryReader.ReadInt16(); return _firstDayOf1980.AddDays(daysFrom1980).AddMilliseconds(milliseconds); } else if (templateTime.HasStart) return (DateTime)templateTime.Start.Value; return _firstDayOf1980; } private static SpatialValue CreateSpatialValue(ISOTime templateTime, byte order, int value) { var dataLogValues = templateTime.DataLogValues; var matchingDlv = dataLogValues.ElementAtOrDefault(order); if (matchingDlv == null) return null; var ddis = DdiLoader.Ddis; var resolution = 1d; if (matchingDlv.ProcessDataDDI != null && ddis.ContainsKey(matchingDlv.ProcessDataDDI.AsInt32DDI())) { resolution = ddis[matchingDlv.ProcessDataDDI.AsInt32DDI()].Resolution; } var spatialValue = new SpatialValue { Id = order, DataLogValue = matchingDlv, Value = value * resolution, }; return spatialValue; } } #endregion Import } }
48.64127
221
0.561252
[ "EPL-1.0" ]
martinsw/ISOv4Plugin
ISOv4Plugin/Mappers/TimeLogMapper.cs
30,644
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.SignalR.Protocol; using Microsoft.Extensions.Internal; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.SignalR.Internal; internal static partial class DefaultHubDispatcherLog { [LoggerMessage(1, LogLevel.Debug, "Received hub invocation: {InvocationMessage}.", EventName = "ReceivedHubInvocation")] public static partial void ReceivedHubInvocation(ILogger logger, InvocationMessage invocationMessage); [LoggerMessage(2, LogLevel.Debug, "Received unsupported message of type '{MessageType}'.", EventName = "UnsupportedMessageReceived")] public static partial void UnsupportedMessageReceived(ILogger logger, string messageType); [LoggerMessage(3, LogLevel.Debug, "Unknown hub method '{HubMethod}'.", EventName = "UnknownHubMethod")] public static partial void UnknownHubMethod(ILogger logger, string hubMethod); // 4, OutboundChannelClosed - removed [LoggerMessage(5, LogLevel.Debug, "Failed to invoke '{HubMethod}' because user is unauthorized.", EventName = "HubMethodNotAuthorized")] public static partial void HubMethodNotAuthorized(ILogger logger, string hubMethod); public static void StreamingResult(ILogger logger, string invocationId, ObjectMethodExecutor objectMethodExecutor) { if (logger.IsEnabled(LogLevel.Trace)) { var resultType = objectMethodExecutor.AsyncResultType == null ? objectMethodExecutor.MethodReturnType : objectMethodExecutor.AsyncResultType; StreamingResult(logger, invocationId, resultType.FullName); } } [LoggerMessage(6, LogLevel.Trace, "InvocationId {InvocationId}: Streaming result of type '{ResultType}'.", EventName = "StreamingResult", SkipEnabledCheck = true)] private static partial void StreamingResult(ILogger logger, string invocationId, string? resultType); public static void SendingResult(ILogger logger, string? invocationId, ObjectMethodExecutor objectMethodExecutor) { if (logger.IsEnabled(LogLevel.Trace)) { var resultType = objectMethodExecutor.AsyncResultType == null ? objectMethodExecutor.MethodReturnType : objectMethodExecutor.AsyncResultType; SendingResult(logger, invocationId, resultType.FullName); } } [LoggerMessage(7, LogLevel.Trace, "InvocationId {InvocationId}: Sending result of type '{ResultType}'.", EventName = "SendingResult", SkipEnabledCheck = true)] private static partial void SendingResult(ILogger logger, string? invocationId, string? resultType); [LoggerMessage(8, LogLevel.Error, "Failed to invoke hub method '{HubMethod}'.", EventName = "FailedInvokingHubMethod")] public static partial void FailedInvokingHubMethod(ILogger logger, string hubMethod, Exception exception); [LoggerMessage(9, LogLevel.Trace, "'{HubName}' hub method '{HubMethod}' is bound.", EventName = "HubMethodBound")] public static partial void HubMethodBound(ILogger logger, string hubName, string hubMethod); [LoggerMessage(10, LogLevel.Debug, "Canceling stream for invocation {InvocationId}.", EventName = "CancelStream")] public static partial void CancelStream(ILogger logger, string invocationId); [LoggerMessage(11, LogLevel.Debug, "CancelInvocationMessage received unexpectedly.", EventName = "UnexpectedCancel")] public static partial void UnexpectedCancel(ILogger logger); [LoggerMessage(12, LogLevel.Debug, "Received stream hub invocation: {InvocationMessage}.", EventName = "ReceivedStreamHubInvocation")] public static partial void ReceivedStreamHubInvocation(ILogger logger, StreamInvocationMessage invocationMessage); [LoggerMessage(13, LogLevel.Debug, "A streaming method was invoked with a non-streaming invocation : {InvocationMessage}.", EventName = "StreamingMethodCalledWithInvoke")] public static partial void StreamingMethodCalledWithInvoke(ILogger logger, HubMethodInvocationMessage invocationMessage); [LoggerMessage(14, LogLevel.Debug, "A non-streaming method was invoked with a streaming invocation : {InvocationMessage}.", EventName = "NonStreamingMethodCalledWithStream")] public static partial void NonStreamingMethodCalledWithStream(ILogger logger, HubMethodInvocationMessage invocationMessage); [LoggerMessage(15, LogLevel.Debug, "A streaming method returned a value that cannot be used to build enumerator {HubMethod}.", EventName = "InvalidReturnValueFromStreamingMethod")] public static partial void InvalidReturnValueFromStreamingMethod(ILogger logger, string hubMethod); public static void ReceivedStreamItem(ILogger logger, StreamItemMessage message) => ReceivedStreamItem(logger, message.InvocationId); [LoggerMessage(16, LogLevel.Trace, "Received item for stream '{StreamId}'.", EventName = "ReceivedStreamItem")] private static partial void ReceivedStreamItem(ILogger logger, string? streamId); [LoggerMessage(17, LogLevel.Trace, "Creating streaming parameter channel '{StreamId}'.", EventName = "StartingParameterStream")] public static partial void StartingParameterStream(ILogger logger, string streamId); public static void CompletingStream(ILogger logger, CompletionMessage message) => CompletingStream(logger, message.InvocationId); [LoggerMessage(18, LogLevel.Trace, "Stream '{StreamId}' has been completed by client.", EventName = "CompletingStream")] private static partial void CompletingStream(ILogger logger, string? streamId); public static void ClosingStreamWithBindingError(ILogger logger, CompletionMessage message) => ClosingStreamWithBindingError(logger, message.InvocationId, message.Error); [LoggerMessage(19, LogLevel.Debug, "Stream '{StreamId}' closed with error '{Error}'.", EventName = "ClosingStreamWithBindingError")] private static partial void ClosingStreamWithBindingError(ILogger logger, string? streamId, string? error); [LoggerMessage(20, LogLevel.Debug, "StreamCompletionMessage received unexpectedly.", EventName = "UnexpectedStreamCompletion")] public static partial void UnexpectedStreamCompletion(ILogger logger); [LoggerMessage(21, LogLevel.Debug, "StreamItemMessage received unexpectedly.", EventName = "UnexpectedStreamItem")] public static partial void UnexpectedStreamItem(ILogger logger); [LoggerMessage(22, LogLevel.Debug, "Parameters to hub method '{HubMethod}' are incorrect.", EventName = "InvalidHubParameters")] public static partial void InvalidHubParameters(ILogger logger, string hubMethod, Exception exception); [LoggerMessage(23, LogLevel.Debug, "Invocation ID '{InvocationId}' is already in use.", EventName = "InvocationIdInUse")] public static partial void InvocationIdInUse(ILogger logger, string InvocationId); }
64.53271
184
0.775815
[ "MIT" ]
3ejki/aspnetcore
src/SignalR/server/Core/src/Internal/DefaultHubDispatcherLog.cs
6,905
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Dyplsapi.Model.V20170525 { public class QuerySecretNoRemainResponse : AcsResponse { private string requestId; private string code; private string message; private QuerySecretNoRemain_SecretRemainDTO secretRemainDTO; public string RequestId { get { return requestId; } set { requestId = value; } } public string Code { get { return code; } set { code = value; } } public string Message { get { return message; } set { message = value; } } public QuerySecretNoRemain_SecretRemainDTO SecretRemainDTO { get { return secretRemainDTO; } set { secretRemainDTO = value; } } public class QuerySecretNoRemain_SecretRemainDTO { private string city; private long? amount; private List<QuerySecretNoRemain_RemainDTO> remainDTOList; public string City { get { return city; } set { city = value; } } public long? Amount { get { return amount; } set { amount = value; } } public List<QuerySecretNoRemain_RemainDTO> RemainDTOList { get { return remainDTOList; } set { remainDTOList = value; } } public class QuerySecretNoRemain_RemainDTO { private string city; private long? amount; public string City { get { return city; } set { city = value; } } public long? Amount { get { return amount; } set { amount = value; } } } } } }
16.404908
63
0.591997
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-dyplsapi/Dyplsapi/Model/V20170525/QuerySecretNoRemainResponse.cs
2,674
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using Luis; using Microsoft.Bot.Solutions.Testing.Mocks; using PhoneSkill.Services.Luis; using PhoneSkill.Tests.Flow.Utterances; namespace PhoneSkill.Tests.TestDouble { public class PhoneSkillMockLuisRecognizerFactory { public static MockLuisRecognizer CreateMockGeneralLuisRecognizer() { var builder = new MockLuisRecognizerBuilder<General, General.Intent>(); builder.AddUtterance(GeneralUtterances.Cancel, General.Intent.Cancel); builder.AddUtterance(GeneralUtterances.Escalate, General.Intent.Escalate); builder.AddUtterance(GeneralUtterances.Help, General.Intent.Help); builder.AddUtterance(GeneralUtterances.Incomprehensible, General.Intent.None); builder.AddUtterance(GeneralUtterances.Logout, General.Intent.Logout); return builder.Build(); } public static MockLuisRecognizer CreateMockPhoneLuisRecognizer() { var builder = new MockLuisRecognizerBuilder<PhoneLuis, PhoneLuis.Intent>(); builder.AddUtterance(GeneralUtterances.Incomprehensible, PhoneLuis.Intent.None); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactName, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "bob", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameMultipleMatchesAndrew, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "andrew", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameMultipleMatchesBotter, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "botter", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameMultipleMatchesNarthwani, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "narthwani", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameMultipleMatchesSanchez, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "sanchez", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameMultipleMatchesWithSpeechRecognitionError, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "not funny", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameMultipleNumbers, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "andrew smith", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameMultipleNumbersWithSameType, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "eve smith", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameNoPhoneNumber, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "christina botter", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameNoPhoneNumberMultipleMatches, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "christina", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameNotFound, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "qqq", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameWithPhoneNumberType, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "andrew smith", StartIndex = 5, }, new MockLuisEntity { Type = "phoneNumberType", Text = "work", StartIndex = 21, ResolvedValue = "BUSINESS", }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameWithPhoneNumberTypeMultipleMatches, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "narthwani", StartIndex = 5, }, new MockLuisEntity { Type = "phoneNumberType", Text = "home", StartIndex = 18, ResolvedValue = "HOME", }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameWithPhoneNumberTypeNotFoundMultipleAlternatives, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "eve smith", StartIndex = 5, }, new MockLuisEntity { Type = "phoneNumberType", Text = "work", StartIndex = 18, ResolvedValue = "BUSINESS", }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameWithPhoneNumberTypeNotFoundSingleAlternative, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "bob botter", StartIndex = 5, }, new MockLuisEntity { Type = "phoneNumberType", Text = "mobile", StartIndex = 19, ResolvedValue = "MOBILE", }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallContactNameWithSpeechRecognitionError, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "sunday not funny", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallNoEntities, PhoneLuis.Intent.OutgoingCall); builder.AddUtterance(OutgoingCallUtterances.OutgoingCallPhoneNumber, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "phoneNumber", Text = "0118 999 88199 9119 725 3", StartIndex = 5, }, }); builder.AddUtterance(OutgoingCallUtterances.RecipientContactName, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "bob", StartIndex = 0, }, }); builder.AddUtterance(OutgoingCallUtterances.RecipientContactNameWithPhoneNumberType, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "andrew smith", StartIndex = 0, }, new MockLuisEntity { Type = "phoneNumberType", Text = "work", StartIndex = 16, ResolvedValue = "BUSINESS", }, }); builder.AddUtterance(OutgoingCallUtterances.RecipientContactNameWithSpeechRecognitionError, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "sunday not funny", StartIndex = 0, }, }); builder.AddUtterance(OutgoingCallUtterances.RecipientPhoneNumber, PhoneLuis.Intent.OutgoingCall, new List<MockLuisEntity>() { new MockLuisEntity { Type = "phoneNumber", Text = "0118 999 88199 9119 725 3", StartIndex = 0, }, }); return builder.Build(); } public static MockLuisRecognizer CreateMockContactSelectionLuisRecognizer() { var builder = new MockLuisRecognizerBuilder<ContactSelectionLuis, ContactSelectionLuis.Intent>(); builder.AddUtterance(OutgoingCallUtterances.ContactSelectionFullName, ContactSelectionLuis.Intent.ContactSelection, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "sanjay narthwani", StartIndex = 7, }, }); builder.AddUtterance(OutgoingCallUtterances.ContactSelectionFullNameWithSpeechRecognitionError, ContactSelectionLuis.Intent.ContactSelection, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "sunday not funny", StartIndex = 7, }, }); builder.AddUtterance(OutgoingCallUtterances.ContactSelectionNoMatches, ContactSelectionLuis.Intent.ContactSelection, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "qqq", StartIndex = 0, }, }); builder.AddUtterance(OutgoingCallUtterances.ContactSelectionPartialNameKeith, ContactSelectionLuis.Intent.ContactSelection, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "keith", StartIndex = 7, }, }); builder.AddUtterance(OutgoingCallUtterances.ContactSelectionPartialNameAndrewJohn, ContactSelectionLuis.Intent.ContactSelection, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "andrew john", StartIndex = 0, }, }); builder.AddUtterance(OutgoingCallUtterances.ContactSelectionPartialNameSanjay, ContactSelectionLuis.Intent.ContactSelection, new List<MockLuisEntity>() { new MockLuisEntity { Type = "contactName", Text = "sanjay", StartIndex = 7, }, }); builder.AddUtterance(OutgoingCallUtterances.SelectionFirst, ContactSelectionLuis.Intent.ContactSelection); builder.AddUtterance(OutgoingCallUtterances.SelectionNoEntities, ContactSelectionLuis.Intent.ContactSelection); return builder.Build(); } public static MockLuisRecognizer CreateMockPhoneNumberSelectionLuisRecognizer() { var builder = new MockLuisRecognizerBuilder<PhoneNumberSelectionLuis, PhoneNumberSelectionLuis.Intent>(); builder.AddUtterance(OutgoingCallUtterances.PhoneNumberSelectionFullNumber, PhoneNumberSelectionLuis.Intent.PhoneNumberSelection); builder.AddUtterance(OutgoingCallUtterances.PhoneNumberSelectionNoMatches, PhoneNumberSelectionLuis.Intent.PhoneNumberSelection, new List<MockLuisEntity>() { new MockLuisEntity { // TODO Change entity type once we support custom phone number types. Type = "phoneNumberType", Text = "fax", StartIndex = 4, }, }); builder.AddUtterance(OutgoingCallUtterances.PhoneNumberSelectionStandardizedType, PhoneNumberSelectionLuis.Intent.PhoneNumberSelection, new List<MockLuisEntity>() { new MockLuisEntity { Type = "phoneNumberType", Text = "cell phone", StartIndex = 9, ResolvedValue = "MOBILE", }, }); builder.AddUtterance(OutgoingCallUtterances.SelectionFirst, PhoneNumberSelectionLuis.Intent.PhoneNumberSelection); builder.AddUtterance(OutgoingCallUtterances.SelectionNoEntities, PhoneNumberSelectionLuis.Intent.PhoneNumberSelection); return builder.Build(); } } }
38.582051
185
0.526018
[ "MIT" ]
ConnectionMaster/botframework-components
skills/csharp/tests/phoneskill.tests/TestDouble/PhoneSkillMockLuisRecognizerFactory.cs
15,049
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Final.Data; using Final.Models; using Microsoft.AspNetCore.Authorization; namespace Final.Areas.Wp_admin.Controllers { [Area("wp-admin")] [Authorize] public class CategoryController : Controller { private readonly ApplicationDbContext _context; public CategoryController(ApplicationDbContext context) { _context = context; } // GET: Category public async Task<IActionResult> Index() { return View(await _context.Category.Where(b => b.Record_Status == 1).ToListAsync()); } // GET: Category/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var blogCategory = await _context.Category.SingleOrDefaultAsync(m => m.CategoryId == id); if (blogCategory == null) { return NotFound(); } return View(blogCategory); } // GET: Category/Create public IActionResult Create() { return View(); } // POST: Category/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("CategoryId,CategoryName,CategoryDes,OrderNo,Status,UserId")] BlogCategory blogCategory) { if (ModelState.IsValid) { blogCategory.Auth_status = "A"; blogCategory.Create_DT = DateTime.Now; blogCategory.Record_Status = 1; _context.Add(blogCategory); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } return View(blogCategory); } // GET: Category/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var blogCategory = await _context.Category.SingleOrDefaultAsync(m => m.CategoryId == id); if (blogCategory == null) { return NotFound(); } return View(blogCategory); } // POST: Category/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("CategoryId,CategoryName,CategoryDes,OrderNo,Notes,Record_Status,Publish_DT")] BlogCategory blogCategory) { if (ModelState.IsValid) { try { blogCategory.Auth_status = "A"; blogCategory.Publish_DT = DateTime.Now; blogCategory.Record_Status = 1; _context.Update(blogCategory); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BlogCategoryExists(blogCategory.CategoryId)) { return NotFound(); } else { throw; } } return RedirectToAction("Index"); } return View(blogCategory); } // GET: Category/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var blogCategory = await _context.Category.SingleOrDefaultAsync(m => m.CategoryId == id); if (blogCategory == null) { return NotFound(); } try { if (blogCategory.Auth_status.Equals("U")) _context.Category.Remove(blogCategory); else { blogCategory.Record_Status = 0; _context.Update(blogCategory); } await _context.SaveChangesAsync(); } catch (Exception) { } return RedirectToAction("Index"); } // POST: Category/Delete/5 //[HttpPost, ActionName("Delete")] //[ValidateAntiForgeryToken] //public async Task<IActionResult> DeleteConfirmed(int id) //{ // var blogCategory = await _context.Category.SingleOrDefaultAsync(m => m.CategoryId == id); // try // { // if (blogCategory.Auth_status.Equals("U")) // _context.Category.Remove(blogCategory); // else // blogCategory.Record_Status = 0; // await _context.SaveChangesAsync(); // } // catch (Exception) { } // return RedirectToAction("Index"); //} private bool BlogCategoryExists(int id) { return _context.Category.Any(e => e.CategoryId == id); } } }
33.245714
166
0.504297
[ "MIT" ]
nguyendev/CNW
Final/src/Final/Areas/Wp-admin/Controllers/CategoryController.cs
5,818
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Iso.Api.Extensions; using Iso.Api.Models; using Microsoft.AspNetCore.Mvc; namespace Iso.Api.Services { internal class CurrenciesService : BaseService<IsoCurrency> { private readonly IEnumerable<IsoCountry> _countries; public CurrenciesService(IEnumerable<IsoCurrency> currencies, IEnumerable<IsoCountry> countries) : base(currencies) { _countries = countries; } public override async Task<IActionResult> GetRelatedEntities(string alpha3Code) { if (string.IsNullOrWhiteSpace(alpha3Code)) { throw new ArgumentNullException(nameof(alpha3Code)); } if (!alpha3Code.IsValidAlpha3Code()) { throw new ArgumentException(nameof(alpha3Code)); } var currencyResult = Data.FirstOrDefault(currency => string.Equals(currency.IsoAlpha3Code, alpha3Code, StringComparison.OrdinalIgnoreCase)); var result = _countries.Where(country => currencyResult.Countries.Contains(country.Name)); return await Task.FromResult((IActionResult) new OkObjectResult(result)).ConfigureAwait(false); } } }
29.9
119
0.733278
[ "MIT" ]
JimbeanZN/iso
src/Iso.Api/Services/CurrenciesService.cs
1,198
C#
using SimpleHomeAuto.Data; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace SimpleHomeAuto.Views { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class InfoPage : Page { public InfoPage() { this.InitializeComponent(); Version.Text = Context.Instance.Version; } private void OnTapped(object sender, TappedRoutedEventArgs e) { Frame.Navigate(typeof(MainPage)); } } }
27.210526
94
0.704062
[ "MIT" ]
nicoschmitt/Home.Auto
SimpleHomeAuto/Views/InfoPage.xaml.cs
1,036
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Surging.Core.CPlatform.Support { public interface IServiceCommandProvider { ValueTask<ServiceCommand> GetCommand(string serviceId); Task<object> Run(string text, params string[] InjectionNamespaces); } }
24.357143
75
0.750733
[ "MIT" ]
16it/surging
src/Surging.Core/Surging.Core.CPlatform/Support/IServiceCommandProvider.cs
343
C#
using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using Cysharp.Threading.Tasks; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace com.enemyhideout.fsm.tests { [TestFixture] public partial class TestFsm { void AssertLog(List<string> objectHistory, params string[] args) { Assert.True(objectHistory.Count == args.Length, "History and expected history values do not match up."); for (int i = 0; i < args.Length; i++) { Assert.AreEqual(args[i], objectHistory[i]); } objectHistory.Clear(); } [UnityTest] public IEnumerator TestFsmChangeState() => UniTask.ToCoroutine(async () => { try { TestActor actor = new TestActor(); actor.fsm.ChangeState(TestActor.States.Sprint); await Task.Delay(1100); AssertLog(actor.ObjectHistory, "Entering Sprint...", "Sprint Entered!"); actor.fsm.ChangeState(TestActor.States.Idle); actor.fsm.ChangeState(TestActor.States.Sprint); await Task.Delay(100); //changing state! we should not see log messages! actor.fsm.ChangeState(TestActor.States.Idle); await Task.Delay(1000); AssertLog(actor.ObjectHistory, "Entering Sprint...", "Exiting Sprint Early."); actor.fsm.ChangeState(TestActor.States.Running); await Task.Delay(1000); AssertLog(actor.ObjectHistory,"Ready...", "Set...", "Go!!!", "Running 0","Running 1","Running 2","Running 3","Running 4"); actor.fsm.ChangeState(TestActor.States.Sprint); await Task.Delay(1100); AssertLog(actor.ObjectHistory, "Exiting Run...","Done running.", "Entering Sprint...", "Sprint Entered!"); actor.fsm.ChangeState(TestActor.States.Hiding); await Task.Delay(10); AssertLog(actor.ObjectHistory, "Hiding"); actor.fsm.ChangeState(TestActor.States.DoubleJump); await UniTask.Yield(); AssertLog(actor.ObjectHistory, "DoubleJump", "DoubleJump2", "DoubleJump3"); // testing changing state while in update loop. actor.fsm.ChangeState(TestActor.States.Turn); await UniTask.WaitUntil(() => actor.fsm.State == TestActor.States.Idle); AssertLog(actor.ObjectHistory, "DoneTurning"); actor.fsm.ChangeState(TestActor.States.TestStateX); actor.fsm.ChangeState(TestActor.States.TestStateY); // state y should not execute, and state x will change the state in _Exit. AssertLog(actor.ObjectHistory, "TestStateX_Exit", "TestStateZ_Enter"); try { actor.fsm.ChangeState(TestActor.States.Dead); await UniTask.Yield(); Assert.Fail("Exception was not thrown."); } catch { } // clean up. actor.fsm.Dispose(); } catch (Exception ex) { Debug.LogException(ex); throw; } }); } }
32.569892
114
0.62826
[ "MIT" ]
robotron2084/enemy-fsm
Enemy-FSM/Assets/enemy-fsm/Tests/TestFsm.cs
3,031
C#
namespace Machete.HL7Schema.V26 { using HL7; /// <summary> /// BPS_O29 (Message) - /// </summary> public interface BPS_O29 : HL7V26Layout { /// <summary> /// MSH /// </summary> Segment<MSH> MSH { get; } /// <summary> /// SFT /// </summary> SegmentList<SFT> SFT { get; } /// <summary> /// UAC /// </summary> Segment<UAC> UAC { get; } /// <summary> /// NTE /// </summary> SegmentList<NTE> NTE { get; } /// <summary> /// PATIENT /// </summary> Layout<BPS_O29_PATIENT> Patient { get; } /// <summary> /// ORDER /// </summary> LayoutList<BPS_O29_ORDER> Order { get; } } }
19.512195
48
0.425
[ "Apache-2.0" ]
ahives/Machete
src/Machete.HL7Schema/V26/Messages/BPS_O29.cs
800
C#
using IPB.LogicApp.Standard.Testing.Model; using IPB.LogicApp.Standard.Testing.Model.WorkflowRunOverview; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Linq; using System.Net.Http; namespace IPB.LogicApp.Standard.Testing.Helpers { public class WorkflowHelper { public string SubscriptionId { get; set; } public string ResourceGroupName { get; set; } public string LogicAppName { get; set; } public string WorkflowName { get; set; } public ManagementApiHelper ManagementApiHelper { get;set;} /// <summary> /// Gets the callback url for the logic app so we can trigger it. The default behaviour is to get the manual trigger so we can run over /// http /// </summary> /// <param name="triggerName"></param> /// <returns></returns> public string GetCallBackUrl(string triggerName = "manual") { var url = $@"/subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Web/sites/{LogicAppName}/hostruntime/runtime/webhooks/workflow/api/management/workflows/{WorkflowName}/triggers/{triggerName}/listCallbackUrl?api-version={ApiSettings.ApiVersion}"; var client = ManagementApiHelper.GetHttpClient(); var content = new StringContent(""); HttpResponseMessage response = client.PostAsync(url, content).Result; var responseText = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); var jsonResponse = JObject.Parse(responseText); return jsonResponse["value"].ToString(); } /// <summary> /// Triggers the logic app with an HTTP post request /// </summary> /// <param name="content"></param> /// <param name="triggerName"></param> /// <returns></returns> public WorkFlowResponse TriggerLogicAppWithPost(StringContent content, string triggerName = "manual") { var url = GetCallBackUrl(triggerName); using (HttpClient client = new HttpClient()) { HttpResponseMessage response = client.PostAsync(url, content).Result; var workflowResponse = new WorkFlowResponse(response); return workflowResponse; } } /// <summary> /// Triggers the logic app with an HTTP GET request /// </summary> /// <param name="content"></param> /// <param name="triggerName"></param> /// <returns></returns> public WorkFlowResponse TriggerLogicAppWithGet(StringContent content, string triggerName = "manual") { var url = GetCallBackUrl(triggerName); using (HttpClient client = new HttpClient()) { HttpResponseMessage response = client.GetAsync(url).Result; var workflowResponse = new WorkFlowResponse(response); return workflowResponse; } } /// <summary> /// Once have ran the logic app we can get a workflow run helper which will let us access details about the run history /// </summary> /// <param name="runId"></param> /// <returns></returns> public WorkflowRunHelper GetWorkflowRunHelper(string runId) { var runHelper = new WorkflowRunHelper(); runHelper.WorkflowHelper = this; runHelper.RunId = runId; runHelper.ManagementApiHelper = ManagementApiHelper; return runHelper; } public RunDetails GetMostRecentRunDetails(DateTime startDate) { var dateString = startDate.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); var url = $@"subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Web/sites/{LogicAppName}/hostruntime/runtime/webhooks/workflow/api/management/workflows/{WorkflowName}/runs?api-version={ApiSettings.ApiVersion}&$filter=startTime ge {dateString}"; var client = ManagementApiHelper.GetHttpClient(); Console.WriteLine($"Query for recent workflow run"); Console.WriteLine($"{url}"); HttpResponseMessage response = client.GetAsync(url).Result; var responseText = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); var runList = JsonConvert.DeserializeObject<WorkflowRunList>(responseText); return runList.Value.FirstOrDefault(); } public RunDetails GetMostRecentRun() { var url = $@"subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Web/sites/{LogicAppName}/hostruntime/runtime/webhooks/workflow/api/management/workflows/{WorkflowName}/runs?api-version={ApiSettings.ApiVersion}&$top=1"; var client = ManagementApiHelper.GetHttpClient(); Console.WriteLine($"Query for recent workflow run"); Console.WriteLine($"{url}"); HttpResponseMessage response = client.GetAsync(url).Result; var responseText = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); var runList = JsonConvert.DeserializeObject<WorkflowRunList>(responseText); return runList.Value.FirstOrDefault(); } public WorkflowRunList GetRunsSince(DateTime startDate) { var dateString = startDate.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); var url = $@"subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Web/sites/{LogicAppName}/hostruntime/runtime/webhooks/workflow/api/management/workflows/{WorkflowName}/runs?api-version={ApiSettings.ApiVersion}&$filter=startTime ge {dateString}"; var client = ManagementApiHelper.GetHttpClient(); Console.WriteLine($"Query for workflow runs since"); Console.WriteLine($"{url}"); HttpResponseMessage response = client.GetAsync(url).Result; var responseText = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); return JsonConvert.DeserializeObject<WorkflowRunList>(responseText); } } }
43.753425
292
0.646838
[ "MIT" ]
michaelstephensonuk/IntegrationPlaybook-LogicApp-Standard-Testing
IPB.LogicApp.Standard.Testing/Helpers/WorkflowHelper.cs
6,390
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TimecardsIOC")] [assembly: AssemblyDescription("IOC container for Timecards")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Dan Hickok")] [assembly: AssemblyProduct("TimecardsIOC")] [assembly: AssemblyCopyright("Copyright © 2019-2021 Dan Hickok")] [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("a4da85eb-7660-4431-9496-4dd55b8ae177")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")]
39.027778
84
0.749466
[ "MIT" ]
danhickok/timecards
Timecards/TimecardsIOC/Properties/AssemblyInfo.cs
1,408
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace DReporting.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
26.045455
70
0.706806
[ "MIT" ]
Ronglin-kooboo/DReportiing
DReporting.Web/Global.asax.cs
575
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the amplify-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Amplify.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Amplify.Model.Internal.MarshallTransformations { /// <summary> /// GetArtifactUrl Request Marshaller /// </summary> public class GetArtifactUrlRequestMarshaller : IMarshaller<IRequest, GetArtifactUrlRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetArtifactUrlRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetArtifactUrlRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Amplify"); request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-07-25"; request.HttpMethod = "GET"; if (!publicRequest.IsSetArtifactId()) throw new AmazonAmplifyException("Request object does not have required field ArtifactId set"); request.AddPathResource("{artifactId}", StringUtils.FromString(publicRequest.ArtifactId)); request.ResourcePath = "/artifacts/{artifactId}"; request.MarshallerVersion = 2; return request; } private static GetArtifactUrlRequestMarshaller _instance = new GetArtifactUrlRequestMarshaller(); internal static GetArtifactUrlRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetArtifactUrlRequestMarshaller Instance { get { return _instance; } } } }
34.715909
143
0.655974
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Amplify/Generated/Model/Internal/MarshallTransformations/GetArtifactUrlRequestMarshaller.cs
3,055
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Cfg { /// <summary> /// Manages an AWS Config Aggregate Authorization /// /// /// /// &gt; This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/r/config_aggregate_authorization.markdown. /// </summary> public partial class AggregateAuthorization : Pulumi.CustomResource { /// <summary> /// Account ID /// </summary> [Output("accountId")] public Output<string> AccountId { get; private set; } = null!; /// <summary> /// The ARN of the authorization /// </summary> [Output("arn")] public Output<string> Arn { get; private set; } = null!; /// <summary> /// Region /// </summary> [Output("region")] public Output<string> Region { get; private set; } = null!; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, object>?> Tags { get; private set; } = null!; /// <summary> /// Create a AggregateAuthorization resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public AggregateAuthorization(string name, AggregateAuthorizationArgs args, CustomResourceOptions? options = null) : base("aws:cfg/aggregateAuthorization:AggregateAuthorization", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, "")) { } private AggregateAuthorization(string name, Input<string> id, AggregateAuthorizationState? state = null, CustomResourceOptions? options = null) : base("aws:cfg/aggregateAuthorization:AggregateAuthorization", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing AggregateAuthorization resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static AggregateAuthorization Get(string name, Input<string> id, AggregateAuthorizationState? state = null, CustomResourceOptions? options = null) { return new AggregateAuthorization(name, id, state, options); } } public sealed class AggregateAuthorizationArgs : Pulumi.ResourceArgs { /// <summary> /// Account ID /// </summary> [Input("accountId", required: true)] public Input<string> AccountId { get; set; } = null!; /// <summary> /// Region /// </summary> [Input("region", required: true)] public Input<string> Region { get; set; } = null!; [Input("tags")] private InputMap<object>? _tags; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> public InputMap<object> Tags { get => _tags ?? (_tags = new InputMap<object>()); set => _tags = value; } public AggregateAuthorizationArgs() { } } public sealed class AggregateAuthorizationState : Pulumi.ResourceArgs { /// <summary> /// Account ID /// </summary> [Input("accountId")] public Input<string>? AccountId { get; set; } /// <summary> /// The ARN of the authorization /// </summary> [Input("arn")] public Input<string>? Arn { get; set; } /// <summary> /// Region /// </summary> [Input("region")] public Input<string>? Region { get; set; } [Input("tags")] private InputMap<object>? _tags; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> public InputMap<object> Tags { get => _tags ?? (_tags = new InputMap<object>()); set => _tags = value; } public AggregateAuthorizationState() { } } }
35.254777
171
0.588076
[ "ECL-2.0", "Apache-2.0" ]
Dominik-K/pulumi-aws
sdk/dotnet/Cfg/AggregateAuthorization.cs
5,535
C#
// Copyright (C) Microsoft Corporation. All rights reserved. using Microsoft.AI.Skills.SkillInterfacePreview; using System; using System.Threading.Tasks; using Windows.Graphics.Imaging; using Windows.Media; using Windows.Storage; using Windows.Storage.Streams; namespace FrameSourceHelper_UWP { public sealed class ImageFileFrameSource : IFrameSource { public uint FrameHeight { get; private set; } public uint FrameWidth { get; private set; } public FrameSourceType FrameSourceType => FrameSourceType.Photo; public event EventHandler<VideoFrame> FrameArrived; private VideoFrame m_videoFrame; private ISkillFeatureImageDescriptor m_desiredImageDescriptor = null; /// <summary> /// Static factory /// </summary> /// <param name="storageFile"></param> /// <param name="imageDescriptor"></param> /// <returns></returns> public static async Task<ImageFileFrameSource> CreateFromStorageFileAsyncTask( StorageFile storageFile, ISkillFeatureImageDescriptor imageDescriptor) { var result = new ImageFileFrameSource() { m_desiredImageDescriptor = imageDescriptor }; await result.GetFrameFromFileAsync(storageFile); return result; } /// <summary> /// Retrieve the corresponding VideoFrame via FrameArrived event /// </summary> public Task StartAsync() { FrameArrived?.Invoke(this, m_videoFrame); // Async not needed, return success return Task.FromResult(true); } /// <summary> /// Private constructor called by static factory /// </summary> private ImageFileFrameSource() { } /// <summary> /// Decode an image file into a VideoFrame /// </summary> /// <param name="file"></param> /// <returns></returns> private async Task GetFrameFromFileAsync(StorageFile file) { // Decoding image file content into a SoftwareBitmap, and wrap into VideoFrame SoftwareBitmap softwareBitmap = null; using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read)) { // Create the decoder from the stream BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); // Get the SoftwareBitmap representation of the file in BGRA8 format softwareBitmap = await decoder.GetSoftwareBitmapAsync(); // Convert to preferred format if specified and encapsulate the image in a VideoFrame instance var convertedSoftwareBitmap = m_desiredImageDescriptor == null ? SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore) : SoftwareBitmap.Convert(softwareBitmap, m_desiredImageDescriptor.SupportedBitmapPixelFormat, m_desiredImageDescriptor.SupportedBitmapAlphaMode); m_videoFrame = VideoFrame.CreateWithSoftwareBitmap(convertedSoftwareBitmap); } // Extract frame dimensions FrameWidth = (uint)softwareBitmap.PixelWidth; FrameHeight = (uint)softwareBitmap.PixelHeight; } } }
37.88764
169
0.639383
[ "MIT" ]
dhung-msft/WindowsVisionSkillsPreview
samples/Common/cs/ImageFileFrameSource.cs
3,374
C#
using DomainFramework.Core; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace OrganizationPersonWithCommonEntities.OrganizationPersonBoundedContext { public class PersonQueryAggregate : GetByIdQueryAggregate<Person, int, PersonOutputDto> { public GetAllLinkedAggregateQueryCollectionOperation<int, Phone, PhoneOutputDto> GetAllPhonesLinkedAggregateQueryOperation { get; set; } public GetLinkedAggregateQuerySingleItemOperation<int, Address, AddressOutputDto> GetAddressLinkedAggregateQueryOperation { get; set; } public PersonQueryAggregate() : this(null) { } public PersonQueryAggregate(HashSet<(string, IEntity)> processedEntities = null) : base(new DomainFramework.DataAccess.RepositoryContext(OrganizationPersonWithCommonEntitiesConnectionClass.GetConnectionName()), processedEntities) { var context = (DomainFramework.DataAccess.RepositoryContext)RepositoryContext; PersonQueryRepository.Register(context); PhoneQueryRepository.Register(context); AddressQueryRepository.Register(context); GetAllPhonesLinkedAggregateQueryOperation = new GetAllLinkedAggregateQueryCollectionOperation<int, Phone, PhoneOutputDto> { GetAllLinkedEntities = (repository, entity, user) => ((PhoneQueryRepository)repository).GetAllPhonesForPerson(RootEntity.Id).ToList(), GetAllLinkedEntitiesAsync = async (repository, entity, user) => { var entities = await ((PhoneQueryRepository)repository).GetAllPhonesForPersonAsync(RootEntity.Id); return entities.ToList(); }, CreateLinkedQueryAggregate = entity => { if (entity is Phone) { return new GetPhoneQueryAggregate(); } else { throw new InvalidOperationException(); } } }; QueryOperations.Enqueue(GetAllPhonesLinkedAggregateQueryOperation); GetAddressLinkedAggregateQueryOperation = new GetLinkedAggregateQuerySingleItemOperation<int, Address, AddressOutputDto> { OnBeforeExecute = entity => { if (ProcessedEntities.Contains(("Address", entity))) { return false; } ProcessedEntities.Add(("Address", entity)); return true; }, GetLinkedEntity = (repository, entity, user) => ((AddressQueryRepository)repository).GetAddressForPerson(RootEntity.Id), GetLinkedEntityAsync = async (repository, entity, user) => await ((AddressQueryRepository)repository).GetAddressForPersonAsync(RootEntity.Id), CreateLinkedQueryAggregate = entity => { if (entity is Address) { return new GetAddressQueryAggregate(); } else { throw new InvalidOperationException(); } } }; QueryOperations.Enqueue(GetAddressLinkedAggregateQueryOperation); } public override void PopulateDto() { OutputDto.PersonId = RootEntity.Id; OutputDto.Name = RootEntity.Name; OutputDto.Phones = GetAllPhonesLinkedAggregateQueryOperation.OutputDtos; OutputDto.Address = GetAddressLinkedAggregateQueryOperation.OutputDto; } } }
39.697917
237
0.602467
[ "MIT" ]
jgonte/DomainFramework
DomainFramework.Tests/OrganizationPersonWithCommonEntities/OrganizationPersonBoundedContext/QueryAggregates/PersonQueryAggregate.cs
3,811
C#
using SoccerManager.Web.Models.Base; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace SoccerManager.Web.Models { public class TransferenciaVM : BaseVM { public Jogador Jogador { get; set; } [Display(Name = "Jogador")] public int Jogador_Id { get; set; } public SelectList Jogadores { get; set; } public Clube Clube { get; set; } [Display(Name = "Clube")] public int? Clube_Id { get; set; } public SelectList Clubes { get; set; } [Display(Name = "Data"), DisplayFormat(DataFormatString ="{0:dd/MM/yyyy}"), DataType(DataType.Date)] public DateTime Data { get; set; } } }
26.033333
108
0.647887
[ "MIT" ]
leonardoacoelho/Soccer_Manager
SoccerManager/SoccerManager.Web/Models/TransferenciaVM.cs
783
C#
using UnityEngine; namespace DiMe.Urarulla { public interface ISelectionResponse { public void OnSelect(Transform selection); public void OnDeselect(Transform selection); public void SetDotProduct(float distance); } }
23.090909
52
0.708661
[ "MIT" ]
JerePystynen/unity-wheel-of-joy
Urarulla/Assets/Scripts/Selecting/ISelectionResponse.cs
254
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace umbraco.cms.presentation.developer.RelationTypes { public partial class EditRelationType { /// <summary> /// tabControl control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.TabView tabControl; /// <summary> /// idPane control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.Pane idPane; /// <summary> /// idPropertyPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel idPropertyPanel; /// <summary> /// idLiteral control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal idLiteral; /// <summary> /// nameAliasPane control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.Pane nameAliasPane; /// <summary> /// nameProperyPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel nameProperyPanel; /// <summary> /// nameTextBox control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox nameTextBox; /// <summary> /// nameRequiredFieldValidator control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator nameRequiredFieldValidator; /// <summary> /// aliasPropertyPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel aliasPropertyPanel; /// <summary> /// aliasTextBox control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox aliasTextBox; /// <summary> /// aliasRequiredFieldValidator control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator aliasRequiredFieldValidator; /// <summary> /// aliasCustomValidator control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CustomValidator aliasCustomValidator; /// <summary> /// directionPane control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.Pane directionPane; /// <summary> /// dualPropertyPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel dualPropertyPanel; /// <summary> /// dualRadioButtonList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RadioButtonList dualRadioButtonList; /// <summary> /// objectTypePane control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.Pane objectTypePane; /// <summary> /// parentPropertyPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel parentPropertyPanel; /// <summary> /// parentLiteral control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal parentLiteral; /// <summary> /// childPropertyPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel childPropertyPanel; /// <summary> /// childLiteral control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal childLiteral; /// <summary> /// relationsCountPane control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.Pane relationsCountPane; /// <summary> /// relationsCountPropertyPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel relationsCountPropertyPanel; /// <summary> /// relationsCountLiteral control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal relationsCountLiteral; /// <summary> /// relationsPane control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.Pane relationsPane; /// <summary> /// relationsPropertyPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::umbraco.uicontrols.PropertyPanel relationsPropertyPanel; /// <summary> /// relationsRepeater control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Repeater relationsRepeater; } }
31.748
98
0.649238
[ "MIT" ]
Abhith/Umbraco-CMS
src/Umbraco.Web/umbraco.presentation/umbraco/developer/RelationTypes/EditRelationType.aspx.designer.cs
7,939
C#
namespace TestBed { partial class NewProject { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txt_name = new System.Windows.Forms.TextBox(); this.txt_cdrom = new System.Windows.Forms.TextBox(); this.btn_cdrom = new System.Windows.Forms.Button(); this.btn_cancel = new System.Windows.Forms.Button(); this.btn_ok = new System.Windows.Forms.Button(); this.btn_emu = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.txt_emu = new System.Windows.Forms.TextBox(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 9; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 80F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 52F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 28F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.Controls.Add(this.label1, 1, 2); this.tableLayoutPanel1.Controls.Add(this.label2, 1, 4); this.tableLayoutPanel1.Controls.Add(this.txt_name, 2, 2); this.tableLayoutPanel1.Controls.Add(this.txt_cdrom, 2, 4); this.tableLayoutPanel1.Controls.Add(this.btn_cdrom, 7, 4); this.tableLayoutPanel1.Controls.Add(this.btn_cancel, 4, 8); this.tableLayoutPanel1.Controls.Add(this.btn_ok, 6, 8); this.tableLayoutPanel1.Controls.Add(this.btn_emu, 7, 6); this.tableLayoutPanel1.Controls.Add(this.label3, 1, 6); this.tableLayoutPanel1.Controls.Add(this.txt_emu, 2, 6); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 10; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 8F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 8F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 32F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(340, 195); this.tableLayoutPanel1.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Location = new System.Drawing.Point(23, 31); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(74, 28); this.label1.TabIndex = 0; this.label1.Text = "Project Name"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Fill; this.label2.Location = new System.Drawing.Point(23, 67); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(74, 28); this.label2.TabIndex = 1; this.label2.Text = "CD Image"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // txt_name // this.tableLayoutPanel1.SetColumnSpan(this.txt_name, 6); this.txt_name.Dock = System.Windows.Forms.DockStyle.Fill; this.txt_name.Location = new System.Drawing.Point(103, 34); this.txt_name.Name = "txt_name"; this.txt_name.Size = new System.Drawing.Size(214, 20); this.txt_name.TabIndex = 1; // // txt_cdrom // this.tableLayoutPanel1.SetColumnSpan(this.txt_cdrom, 5); this.txt_cdrom.Dock = System.Windows.Forms.DockStyle.Fill; this.txt_cdrom.Location = new System.Drawing.Point(103, 70); this.txt_cdrom.Name = "txt_cdrom"; this.txt_cdrom.Size = new System.Drawing.Size(186, 20); this.txt_cdrom.TabIndex = 2; // // btn_cdrom // this.btn_cdrom.Dock = System.Windows.Forms.DockStyle.Fill; this.btn_cdrom.Location = new System.Drawing.Point(295, 70); this.btn_cdrom.Name = "btn_cdrom"; this.btn_cdrom.Size = new System.Drawing.Size(22, 22); this.btn_cdrom.TabIndex = 3; this.btn_cdrom.UseVisualStyleBackColor = true; this.btn_cdrom.Click += new System.EventHandler(this.btn_cdrom_Click); // // btn_cancel // this.btn_cancel.Dock = System.Windows.Forms.DockStyle.Fill; this.btn_cancel.Location = new System.Drawing.Point(143, 145); this.btn_cancel.Name = "btn_cancel"; this.btn_cancel.Size = new System.Drawing.Size(74, 26); this.btn_cancel.TabIndex = 6; this.btn_cancel.Text = "Cancel"; this.btn_cancel.UseVisualStyleBackColor = true; this.btn_cancel.Click += new System.EventHandler(this.btn_cancel_Click); // // btn_ok // this.tableLayoutPanel1.SetColumnSpan(this.btn_ok, 2); this.btn_ok.Dock = System.Windows.Forms.DockStyle.Fill; this.btn_ok.Location = new System.Drawing.Point(243, 145); this.btn_ok.Name = "btn_ok"; this.btn_ok.Size = new System.Drawing.Size(74, 26); this.btn_ok.TabIndex = 7; this.btn_ok.Text = "OK"; this.btn_ok.UseVisualStyleBackColor = true; this.btn_ok.Click += new System.EventHandler(this.btn_ok_Click); // // btn_emu // this.btn_emu.Dock = System.Windows.Forms.DockStyle.Fill; this.btn_emu.Location = new System.Drawing.Point(295, 106); this.btn_emu.Name = "btn_emu"; this.btn_emu.Size = new System.Drawing.Size(22, 22); this.btn_emu.TabIndex = 5; this.btn_emu.UseVisualStyleBackColor = true; // // label3 // this.label3.AutoSize = true; this.label3.Dock = System.Windows.Forms.DockStyle.Fill; this.label3.Location = new System.Drawing.Point(23, 103); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(74, 28); this.label3.TabIndex = 9; this.label3.Text = "Emulator"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // txt_emu // this.tableLayoutPanel1.SetColumnSpan(this.txt_emu, 5); this.txt_emu.Dock = System.Windows.Forms.DockStyle.Fill; this.txt_emu.Location = new System.Drawing.Point(103, 106); this.txt_emu.Name = "txt_emu"; this.txt_emu.Size = new System.Drawing.Size(186, 20); this.txt_emu.TabIndex = 4; // // NewProject // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(340, 195); this.Controls.Add(this.tableLayoutPanel1); this.Name = "NewProject"; this.Text = "New Project"; this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txt_name; private System.Windows.Forms.TextBox txt_cdrom; private System.Windows.Forms.Button btn_cdrom; private System.Windows.Forms.Button btn_cancel; private System.Windows.Forms.Button btn_ok; private System.Windows.Forms.Button btn_emu; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txt_emu; } }
55.444976
136
0.61719
[ "MIT" ]
collinsmichael/GodHands
WinForms/GodHands/TestBed/NewProject.Designer.cs
11,590
C#
using System; // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedParameter.Global namespace aoc2020.Days { public class Day25 : IDay { public (Func<string> Part1, Func<string> Part2) Parts(string input) { var lines = input.SplitAsInt(); return ( () => Part1(lines).ToString(), () => string.Empty ); } public static long Part1(int[] input) { var (cardPkey, doorPkey, _) = input; var doorLoopSize = GetLoopSize(doorPkey); return Transform(doorLoopSize, cardPkey); } private static int GetLoopSize(in long cardPkey) { var loopSize = 1; const int subjectNumber = 7; var previousValue = 1L; while (true) { var val = previousValue * subjectNumber; val %= 20201227; if (val == cardPkey) return loopSize; previousValue = val; loopSize++; } } private static long Transform(int loopSize, int subjectNumber) { var val = 1L; for (var i = 0; i < loopSize; i++) { val *= subjectNumber; val %= 20201227; } return val; } } }
24.859649
75
0.474241
[ "MIT" ]
hillerstorm/aoc2020-csharp
aoc2020-csharp/Days/Day25.cs
1,419
C#
/**************************************************************************** Copyright (c) 2013-2015 scutgame.com http://www.scutgame.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; namespace ZyGames.Framework.Game.Pay { /// <summary> /// 游戏服信息 /// </summary> public class ServerInfo { /// <summary> /// Gets or sets the I. /// </summary> /// <value>The I.</value> public int ID { get; set; } /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public string Name { get; set; } /// <summary> /// Gets or sets the game I. /// </summary> /// <value>The game I.</value> public int GameID { get; set; } /// <summary> /// Gets or sets the name of the game. /// </summary> /// <value>The name of the game.</value> public string GameName { get; set; } } }
31.057143
79
0.574057
[ "Unlicense" ]
HongXiao/Scut
Source/Middleware/ZyGames.Framework.Game/Pay/ServerInfo.cs
2,186
C#
using System; using System.Diagnostics; using System.Text.Json; using System.IO; using TyphonHIRBackend; class Program { static Stopwatch _init = Stopwatch.StartNew(); static void ReportElapsed(string operation) { Console.WriteLine($"{operation} finished. Elapsed: {_init.Elapsed.TotalMilliseconds:0.000} ms."); _init = Stopwatch.StartNew(); } static void Main(string[] args) { ReportElapsed("Initialization"); var hirDoc = JsonDocument.Parse(File.ReadAllText(args[0])); ReportElapsed("Parsing"); var hirCompiler = new HIRCompiler(hirDoc.RootElement); var compiledModule = hirCompiler.Compile(); ReportElapsed("Compile"); var mainKlass = compiledModule.GetType("__global__"); var entry = mainKlass.GetMethod("__main__"); Console.WriteLine( "__main__ returns `{0}`.", entry.Invoke(Activator.CreateInstance(mainKlass), new object[0]) ); ReportElapsed("Run"); } }
31.84375
105
0.652601
[ "Apache-2.0" ]
eliphatfs/typhon
typhon-hir-backend/Program.cs
1,021
C#
using JT808.Protocol.Enums; using JT808.Protocol.Formatters; using JT808.Protocol.MessagePack; using JT808.Protocol.Metadata; using System.Collections.Generic; namespace JT808.Protocol.MessageBody { /// <summary> /// 设置电话本 /// </summary> public class JT808_0x8401 : JT808Bodies, IJT808MessagePackFormatter<JT808_0x8401> { public override ushort MsgId { get; } = 0x8401; /// <summary> /// 设置类型 /// </summary> public JT808SettingTelephoneBook SettingTelephoneBook { get; set; } /// <summary> /// 联系人总数 /// </summary> public byte ContactCount { get; set; } /// <summary> /// 联系人项 /// </summary> public IList<JT808ContactProperty> JT808ContactProperties { get; set; } public JT808_0x8401 Deserialize(ref JT808MessagePackReader reader, IJT808Config config) { JT808_0x8401 jT808_0X8401 = new JT808_0x8401(); jT808_0X8401.SettingTelephoneBook = (JT808SettingTelephoneBook)reader.ReadByte(); jT808_0X8401.ContactCount = reader.ReadByte(); List<JT808ContactProperty> jT808_0X8401s = new List<JT808ContactProperty>(); for (var i = 0; i < jT808_0X8401.ContactCount; i++) { JT808ContactProperty jT808ContactProperty = new JT808ContactProperty(); jT808ContactProperty.TelephoneBookContactType = (JT808TelephoneBookContactType)reader.ReadByte(); jT808ContactProperty.PhoneNumberLength = reader.ReadByte(); jT808ContactProperty.PhoneNumber = reader.ReadString(jT808ContactProperty.PhoneNumberLength); jT808ContactProperty.ContactLength = reader.ReadByte(); jT808ContactProperty.Contact = reader.ReadString(jT808ContactProperty.ContactLength); jT808_0X8401s.Add(jT808ContactProperty); } jT808_0X8401.JT808ContactProperties = jT808_0X8401s; return jT808_0X8401; } public void Serialize(ref JT808MessagePackWriter writer, JT808_0x8401 value, IJT808Config config) { writer.WriteByte((byte)value.SettingTelephoneBook); writer.WriteByte((byte)value.JT808ContactProperties.Count); foreach (var item in value.JT808ContactProperties) { writer.WriteByte((byte)item.TelephoneBookContactType); writer.WriteByte((byte)item.PhoneNumber.Length); writer.WriteString(item.PhoneNumber); writer.WriteByte((byte)item.Contact.Length); writer.WriteString(item.Contact); } } } }
43.225806
113
0.645896
[ "MIT" ]
491134648/JT808
src/JT808.Protocol/MessageBody/JT808_0x8401.cs
2,718
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Puppet.Common.Devices; using Puppet.Common.Events; using Puppet.Common.Notifiers; using Puppet.Common.Services; namespace Puppet.Common.Automation { public abstract class DoorWatcherBase : AutomationBase { public TimeSpan HowLong { get; set; } public bool MakeAnnouncement { get; set; } public bool PushNotification { get; set; } public string NotificationFormat { get; set; } public int NumberOfNotifications { get; set; } public bool NotifyOnClose { get; set; } public INotifier AnnouncementNotifier { get; set; } public INotifier PushNotifier { get; set; } public DoorWatcherBase(HomeAutomationPlatform hub, HubEvent evt) : base(hub, evt) {} protected override async Task Handle() { if (!(PushNotification || MakeAnnouncement)) { return; } if (_evt.IsOpenEvent) { if (NumberOfNotifications < 1) NumberOfNotifications = 1; if (String.IsNullOrEmpty(NotificationFormat)) NotificationFormat = @"{0} has been open {1} minutes."; for (int i = 0; i < NumberOfNotifications; i++) { await WaitForCancellationAsync(HowLong); var textToSend = String.Format(NotificationFormat, _evt.DisplayName, HowLong.TotalMinutes * (i + 1), HowLong.TotalSeconds * (i + 1)); // There's an unused string parameter being passed into String.Format. // That way the deriving class can set the NotificationFormat to mention // either "seconds" or "minutes." if (MakeAnnouncement) { if (AnnouncementNotifier is not null) { await AnnouncementNotifier.SendNotification(textToSend); } else { await _hub.Announce(textToSend); } } if (PushNotification) { if (PushNotifier is not null) { await PushNotifier.SendNotification(textToSend); } else { await _hub.Push(textToSend); } } } } else if (_evt.IsClosedEvent && NotifyOnClose) { var textToSend = $"{_evt.DisplayName} is closed."; if (MakeAnnouncement) await _hub.Announce(textToSend); if (PushNotification) await _hub.Push(textToSend); } } } }
36.901235
117
0.50552
[ "MIT" ]
CamSoper/puppet
Puppet.Common/Automation/DoorWatcherBase.cs
2,991
C#
using System.Data; namespace Jerrycurl.Cqs.Commands.Internal.Compilation { internal delegate void BufferWriter(IDataReader dataReader, FieldBuffer[] buffers); }
23.857143
87
0.802395
[ "MIT" ]
rhodosaur/jerrycurl
src/Mvc/Jerrycurl.Cqs/Commands/Internal/Compilation/BufferWriter.cs
169
C#
using Microsoft.Azure.Devices.Client; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography.X509Certificates; namespace Robin { class Program { static DeviceClient deviceClient; static string deviceID = "Robin"; static void Main(string[] args) { Console.WriteLine($"Simulated device: {deviceID}. Check certificate"); InitCert(); Console.WriteLine("Certificate ok"); deviceClient = DeviceClient.CreateFromConnectionString(ConfigurationManager.AppSettings["connStringTGWVM"], TransportType.Mqtt); Console.WriteLine("Connection established"); SendDeviceToCloudMessagesAsync().Wait(); Console.ReadLine(); } private static async Task SendDeviceToCloudMessagesAsync() { double minTemperature = 20; int messageId = 1; Random rand = new Random(); while (true) { double currentTemperature = Math.Round((minTemperature + rand.NextDouble() * 15), 2); string level = (currentTemperature > 30 ? "critical" : "normal"); var telemetryDataPoint = new { messageId = messageId++, deviceId = deviceID, temperature = currentTemperature, }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Message(Encoding.ASCII.GetBytes(messageString)); message.Properties.Add("level", level); await deviceClient.SendEventAsync(message); Console.WriteLine("{0} > Sending message - level: {1} - {2}", DateTime.Now, level, messageString); await Task.Delay(100); } } private static void InitCert() { X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadWrite); store.Add(new X509Certificate2(X509Certificate2.CreateFromCertFile(ConfigurationManager.AppSettings["certPath"]))); store.Close(); } } }
33.514286
140
0.603154
[ "Apache-2.0" ]
erryB/IoT_simDevices
Robin/Program.cs
2,348
C#
using System; using System.Reflection; using Xunit; namespace Atc.Tests.Extensions.Reflection { public class AssemblyExtensionsTests { [Fact] public void IsAssemblyDebugBuild() { // Act var actual = Assembly.GetExecutingAssembly().IsDebugBuild(); // Assert Assert.True(actual); } [Theory] [InlineData(null, nameof(UnexpectedTypeException))] [InlineData(typeof(AssemblyExtensionsTests), nameof(AssemblyExtensionsTests))] public void GetExportedTypeByName(Type expected, string typeName) { // Arrange var assembly = Assembly.GetExecutingAssembly(); // Act var actual = assembly.GetExportedTypeByName(typeName); // Assert if (expected == null) { Assert.Null(actual); } else { Assert.NotNull(actual); Assert.Equal(expected, actual); } } [Fact] public void GetPrettyName() { // Act var actual = Assembly.GetExecutingAssembly().GetBeautifiedName(); // Assert Assert.NotNull(actual); Assert.Equal("Atc Tests", actual); } } }
25.226415
86
0.529544
[ "MIT" ]
TomMalow/atc
test/Atc.Tests/Extensions/Reflection/AssemblyExtensionsTests.cs
1,339
C#
using System; namespace ProceduralLevel.UnityPlugins.Input.Unity { public class GroupProvider : AListProvider { private AInputProvider m_UsedProvider; public AInputProvider UsedProvider { get { return m_UsedProvider; } } public GroupProvider() { } protected override RawInputState GetState() { float axis = 0f; bool isRealAxis = false; bool isAnyProviderActive = false; m_UsedProvider = null; int count = m_Providers.Count; for(int x = 0; x < count; ++x) { AInputProvider provider = m_Providers[x]; RawInputState data = provider.UpdateState(m_UpdateTick); if(data.IsActive) { isAnyProviderActive = true; m_UsedProvider = provider; if(data.IsRealAxis) { isRealAxis = true; axis = Math.Max(data.Axis, axis); } else if(!isRealAxis) { axis = data.Axis; } } } return new RawInputState(isAnyProviderActive, axis, isRealAxis); } } }
20.9375
72
0.629851
[ "MIT" ]
LukaszKr/UnityPlugins.Input
Unity/Provider/Impl/List/GroupProvider.cs
1,007
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using FluentNHibernate.MappingModel; namespace FluentNHibernate.Conventions.Inspections { public class DiscriminatorInspector : ColumnBasedInspector, IDiscriminatorInspector { private readonly InspectorModelMapper<IDiscriminatorInspector, DiscriminatorMapping> propertyMappings = new InspectorModelMapper<IDiscriminatorInspector, DiscriminatorMapping>(); private readonly DiscriminatorMapping mapping; public DiscriminatorInspector(DiscriminatorMapping mapping) : base(mapping.Columns) { this.mapping = mapping; propertyMappings.Map(x => x.Nullable, "NotNull"); } public bool Insert { get { return mapping.Insert; } } public bool Force { get { return mapping.Force; } } public string Formula { get { return mapping.Formula; } } public TypeReference Type { get { return mapping.Type; } } public Type EntityType { get { return mapping.ContainingEntityType; } } public string StringIdentifierForModel { get { return mapping.Type.Name; } } public IEnumerable<IColumnInspector> Columns { get { return mapping.Columns .Select(x => new ColumnInspector(mapping.ContainingEntityType, x)) .Cast<IColumnInspector>() .ToList(); } } public bool IsSet(Member property) { return mapping.IsSpecified(propertyMappings.Get(property)); } } }
27.850746
187
0.566988
[ "BSD-3-Clause" ]
BrunoJuchli/fluent-nhibernate
src/FluentNHibernate/Conventions/Inspections/DiscriminatorInspector.cs
1,866
C#
using System; using Menu; using Override; using UnityEngine; using ZeoFlow.Pickup.Interfaces; namespace Puzzle { /// <summary> /// <para> PyramidController </para> /// <author> @TeodorHMX1 </author> /// </summary> public class PyramidController : MonoBehaviour, IOnPuzzle { [Header("States Data")] [Range(3, 8)] public int pyramidSides = 4; public PyramidState startSide = PyramidState.Side1; public PyramidState winState = PyramidState.Side1; public int timeLimit = 4; [Header("Details")] [Range(0.5f, 10.0f)] public float rotationSpeed = 1.0f; public Light finishLight; public AudioClip puzzleNoise; public int pyramidOrder; [Header("Pyramid Design")] public GameObject variant1; public GameObject variant2; public GameObject variant3; public PyramidDeign pyramidDeign = PyramidDeign.Variant1; private int _currentProgress; private PyramidState _currentState; private bool _isMoving; private float _rotateByCurrent; private Vector3 _startAngle; private GameObject _parentGameObj; private bool _isParentGameObjNotNull; private PyramidPuzzle _puzzleDetails; private bool _countdownStarted; private int _time; private bool _flashEnabled; /// <summary> /// <para> Start </para> /// <author> @TeodorHMX1 </author> /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> private void Start() { _startAngle = transform.rotation.eulerAngles; finishLight.enabled = false; switch (startSide) { case PyramidState.Side1: RotatePyramid(360 / pyramidSides * 0); break; case PyramidState.Side2: RotatePyramid(360 / pyramidSides * 1); break; case PyramidState.Side3: RotatePyramid(360 / pyramidSides * 2); break; case PyramidState.Side4: RotatePyramid(360 / pyramidSides * 3); break; case PyramidState.Side5: RotatePyramid(360 / pyramidSides * 4); break; case PyramidState.Side6: RotatePyramid(360 / pyramidSides * 5); break; case PyramidState.Side7: RotatePyramid(360 / pyramidSides * 6); break; case PyramidState.Side8: RotatePyramid(360 / pyramidSides * 7); break; } variant1.gameObject.SetActive(false); variant2.gameObject.SetActive(false); variant3.gameObject.SetActive(false); switch (pyramidDeign) { case PyramidDeign.Variant1: variant1.gameObject.SetActive(true); break; case PyramidDeign.Variant2: variant2.gameObject.SetActive(true); break; case PyramidDeign.Variant3: variant3.gameObject.SetActive(true); break; } _currentState = startSide; _parentGameObj = transform.parent.gameObject; _isParentGameObjNotNull = _parentGameObj != null; if (!_isParentGameObjNotNull) return; _puzzleDetails = _parentGameObj.GetComponent<PyramidPuzzle>(); } /// <summary> /// <para> Update </para> /// <author> @TeodorHMX1 </author> /// </summary> private void Update() { if (Pause.IsPaused) { return; } if (!IsWinState() && !_flashEnabled) { finishLight.enabled = false; } if (_countdownStarted) { _time++; if (_time == timeLimit * 60) { _puzzleDetails.Reset(); } } if (!_isMoving) return; if (_currentProgress < 90) { RotatePyramidBy(_rotateByCurrent); } else { _currentProgress = 0; _isMoving = false; CheckState(); if (!IsWinState()) return; switch (_puzzleDetails.pyramidModel) { case PyramidModel.Default: finishLight.enabled = true; break; case PyramidModel.FlashNext: if (pyramidOrder < _puzzleDetails.pyramids.Count) { _puzzleDetails.pyramids[pyramidOrder].EnableLight(); _puzzleDetails.pyramids[pyramidOrder].StartCountdown(); } break; } } } /// <summary> /// <para> ONMovement </para> /// <author> @TeodorHMX1 </author> /// </summary> /// <param name="toRight"></param> public void ONMovement(bool toRight) { if (IsWinState()) return; if (_isMoving) return; _flashEnabled = false; _countdownStarted = false; _isMoving = true; new AudioBuilder() .WithClip(puzzleNoise) .WithName("Pyramid_PuzzleRotation") .WithVolume(SoundVolume.Normal) .Play(); _rotateByCurrent = !toRight ? rotationSpeed : rotationSpeed * -1; } /// <summary> /// <para> ONIsMoving </para> /// <author> @TeodorHMX1 </author> /// </summary> /// <returns param="_isMoving"></returns> public bool ONIsMoving() { return _isMoving; } /// <summary> /// <para> RotatePyramid </para> /// <author> @TeodorHMX1 </author> /// </summary> /// <param name="angle"></param> private void RotatePyramid(int angle) { transform.Rotate(0, 0, angle); } /// <summary> /// <para> RotatePyramidBy </para> /// <author> @TeodorHMX1 </author> /// </summary> /// <param name="angle"></param> private void RotatePyramidBy(float angle) { transform.Rotate(0, 0, angle); _currentProgress++; } /// <summary> /// <para> CheckState </para> /// <author> @TeodorHMX1 </author> /// </summary> private void CheckState() { var currentRotation = transform.rotation.eulerAngles.y; currentRotation = Math.Abs((int) currentRotation) - (int) _startAngle.y; // ReSharper disable once CompareOfFloatsByEqualityOperator if (currentRotation % 90 == 89) { currentRotation += 1; } switch (currentRotation) { case 0: _currentState = PyramidState.Side1; break; case 90: _currentState = PyramidState.Side2; break; case 180: _currentState = PyramidState.Side3; break; case 270: _currentState = PyramidState.Side4; break; } } /// <summary> /// <para> IsWinState </para> /// <author> @TeodorHMX1 </author> /// </summary> /// <returns name="winState"></returns> public bool IsWinState() { if (_isMoving) return false; return winState == _currentState; } /// <summary> /// <para> EnableLight </para> /// <author> @TeodorHMX1 </author> /// </summary> /// <param name="enable"></param> private void EnableLight(bool enable = true) { finishLight.enabled = enable; _flashEnabled = enable; } /// <summary> /// <para> StartCountdown </para> /// <author> @TeodorHMX1 </author> /// </summary> private void StartCountdown() { _countdownStarted = true; _time = 0; } /// <summary> /// <para> Reset </para> /// <author> @TeodorHMX1 </author> /// </summary> public void Reset() { _flashEnabled = false; _countdownStarted = false; _time = 0; finishLight.enabled = false; switch (startSide) { case PyramidState.Side1: RotatePyramid(360 / pyramidSides * 0); break; case PyramidState.Side2: RotatePyramid(360 / pyramidSides * 1); break; case PyramidState.Side3: RotatePyramid(360 / pyramidSides * 2); break; case PyramidState.Side4: RotatePyramid(360 / pyramidSides * 3); break; case PyramidState.Side5: RotatePyramid(360 / pyramidSides * 4); break; case PyramidState.Side6: RotatePyramid(360 / pyramidSides * 5); break; case PyramidState.Side7: RotatePyramid(360 / pyramidSides * 6); break; case PyramidState.Side8: RotatePyramid(360 / pyramidSides * 7); break; default: throw new ArgumentOutOfRangeException(); } _currentState = startSide; } } }
32.571429
84
0.473099
[ "Apache-2.0" ]
TeodorHMX1/descent
Assets/Plugins/Scripts/Puzzle/PyramidController.cs
10,262
C#
using System; using System.Windows.Forms; namespace ArchiveTools { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FrmMain()); } } }
21.5
65
0.572093
[ "MIT" ]
GridProtectionAlliance/openHistorian
Source/Tools/ArchiveTools/Program.cs
432
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SilupostWeb.Data.Entity { public class SystemWebAdminUserRolesModel { public string SystemWebAdminUserRoleId { get; set; } public SystemWebAdminRoleModel SystemWebAdminRole { get; set; } public SystemUserModel SystemUser { get; set; } public SystemRecordManagerModel SystemRecordManager { get; set; } public EntityStatusModel EntityStatus { get; set; } public PageResultsModel PageResult { get; set; } } }
31.263158
73
0.723906
[ "Apache-2.0" ]
erwin-io/Silupost
SilupostWebApp/SilupostWeb.Data/Entity/SystemWebAdminUserRolesModel.cs
596
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 Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Microsoft.EntityFrameworkCore.Metadata { /// <summary> /// Represents a database sequence in the model in a form that /// can be mutated while building the model. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-sequences">Database sequences</see> for more information. /// </remarks> public interface IConventionSequence : IReadOnlySequence, IConventionAnnotatable { /// <summary> /// Gets the <see cref="IConventionModel" /> in which this sequence is defined. /// </summary> new IConventionModel Model { get; } /// <summary> /// Gets the builder that can be used to configure this sequence. /// </summary> /// <exception cref="InvalidOperationException">If the sequence has been removed from the model.</exception> new IConventionSequenceBuilder Builder { get; } /// <summary> /// Gets the configuration source for this <see cref="IConventionSequence" />. /// </summary> /// <returns>The configuration source for <see cref="IConventionSequence" />.</returns> ConfigurationSource GetConfigurationSource(); /// <summary> /// Sets the value at which the sequence will start. /// </summary> /// <param name="startValue">The value at which the sequence will start.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns>The configured value.</returns> long? SetStartValue(long? startValue, bool fromDataAnnotation = false); /// <summary> /// Returns the configuration source for <see cref="IReadOnlySequence.StartValue" />. /// </summary> /// <returns>The configuration source for <see cref="IReadOnlySequence.StartValue" />.</returns> ConfigurationSource? GetStartValueConfigurationSource(); /// <summary> /// Sets the amount incremented to obtain each new value in the sequence. /// </summary> /// <param name="incrementBy">The amount incremented to obtain each new value in the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns>The configured value.</returns> int? SetIncrementBy(int? incrementBy, bool fromDataAnnotation = false); /// <summary> /// Gets the configuration source for <see cref="IReadOnlySequence.IncrementBy" />. /// </summary> /// <returns>The configuration source for <see cref="IReadOnlySequence.IncrementBy" />.</returns> ConfigurationSource? GetIncrementByConfigurationSource(); /// <summary> /// Sets the minimum value supported by the sequence. /// </summary> /// <param name="minValue">The minimum value supported by the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns>The configured value.</returns> long? SetMinValue(long? minValue, bool fromDataAnnotation = false); /// <summary> /// Returns the configuration source for <see cref="IReadOnlySequence.MinValue" />. /// </summary> /// <returns>The configuration source for <see cref="IReadOnlySequence.MinValue" />.</returns> ConfigurationSource? GetMinValueConfigurationSource(); /// <summary> /// Sets the maximum value supported by the sequence. /// </summary> /// <param name="maxValue">The maximum value supported by the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns>The configured value.</returns> long? SetMaxValue(long? maxValue, bool fromDataAnnotation = false); /// <summary> /// Gets the configuration source for <see cref="IReadOnlySequence.MaxValue" />. /// </summary> /// <returns>The configuration source for <see cref="IReadOnlySequence.MaxValue" />.</returns> ConfigurationSource? GetMaxValueConfigurationSource(); /// <summary> /// Sets the <see cref="Type" /> of values returned by the sequence. /// </summary> /// <param name="type">The <see cref="Type" /> of values returned by the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns>The configured value.</returns> Type? SetType(Type? type, bool fromDataAnnotation = false); /// <summary> /// Gets the configuration source for <see cref="IReadOnlySequence.ClrType" />. /// </summary> /// <returns>The configuration source for <see cref="IReadOnlySequence.ClrType" />.</returns> ConfigurationSource? GetTypeConfigurationSource(); /// <summary> /// Sets the <see cref="Type" /> of values returned by the sequence. /// </summary> /// <param name="type">The <see cref="Type" /> of values returned by the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns>The configured value.</returns> [Obsolete("Use SetType")] Type? SetClrType(Type? type, bool fromDataAnnotation = false); /// <summary> /// Gets the configuration source for <see cref="IReadOnlySequence.ClrType" />. /// </summary> /// <returns>The configuration source for <see cref="IReadOnlySequence.ClrType" />.</returns> [Obsolete("Use GetTypeConfigurationSource")] ConfigurationSource? GetClrTypeConfigurationSource(); /// <summary> /// Sets whether the sequence will start again from the beginning when the max value is reached. /// </summary> /// <param name="cyclic"> /// If <see langword="true" />, then the sequence will start again from the beginning when the max value /// is reached. /// </param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns>The configured value.</returns> bool? SetIsCyclic(bool? cyclic, bool fromDataAnnotation = false); /// <summary> /// Gets the configuration source for <see cref="IReadOnlySequence.IsCyclic" />. /// </summary> /// <returns>The configuration source for <see cref="IReadOnlySequence.IsCyclic" />.</returns> ConfigurationSource? GetIsCyclicConfigurationSource(); } }
51.143885
127
0.642003
[ "MIT" ]
KaloyanIT/efcore
src/EFCore.Relational/Metadata/IConventionSequence.cs
7,109
C#
using System; using System.Collections.Generic; using System.Linq; using System.Collections.Concurrent; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Collections; using Speckle.Newtonsoft.Json; using Speckle.Core.Models; using Speckle.Core.Kits; using Speckle.Core.Api; using Speckle.DesktopUI; using Speckle.DesktopUI.Utils; using ProgressReport = Speckle.DesktopUI.Utils.ProgressReport; using Speckle.Core.Transports; using Speckle.ConnectorAutocadCivil.Entry; using Speckle.ConnectorAutocadCivil.Storage; using AcadApp = Autodesk.AutoCAD.ApplicationServices; using AcadDb = Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.Colors; using Stylet; using Autodesk.AutoCAD.DatabaseServices; namespace Speckle.ConnectorAutocadCivil.UI { public partial class ConnectorBindingsAutocad : ConnectorBindings { public Document Doc => Application.DocumentManager.MdiActiveDocument; /// <summary> /// TODO: Any errors thrown should be stored here and passed to the ui state /// </summary> public List<Exception> Exceptions { get; set; } = new List<Exception>(); // AutoCAD API should only be called on the main thread. // Not doing so results in botched conversions for any that require adding objects to Document model space before modifying (eg adding vertices and faces for meshes) // There's no easy way to access main thread from document object, therefore we are creating a control during Connector Bindings constructor (since it's called on main thread) that allows for invoking worker threads on the main thread public System.Windows.Forms.Control Control; public ConnectorBindingsAutocad() : base() { Control = new System.Windows.Forms.Control(); Control.CreateControl(); } public void SetExecutorAndInit() { Application.DocumentManager.DocumentActivated += Application_DocumentActivated; Doc.BeginDocumentClose += Application_DocumentClosed; } #region local streams public override void AddNewStream(StreamState state) { SpeckleStreamManager.AddSpeckleStream(state.Stream.id, JsonConvert.SerializeObject(state)); } public override void RemoveStreamFromFile(string streamId) { SpeckleStreamManager.RemoveSpeckleStream(streamId); } public override void PersistAndUpdateStreamInFile(StreamState state) { SpeckleStreamManager.UpdateSpeckleStream(state.Stream.id, JsonConvert.SerializeObject(state)); } public override List<StreamState> GetStreamsInFile() { List<string> strings = SpeckleStreamManager.GetSpeckleStreams(); return strings.Select(s => JsonConvert.DeserializeObject<StreamState>(s)).ToList(); } #endregion #region boilerplate public override string GetActiveViewName() { return "Entire Document"; // TODO: handle views } public override List<string> GetObjectsInView() // TODO: this returns all visible doc objects. handle views later. { var objs = new List<string>(); using (Transaction tr = Doc.Database.TransactionManager.StartTransaction()) { BlockTableRecord modelSpace = Doc.Database.GetModelSpace(); foreach (ObjectId id in modelSpace) { var dbObj = tr.GetObject(id, OpenMode.ForRead); if (dbObj.Visible()) objs.Add(dbObj.Handle.ToString()); } tr.Commit(); } return objs; } public override string GetHostAppName() => Utils.AutocadAppName.Replace("AutoCAD", "AutoCAD ").Replace("Civil", "Civil 3D "); //hack for ADSK store; public override string GetDocumentId() { string path = HostApplicationServices.Current.FindFile(Doc.Name, Doc.Database, FindFileHint.Default); return Core.Models.Utilities.hashString("X" + path + Doc?.Name, Core.Models.Utilities.HashingFuctions.MD5); // what is the "X" prefix for? } public override string GetDocumentLocation() => AcadDb.HostApplicationServices.Current.FindFile(Doc.Name, Doc.Database, AcadDb.FindFileHint.Default); public override string GetFileName() => Doc?.Name; public override List<string> GetSelectedObjects() { var objs = new List<string>(); if (Doc != null) { PromptSelectionResult selection = Doc.Editor.SelectImplied(); if (selection.Status == PromptStatus.OK) objs = selection.Value.GetHandles(); } return objs; } public override List<ISelectionFilter> GetSelectionFilters() { var layers = new List<string>(); if (Doc != null) { using (Transaction tr = Doc.Database.TransactionManager.StartTransaction()) { LayerTable lyrTbl = tr.GetObject(Doc.Database.LayerTableId, OpenMode.ForRead) as LayerTable; foreach (ObjectId objId in lyrTbl) { LayerTableRecord lyrTblRec = tr.GetObject(objId, OpenMode.ForRead) as LayerTableRecord; layers.Add(lyrTblRec.Name); } tr.Commit(); } } return new List<ISelectionFilter>() { new ListSelectionFilter {Slug="layer", Name = "Layers", Icon = "LayersTriple", Description = "Selects objects based on their layers.", Values = layers }, new AllSelectionFilter {Slug="all", Name = "All", Icon = "CubeScan", Description = "Selects all document objects." } }; } public override void SelectClientObjects(string args) { throw new NotImplementedException(); } private void UpdateProgress(ConcurrentDictionary<string, int> dict, ProgressReport progress) { if (progress == null) { return; } Execute.PostToUIThread(() => { progress.ProgressDict = dict; progress.Value = dict.Values.Last(); }); } #endregion #region receiving public override async Task<StreamState> ReceiveStream(StreamState state) { if (Doc == null) { state.Errors.Add(new Exception($"No Document is open.")); return null; } Exceptions.Clear(); var kit = KitManager.GetDefaultKit(); var converter = kit.LoadConverter(Utils.AutocadAppName); var transport = new ServerTransport(state.Client.Account, state.Stream.id); var stream = await state.Client.StreamGet(state.Stream.id); if (state.CancellationTokenSource.Token.IsCancellationRequested) { return null; } string referencedObject = state.Commit.referencedObject; var commitId = state.Commit.id; var commitMsg = state.Commit.message; //if "latest", always make sure we get the latest commit when the user clicks "receive" if (commitId == "latest") { var res = await state.Client.BranchGet(state.CancellationTokenSource.Token, state.Stream.id, state.Branch.name, 1); var commit = res.commits.items.FirstOrDefault(); commitId = commit.id; commitMsg = commit.message; referencedObject = commit.referencedObject; } var commitObject = await Operations.Receive( referencedObject, state.CancellationTokenSource.Token, transport, onProgressAction: d => UpdateProgress(d, state.Progress), onTotalChildrenCountKnown: num => Execute.PostToUIThread(() => state.Progress.Maximum = num), onErrorAction: (message, exception) => { Exceptions.Add(exception); }, disposeTransports: true ); try { await state.Client.CommitReceived(new CommitReceivedInput { streamId = stream.id, commitId = commitId, message = commitMsg, sourceApplication = Utils.AutocadAppName }); } catch { // Do nothing! } if (Exceptions.Count != 0) { RaiseNotification($"Encountered error: {Exceptions.Last().Message}"); } // invoke conversions on the main thread via control if (Control.InvokeRequired) Control.Invoke(new ConversionDelegate(ConvertCommit), new object[] { commitObject, converter, state, stream, commitId }); else ConvertCommit(commitObject, converter, state, stream, commitId); return state; } delegate void ConversionDelegate(Base commitObject, ISpeckleConverter converter, StreamState state, Stream stream, string id); private void ConvertCommit(Base commitObject, ISpeckleConverter converter, StreamState state, Stream stream, string id) { using (DocumentLock l = Doc.LockDocument()) { using (Transaction tr = Doc.Database.TransactionManager.StartTransaction()) { // set the context doc for conversion - this is set inside the transaction loop because the converter retrieves this transaction for all db editing when the context doc is set! converter.SetContextDocument(Doc); // keep track of conversion progress here var conversionProgressDict = new ConcurrentDictionary<string, int>(); conversionProgressDict["Conversion"] = 0; Execute.PostToUIThread(() => state.Progress.Maximum = state.SelectedObjectIds.Count()); Action updateProgressAction = () => { conversionProgressDict["Conversion"]++; UpdateProgress(conversionProgressDict, state.Progress); }; // keep track of any layer name changes for notification here bool changedLayerNames = false; // create a commit layer prefix: all nested layers will be concatenated with this var commitPrefix = DesktopUI.Utils.Formatting.CommitInfo(stream.name, state.Branch.name, id); // give converter a way to access the commit info if (Doc.UserData.ContainsKey("commit")) Doc.UserData["commit"] = commitPrefix; else Doc.UserData.Add("commit", commitPrefix); // delete existing commit layers and block instances try { DeleteBlocksWithPrefix(commitPrefix, tr); DeleteLayersWithPrefix(commitPrefix, tr); } catch { RaiseNotification($"could not remove existing layers or blocks starting with {commitPrefix} before importing new geometry."); state.Errors.Add(new Exception($"could not remove existing layers or blocks starting with {commitPrefix} before importing new geometry.")); } // flatten the commit object to retrieve children objs int count = 0; var commitObjs = FlattenCommitObject(commitObject, converter, commitPrefix, state, ref count); // TODO: create dictionaries here for linetype and layer linewidth // More efficient this way than doing this per object var lineTypeDictionary = new Dictionary<string, ObjectId>(); var lineTypeTable = (LinetypeTable)tr.GetObject(Doc.Database.LinetypeTableId, OpenMode.ForRead); foreach (ObjectId lineTypeId in lineTypeTable) { var linetype = (LinetypeTableRecord)tr.GetObject(lineTypeId, OpenMode.ForRead); lineTypeDictionary.Add(linetype.Name, lineTypeId); } foreach (var commitObj in commitObjs) { // create the object's bake layer if it doesn't already exist (Base obj, string layerName) = commitObj; var converted = converter.ConvertToNative(obj); var convertedEntity = converted as Entity; if (convertedEntity != null) { if (GetOrMakeLayer(layerName, tr, out string cleanName)) { // record if layer name has been modified if (!cleanName.Equals(layerName)) changedLayerNames = true; var appended = convertedEntity.Append(cleanName); if (appended.IsValid) { // handle display Base display = obj[@"displayStyle"] as Base; if (display != null) { var color = display["color"] as int?; var lineType = display["linetype"] as string; var lineWidth = display["lineweight"] as double?; if (color != null) { var systemColor = System.Drawing.Color.FromArgb((int)color); convertedEntity.Color = Color.FromRgb(systemColor.R, systemColor.G, systemColor.B); convertedEntity.Transparency = new Transparency(systemColor.A); } if (lineWidth != null) { convertedEntity.LineWeight = Utils.GetLineWeight((double)lineWidth); } if (lineType != null) { if (lineTypeDictionary.ContainsKey(lineType)) { convertedEntity.LinetypeId = lineTypeDictionary[lineType]; } } } tr.TransactionManager.QueueForGraphicsFlush(); } else { state.Errors.Add(new Exception($"Failed to bake object {obj.id} of type {obj.speckle_type}.")); } } else state.Errors.Add(new Exception($"Could not create layer {layerName} to bake objects into.")); } else if (converted == null) { state.Errors.Add(new Exception($"Failed to convert object {obj.id} of type {obj.speckle_type}.")); } } // raise any warnings from layer name modification if (changedLayerNames) state.Errors.Add(new Exception($"Layer names were modified: one or more layers contained invalid characters {Utils.invalidChars}")); // remove commit info from doc userdata Doc.UserData.Remove("commit"); tr.Commit(); } } } // Recurses through the commit object and flattens it. Returns list of Base objects with their bake layers private List<Tuple<Base, string>> FlattenCommitObject(object obj, ISpeckleConverter converter, string layer, StreamState state, ref int count, bool foundConvertibleMember = false) { var objects = new List<Tuple<Base, string>>(); if (obj is Base @base) { if (converter.CanConvertToNative(@base)) { objects.Add(new Tuple<Base, string>(@base, layer)); return objects; } else { int totalMembers = @base.GetDynamicMembers().Count(); foreach (var prop in @base.GetDynamicMembers()) { count++; // get bake layer name string objLayerName = prop.StartsWith("@") ? prop.Remove(0, 1) : prop; string acLayerName = $"{layer}${objLayerName}"; var nestedObjects = FlattenCommitObject(@base[prop], converter, acLayerName, state, ref count, foundConvertibleMember); if (nestedObjects.Count > 0) { objects.AddRange(nestedObjects); foundConvertibleMember = true; } } if (!foundConvertibleMember && count == totalMembers) // this was an unsupported geo state.Errors.Add(new Exception($"Receiving {@base.speckle_type} objects is not supported. Object {@base.id} not baked.")); return objects; } } if (obj is List<object> list) { count = 0; foreach (var listObj in list) objects.AddRange(FlattenCommitObject(listObj, converter, layer, state, ref count)); return objects; } if (obj is IDictionary dict) { count = 0; foreach (DictionaryEntry kvp in dict) objects.AddRange(FlattenCommitObject(kvp.Value, converter, layer, state, ref count)); return objects; } return objects; } private void DeleteLayersWithPrefix(string prefix, AcadDb.Transaction tr) { // Open the Layer table for read var lyrTbl = (AcadDb.LayerTable)tr.GetObject(Doc.Database.LayerTableId, AcadDb.OpenMode.ForRead); foreach (AcadDb.ObjectId layerId in lyrTbl) { AcadDb.LayerTableRecord layer = (AcadDb.LayerTableRecord)tr.GetObject(layerId, AcadDb.OpenMode.ForRead); string layerName = layer.Name; if (layerName.StartsWith(prefix)) { layer.UpgradeOpen(); // cannot delete current layer: swap current layer to default layer "0" if current layer is to be deleted if (Doc.Database.Clayer == layerId) { var defaultLayerID = lyrTbl["0"]; Doc.Database.Clayer = defaultLayerID; } layer.IsLocked = false; // delete all objects on this layer // TODO: this is ugly! is there a better way to delete layer objs instead of looping through each one? var bt = (AcadDb.BlockTable)tr.GetObject(Doc.Database.BlockTableId, AcadDb.OpenMode.ForRead); foreach (var btId in bt) { var block = (AcadDb.BlockTableRecord)tr.GetObject(btId, AcadDb.OpenMode.ForRead); foreach (var entId in block) { var ent = (AcadDb.Entity)tr.GetObject(entId, AcadDb.OpenMode.ForRead); if (ent.Layer == layerName) { ent.UpgradeOpen(); ent.Erase(); } } } layer.Erase(); } } } private void DeleteBlocksWithPrefix(string prefix, Transaction tr) { BlockTable blockTable = tr.GetObject(Doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable; foreach (ObjectId blockId in blockTable) { BlockTableRecord block = (BlockTableRecord)tr.GetObject(blockId, OpenMode.ForRead); if (block.Name.StartsWith(prefix)) { block.UpgradeOpen(); block.Erase(); } } } private bool GetOrMakeLayer(string layerName, AcadDb.Transaction tr, out string cleanName) { cleanName = Utils.RemoveInvalidChars(layerName); try { AcadDb.LayerTable lyrTbl = tr.GetObject(Doc.Database.LayerTableId, AcadDb.OpenMode.ForRead) as AcadDb.LayerTable; if (lyrTbl.Has(cleanName)) { return true; } else { lyrTbl.UpgradeOpen(); var _layer = new AcadDb.LayerTableRecord(); // Assign the layer properties _layer.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByColor, 7); // white _layer.Name = cleanName; // Append the new layer to the layer table and the transaction lyrTbl.Add(_layer); tr.AddNewlyCreatedDBObject(_layer, true); } } catch { return false; } return true; } #endregion #region sending public override async Task<StreamState> SendStream(StreamState state) { var kit = KitManager.GetDefaultKit(); var converter = kit.LoadConverter(Utils.AutocadAppName); var streamId = state.Stream.id; var client = state.Client; if (state.Filter != null) { state.SelectedObjectIds = GetObjectsFromFilter(state.Filter, converter); } // remove deleted object ids var deletedElements = new List<string>(); foreach (var handle in state.SelectedObjectIds) if (Doc.Database.TryGetObjectId(Utils.GetHandle(handle), out AcadDb.ObjectId id)) if (id.IsErased || id.IsNull) deletedElements.Add(handle); state.SelectedObjectIds = state.SelectedObjectIds.Where(o => !deletedElements.Contains(o)).ToList(); if (state.SelectedObjectIds.Count == 0) { RaiseNotification("Zero objects selected; send stopped. Please select some objects, or check that your filter can actually select something."); return state; } var commitObj = new Base(); /* Deprecated until we decide whether or not commit objs need units. If so, should add UnitsToSpeckle conversion method to connector var units = Units.GetUnitsFromString(Doc.Database.Insunits.ToString()); commitObj["units"] = units; */ var conversionProgressDict = new ConcurrentDictionary<string, int>(); conversionProgressDict["Conversion"] = 0; Execute.PostToUIThread(() => state.Progress.Maximum = state.SelectedObjectIds.Count()); int convertedCount = 0; bool renamedlayers = false; using (Transaction tr = Doc.Database.TransactionManager.StartTransaction()) { converter.SetContextDocument(Doc); // set context doc here to capture transaction prop foreach (var autocadObjectHandle in state.SelectedObjectIds) { if (state.CancellationTokenSource.Token.IsCancellationRequested) { return null; } // get the db object from id AcadDb.Handle hn = Utils.GetHandle(autocadObjectHandle); AcadDb.DBObject obj = hn.GetObject(out string type, out string layer); if (obj == null) { state.Errors.Add(new Exception($"Failed to find local object ${autocadObjectHandle}.")); continue; } if (!converter.CanConvertToSpeckle(obj)) { state.Errors.Add(new Exception($"Objects of type ${type} are not supported")); continue; } // convert obj // try catch to prevent memory access violation crash in case a conversion goes wrong Base converted = null; string containerName = string.Empty; try { converted = converter.ConvertToSpeckle(obj); if (converted == null) { state.Errors.Add(new Exception($"Failed to convert object ${autocadObjectHandle} of type ${type}.")); continue; } } catch { state.Errors.Add(new Exception($"Failed to convert object {autocadObjectHandle} of type {type}.")); continue; } /* TODO: adding the extension dictionary / xdata per object foreach (var key in obj.ExtensionDictionary) { converted[key] = obj.ExtensionDictionary.GetUserString(key); } */ if (obj is BlockReference) containerName = "Blocks"; else { // remove invalid chars from layer name string cleanLayerName = Utils.RemoveInvalidDynamicPropChars(layer); containerName = cleanLayerName; if (!cleanLayerName.Equals(layer)) renamedlayers = true; } if (commitObj[$"@{containerName}"] == null) commitObj[$"@{containerName}"] = new List<Base>(); ((List<Base>)commitObj[$"@{containerName}"]).Add(converted); conversionProgressDict["Conversion"]++; UpdateProgress(conversionProgressDict, state.Progress); converted.applicationId = autocadObjectHandle; convertedCount++; } tr.Commit(); } if (renamedlayers) RaiseNotification("Replaced illegal chars ./ with - in one or more layer names."); if (state.CancellationTokenSource.Token.IsCancellationRequested) { return null; } Execute.PostToUIThread(() => state.Progress.Maximum = convertedCount); var transports = new List<ITransport>() { new ServerTransport(client.Account, streamId) }; var commitObjId = await Operations.Send( commitObj, state.CancellationTokenSource.Token, transports, onProgressAction: dict => UpdateProgress(dict, state.Progress), onErrorAction: (err, exception) => { Exceptions.Add(exception); }, disposeTransports: true ); if (Exceptions.Count != 0) { RaiseNotification($"Failed to send: \n {Exceptions.Last().Message}"); return null; } if (convertedCount > 0) { var actualCommit = new CommitCreateInput { streamId = streamId, objectId = commitObjId, branchName = state.Branch.name, message = state.CommitMessage != null ? state.CommitMessage : $"Pushed {convertedCount} elements from {Utils.AppName}.", sourceApplication = Utils.AutocadAppName }; if (state.PreviousCommitId != null) { actualCommit.parents = new List<string>() { state.PreviousCommitId }; } try { var commitId = await client.CommitCreate(actualCommit); await state.RefreshStream(); state.PreviousCommitId = commitId; PersistAndUpdateStreamInFile(state); RaiseNotification($"{convertedCount} objects sent to {state.Stream.name}."); } catch (Exception e) { Globals.Notify($"Failed to create commit.\n{e.Message}"); state.Errors.Add(e); } } else { Globals.Notify($"Did not create commit: no objects could be converted."); } return state; } private List<string> GetObjectsFromFilter(ISelectionFilter filter, ISpeckleConverter converter) { switch (filter.Slug) { case "all": return Doc.ConvertibleObjects(converter); case "layer": var layerObjs = new List<string>(); foreach (var layerName in filter.Selection) { AcadDb.TypedValue[] layerType = new AcadDb.TypedValue[1] { new AcadDb.TypedValue((int)AcadDb.DxfCode.LayerName, layerName) }; PromptSelectionResult prompt = Doc.Editor.SelectAll(new SelectionFilter(layerType)); if (prompt.Status == PromptStatus.OK) layerObjs.AddRange(prompt.Value.GetHandles()); } return layerObjs; default: RaiseNotification("Filter type is not supported in this app. Why did the developer implement it in the first place?"); return new List<string>(); } } #endregion #region events private void Application_DocumentClosed(object sender, DocumentBeginCloseEventArgs e) { // Triggered just after a request is received to close a drawing. if (Doc != null) return; SpeckleAutocadCommand.Bootstrapper.Application.MainWindow.Hide(); var appEvent = new ApplicationEvent() { Type = ApplicationEvent.EventType.DocumentClosed }; NotifyUi(appEvent); } private void Application_DocumentActivated(object sender, DocumentCollectionEventArgs e) { // Triggered when a document window is activated. This will happen automatically if a document is newly created or opened. var appEvent = new ApplicationEvent() { Type = ApplicationEvent.EventType.DocumentOpened, DynamicInfo = GetStreamsInFile() }; NotifyUi(appEvent); } #endregion } }
36.006596
238
0.623933
[ "Apache-2.0" ]
bimgeek/speckle-sharp
ConnectorAutocadCivil/ConnectorAutocadCivil/UI/ConnectorBindingsAutocadCivil.cs
27,295
C#
namespace gov.sandia.sld.common.requestresponse { /// <summary> /// Used when doing debugging testing so we can simulate a SMART HD failure-is-predicted. /// </summary> //public class SMARTFailureRequest : Request //{ // public bool FailureIsPredicted { get; set; } // public SMARTFailureRequest(string name) // : base(name) // { // FailureIsPredicted = false; // } //} }
26.352941
93
0.587054
[ "MIT" ]
gaybro8777/common
src/RequestResponseLib/SMARTFailureRequest.cs
450
C#
using Application.Interfaces.Repositories; using Domain.Entities; using Infrastructure.Persistence.Contexts; using Infrastructure.Persistence.Repository; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using System.Linq; using Microsoft.Data.SqlClient; namespace Infrastructure.Persistence.Repositories { public class NcmRepositoryAysnc : GenericRepositoryAsync<customermaster>, INcmRepositoryAysnc { private readonly ApplicationDbContext _dbContext; public NcmRepositoryAysnc(ApplicationDbContext dbContext) : base(dbContext) { _dbContext = dbContext; } public async Task<ddlncmreport> getddlistreport(string region,string location,string customer) { ddlncmreport ddl = new ddlncmreport(); var regionlist = (from e in _dbContext.regionmast select new regionmast { regioncode = e.regioncode, regionname = e.regionname }).ToList(); ddl.lstregionmast = regionlist; var customerlist = (from e in _dbContext.customermaster select new customermaster { customercode = e.customercode, customername = e.customername }).ToList(); ddl.lstcustomer = customerlist; if (!string.IsNullOrEmpty(region)) { var locationlist = (from a in _dbContext.locationmast where a.regioncode == region select new locationmast { locationcode = a.locationcode, locationname = a.locationname }).ToList(); ddl.lstlocationmast = locationlist; } var hublocationlist = (from a in _dbContext.hublocationmast where a.hublocationcode == "1001" select new hublocationmast { hublocationcode = a.hublocationcode, hublocationname = a.hublocationname }).ToList(); ddl.lsthublocationmast = hublocationlist; if (!string.IsNullOrEmpty(location) && !string.IsNullOrEmpty(customer)) { var crnlist = (from a in _dbContext.ClientCustMaster where a.locationcode == location && a.customercode == customer select new ClientCustMaster { clientcustcode = a.clientcustcode, clientcustname = a.clientcustname }).ToList(); ddl.lstcrn = crnlist; } var m = await Task.Run(() => ddl); return m; } public virtual async Task<List<ncmreportoutput>> getNcmReport(string region, string location, string customer, string fromdate, string todate,string scrn,string reporttype) { if (customer==null) { customer = "undefined"; } if (location == null) { location = "undefined"; } var customerparam = new SqlParameter("@customer", customer); var locationparam = new SqlParameter("@location", location); var fromdateparam = new SqlParameter("@fromdate", fromdate); var todateparam = new SqlParameter("@todate", todate); var type = new SqlParameter("@type", reporttype); var crn = new SqlParameter("@crn", scrn); var lstncmreportoutput = _dbContext .ncmreportoutput .FromSqlRaw("exec sp_ncmcostingreport @customer, @location,@fromdate,@todate,@type,@crn", customerparam, locationparam, fromdateparam, todateparam, type, crn) .ToList(); var m = await Task.Run(() => lstncmreportoutput); return m.ToList(); } public virtual async Task<List<ncmreportoutputsum>> getNcmReportSum(string region, string location, string customer, string fromdate, string todate, string scrn, string reporttype) { if (customer == null) { customer = "undefined"; } if (location == null) { location = "undefined"; } var customerparam = new SqlParameter("@customer", customer); var locationparam = new SqlParameter("@location", location); var fromdateparam = new SqlParameter("@fromdate", fromdate); var todateparam = new SqlParameter("@todate", todate); var type = new SqlParameter("@type", reporttype); var crn = new SqlParameter("@crn", scrn); var lstncmreportoutput = _dbContext .ncmreportoutputsum .FromSqlRaw("exec sp_ncmcostingreport @customer, @location,@fromdate,@todate,@type,@crn", customerparam, locationparam, fromdateparam, todateparam, type, crn) .ToList(); var m = await Task.Run(() => lstncmreportoutput); return m.ToList(); } public virtual async Task<List<PartnerBankRates>> GetPartnerBank() { var lstPartnerBankRates = _dbContext .PartnerBankRates .FromSqlRaw("exec sp_getncmaccountrates") .ToList(); var m = await Task.Run(() => lstPartnerBankRates); return m.ToList(); } public void updatePartnerBankRates(List<CustomerBranchMaster> objCustomerBranchMaster) { foreach (CustomerBranchMaster tmptilist in objCustomerBranchMaster) { CustomerBranchMaster tc = (from c in _dbContext.CustomerBranchMaster where c.customerbranchcode == tmptilist.customerbranchcode && c.customercode == tmptilist.customercode select c).FirstOrDefault(); if (tmptilist.PartnerBankRate > 0) { tc.PartnerBankRate = tmptilist.PartnerBankRate; _dbContext.Entry(tc).State = EntityState.Modified; } } } /* public virtual async Task<List<customermaster>> GetCustomer() { var tc = (from a in _dbContext.customermaster select new customermaster { customercode = a.customercode, customername = a.customername, ncmbillingrate = a.ncmbillingrate }).ToList(); var m = await Task.Run(() => tc); return m.ToList(); } */ public virtual async Task<List<ncmbillingrate>> GetCustomer() { // var tc = (from a in _dbContext.ClientCustMaster join c in _dbContext.customermaster on a.customercode equals c.customercode join r in _dbContext.regionmast on a.regioncode equals r.regioncode join l in _dbContext.locationmast on a.locationcode equals l.locationcode join b in _dbContext.clientcustbankdetails on a.clientcustcode equals b.clientcustcode where b.depositiontype == "NCM" && a.enddate == null select new ncmbillingrate { clientcustcode = a.clientcustcode, clientcustname = a.clientcustname, customername = c.customername, regionname = r.regionname, locationname =l.locationname, billingrate = a.billingrate }).ToList(); var m = await Task.Run(() => tc); return m.ToList(); } public void updateCustomerRates(List<customermaster> objcustomer) { foreach (customermaster tmptilist in objcustomer) { ClientCustMaster tc = (from c in _dbContext.ClientCustMaster where c.clientcustcode == tmptilist.customercode select c).FirstOrDefault(); if (tmptilist.ncmbillingrate>0) { tc.billingrate = tmptilist.ncmbillingrate; _dbContext.Entry(tc).State = EntityState.Modified; } } //_dbContext.SaveChangesAsync(); } } }
38.316872
188
0.511868
[ "MIT" ]
arvindgawas/rcmconvapi
Infrastructure.Persistence/Repositories/NcmRepositoryAysnc.cs
9,313
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace HoloToolkit.Unity { public class UAudioProfiler : EditorWindow { private int currentFrame = 0; private List<ProfilerEvent[]> eventTimeline; private Vector2 scrollOffset = new Vector2(); private const int MaxFrames = 300; private class ProfilerEvent { public string EventName = ""; public string EmitterName = ""; public string BusName = ""; } [MenuItem("HoloToolkit/UAudioTools/Profiler", false, 200)] static void ShowEditor() { UAudioProfiler profilerWindow = GetWindow<UAudioProfiler>(); if (profilerWindow.eventTimeline == null) { profilerWindow.currentFrame = 0; profilerWindow.eventTimeline = new List<ProfilerEvent[]>(); } profilerWindow.Show(); } // Only update the currently-playing events 10 times a second - we don't need millisecond-accurate profiling private void OnInspectorUpdate() { if (!EditorApplication.isPlaying) { return; } ProfilerEvent[] currentEvents = new ProfilerEvent[0]; if (this.eventTimeline == null) { this.eventTimeline = new List<ProfilerEvent[]>(); } if (UAudioManager.Instance != null && !EditorApplication.isPaused) { CollectProfilerEvents(currentEvents); } Repaint(); } // Populate an array of the active events, and add it to the timeline list of all captured audio frames. private void CollectProfilerEvents(ProfilerEvent[] currentEvents) { List<ActiveEvent> activeEvents = UAudioManager.Instance.ProfilerEvents; currentEvents = new ProfilerEvent[activeEvents.Count]; for (int i = 0; i < currentEvents.Length; i++) { ActiveEvent currentEvent = activeEvents[i]; ProfilerEvent tempEvent = new ProfilerEvent(); tempEvent.EventName = currentEvent.audioEvent.name; tempEvent.EmitterName = currentEvent.AudioEmitter.name; // The bus might be null, Unity defaults to Editor-hidden master bus. if (currentEvent.audioEvent.bus == null) { tempEvent.BusName = "-MasterBus-"; } else { tempEvent.BusName = currentEvent.audioEvent.bus.name; } currentEvents[i] = tempEvent; } this.eventTimeline.Add(currentEvents); // Trim the first event if we have exceeded the maximum stored frames. if (this.eventTimeline.Count > MaxFrames) { this.eventTimeline.RemoveAt(0); } this.currentFrame = this.eventTimeline.Count - 1; } // Draw the profiler window. private void OnGUI() { if (!EditorApplication.isPlaying) { EditorGUILayoutExtensions.Label("Profiler only active in play mode!"); return; } //Fix null reference exception when launching with profiler is open if(eventTimeline!=null) { this.currentFrame = EditorGUILayout.IntSlider(this.currentFrame, 0, this.eventTimeline.Count - 1); scrollOffset = EditorGUILayout.BeginScrollView(scrollOffset); if (this.eventTimeline.Count > this.currentFrame) { for (int i = 0; i < this.eventTimeline[this.currentFrame].Length; i++) { DrawEventButton(this.eventTimeline[this.currentFrame][i], i); } } EditorGUILayout.EndScrollView(); } } private void DrawEventButton(ProfilerEvent currentEvent, int id) { EditorGUILayout.SelectableLabel(currentEvent.EventName + "-->(" + currentEvent.EmitterName + ")-->(" + currentEvent.BusName + ")"); } } }
35.531746
143
0.559303
[ "MIT" ]
AllBecomesGood/Share-UpdateHolograms
ShareAndKeepSynced/Assets/HoloToolKit/SpatialSound/Scripts/UAudioManager/Editor/UAudioProfiler.cs
4,479
C#
namespace XSerialization { /// <summary> /// Provides an interface for all XSerializationAttribute /// TOCHECK : Gathers all XSerialization attributes for them to be find easier /// </summary> public interface IXSerializationAttribute { } }
24.545455
82
0.688889
[ "MIT" ]
mastertnt/XRay
XSerialization/IXSerializationAttribute.cs
272
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IMethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IDirectoryObjectGetUserOwnedObjectsRequestBuilder. /// </summary> public partial interface IDirectoryObjectGetUserOwnedObjectsRequestBuilder : IBaseRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> IDirectoryObjectGetUserOwnedObjectsRequest Request(IEnumerable<Option> options = null); } }
38.448276
153
0.599103
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IDirectoryObjectGetUserOwnedObjectsRequestBuilder.cs
1,115
C#
using System; using System.Drawing; using System.IO; using System.Net.Sockets; using System.Windows.Forms; using Server; using VenomRAT_HVNC.Server.Connection; using VenomRAT_HVNC.Server.Helper; namespace VenomRAT_HVNC.Server.Forms { public partial class FormDownloadFile : Form { public Form1 F { get; set; } internal Clients Client { get; set; } public FormDownloadFile() { this.InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { if (this.FileSize >= 2147483647L) { this.timer1.Stop(); MessageBox.Show("Don't support files larger than 2GB."); base.Dispose(); return; } if (!this.IsUpload) { this.labelsize.Text = Methods.BytesToString(this.FileSize) + " \\ " + Methods.BytesToString(this.Client.BytesRecevied); if (this.Client.BytesRecevied >= this.FileSize) { this.labelsize.Text = "Downloaded"; this.labelsize.ForeColor = Color.Green; this.timer1.Stop(); return; } } else { this.labelsize.Text = Methods.BytesToString(this.FileSize) + " \\ " + Methods.BytesToString(this.BytesSent); if (this.BytesSent >= this.FileSize) { this.labelsize.Text = "Uploaded"; this.labelsize.ForeColor = Color.Green; this.timer1.Stop(); } } } private void SocketDownload_FormClosed(object sender, FormClosedEventArgs e) { try { Clients client = this.Client; if (client != null) { client.Disconnected(); } Timer timer = this.timer1; if (timer != null) { timer.Dispose(); } } catch { } } public void Send(object obj) { object sendSync = this.Client.SendSync; lock (sendSync) { try { this.IsUpload = true; byte[] array = (byte[])obj; byte[] bytes = BitConverter.GetBytes(array.Length); this.Client.TcpClient.Poll(-1, SelectMode.SelectWrite); this.Client.SslClient.Write(bytes, 0, bytes.Length); using (MemoryStream memoryStream = new MemoryStream(array)) { memoryStream.Position = 0L; byte[] array2 = new byte[50000]; int num; while ((num = memoryStream.Read(array2, 0, array2.Length)) > 0) { this.Client.TcpClient.Poll(-1, SelectMode.SelectWrite); this.Client.SslClient.Write(array2, 0, num); this.BytesSent += (long)num; } } Program.form1.BeginInvoke(new MethodInvoker(delegate () { base.Close(); })); } catch { Clients client = this.Client; if (client != null) { client.Disconnected(); } Program.form1.BeginInvoke(new MethodInvoker(delegate () { this.labelsize.Text = "Error"; this.labelsize.ForeColor = Color.Red; })); } } } public long FileSize; private long BytesSent; public string FullFileName; public string ClientFullFileName; private bool IsUpload; public string DirPath; } }
31.578947
135
0.441905
[ "Unlicense" ]
GitPlaya/Venom5-HVNC-Rat
VenomRAT_HVNC/Server/Forms/FormDownloadFile.cs
4,200
C#
// <auto-generated /> using System; using AccountManager.Models.Contexts; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace AccountManager.Migrations { [DbContext(typeof(AccountContext))] partial class AccountContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.10") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("AccountManager.Models.ExpenseItem", b => { b.Property<int>("ItemId") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<decimal>("Amount") .HasColumnType("decimal(10, 2)"); b.Property<string>("Category") .IsRequired() .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<DateTime>("ExpenseDate") .HasColumnType("datetime(6)"); b.Property<string>("ItemName") .IsRequired() .HasColumnType("longtext CHARACTER SET utf8mb4"); b.HasKey("ItemId"); b.ToTable("ExpenseItems"); }); modelBuilder.Entity("AccountManager.Models.OnlineAccount", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasColumnType("varchar(100) CHARACTER SET utf8mb4") .HasMaxLength(100); b.Property<string>("Notes") .HasColumnType("varchar(500) CHARACTER SET utf8mb4") .HasMaxLength(500); b.Property<string>("Password") .IsRequired() .HasColumnType("varchar(50) CHARACTER SET utf8mb4") .HasMaxLength(50); b.Property<string>("UserId") .IsRequired() .HasColumnType("varchar(50) CHARACTER SET utf8mb4") .HasMaxLength(50); b.HasKey("Id"); b.ToTable("OnlineAccounts"); }); #pragma warning restore 612, 618 } } }
34.769231
76
0.496313
[ "MIT" ]
imdanix007/Account-Manager
Migrations/AccountContextModelSnapshot.cs
2,714
C#
using CadEditor; using System; //css_include shared_settings/BlockUtils.cs; //css_include shared_settings/SharedUtils.cs; public class Data { public OffsetRec getScreensOffset() { return new OffsetRec(0x9610, 4, 16*16, 16, 16); } public bool isBigBlockEditorEnabled() { return false; } public bool isBlockEditorEnabled() { return true; } public bool isEnemyEditorEnabled() { return false; } public GetVideoPageAddrFunc getVideoPageAddrFunc() { return SharedUtils.fakeVideoAddr(); } public GetVideoChunkFunc getVideoChunkFunc() { return SharedUtils.getVideoChunk(new[] {"chr2-2.bin"}); } public SetVideoChunkFunc setVideoChunkFunc() { return null; } public bool isBuildScreenFromSmallBlocks() { return true; } public OffsetRec getBlocksOffset() { return new OffsetRec(0x9a10, 1 , 0x1000); } public int getBlocksCount() { return 256; } public int getBigBlocksCount() { return 256; } public GetBlocksFunc getBlocksFunc() { return BlockUtils.getBlocksFromAlignedArrays;} public SetBlocksFunc setBlocksFunc() { return BlockUtils.setBlocksToAlignedArrays;} public GetPalFunc getPalFunc() { return SharedUtils.readPalFromBin(new[] {"pal2-2.bin"}); } public SetPalFunc setPalFunc() { return null;} }
49.259259
113
0.706015
[ "MIT" ]
spiiin/CadEditor
CadEditor/settings_nes/final_fight_3_unl/Settings_FinalFight3_NES-2-2.cs
1,330
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.ObjectModel; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Editor.Razor; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Projection; using Moq; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.Razor { public class DefaultVisualStudioWorkspaceAccessorTest { private static readonly LiveShareWorkspaceProvider NoLiveShare = null; [Fact] public void TryGetWorkspace_PrioritizesLiveShareWhenResolvingWorkspaces() { // Arrange var expectedWorkspace = TestWorkspace.Create(); var liveShareWorkspaceProvider = new Mock<LiveShareWorkspaceProvider>(); liveShareWorkspaceProvider.Setup(provider => provider.TryGetWorkspace(It.IsAny<ITextBuffer>(), out expectedWorkspace)) .Returns(true); var workspaceAccessor = new TestWorkspaceAccessor(canGetWorkspaceFromProjectionBuffer: true, canGetWorkspaceFromHostProject: true, liveShareWorkspaceProvider.Object); var textBuffer = Mock.Of<ITextBuffer>(); // Act var result = workspaceAccessor.TryGetWorkspace(textBuffer, out var workspace); // Assert Assert.True(result); Assert.Same(expectedWorkspace, workspace); } [Fact] public void TryGetWorkspace_CanGetWorkspaceFromProjectionBuffersOnly() { // Arrange var textBuffer = Mock.Of<ITextBuffer>(); var workspaceAccessor = new TestWorkspaceAccessor(true, false); // Act var result = workspaceAccessor.TryGetWorkspace(textBuffer, out var workspace); // Assert Assert.True(result); } [Fact] public void TryGetWorkspace_CanGetWorkspaceFromBuffersInHierarchyOnly() { // Arrange var textBuffer = Mock.Of<ITextBuffer>(); var workspaceAccessor = new TestWorkspaceAccessor(false, true); // Act var result = workspaceAccessor.TryGetWorkspace(textBuffer, out var workspace); // Assert Assert.True(result); } [Fact] public void TryGetWorkspace_CanGetWorkspaceFromBuffersInHierarchyOrProjectionBuffers() { // Arrange var textBuffer = Mock.Of<ITextBuffer>(); var workspaceAccessor = new TestWorkspaceAccessor(true, true); // Act var result = workspaceAccessor.TryGetWorkspace(textBuffer, out var workspace); // Assert Assert.True(result); } [Fact] public void TryGetWorkspaceFromLiveShare_NoLiveShareProvider_ReturnsFalse() { // Arrange var workspaceAccessor = new DefaultVisualStudioWorkspaceAccessor(Mock.Of<IBufferGraphFactoryService>(), Mock.Of<TextBufferProjectService>(), TestWorkspace.Create(), NoLiveShare); var textBuffer = Mock.Of<ITextBuffer>(); // Act var result = workspaceAccessor.TryGetWorkspaceFromLiveShare(textBuffer, out var workspace); // Assert Assert.False(result); } [Fact] public void TryGetWorkspaceFromLiveShare_CanNotFindWorkspace_ReturnsFalse() { // Arrange Workspace nullWorkspace = null; var liveShareWorkspaceProvider = new Mock<LiveShareWorkspaceProvider>(); liveShareWorkspaceProvider.Setup(provider => provider.TryGetWorkspace(It.IsAny<ITextBuffer>(), out nullWorkspace)) .Returns(false); var workspaceAccessor = new DefaultVisualStudioWorkspaceAccessor(Mock.Of<IBufferGraphFactoryService>(), Mock.Of<TextBufferProjectService>(), TestWorkspace.Create(), liveShareWorkspaceProvider.Object); var textBuffer = Mock.Of<ITextBuffer>(); // Act var result = workspaceAccessor.TryGetWorkspaceFromLiveShare(textBuffer, out var workspace); // Assert Assert.False(result); } [Fact] public void TryGetWorkspaceFromLiveShare_CanFindWorkspace_ReturnsTrue() { // Arrange var expectedWorkspace = TestWorkspace.Create(); var liveShareWorkspaceProvider = new Mock<LiveShareWorkspaceProvider>(); liveShareWorkspaceProvider.Setup(provider => provider.TryGetWorkspace(It.IsAny<ITextBuffer>(), out expectedWorkspace)) .Returns(true); var workspaceAccessor = new DefaultVisualStudioWorkspaceAccessor(Mock.Of<IBufferGraphFactoryService>(), Mock.Of<TextBufferProjectService>(), TestWorkspace.Create(), liveShareWorkspaceProvider.Object); var textBuffer = Mock.Of<ITextBuffer>(); // Act var result = workspaceAccessor.TryGetWorkspaceFromLiveShare(textBuffer, out var workspace); // Assert Assert.True(result); Assert.Same(expectedWorkspace, workspace); } [Fact] public void TryGetWorkspaceFromProjectionBuffer_NoProjectionBuffer_ReturnsFalse() { // Arrange var bufferGraph = new Mock<IBufferGraph>(); bufferGraph.Setup(graph => graph.GetTextBuffers(It.IsAny<Predicate<ITextBuffer>>())) .Returns<Predicate<ITextBuffer>>(predicate => new Collection<ITextBuffer>()); var bufferGraphService = new Mock<IBufferGraphFactoryService>(); bufferGraphService.Setup(service => service.CreateBufferGraph(It.IsAny<ITextBuffer>())) .Returns(bufferGraph.Object); var workspaceAccessor = new DefaultVisualStudioWorkspaceAccessor(bufferGraphService.Object, Mock.Of<TextBufferProjectService>(), TestWorkspace.Create(), NoLiveShare); var textBuffer = Mock.Of<ITextBuffer>(); // Act var result = workspaceAccessor.TryGetWorkspaceFromProjectionBuffer(textBuffer, out var workspace); // Assert Assert.False(result); } [Fact] public void TryGetWorkspaceFromHostProject_NoHostProject_ReturnsFalse() { // Arrange var workspaceAccessor = new DefaultVisualStudioWorkspaceAccessor(Mock.Of<IBufferGraphFactoryService>(), Mock.Of<TextBufferProjectService>(), TestWorkspace.Create(), NoLiveShare); var textBuffer = Mock.Of<ITextBuffer>(); // Act var result = workspaceAccessor.TryGetWorkspaceFromHostProject(textBuffer, out var workspace); // Assert Assert.False(result); } [Fact] public void TryGetWorkspaceFromHostProject_HasHostProject_ReturnsTrueWithDefaultWorkspace() { // Arrange var textBuffer = Mock.Of<ITextBuffer>(); var projectService = Mock.Of<TextBufferProjectService>(service => service.GetHostProject(textBuffer) == new object()); var defaultWorkspace = TestWorkspace.Create(); var workspaceAccessor = new DefaultVisualStudioWorkspaceAccessor(Mock.Of<IBufferGraphFactoryService>(), projectService, defaultWorkspace, NoLiveShare); // Act var result = workspaceAccessor.TryGetWorkspaceFromHostProject(textBuffer, out var workspace); // Assert Assert.True(result); Assert.Same(defaultWorkspace, workspace); } private class TestWorkspaceAccessor : DefaultVisualStudioWorkspaceAccessor { private readonly bool _canGetWorkspaceFromProjectionBuffer; private readonly bool _canGetWorkspaceFromHostProject; internal TestWorkspaceAccessor(bool canGetWorkspaceFromProjectionBuffer, bool canGetWorkspaceFromHostProject) : this(canGetWorkspaceFromProjectionBuffer, canGetWorkspaceFromHostProject, NoLiveShare) { } internal TestWorkspaceAccessor( bool canGetWorkspaceFromProjectionBuffer, bool canGetWorkspaceFromHostProject, LiveShareWorkspaceProvider liveShareWorkspaceProvider) : base( Mock.Of<IBufferGraphFactoryService>(), Mock.Of<TextBufferProjectService>(), TestWorkspace.Create(), liveShareWorkspaceProvider) { _canGetWorkspaceFromProjectionBuffer = canGetWorkspaceFromProjectionBuffer; _canGetWorkspaceFromHostProject = canGetWorkspaceFromHostProject; } internal override bool TryGetWorkspaceFromProjectionBuffer(ITextBuffer textBuffer, out Workspace workspace) { if (_canGetWorkspaceFromProjectionBuffer) { workspace = TestWorkspace.Create(); return true; } workspace = null; return false; } internal override bool TryGetWorkspaceFromHostProject(ITextBuffer textBuffer, out Workspace workspace) { if (_canGetWorkspaceFromHostProject) { workspace = TestWorkspace.Create(); return true; } workspace = null; return false; } } } }
41.450216
212
0.643133
[ "Apache-2.0" ]
AmadeusW/Razor
test/Microsoft.VisualStudio.LanguageServices.Razor.Test/DefaultVisualStudioWorkspaceAccessorTest.cs
9,577
C#
using UnityEngine; namespace Gameframe.InfoTables { /// <summary> /// Scriptable object with a InfoId /// Intended to be used with an InfoTable /// </summary> public class InfoScriptableObject : ScriptableObject { [SerializeField,Tooltip("The InfoId's hashed value will be used as the integer value when exported to enum")] private InfoId id; public InfoId Id { get => id; set => id = value; } } }
20.454545
114
0.653333
[ "Apache-2.0" ]
coryleach/UnityInfoTables
Runtime/InfoScriptableObject.cs
452
C#
using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Scoping; namespace Umbraco.Core.Services.Implement { // fixme that one does not add anything = kill public abstract class ScopeRepositoryService : RepositoryService { protected ScopeRepositoryService(IScopeProvider provider, ILogger logger, IEventMessagesFactory eventMessagesFactory) : base(provider, logger, eventMessagesFactory) { } } }
30.666667
125
0.743478
[ "MIT" ]
bharanijayasuri/umbraco8
src/Umbraco.Core/Services/Implement/ScopeRepositoryService.cs
462
C#
namespace LiteNetLibManager { public static partial class GameReqTypes { public const ushort EnterGame = 0; public const ushort ClientReady = 1; public const ushort ClientNotReady = 2; } }
22.6
47
0.663717
[ "MIT" ]
AldeRoberge/LiteNetLibManager
Scripts/GameApi/GameReqTypes.cs
228
C#
using System.Net.Security; using System.Security.Authentication; namespace CookedRabbit.Library.Models { /// <summary> /// Class to fully season RabbitServices to your taste! /// </summary> public class SslSeasoning { #region RabbitMQ SSL/TLS Settings /// <summary> /// RabbitMQ option to enable SSL. /// <para>Set Cf_RabbitPort to 5671 as well as enabling this.</para> /// <para>To configure client and server: http://www.rabbitmq.com/ssl.html#configuring-dotnet</para> /// </summary> public bool EnableSsl { get; set; } = false; /// <summary> /// RabbitMQ to set the Certificate Server Name. /// </summary> public string CertServerName { get; set; } = string.Empty; /// <summary> /// RabbitMQ option to set the local file name path of the cert to use for authentication. /// </summary> public string LocalCertPath { get; set; } = string.Empty; /// <summary> /// RabbitMQ option to set the password for the local certificate in use. /// </summary> public string LocalCertPassword { get; set; } = string.Empty; /// <summary> /// RabbitMQ option to allow the following acceptable policy errors (if any). /// </summary> public SslPolicyErrors AcceptedPolicyErrors { get; set; } = SslPolicyErrors.RemoteCertificateNotAvailable | SslPolicyErrors.RemoteCertificateNameMismatch; /// <summary> /// RabbitMQ option to specify which secure SSL protocols to use/allow. /// <para>Recommend Tls12 as the most recent/secure protocol.</para> /// </summary> public SslProtocols ProtocolVersions { get; set; } = SslProtocols.Tls12; #endregion } }
36.653061
162
0.626392
[ "MIT" ]
area55git/CookedRabbit
CookedRabbit.Library/Models/SslSeasoning.cs
1,798
C#
//============================= //作者:龙英杰 //日期:2015/10/26 //用途:技能符文表 //============================= using UnityEngine; using System.Collections; using System.Collections.Generic; public class SkillRuneRefTable : AssetTable { public List<SkillRuneRef> infoList = new List<SkillRuneRef>(); } [System.Serializable] public class SkillRuneRef { /// <summary> /// ID /// </summary> public int runeId; /// <summary> /// 解锁需求玩家等级 /// </summary> public int unlockPlayerLvl; /// <summary> /// 解锁需求技能等级 /// </summary> public int unlockSkillLvl; /// <summary> /// 解锁需求资源数 /// </summary> public int unlockPrice; /// <summary> /// 解锁所需道具 /// </summary> public int unlockItem; /// <summary> /// 符文名 /// </summary> public string name; /// <summary> /// 符文说明 /// </summary> public string des; /// <summary> /// 符文图标 /// </summary> public string runeIcon; /// <summary> /// 符文对应的技能 /// </summary> public int performanceID; /// <summary> /// 从属技能ID /// </summary> public int skillMainId; }
18.126984
66
0.530648
[ "BSD-3-Clause" ]
cheng219/tianyu
Assets/Shares/Tables/SkillRuneRefTable.cs
1,280
C#
using System; using System.Threading; using Otii; namespace BasicMeasurement { class Program { private const int RecordingTime = 30000; static void Main(string[] args) { // Calling Connect without parameters will connect to a local instance of Otii var client = new OtiiClient(); client.Connect(); // Create a local reference to the Otii property for convenience var otii = client.Otii; // Get a list of all Otii devices available var devices = otii.GetDevices(); if (devices.Length == 0) { throw new Exception("No available devices"); } // Get a reference to the first device in the list var arc = devices[0]; var project = otii.GetActiveProject(); if (project == null) { project = otii.CreateProject(); } // Configuration arc.SetMainVoltage(3.3); arc.SetMaxCurrent(0.5); arc.EnableUart(true); arc.SetUartBaudrate(115200); arc.EnableChannel("mc", true); arc.EnableChannel("mv", true); arc.EnableChannel("rx", true); arc.EnableChannel("i1", true); // Record project.StartRecording(); arc.SetMain(true); Thread.Sleep(RecordingTime); arc.SetMain(false); project.StopRecording(); // Close the connection client.Close(); } } }
29.603774
90
0.533461
[ "MIT" ]
qoitech/otii-tcp-client-csharp
Examples/BasicMeasurement/Program.cs
1,571
C#
/* * SimScale API * * The version of the OpenAPI document: 0.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using OpenAPIDateConverter = SimScale.Sdk.Client.OpenAPIDateConverter; namespace SimScale.Sdk.Model { /// <summary> /// &lt;p&gt;Choose a linear equation system solver for your calculation:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;Multfront&lt;/b&gt; is a direct solver of the multifrontal type. It is easy to set up and behaves well for most problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;MUMPS&lt;/b&gt; is a general purpose direct solver of the multifrontal type. It provides a lot of parameter settings to allow the best fitting to your problems needs.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;LDLT&lt;/b&gt; is a direct solver which uses a Gaussian Algortihm. It is comparatively slow for big problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;PETSC&lt;/b&gt; is an iterative solver specially designed to deal with large systems. It scales very effectively in parallel and is the best choice for large problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;GCPC&lt;/b&gt; is an iterative solver of the pre-conditioned conjugate gradient type. It scales well in parallel and is also usable for large problems.&lt;/p&gt;&lt;/ul&gt; /// </summary> [DataContract] public partial class MUMPSSolver : OneOfSolidNumericsSolver, IEquatable<MUMPSSolver> { /// <summary> /// &lt;p&gt;Choose the type of your system matrix by directly selecting the appropriate type or using the &lt;b&gt;automatic detection&lt;/b&gt;. With the selection &lt;b&gt;automatic detection&lt;/b&gt; the matrix type &lt;b&gt;symmetric positive indefinite&lt;/b&gt; is selected if a symmetric system matrix is detected, and &lt;b&gt;asymmetric&lt;/b&gt; otherwise. /// </summary> /// <value>&lt;p&gt;Choose the type of your system matrix by directly selecting the appropriate type or using the &lt;b&gt;automatic detection&lt;/b&gt;. With the selection &lt;b&gt;automatic detection&lt;/b&gt; the matrix type &lt;b&gt;symmetric positive indefinite&lt;/b&gt; is selected if a symmetric system matrix is detected, and &lt;b&gt;asymmetric&lt;/b&gt; otherwise.</value> [JsonConverter(typeof(StringEnumConverter))] public enum MatrixTypeEnum { /// <summary> /// Enum ASYMMETRIC for value: ASYMMETRIC /// </summary> [EnumMember(Value = "ASYMMETRIC")] ASYMMETRIC = 1, /// <summary> /// Enum AUTOMATICDETECTION for value: AUTOMATIC_DETECTION /// </summary> [EnumMember(Value = "AUTOMATIC_DETECTION")] AUTOMATICDETECTION = 2, /// <summary> /// Enum SYMMETRICPOSITIVEINDEFINITE for value: SYMMETRIC_POSITIVE_INDEFINITE /// </summary> [EnumMember(Value = "SYMMETRIC_POSITIVE_INDEFINITE")] SYMMETRICPOSITIVEINDEFINITE = 3 } /// <summary> /// &lt;p&gt;Choose the type of your system matrix by directly selecting the appropriate type or using the &lt;b&gt;automatic detection&lt;/b&gt;. With the selection &lt;b&gt;automatic detection&lt;/b&gt; the matrix type &lt;b&gt;symmetric positive indefinite&lt;/b&gt; is selected if a symmetric system matrix is detected, and &lt;b&gt;asymmetric&lt;/b&gt; otherwise. /// </summary> /// <value>&lt;p&gt;Choose the type of your system matrix by directly selecting the appropriate type or using the &lt;b&gt;automatic detection&lt;/b&gt;. With the selection &lt;b&gt;automatic detection&lt;/b&gt; the matrix type &lt;b&gt;symmetric positive indefinite&lt;/b&gt; is selected if a symmetric system matrix is detected, and &lt;b&gt;asymmetric&lt;/b&gt; otherwise.</value> [DataMember(Name="matrixType", EmitDefaultValue=false)] public MatrixTypeEnum? MatrixType { get; set; } /// <summary> /// Choose the renumbering method for the system matrix entries. The choice of the renumbering method has a big impact on the memory consumption and the solution time. Currently supported are:&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;SCOTCH&lt;/b&gt; is a powerful renumbering tool, suited for most scenarios and the standard choice for MUMPS.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;PORD&lt;/b&gt; is a renumbering tool that comes with MUMPS.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;AMD&lt;/b&gt; uses the &lt;i&gt;Approximate Minimum Degree&lt;/i&gt; method.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;AMF&lt;/b&gt; uses the &lt;i&gt;Approximate Minimum Fill&lt;/i&gt; method.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;QAMD&lt;/b&gt; is a variant of AMD with automatic detection of quasi-dense matrix lines.&lt;/p&gt;&lt;/ul&gt;If &lt;b&gt;automatic&lt;/b&gt; is selected the user let MUMPS choose the renumbering tool. The methods AMD, AMF and QAMD are generally inferior to the more sophisticated methods SCOTCH and PORD but may be a better choice in some cases. /// </summary> /// <value>Choose the renumbering method for the system matrix entries. The choice of the renumbering method has a big impact on the memory consumption and the solution time. Currently supported are:&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;SCOTCH&lt;/b&gt; is a powerful renumbering tool, suited for most scenarios and the standard choice for MUMPS.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;PORD&lt;/b&gt; is a renumbering tool that comes with MUMPS.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;AMD&lt;/b&gt; uses the &lt;i&gt;Approximate Minimum Degree&lt;/i&gt; method.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;AMF&lt;/b&gt; uses the &lt;i&gt;Approximate Minimum Fill&lt;/i&gt; method.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;QAMD&lt;/b&gt; is a variant of AMD with automatic detection of quasi-dense matrix lines.&lt;/p&gt;&lt;/ul&gt;If &lt;b&gt;automatic&lt;/b&gt; is selected the user let MUMPS choose the renumbering tool. The methods AMD, AMF and QAMD are generally inferior to the more sophisticated methods SCOTCH and PORD but may be a better choice in some cases.</value> [JsonConverter(typeof(StringEnumConverter))] public enum RenumberingMethodEnum { /// <summary> /// Enum AMD for value: AMD /// </summary> [EnumMember(Value = "AMD")] AMD = 1, /// <summary> /// Enum SCOTCH for value: SCOTCH /// </summary> [EnumMember(Value = "SCOTCH")] SCOTCH = 2, /// <summary> /// Enum AMF for value: AMF /// </summary> [EnumMember(Value = "AMF")] AMF = 3, /// <summary> /// Enum PORD for value: PORD /// </summary> [EnumMember(Value = "PORD")] PORD = 4, /// <summary> /// Enum QAMD for value: QAMD /// </summary> [EnumMember(Value = "QAMD")] QAMD = 5, /// <summary> /// Enum AUTOMATIC for value: AUTOMATIC /// </summary> [EnumMember(Value = "AUTOMATIC")] AUTOMATIC = 6 } /// <summary> /// Choose the renumbering method for the system matrix entries. The choice of the renumbering method has a big impact on the memory consumption and the solution time. Currently supported are:&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;SCOTCH&lt;/b&gt; is a powerful renumbering tool, suited for most scenarios and the standard choice for MUMPS.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;PORD&lt;/b&gt; is a renumbering tool that comes with MUMPS.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;AMD&lt;/b&gt; uses the &lt;i&gt;Approximate Minimum Degree&lt;/i&gt; method.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;AMF&lt;/b&gt; uses the &lt;i&gt;Approximate Minimum Fill&lt;/i&gt; method.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;QAMD&lt;/b&gt; is a variant of AMD with automatic detection of quasi-dense matrix lines.&lt;/p&gt;&lt;/ul&gt;If &lt;b&gt;automatic&lt;/b&gt; is selected the user let MUMPS choose the renumbering tool. The methods AMD, AMF and QAMD are generally inferior to the more sophisticated methods SCOTCH and PORD but may be a better choice in some cases. /// </summary> /// <value>Choose the renumbering method for the system matrix entries. The choice of the renumbering method has a big impact on the memory consumption and the solution time. Currently supported are:&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;SCOTCH&lt;/b&gt; is a powerful renumbering tool, suited for most scenarios and the standard choice for MUMPS.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;PORD&lt;/b&gt; is a renumbering tool that comes with MUMPS.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;AMD&lt;/b&gt; uses the &lt;i&gt;Approximate Minimum Degree&lt;/i&gt; method.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;AMF&lt;/b&gt; uses the &lt;i&gt;Approximate Minimum Fill&lt;/i&gt; method.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;QAMD&lt;/b&gt; is a variant of AMD with automatic detection of quasi-dense matrix lines.&lt;/p&gt;&lt;/ul&gt;If &lt;b&gt;automatic&lt;/b&gt; is selected the user let MUMPS choose the renumbering tool. The methods AMD, AMF and QAMD are generally inferior to the more sophisticated methods SCOTCH and PORD but may be a better choice in some cases.</value> [DataMember(Name="renumberingMethod", EmitDefaultValue=false)] public RenumberingMethodEnum? RenumberingMethod { get; set; } /// <summary> /// With this option the user can control the iterative refinement of the linear system solution. This option only has an effect if the value of the &lt;b&gt; linear system relative residual&lt;/b&gt; given by the user is greater than zero, otherwise it is ignored. If it is &lt;b&gt;activate&lt;/b&gt; MUMPS carries out at least one additional iteration of the linear system resolution and at most 10 iterations. The process is stopped if the residual isn&#39;t reduced by at least a factor of 5. If this option is set to be &lt;b&gt;inactive&lt;/b&gt; no additional iteration is done and if &lt;b&gt;automatic&lt;/b&gt; is chosen MUMPS automatically decides if additional iterations should be done and the maximum number of iterations is set to 4. /// </summary> /// <value>With this option the user can control the iterative refinement of the linear system solution. This option only has an effect if the value of the &lt;b&gt; linear system relative residual&lt;/b&gt; given by the user is greater than zero, otherwise it is ignored. If it is &lt;b&gt;activate&lt;/b&gt; MUMPS carries out at least one additional iteration of the linear system resolution and at most 10 iterations. The process is stopped if the residual isn&#39;t reduced by at least a factor of 5. If this option is set to be &lt;b&gt;inactive&lt;/b&gt; no additional iteration is done and if &lt;b&gt;automatic&lt;/b&gt; is chosen MUMPS automatically decides if additional iterations should be done and the maximum number of iterations is set to 4.</value> [JsonConverter(typeof(StringEnumConverter))] public enum PostprocessingEnum { /// <summary> /// Enum INACTIVE for value: INACTIVE /// </summary> [EnumMember(Value = "INACTIVE")] INACTIVE = 1, /// <summary> /// Enum ACTIVE for value: ACTIVE /// </summary> [EnumMember(Value = "ACTIVE")] ACTIVE = 2, /// <summary> /// Enum AUTOMATIC for value: AUTOMATIC /// </summary> [EnumMember(Value = "AUTOMATIC")] AUTOMATIC = 3 } /// <summary> /// With this option the user can control the iterative refinement of the linear system solution. This option only has an effect if the value of the &lt;b&gt; linear system relative residual&lt;/b&gt; given by the user is greater than zero, otherwise it is ignored. If it is &lt;b&gt;activate&lt;/b&gt; MUMPS carries out at least one additional iteration of the linear system resolution and at most 10 iterations. The process is stopped if the residual isn&#39;t reduced by at least a factor of 5. If this option is set to be &lt;b&gt;inactive&lt;/b&gt; no additional iteration is done and if &lt;b&gt;automatic&lt;/b&gt; is chosen MUMPS automatically decides if additional iterations should be done and the maximum number of iterations is set to 4. /// </summary> /// <value>With this option the user can control the iterative refinement of the linear system solution. This option only has an effect if the value of the &lt;b&gt; linear system relative residual&lt;/b&gt; given by the user is greater than zero, otherwise it is ignored. If it is &lt;b&gt;activate&lt;/b&gt; MUMPS carries out at least one additional iteration of the linear system resolution and at most 10 iterations. The process is stopped if the residual isn&#39;t reduced by at least a factor of 5. If this option is set to be &lt;b&gt;inactive&lt;/b&gt; no additional iteration is done and if &lt;b&gt;automatic&lt;/b&gt; is chosen MUMPS automatically decides if additional iterations should be done and the maximum number of iterations is set to 4.</value> [DataMember(Name="postprocessing", EmitDefaultValue=false)] public PostprocessingEnum? Postprocessing { get; set; } /// <summary> /// Choose the memory managment priority of the MUMPS solver. If &lt;b&gt;in-core&lt;/b&gt; is used the memory managment is optimized with respect to the calculation time by saving all objects in the RAM. If &lt;b&gt;out-of-core&lt;/b&gt; is chosen, the memory managment is optimized for a minimal RAM usage. If &lt;b&gt;automatic&lt;/b&gt; is selected, MUMPS choses automatically a reasonable memory managment mode. The option &lt;b&gt;memory demand evaluation&lt;/b&gt; is helpful to estimate the RAM consumption. This estimate is written to the solver log file. In this case the solution process aborts after the memory usage is estimated, allowing the user to start a new run with the best settings. /// </summary> /// <value>Choose the memory managment priority of the MUMPS solver. If &lt;b&gt;in-core&lt;/b&gt; is used the memory managment is optimized with respect to the calculation time by saving all objects in the RAM. If &lt;b&gt;out-of-core&lt;/b&gt; is chosen, the memory managment is optimized for a minimal RAM usage. If &lt;b&gt;automatic&lt;/b&gt; is selected, MUMPS choses automatically a reasonable memory managment mode. The option &lt;b&gt;memory demand evaluation&lt;/b&gt; is helpful to estimate the RAM consumption. This estimate is written to the solver log file. In this case the solution process aborts after the memory usage is estimated, allowing the user to start a new run with the best settings.</value> [JsonConverter(typeof(StringEnumConverter))] public enum MemoryManagementEnum { /// <summary> /// Enum AUTOMATIC for value: AUTOMATIC /// </summary> [EnumMember(Value = "AUTOMATIC")] AUTOMATIC = 1, /// <summary> /// Enum INCORE for value: IN_CORE /// </summary> [EnumMember(Value = "IN_CORE")] INCORE = 2, /// <summary> /// Enum MEMORYDEMANDEVALUATION for value: MEMORY_DEMAND_EVALUATION /// </summary> [EnumMember(Value = "MEMORY_DEMAND_EVALUATION")] MEMORYDEMANDEVALUATION = 3, /// <summary> /// Enum OUTOFCORE for value: OUT_OF_CORE /// </summary> [EnumMember(Value = "OUT_OF_CORE")] OUTOFCORE = 4 } /// <summary> /// Choose the memory managment priority of the MUMPS solver. If &lt;b&gt;in-core&lt;/b&gt; is used the memory managment is optimized with respect to the calculation time by saving all objects in the RAM. If &lt;b&gt;out-of-core&lt;/b&gt; is chosen, the memory managment is optimized for a minimal RAM usage. If &lt;b&gt;automatic&lt;/b&gt; is selected, MUMPS choses automatically a reasonable memory managment mode. The option &lt;b&gt;memory demand evaluation&lt;/b&gt; is helpful to estimate the RAM consumption. This estimate is written to the solver log file. In this case the solution process aborts after the memory usage is estimated, allowing the user to start a new run with the best settings. /// </summary> /// <value>Choose the memory managment priority of the MUMPS solver. If &lt;b&gt;in-core&lt;/b&gt; is used the memory managment is optimized with respect to the calculation time by saving all objects in the RAM. If &lt;b&gt;out-of-core&lt;/b&gt; is chosen, the memory managment is optimized for a minimal RAM usage. If &lt;b&gt;automatic&lt;/b&gt; is selected, MUMPS choses automatically a reasonable memory managment mode. The option &lt;b&gt;memory demand evaluation&lt;/b&gt; is helpful to estimate the RAM consumption. This estimate is written to the solver log file. In this case the solution process aborts after the memory usage is estimated, allowing the user to start a new run with the best settings.</value> [DataMember(Name="memoryManagement", EmitDefaultValue=false)] public MemoryManagementEnum? MemoryManagement { get; set; } /// <summary> /// Initializes a new instance of the <see cref="MUMPSSolver" /> class. /// </summary> [JsonConstructorAttribute] protected MUMPSSolver() { } /// <summary> /// Initializes a new instance of the <see cref="MUMPSSolver" /> class. /// </summary> /// <param name="type">&lt;p&gt;Choose a linear equation system solver for your calculation:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;Multfront&lt;/b&gt; is a direct solver of the multifrontal type. It is easy to set up and behaves well for most problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;MUMPS&lt;/b&gt; is a general purpose direct solver of the multifrontal type. It provides a lot of parameter settings to allow the best fitting to your problems needs.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;LDLT&lt;/b&gt; is a direct solver which uses a Gaussian Algortihm. It is comparatively slow for big problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;PETSC&lt;/b&gt; is an iterative solver specially designed to deal with large systems. It scales very effectively in parallel and is the best choice for large problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;GCPC&lt;/b&gt; is an iterative solver of the pre-conditioned conjugate gradient type. It scales well in parallel and is also usable for large problems.&lt;/p&gt;&lt;/ul&gt; Schema name: MUMPSSolver (required) (default to &quot;MUMPS&quot;).</param> /// <param name="forceSymmetric">Choose if you want to enforce a symmetric matrix. (default to false).</param> /// <param name="precisionSingularityDetection">Define the precision value for the detection of a singular matrix. (default to 8).</param> /// <param name="stopIfSingular">Choose if the calculation should be stopped if the problem turns out to be singular. (default to true).</param> /// <param name="matrixType">&lt;p&gt;Choose the type of your system matrix by directly selecting the appropriate type or using the &lt;b&gt;automatic detection&lt;/b&gt;. With the selection &lt;b&gt;automatic detection&lt;/b&gt; the matrix type &lt;b&gt;symmetric positive indefinite&lt;/b&gt; is selected if a symmetric system matrix is detected, and &lt;b&gt;asymmetric&lt;/b&gt; otherwise. (default to MatrixTypeEnum.AUTOMATICDETECTION).</param> /// <param name="memoryPercentageForPivoting">Define how much additional memory should be reserved for the pivoting operations. If MUMPS estimates that the necessary space for factorising the matrix would be 100, choosing a value of 20 would mean that MUMPS allocates a memory space of 120. (default to 20M).</param> /// <param name="linearSystemRelativeResidual">Choose a value for the maximum relative residual for each linear system resolution compared to the exact solution. In a nonlinear calculation the user can deactivate this check by selecting a negative value (for example, -1.0) since the quality of the solution is controlled within the Newton loop..</param> /// <param name="matrixFilteringThreshold">This parameter allows a filtration of the matrix entries that are saved and possibly passed to the nonlinear algorithm (Newton) and is similar to a relaxation mechanism. If the given threshold value is strictly positive, MUMPS only saves the matrix entries that satisfy the following condition: |K&lt;sub&gt;ij&lt;/sub&gt;| value*(|K&lt;sub&gt;ii&lt;/sub&gt;|+|K&lt;sub&gt;jj&lt;/sub&gt;|). Thus using this functionality might save computation time as well as memory consumption, but the effects strongly depend on the given value and is only advised for the experienced user. (default to -1M).</param> /// <param name="singlePrecision">If this option is activated the matrix factorisation is done with single precision and thus a reduction in memory consumption (often about 50%) and computation time is gained if the problem is well conditioned. If the problem is ill-conditioned one risks that in a nonlinear computation the newton algorithm fails to converge. (default to false).</param> /// <param name="preprocessing">If this option is activated MUMPS performs a pre-processing on order to identify the best parameter setting for some internal parameters adapted to the current problem. (default to true).</param> /// <param name="renumberingMethod">Choose the renumbering method for the system matrix entries. The choice of the renumbering method has a big impact on the memory consumption and the solution time. Currently supported are:&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;SCOTCH&lt;/b&gt; is a powerful renumbering tool, suited for most scenarios and the standard choice for MUMPS.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;PORD&lt;/b&gt; is a renumbering tool that comes with MUMPS.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;AMD&lt;/b&gt; uses the &lt;i&gt;Approximate Minimum Degree&lt;/i&gt; method.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;AMF&lt;/b&gt; uses the &lt;i&gt;Approximate Minimum Fill&lt;/i&gt; method.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;QAMD&lt;/b&gt; is a variant of AMD with automatic detection of quasi-dense matrix lines.&lt;/p&gt;&lt;/ul&gt;If &lt;b&gt;automatic&lt;/b&gt; is selected the user let MUMPS choose the renumbering tool. The methods AMD, AMF and QAMD are generally inferior to the more sophisticated methods SCOTCH and PORD but may be a better choice in some cases..</param> /// <param name="postprocessing">With this option the user can control the iterative refinement of the linear system solution. This option only has an effect if the value of the &lt;b&gt; linear system relative residual&lt;/b&gt; given by the user is greater than zero, otherwise it is ignored. If it is &lt;b&gt;activate&lt;/b&gt; MUMPS carries out at least one additional iteration of the linear system resolution and at most 10 iterations. The process is stopped if the residual isn&#39;t reduced by at least a factor of 5. If this option is set to be &lt;b&gt;inactive&lt;/b&gt; no additional iteration is done and if &lt;b&gt;automatic&lt;/b&gt; is chosen MUMPS automatically decides if additional iterations should be done and the maximum number of iterations is set to 4. (default to PostprocessingEnum.ACTIVE).</param> /// <param name="distributedMatrixStorage">Choose this parameter as &lt;b&gt;true&lt;/b&gt; to ensure that the system matrix saving is distributed among the processors of the computation. If multiple cores are used only the relevant part for each core is saved. If it is set to false the whole matrix is saved for each processor. This parameter has currently no effect for &lt;i&gt;Harmonic&lt;/i&gt; simulations. (default to true).</param> /// <param name="memoryManagement">Choose the memory managment priority of the MUMPS solver. If &lt;b&gt;in-core&lt;/b&gt; is used the memory managment is optimized with respect to the calculation time by saving all objects in the RAM. If &lt;b&gt;out-of-core&lt;/b&gt; is chosen, the memory managment is optimized for a minimal RAM usage. If &lt;b&gt;automatic&lt;/b&gt; is selected, MUMPS choses automatically a reasonable memory managment mode. The option &lt;b&gt;memory demand evaluation&lt;/b&gt; is helpful to estimate the RAM consumption. This estimate is written to the solver log file. In this case the solution process aborts after the memory usage is estimated, allowing the user to start a new run with the best settings. (default to MemoryManagementEnum.AUTOMATIC).</param> public MUMPSSolver(string type = "MUMPS", bool? forceSymmetric = default(bool?), int? precisionSingularityDetection = default(int?), bool? stopIfSingular = default(bool?), MatrixTypeEnum? matrixType = default(MatrixTypeEnum?), decimal? memoryPercentageForPivoting = default(decimal?), decimal? linearSystemRelativeResidual = default(decimal?), decimal? matrixFilteringThreshold = default(decimal?), bool? singlePrecision = default(bool?), bool? preprocessing = default(bool?), RenumberingMethodEnum? renumberingMethod = default(RenumberingMethodEnum?), PostprocessingEnum? postprocessing = default(PostprocessingEnum?), bool? distributedMatrixStorage = default(bool?), MemoryManagementEnum? memoryManagement = default(MemoryManagementEnum?)) { // to ensure "type" is required (not null) this.Type = type ?? throw new ArgumentNullException("type is a required property for MUMPSSolver and cannot be null"); this.ForceSymmetric = forceSymmetric; this.PrecisionSingularityDetection = precisionSingularityDetection; this.StopIfSingular = stopIfSingular; this.MatrixType = matrixType; this.MemoryPercentageForPivoting = memoryPercentageForPivoting; this.LinearSystemRelativeResidual = linearSystemRelativeResidual; this.MatrixFilteringThreshold = matrixFilteringThreshold; this.SinglePrecision = singlePrecision; this.Preprocessing = preprocessing; this.RenumberingMethod = renumberingMethod; this.Postprocessing = postprocessing; this.DistributedMatrixStorage = distributedMatrixStorage; this.MemoryManagement = memoryManagement; } /// <summary> /// &lt;p&gt;Choose a linear equation system solver for your calculation:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;Multfront&lt;/b&gt; is a direct solver of the multifrontal type. It is easy to set up and behaves well for most problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;MUMPS&lt;/b&gt; is a general purpose direct solver of the multifrontal type. It provides a lot of parameter settings to allow the best fitting to your problems needs.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;LDLT&lt;/b&gt; is a direct solver which uses a Gaussian Algortihm. It is comparatively slow for big problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;PETSC&lt;/b&gt; is an iterative solver specially designed to deal with large systems. It scales very effectively in parallel and is the best choice for large problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;GCPC&lt;/b&gt; is an iterative solver of the pre-conditioned conjugate gradient type. It scales well in parallel and is also usable for large problems.&lt;/p&gt;&lt;/ul&gt; Schema name: MUMPSSolver /// </summary> /// <value>&lt;p&gt;Choose a linear equation system solver for your calculation:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;Multfront&lt;/b&gt; is a direct solver of the multifrontal type. It is easy to set up and behaves well for most problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;MUMPS&lt;/b&gt; is a general purpose direct solver of the multifrontal type. It provides a lot of parameter settings to allow the best fitting to your problems needs.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;LDLT&lt;/b&gt; is a direct solver which uses a Gaussian Algortihm. It is comparatively slow for big problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;PETSC&lt;/b&gt; is an iterative solver specially designed to deal with large systems. It scales very effectively in parallel and is the best choice for large problems.&lt;/p&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;&lt;b&gt;GCPC&lt;/b&gt; is an iterative solver of the pre-conditioned conjugate gradient type. It scales well in parallel and is also usable for large problems.&lt;/p&gt;&lt;/ul&gt; Schema name: MUMPSSolver</value> [DataMember(Name="type", EmitDefaultValue=false)] public string Type { get; set; } /// <summary> /// Choose if you want to enforce a symmetric matrix. /// </summary> /// <value>Choose if you want to enforce a symmetric matrix.</value> [DataMember(Name="forceSymmetric", EmitDefaultValue=false)] public bool? ForceSymmetric { get; set; } /// <summary> /// Define the precision value for the detection of a singular matrix. /// </summary> /// <value>Define the precision value for the detection of a singular matrix.</value> [DataMember(Name="precisionSingularityDetection", EmitDefaultValue=false)] public int? PrecisionSingularityDetection { get; set; } /// <summary> /// Choose if the calculation should be stopped if the problem turns out to be singular. /// </summary> /// <value>Choose if the calculation should be stopped if the problem turns out to be singular.</value> [DataMember(Name="stopIfSingular", EmitDefaultValue=false)] public bool? StopIfSingular { get; set; } /// <summary> /// Define how much additional memory should be reserved for the pivoting operations. If MUMPS estimates that the necessary space for factorising the matrix would be 100, choosing a value of 20 would mean that MUMPS allocates a memory space of 120. /// </summary> /// <value>Define how much additional memory should be reserved for the pivoting operations. If MUMPS estimates that the necessary space for factorising the matrix would be 100, choosing a value of 20 would mean that MUMPS allocates a memory space of 120.</value> [DataMember(Name="memoryPercentageForPivoting", EmitDefaultValue=false)] public decimal? MemoryPercentageForPivoting { get; set; } /// <summary> /// Choose a value for the maximum relative residual for each linear system resolution compared to the exact solution. In a nonlinear calculation the user can deactivate this check by selecting a negative value (for example, -1.0) since the quality of the solution is controlled within the Newton loop. /// </summary> /// <value>Choose a value for the maximum relative residual for each linear system resolution compared to the exact solution. In a nonlinear calculation the user can deactivate this check by selecting a negative value (for example, -1.0) since the quality of the solution is controlled within the Newton loop.</value> [DataMember(Name="linearSystemRelativeResidual", EmitDefaultValue=false)] public decimal? LinearSystemRelativeResidual { get; set; } /// <summary> /// This parameter allows a filtration of the matrix entries that are saved and possibly passed to the nonlinear algorithm (Newton) and is similar to a relaxation mechanism. If the given threshold value is strictly positive, MUMPS only saves the matrix entries that satisfy the following condition: |K&lt;sub&gt;ij&lt;/sub&gt;| value*(|K&lt;sub&gt;ii&lt;/sub&gt;|+|K&lt;sub&gt;jj&lt;/sub&gt;|). Thus using this functionality might save computation time as well as memory consumption, but the effects strongly depend on the given value and is only advised for the experienced user. /// </summary> /// <value>This parameter allows a filtration of the matrix entries that are saved and possibly passed to the nonlinear algorithm (Newton) and is similar to a relaxation mechanism. If the given threshold value is strictly positive, MUMPS only saves the matrix entries that satisfy the following condition: |K&lt;sub&gt;ij&lt;/sub&gt;| value*(|K&lt;sub&gt;ii&lt;/sub&gt;|+|K&lt;sub&gt;jj&lt;/sub&gt;|). Thus using this functionality might save computation time as well as memory consumption, but the effects strongly depend on the given value and is only advised for the experienced user.</value> [DataMember(Name="matrixFilteringThreshold", EmitDefaultValue=false)] public decimal? MatrixFilteringThreshold { get; set; } /// <summary> /// If this option is activated the matrix factorisation is done with single precision and thus a reduction in memory consumption (often about 50%) and computation time is gained if the problem is well conditioned. If the problem is ill-conditioned one risks that in a nonlinear computation the newton algorithm fails to converge. /// </summary> /// <value>If this option is activated the matrix factorisation is done with single precision and thus a reduction in memory consumption (often about 50%) and computation time is gained if the problem is well conditioned. If the problem is ill-conditioned one risks that in a nonlinear computation the newton algorithm fails to converge.</value> [DataMember(Name="singlePrecision", EmitDefaultValue=false)] public bool? SinglePrecision { get; set; } /// <summary> /// If this option is activated MUMPS performs a pre-processing on order to identify the best parameter setting for some internal parameters adapted to the current problem. /// </summary> /// <value>If this option is activated MUMPS performs a pre-processing on order to identify the best parameter setting for some internal parameters adapted to the current problem.</value> [DataMember(Name="preprocessing", EmitDefaultValue=false)] public bool? Preprocessing { get; set; } /// <summary> /// Choose this parameter as &lt;b&gt;true&lt;/b&gt; to ensure that the system matrix saving is distributed among the processors of the computation. If multiple cores are used only the relevant part for each core is saved. If it is set to false the whole matrix is saved for each processor. This parameter has currently no effect for &lt;i&gt;Harmonic&lt;/i&gt; simulations. /// </summary> /// <value>Choose this parameter as &lt;b&gt;true&lt;/b&gt; to ensure that the system matrix saving is distributed among the processors of the computation. If multiple cores are used only the relevant part for each core is saved. If it is set to false the whole matrix is saved for each processor. This parameter has currently no effect for &lt;i&gt;Harmonic&lt;/i&gt; simulations.</value> [DataMember(Name="distributedMatrixStorage", EmitDefaultValue=false)] public bool? DistributedMatrixStorage { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class MUMPSSolver {\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" ForceSymmetric: ").Append(ForceSymmetric).Append("\n"); sb.Append(" PrecisionSingularityDetection: ").Append(PrecisionSingularityDetection).Append("\n"); sb.Append(" StopIfSingular: ").Append(StopIfSingular).Append("\n"); sb.Append(" MatrixType: ").Append(MatrixType).Append("\n"); sb.Append(" MemoryPercentageForPivoting: ").Append(MemoryPercentageForPivoting).Append("\n"); sb.Append(" LinearSystemRelativeResidual: ").Append(LinearSystemRelativeResidual).Append("\n"); sb.Append(" MatrixFilteringThreshold: ").Append(MatrixFilteringThreshold).Append("\n"); sb.Append(" SinglePrecision: ").Append(SinglePrecision).Append("\n"); sb.Append(" Preprocessing: ").Append(Preprocessing).Append("\n"); sb.Append(" RenumberingMethod: ").Append(RenumberingMethod).Append("\n"); sb.Append(" Postprocessing: ").Append(Postprocessing).Append("\n"); sb.Append(" DistributedMatrixStorage: ").Append(DistributedMatrixStorage).Append("\n"); sb.Append(" MemoryManagement: ").Append(MemoryManagement).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as MUMPSSolver); } /// <summary> /// Returns true if MUMPSSolver instances are equal /// </summary> /// <param name="input">Instance of MUMPSSolver to be compared</param> /// <returns>Boolean</returns> public bool Equals(MUMPSSolver input) { if (input == null) return false; return ( this.Type == input.Type || (this.Type != null && this.Type.Equals(input.Type)) ) && ( this.ForceSymmetric == input.ForceSymmetric || (this.ForceSymmetric != null && this.ForceSymmetric.Equals(input.ForceSymmetric)) ) && ( this.PrecisionSingularityDetection == input.PrecisionSingularityDetection || (this.PrecisionSingularityDetection != null && this.PrecisionSingularityDetection.Equals(input.PrecisionSingularityDetection)) ) && ( this.StopIfSingular == input.StopIfSingular || (this.StopIfSingular != null && this.StopIfSingular.Equals(input.StopIfSingular)) ) && ( this.MatrixType == input.MatrixType || this.MatrixType.Equals(input.MatrixType) ) && ( this.MemoryPercentageForPivoting == input.MemoryPercentageForPivoting || (this.MemoryPercentageForPivoting != null && this.MemoryPercentageForPivoting.Equals(input.MemoryPercentageForPivoting)) ) && ( this.LinearSystemRelativeResidual == input.LinearSystemRelativeResidual || (this.LinearSystemRelativeResidual != null && this.LinearSystemRelativeResidual.Equals(input.LinearSystemRelativeResidual)) ) && ( this.MatrixFilteringThreshold == input.MatrixFilteringThreshold || (this.MatrixFilteringThreshold != null && this.MatrixFilteringThreshold.Equals(input.MatrixFilteringThreshold)) ) && ( this.SinglePrecision == input.SinglePrecision || (this.SinglePrecision != null && this.SinglePrecision.Equals(input.SinglePrecision)) ) && ( this.Preprocessing == input.Preprocessing || (this.Preprocessing != null && this.Preprocessing.Equals(input.Preprocessing)) ) && ( this.RenumberingMethod == input.RenumberingMethod || this.RenumberingMethod.Equals(input.RenumberingMethod) ) && ( this.Postprocessing == input.Postprocessing || this.Postprocessing.Equals(input.Postprocessing) ) && ( this.DistributedMatrixStorage == input.DistributedMatrixStorage || (this.DistributedMatrixStorage != null && this.DistributedMatrixStorage.Equals(input.DistributedMatrixStorage)) ) && ( this.MemoryManagement == input.MemoryManagement || this.MemoryManagement.Equals(input.MemoryManagement) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Type != null) hashCode = hashCode * 59 + this.Type.GetHashCode(); if (this.ForceSymmetric != null) hashCode = hashCode * 59 + this.ForceSymmetric.GetHashCode(); if (this.PrecisionSingularityDetection != null) hashCode = hashCode * 59 + this.PrecisionSingularityDetection.GetHashCode(); if (this.StopIfSingular != null) hashCode = hashCode * 59 + this.StopIfSingular.GetHashCode(); hashCode = hashCode * 59 + this.MatrixType.GetHashCode(); if (this.MemoryPercentageForPivoting != null) hashCode = hashCode * 59 + this.MemoryPercentageForPivoting.GetHashCode(); if (this.LinearSystemRelativeResidual != null) hashCode = hashCode * 59 + this.LinearSystemRelativeResidual.GetHashCode(); if (this.MatrixFilteringThreshold != null) hashCode = hashCode * 59 + this.MatrixFilteringThreshold.GetHashCode(); if (this.SinglePrecision != null) hashCode = hashCode * 59 + this.SinglePrecision.GetHashCode(); if (this.Preprocessing != null) hashCode = hashCode * 59 + this.Preprocessing.GetHashCode(); hashCode = hashCode * 59 + this.RenumberingMethod.GetHashCode(); hashCode = hashCode * 59 + this.Postprocessing.GetHashCode(); if (this.DistributedMatrixStorage != null) hashCode = hashCode * 59 + this.DistributedMatrixStorage.GetHashCode(); hashCode = hashCode * 59 + this.MemoryManagement.GetHashCode(); return hashCode; } } } }
95.642857
1,196
0.676534
[ "MIT" ]
SimScaleGmbH/simscale-csharp-sdk
src/SimScale.Sdk/Model/MUMPSSolver.cs
44,187
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.IO; public class IniHelper { private static Dictionary<string, object> _cache = new Dictionary<string, object>(); private static Dictionary<string, FileSystemWatcher> _watcher = new Dictionary<string, FileSystemWatcher>(); private static object _lock = new object(); private static object loadAndCache(string path) { path = TranslateUrl(path); object ret = null; if (!_cache.TryGetValue(path, out ret)) { object value2 = LoadIniNotCache(path); string dir = Path.GetDirectoryName(path); string name = Path.GetFileName(path); FileSystemWatcher fsw = new FileSystemWatcher(dir, name); fsw.IncludeSubdirectories = false; fsw.Changed += watcher_handler; fsw.Renamed += watcher_handler; fsw.EnableRaisingEvents = false; lock (_lock) { if (!_cache.TryGetValue(path, out ret)) { _cache.Add(path, ret = value2); _watcher.Add(path, fsw); fsw.EnableRaisingEvents = true; } else { fsw.Dispose(); } } } return ret; } private static void watcher_handler(object sender, FileSystemEventArgs e) { lock (_lock) { _cache.Remove(e.FullPath); FileSystemWatcher fsw = null; if (_watcher.TryGetValue(e.FullPath, out fsw)) { fsw.EnableRaisingEvents = false; fsw.Dispose(); } } } public static Dictionary<string, NameValueCollection> LoadIni(string path) { return loadAndCache(path) as Dictionary<string, NameValueCollection>; } public static Dictionary<string, NameValueCollection> LoadIniNotCache(string path) { Dictionary<string, NameValueCollection> ret = new Dictionary<string, NameValueCollection>(); string[] lines = ReadTextFile(path).Split(new string[] { "\n" }, StringSplitOptions.None); string key = ""; foreach (string line2 in lines) { string line = line2.Trim(); if (string.IsNullOrEmpty(line) || line.StartsWith("#") || line.StartsWith(";")) continue; Match m = Regex.Match(line, @"^\[([^\]]+)\]$"); if (m.Success) { key = m.Groups[1].Value; continue; } if (!ret.ContainsKey(key)) ret.Add(key, new NameValueCollection()); string[] kv = line.Split(new char[] { '=' }, 2); if (!string.IsNullOrEmpty(kv[0])) { ret[key][kv[0]] = kv.Length > 1 ? kv[1] : null; } } return ret; } public static string ReadTextFile(string path) { byte[] bytes = ReadFile(path); return Encoding.UTF8.GetString(bytes).TrimStart((char)65279); } public static byte[] ReadFile(string path) { if (File.Exists(path)) { string destFileName = Path.GetTempFileName(); File.Copy(path, destFileName, true); int read = 0; byte[] data = new byte[1024]; using (MemoryStream ms = new MemoryStream()) { using (FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Read)) { do { read = fs.Read(data, 0, data.Length); if (read <= 0) break; ms.Write(data, 0, read); } while (true); } File.Delete(destFileName); data = ms.ToArray(); } return data; } return new byte[] { }; } public static string TranslateUrl(string url) { return TranslateUrl(url, null); } public static string TranslateUrl(string url, string baseDir) { if (string.IsNullOrEmpty(baseDir)) baseDir = AppContext.BaseDirectory + "/"; if (string.IsNullOrEmpty(url)) return Path.GetDirectoryName(baseDir); if (url.StartsWith("~/")) url = url.Substring(1); if (url.StartsWith("/")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('/'))); if (url.StartsWith("\\")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('\\'))); if (url.IndexOf(":\\") != -1) return url; return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url)); } }
34.714286
119
0.686471
[ "Apache-2.0" ]
2881099/dotnetGen_mysql
GenMy/Lib/IniHelper.cs
3,890
C#
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2019 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // 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.ComponentModel; using System.Threading; using PdfSharp.Pdf.Internal; namespace PdfSharp.Internal { /// <summary> /// Static locking functions to make PDFsharp thread save. /// </summary> internal static class Lock { public static void EnterGdiPlus() { //if (_fontFactoryLockCount > 0) // throw new InvalidOperationException(""); Monitor.Enter(GdiPlus); _gdiPlusLockCount++; } public static void ExitGdiPlus() { _gdiPlusLockCount--; Monitor.Exit(GdiPlus); } static readonly object GdiPlus = new object(); static int _gdiPlusLockCount; public static void EnterFontFactory() { Monitor.Enter(FontFactory); _fontFactoryLockCount++; } public static void ExitFontFactory() { _fontFactoryLockCount--; Monitor.Exit(FontFactory); } static readonly object FontFactory = new object(); [ThreadStatic] static int _fontFactoryLockCount; } }
32.434211
77
0.675456
[ "MIT" ]
0xced/PDFsharp
src/PdfSharp/Internal/Lock.cs
2,465
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace UnrealProjectTool.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("UnrealProjectTool.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to . /// </summary> internal static string EmptyModuleFiles { get { return ResourceManager.GetString("EmptyModuleFiles", resourceCulture); } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] EmptyModuleTemplate { get { object obj = ResourceManager.GetObject("EmptyModuleTemplate", resourceCulture); return ((byte[])(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap UPT_Background { get { object obj = ResourceManager.GetObject("UPT_Background", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap UPT_Icon { get { object obj = ResourceManager.GetObject("UPT_Icon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
40.640777
183
0.582418
[ "MIT" ]
MegaRGJ/UPT
Properties/Resources.Designer.cs
4,188
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System.Diagnostics; using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.DebugAdapter { public class ScopesRequest { public static readonly RequestType<ScopesRequestArguments, ScopesResponseBody, object, object> Type = RequestType<ScopesRequestArguments, ScopesResponseBody, object, object>.Create("scopes"); } [DebuggerDisplay("FrameId = {FrameId}")] public class ScopesRequestArguments { public int FrameId { get; set; } } public class ScopesResponseBody { public Scope[] Scopes { get; set; } } }
27.5
101
0.707879
[ "MIT" ]
Benny1007/PowerShellEditorServices
src/PowerShellEditorServices.Protocol/DebugAdapter/ScopesRequest.cs
825
C#
namespace WindowsFormsApplication10.pl { partial class FRM_LOGIN { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.txtid = new System.Windows.Forms.TextBox(); this.txtpwo = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.btnlogin = new System.Windows.Forms.Button(); this.btncancel = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // txtid // this.txtid.Location = new System.Drawing.Point(121, 73); this.txtid.Name = "txtid"; this.txtid.Size = new System.Drawing.Size(140, 20); this.txtid.TabIndex = 1; this.txtid.Text = "admin"; // // txtpwo // this.txtpwo.Location = new System.Drawing.Point(121, 108); this.txtpwo.Name = "txtpwo"; this.txtpwo.PasswordChar = '*'; this.txtpwo.Size = new System.Drawing.Size(140, 20); this.txtpwo.TabIndex = 2; this.txtpwo.Text = "ad123"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(20, 80); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(81, 13); this.label1.TabIndex = 2; this.label1.Text = "اسم المستخدم"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(20, 115); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(62, 13); this.label2.TabIndex = 3; this.label2.Text = "كلمة المرور "; // // btnlogin // this.btnlogin.Location = new System.Drawing.Point(274, 73); this.btnlogin.Name = "btnlogin"; this.btnlogin.Size = new System.Drawing.Size(75, 55); this.btnlogin.TabIndex = 3; this.btnlogin.Text = "دخول"; this.btnlogin.UseVisualStyleBackColor = true; this.btnlogin.Click += new System.EventHandler(this.btnlogin_Click); // // btncancel // this.btncancel.Location = new System.Drawing.Point(23, 134); this.btncancel.Name = "btncancel"; this.btncancel.Size = new System.Drawing.Size(326, 60); this.btncancel.TabIndex = 4; this.btncancel.Text = "خروج"; this.btncancel.UseVisualStyleBackColor = true; this.btncancel.Click += new System.EventHandler(this.btncancel_Click); // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Aref_Menna", 21.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(113, 9); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(150, 47); this.label3.TabIndex = 3; this.label3.Text = "تسجيل الدخول"; // // FRM_LOGIN // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(366, 232); this.Controls.Add(this.label3); this.Controls.Add(this.btncancel); this.Controls.Add(this.btnlogin); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.txtpwo); this.Controls.Add(this.txtid); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FRM_LOGIN"; this.RightToLeft = System.Windows.Forms.RightToLeft.Yes; this.RightToLeftLayout = true; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "نافذه الدخول"; this.Load += new System.EventHandler(this.FRM_LOGIN_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtid; private System.Windows.Forms.TextBox txtpwo; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button btnlogin; private System.Windows.Forms.Button btncancel; private System.Windows.Forms.Label label3; } }
40.642857
156
0.556415
[ "MIT" ]
ayman101440/final
pl/FRM_LOGIN.Designer.cs
5,743
C#
using Magnum.Core.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Magnum.Core.Services { /// <summary> /// Interface IContentHandlerRegistry /// </summary> public interface IContentHandlerRegistry { /// <summary> /// Register a content handler with the registry /// </summary> /// <param name="handler">The content handler</param> /// <returns><c>true</c> if successful, <c>false</c> otherwise</returns> bool Register(IContentHandler handler); /// <summary> /// Unregisters a content handler /// </summary> /// <param name="handler">The handler to remove</param> /// <returns><c>true</c> if successfully unregistered, <c>false</c> otherwise</returns> bool Unregister(IContentHandler handler); /// <summary> /// Returns a content view model for the specified object which needs to be displayed as a document /// The object could be anything - based on the handlers, a content view model is returned /// </summary> /// <param name="info">The object which needs to be displayed as a document</param> /// <returns>The content view model for the given info</returns> ITool GetViewModel(object info); /// <summary> /// Returns a content view model for the specified contentID which needs to be displayed as a document /// The contentID is the ID used in AvalonDock /// </summary> /// <param name="contentId">The contentID which needs to be displayed as a document</param> /// <returns>The content view model for the given info</returns> ITool GetViewModelFromContentId(string contentId); } }
36.804348
106
0.689309
[ "Apache-2.0" ]
DISN/Magnum
Src/Magnum.Core/Services/IContentHandlerRegistry.cs
1,695
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.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.IdentifiersShouldNotMatchKeywordsAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpIdentifiersShouldNotMatchKeywordsFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.IdentifiersShouldNotMatchKeywordsAnalyzer, Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicIdentifiersShouldNotMatchKeywordsFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { /// <summary> /// Contains those unit tests for the IdentifiersShouldNotMatchKeywords analyzer that /// pertain to the TypeRule, which applies to the names of types. /// </summary> public class IdentifiersShouldNotMatchKeywordsTypeRuleTests { [Fact] public async Task CSharpDiagnosticForKeywordNamedPublicType() { await VerifyCS.VerifyAnalyzerAsync(@" public class @class {} ", GetCSharpResultAt(2, 14, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "class", "class")); } [Fact] public async Task BasicDiagnosticForKeywordNamedPublicType() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class [Class] End Class ", GetBasicResultAt(2, 14, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "Class", "Class")); } [Fact] public async Task CSharpNoDiagnosticForCaseSensitiveKeywordNamedPublicTypeWithDifferentCasing() { await VerifyCS.VerifyAnalyzerAsync(@" public class iNtErNaL {} "); } [Fact] public async Task BasicNoDiagnosticForCaseSensitiveKeywordNamedPublicTypeWithDifferentCasing() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class iNtErNaL End Class"); } [Fact] public async Task CSharpDiagnosticForCaseInsensitiveKeywordNamedPublicType() { await VerifyCS.VerifyAnalyzerAsync(@" public struct aDdHaNdLeR {} ", GetCSharpResultAt(2, 15, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "aDdHaNdLeR", "AddHandler")); } [Fact] public async Task BasicDiagnosticForCaseInsensitiveKeywordNamedPublicType() { await VerifyVB.VerifyAnalyzerAsync(@" Public Structure [aDdHaNdLeR] End Structure", GetBasicResultAt(2, 18, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "aDdHaNdLeR", "AddHandler")); } [Fact] public async Task CSharpNoDiagnosticForKeywordNamedInternalype() { await VerifyCS.VerifyAnalyzerAsync(@" internal class @class {} "); } [Fact] public async Task BasicNoDiagnosticForKeywordNamedInternalType() { await VerifyVB.VerifyAnalyzerAsync(@" Friend Class [Class] End Class "); } [Fact] public async Task CSharpNoDiagnosticForNonKeywordNamedPublicType() { await VerifyCS.VerifyAnalyzerAsync(@" public class classic {} "); } [Fact] public async Task BasicNoDiagnosticForNonKeywordNamedPublicType() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class Classic End Class "); } [Fact] public async Task CSharpDiagnosticForKeywordNamedPublicTypeInNamespace() { await VerifyCS.VerifyAnalyzerAsync(@" namespace N { public enum @enum {} } ", GetCSharpResultAt(4, 17, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "enum", "enum")); } [Fact] public async Task BasicDiagnosticForKeywordNamedPublicTypeInNamespace() { await VerifyVB.VerifyAnalyzerAsync(@" Namespace N Public Enum [Enum] X End Enum End Namespace ", GetBasicResultAt(3, 17, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "Enum", "Enum")); } [Fact] public async Task CSharpDiagnosticForKeywordNamedProtectedTypeNestedInPublicClass() { await VerifyCS.VerifyAnalyzerAsync(@" public class C { protected class @protected {} } ", GetCSharpResultAt(4, 21, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "C.protected", "protected")); } [Fact] public async Task BasicDiagnosticForKeywordNamedProtectedTypeNestedInPublicClass() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class C Protected Class [Protected] End Class End Class ", GetBasicResultAt(3, 21, IdentifiersShouldNotMatchKeywordsAnalyzer.TypeRule, "C.Protected", "Protected")); } private DiagnosticResult GetCSharpResultAt(int line, int column, DiagnosticDescriptor rule, string arg1, string arg2) => new DiagnosticResult(rule) .WithLocation(line, column) .WithArguments(arg1, arg2); private DiagnosticResult GetBasicResultAt(int line, int column, DiagnosticDescriptor rule, string arg1, string arg2) => new DiagnosticResult(rule) .WithLocation(line, column) .WithArguments(arg1, arg2); } }
32.804734
161
0.684343
[ "Apache-2.0" ]
edespong/roslyn-analyzers
src/Microsoft.CodeQuality.Analyzers/UnitTests/ApiDesignGuidelines/IdentifiersShouldNotMatchKeywordsTypeRuleTests.cs
5,546
C#
using QuarterShare.Command; using QuarterShare.Connection; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace QuarterShare.Worker { class ServerWorker : Worker { public QuarterServer Server; public ServerWorker(ServerConfig init) { Server = new QuarterServer(init); new Thread(MainThread).Start(Server); } private static void MainThread(object data) { QuarterServer server = (QuarterServer)data; ColorPrint( "@@@@@@@@@@@ Quarter Share\n@@@@@@@@@@@\n@@@@@@@@@@@ Use command "); Blue(".help"); ColorPrint( " to learn more about the server's\n@@@###@###@ internal commands\n@@@@@#@#@@@\n" + "@@@###@###@ The server is running at " + server.Host + ":" + server.Port + "\n" + "@@@#@@@@@#@\n@#@###@###@\n@@@@@@@@@@@\n@@@@@@@@@@@\n@@@@@@@@@@@\n\n"); while (true) { try { TcpClient connection = server.Listener.AcceptTcpClient(); new ClientWorker(server, connection); } catch { Red("Failed to accept tcp connection"); } } } private static void ColorPrint(string str) { for (int i = 0; i < str.Length; i ++) { char c = str[i]; if (c == '@') Red("■"); else if (c == '#') White("■"); else White(c); } } } }
26.955882
100
0.436989
[ "MIT" ]
Jerrylum/.25share-windows
QuarterShare/Worker/ServerWorker.cs
1,839
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace santennio.utils.ui { public class FixLayoutWithFit : MonoBehaviour { // Start is called before the first frame update void OnEnable() { LayoutRebuilder.ForceRebuildLayoutImmediate(this.GetComponent<RectTransform>()); } } }
20.1
92
0.674129
[ "MIT" ]
SantEnnio/InstagramUI_InUnity
Assets/Scenes/Scripts/FixLayoutWithFit.cs
402
C#
using CDK.Damage; using CDK.Data; using UnityEngine; namespace CDK { [CreateAssetMenu(fileName = "ammo_", menuName = CConst.EDITOR_SCRIPTABLEOBJECT_CREATION_PREFIX + "Ammo data", order = 51)] public class CAmmoScriptableObject : CItemBaseScriptableObject, ICDamageDealerItem { public CHitInfoData HitInfo { get { return this.hitInfo; } } [SerializeField] private CHitInfoData hitInfo; public CAmmoType CAmmoType { get { return this._ammoType; } } [SerializeField] private CAmmoType _ammoType; public CProjectileType CProjectileType { get { return this.cProjectileType; } } [SerializeField] private CProjectileType cProjectileType; public GameObject ProjectilePrefabToSpawn { get { return this._projectilePrefabToSpawn; } } [SerializeField] private GameObject _projectilePrefabToSpawn; public float ProjectileInitialSpeed { get { return this._projectileInitialSpeed; } } [SerializeField] private float _projectileInitialSpeed = 1f; public float ProjectileLifetime { get { return this._projectileLifetime; } } [SerializeField] private float _projectileLifetime = 0.1f; public bool IsInfinite { get { return this._isInfinite; } } [SerializeField] private bool _isInfinite; public float SelfRepulsionMultiplier { get { return this._selfRepulsionMultiplier; } } [SerializeField] private float _selfRepulsionMultiplier = 10f; } }
27.666667
123
0.761162
[ "MIT" ]
Chrisdbhr/CDK
Scripts/Gameplay/Items/ScriptableObjects/CAmmoScriptableObject.cs
1,411
C#
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers * for more information concerning the license and the contributors participating to this project. */ using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OAuth; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; namespace AspNet.Security.OAuth.Myob { public class MyobAuthenticationHandler : OAuthHandler<MyobAuthenticationOptions> { public MyobAuthenticationHandler( [NotNull] IOptionsMonitor<MyobAuthenticationOptions> options, [NotNull] ILoggerFactory logger, [NotNull] UrlEncoder encoder, [NotNull] ISystemClock clock) : base(options, logger, encoder, clock) { } protected override async Task<AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) { // Note: MYOB doesn't provide a user information endpoint, // so we rely on the details sent back in the token request. var user = (JObject) tokens.Response.SelectToken("user"); var principal = new ClaimsPrincipal(identity); var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, user); context.RunClaimActions(user); await Options.Events.CreatingTicket(context); return new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name); } } }
40.913043
133
0.714134
[ "Apache-2.0" ]
cfdd73/AspNet.Security.OAuth.Providers
src/AspNet.Security.OAuth.Myob/MyobAuthenticationHandler.cs
1,882
C#
// Copyright (c) 2021 EPAM Systems // // 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 NUnit.Framework; namespace Epam.FixAntenna.NetCore.FixEngine.ResetLogon { [TestFixture] internal class InitiatorResetLogonTest : AbstractInitiatorResetTst { [Test] public virtual void TestReceiveResetLogon() { ResetSeqNums(); var message = AcceptorSessionEmulator.GetLastReceivedMessage(); Assert.AreEqual(message.MsgSeqNumber, 1); Assert.AreEqual(message.GetTagValueAsString(141), "Y"); } [Test] public virtual void TestReceiveAndSendResetLogon() { ResetSeqNums(); AcceptorSessionEmulator.SendResetLogon(); AcceptorSessionEmulator.ReceiveAnyMessage(); var message = AcceptorSessionEmulator.GetLastReceivedMessage(); Assert.AreEqual(message.MsgSeqNumber, 2); Assert.AreEqual(message.GetTagValueAsString(35), "0"); } } }
30.488889
75
0.75656
[ "Apache-2.0" ]
epam/fix-antenna-net-core
Tests/Core.Tests/FixEngine/ResetLogon/InitiatorResetLogonTest.cs
1,374
C#
namespace System.Web.Routing { using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; [TypeForwardedFrom("System.Web.Routing, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")] public class RouteValueDictionary : IDictionary<string, object> { private Dictionary<string, object> _dictionary; public RouteValueDictionary() { _dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); } public RouteValueDictionary(object values) { _dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); AddValues(values); } public RouteValueDictionary(IDictionary<string, object> dictionary) { _dictionary = new Dictionary<string, object>(dictionary, StringComparer.OrdinalIgnoreCase); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] public int Count { get { return _dictionary.Count; } } public Dictionary<string, object>.KeyCollection Keys { get { return _dictionary.Keys; } } public Dictionary<string, object>.ValueCollection Values { get { return _dictionary.Values; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] public object this[string key] { get { object value; TryGetValue(key, out value); return value; } set { _dictionary[key] = value; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] public void Add(string key, object value) { _dictionary.Add(key, value); } private void AddValues(object values) { if (values != null) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(values); foreach (PropertyDescriptor prop in props) { object val = prop.GetValue(values); Add(prop.Name, val); } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] public void Clear() { _dictionary.Clear(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] public bool ContainsKey(string key) { return _dictionary.ContainsKey(key); } public bool ContainsValue(object value) { return _dictionary.ContainsValue(value); } public Dictionary<string, object>.Enumerator GetEnumerator() { return _dictionary.GetEnumerator(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] public bool Remove(string key) { return _dictionary.Remove(key); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] public bool TryGetValue(string key, out object value) { return _dictionary.TryGetValue(key, out value); } #region IDictionary<string,object> Members [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] ICollection<string> IDictionary<string, object>.Keys { get { return _dictionary.Keys; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] ICollection<object> IDictionary<string, object>.Values { get { return _dictionary.Values; } } #endregion #region ICollection<KeyValuePair<string,object>> Members [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item) { ((ICollection<KeyValuePair<string, object>>)_dictionary).Add(item); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item) { return ((ICollection<KeyValuePair<string, object>>)_dictionary).Contains(item); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { ((ICollection<KeyValuePair<string, object>>)_dictionary).CopyTo(array, arrayIndex); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] bool ICollection<KeyValuePair<string, object>>.IsReadOnly { get { return ((ICollection<KeyValuePair<string, object>>)_dictionary).IsReadOnly; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item) { return ((ICollection<KeyValuePair<string, object>>)_dictionary).Remove(item); } #endregion #region IEnumerable<KeyValuePair<string,object>> Members [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator() { return GetEnumerator(); } #endregion #region IEnumerable Members [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
42.440252
132
0.66064
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/xsp/system/Web/Routing/RouteValueDictionary.cs
6,750
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.EntityFrameworkCore.Infrastructure; namespace Microsoft.EntityFrameworkCore.Metadata.Builders { /// <summary> /// <para> /// Provides a simple API for configuring a <see cref="IMutableKey" />. /// </para> /// <para> /// Instances of this class are returned from methods when using the <see cref="ModelBuilder" /> API /// and it is not designed to be directly constructed in your application code. /// </para> /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information. /// </remarks> // ReSharper disable once UnusedTypeParameter public class KeyBuilder<T> : KeyBuilder { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [EntityFrameworkInternal] public KeyBuilder(IMutableKey key) : base(key) { } /// <summary> /// Adds or updates an annotation on the key. If an annotation with the key specified in /// <paramref name="annotation" /> already exists its value will be updated. /// </summary> /// <param name="annotation">The key of the annotation to be added or updated.</param> /// <param name="value">The value to be stored in the annotation.</param> /// <returns>The same builder instance so that multiple configuration calls can be chained.</returns> public new virtual KeyBuilder<T> HasAnnotation(string annotation, object? value) => (KeyBuilder<T>)base.HasAnnotation(annotation, value); } }
48.5
131
0.64545
[ "MIT" ]
KaloyanIT/efcore
src/EFCore/Metadata/Builders/KeyBuilder`.cs
2,231
C#
using SD.Data.Models.DomainModels; using System; namespace SD.Web.Areas.Administration.Models.SensorViewModels { public class SensorTableViewModel { public SensorTableViewModel(){} public SensorTableViewModel(UserSensor userSensor) { this.Id = userSensor.Id; this.Name = userSensor.Name; this.Latitude = userSensor.Latitude; this.Longitude = userSensor.Longitude; this.AlarmMax = userSensor.AlarmMax; this.AlarmMin = userSensor.AlarmMin; this.IsPublic = userSensor.IsPublic; this.LastValue = double.Parse(userSensor.Sensor.LastValue); this.IsState = userSensor.Sensor.IsState; this.IsDeleted = userSensor.IsDeleted; } public string Id { get; set; } public string Name { get; set; } public string Latitude { get; set; } public string Longitude { get; set; } public double AlarmMax { get; set; } public double AlarmMin { get; set; } public bool IsPublic { get; set; } public bool AlarmTriggered { get; set; } public double LastValue { get; set; } public bool IsState { get; set; } public bool IsDeleted { get; set; } } }
22.854167
62
0.711942
[ "MIT" ]
ateber91/TelerikProject
SD.Web/SD.Web/Areas/Administration/Models/SensorViewModels/SensorTableViewModel.cs
1,099
C#
using DaRT.Properties; using System; using System.Windows.Forms; namespace DaRT { public partial class GUIban : Form { private RCon _rcon; private Ban _ban; public GUIban(RCon rcon, int id, string name, string guid, string ip, bool online) { InitializeComponent(); _rcon = rcon; _rcon.Pending = name; _ban = new Ban(id, name, guid, ip, online); if (_ban.Online) this.Text = "Ban " + _ban.Name; else this.Text = "Ban " + _ban.Name + " (Offline)"; try { span.SelectedIndex = Settings.Default.span; } catch { Settings.Default.span = 0; } if (_ban.Online) { if (Settings.Default.banGUID && Settings.Default.banIP) mode.SelectedIndex = 2; if (Settings.Default.banGUID) mode.SelectedIndex = 0; else if (Settings.Default.banIP) mode.SelectedIndex = 1; } else { mode.SelectedIndex = 0; mode.Enabled = false; } } private void ban_Click(object sender, EventArgs e) { _ban.Reason = reason.Text; int duration = 0; try { duration = int.Parse(this.duration.Text); } catch { MessageBox.Show("Duration must be a number!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (span.SelectedIndex == 1) duration *= 60; else if (span.SelectedIndex == 2) duration *= 1440; else if (span.SelectedIndex == 3) duration *= 10080; _ban.Duration = duration; if (mode.SelectedIndex == 0) _ban.IP = ""; else if (mode.SelectedIndex == 1) _ban.GUID = ""; if (!_rcon.PendingLeft) { _rcon.Ban(_ban); } else { if (MessageBox.Show("The player you were about to ban left the game.\r\nPress OK to ban him offline (GUID only) instead.", "Attention!", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK) { _ban.Online = false; _rcon.Ban(_ban); } } _rcon.Pending = ""; _rcon.PendingLeft = false; Settings.Default.span = span.SelectedIndex; if (_ban.Online) { if (mode.SelectedIndex == 0) { Settings.Default.banGUID = true; Settings.Default.banIP = false; } else if (mode.SelectedIndex == 1) { Settings.Default.banGUID = false; Settings.Default.banIP = true; } else if (mode.SelectedIndex == 2) { Settings.Default.banGUID = true; Settings.Default.banIP = true; } } Settings.Default.Save(); this.Close(); } private void abort_Click(object sender, EventArgs e) { this.Close(); } private void duration_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsNumber(e.KeyChar) && !char.IsControl(e.KeyChar)) { e.Handled = true; } } } }
28.051852
222
0.442567
[ "MIT" ]
bravo10delta/DaRT
DaRT/Windows/GUIban.cs
3,789
C#
using Discount.API.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Discount.API.Repositories { public interface IDiscountRepo { Task<Coupon> GetDisc(string productName); Task<bool> CreateDisc(Coupon coupon); Task<bool> UpdateDisc(Coupon coupon); Task<bool> DeleteDisc(string productName); } }
22.722222
50
0.716381
[ "MIT" ]
Daniels-Main/MicroServices
src/Services/Discount/Discount.API/Repositories/IDiscountRepo.cs
411
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.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class CompilationErrorTests : CompilingTestBase { #region Symbol Error Tests private static readonly ModuleMetadata s_mod1 = ModuleMetadata.CreateFromImage(TestResources.DiagnosticTests.DiagnosticTests.ErrTestMod01); private static readonly ModuleMetadata s_mod2 = ModuleMetadata.CreateFromImage(TestResources.DiagnosticTests.DiagnosticTests.ErrTestMod02); [Fact()] public void CS0148ERR_BadDelegateConstructor() { var il = @" .class public auto ansi sealed F extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor( //object 'object', native int 'method') runtime managed { } // end of method F::.ctor .method public hidebysig newslot virtual instance void Invoke() runtime managed { } // end of method F::Invoke .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { } // end of method F::BeginInvoke .method public hidebysig newslot virtual instance void EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed { } // end of method F::EndInvoke } // end of class F "; var source = @" class C { void Foo() { F del = Foo; del(); //need to use del or the delegate receiver alone is emitted in optimized code. } } "; var comp = CreateCompilationWithCustomILSource(source, il); var emitResult = comp.Emit(new System.IO.MemoryStream()); emitResult.Diagnostics.Verify(Diagnostic(ErrorCode.ERR_BadDelegateConstructor, "Foo").WithArguments("F")); } /// <summary> /// This error is specific to netmodule scenarios /// We used to give error CS0011: The base class or interface 'A' in assembly 'xxx' referenced by type 'B' could not be resolved /// In Roslyn we do not know the context in which the lookup was occuring, so we give a new, more generic message. /// </summary> [WorkItem(546451, "DevDiv")] [Fact()] public void CS0011ERR_CantImportBase01() { var text1 = @"class A {}"; var text2 = @"class B : A {}"; var text = @" class Test { B b; void M() { Test x = b; } }"; var name1 = GetUniqueName(); var module1 = CreateCompilationWithMscorlib(text1, options: TestOptions.ReleaseModule, assemblyName: name1); var module2 = CreateCompilationWithMscorlib(text2, options: TestOptions.ReleaseModule, references: new[] { ModuleMetadata.CreateFromImage(module1.EmitToArray(options: new EmitOptions(metadataOnly: true))).GetReference() }); // use ref2 only var comp = CreateCompilationWithMscorlib(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new Dictionary<string, ReportDiagnostic>() { { MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_UnreferencedField), ReportDiagnostic.Suppress } }), references: new[] { ModuleMetadata.CreateFromImage(module2.EmitToArray(options: new EmitOptions(metadataOnly: true))).GetReference() }); comp.VerifyDiagnostics( // error CS8014: Reference to '1b2d660e-e892-4338-a4e7-f78ce7960ce9.netmodule' netmodule missing. Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments(name1 + ".netmodule"), // (8,18): error CS7079: The type 'A' is defined in a module that has not been added. You must add the module '2bddf16b-09e6-4c4d-bd08-f348e194eca4.netmodule'. // Test x = b; Diagnostic(ErrorCode.ERR_NoTypeDefFromModule, "b").WithArguments("A", name1 + ".netmodule"), // (8,18): error CS0029: Cannot implicitly convert type 'B' to 'Test' // Test x = b; Diagnostic(ErrorCode.ERR_NoImplicitConv, "b").WithArguments("B", "Test"), // (4,7): warning CS0649: Field 'Test.b' is never assigned to, and will always have its default value null // B b; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "b").WithArguments("Test.b", "null") ); } [Fact] public void CS0012ERR_NoTypeDef01() { var text = @"namespace NS { class Test { TC5<string, string> var; // inherit C1 from MDTestLib1.dll void M() { Test x = var; } } }"; var ref2 = TestReferences.SymbolsTests.MDTestLib2; var comp = CreateCompilationWithMscorlib(text, references: new MetadataReference[] { ref2 }, assemblyName: "Test3"); comp.VerifyDiagnostics( // (9,22): error CS0012: The type 'C1<>.C2<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'MDTestLib1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Test x = var; Diagnostic(ErrorCode.ERR_NoTypeDef, "var").WithArguments("C1<>.C2<>", "MDTestLib1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (9,22): error CS0029: Cannot implicitly convert type 'TC5<string, string>' to 'NS.Test' // Test x = var; Diagnostic(ErrorCode.ERR_NoImplicitConv, "var").WithArguments("TC5<string, string>", "NS.Test"), // (5,28): warning CS0649: Field 'NS.Test.var' is never assigned to, and will always have its default value null // TC5<string, string> var; // inherit C1 from MDTestLib1.dll Diagnostic(ErrorCode.WRN_UnassignedInternalField, "var").WithArguments("NS.Test.var", "null") ); } [Fact, WorkItem(8574, "DevDiv_Projects/Roslyn")] public void CS0029ERR_CannotImplicitlyConvertTypedReferenceToObject() { var text = @" class Program { static void M(System.TypedReference r) { var t = r.GetType(); } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,17): error CS0029: Cannot implicitly convert type 'System.TypedReference' to 'object' // var t = r.GetType(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "r").WithArguments("System.TypedReference", "object")); } // CS0036: see AttributeTests.InOutAttributes_Errors [Fact] public void CS0050ERR_BadVisReturnType() { var text = @"class MyClass { } public class MyClass2 { public static MyClass MyMethod() // CS0050 { return new MyClass(); } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisReturnType, Line = 7, Column = 27 }); } [Fact] public void CS0051ERR_BadVisParamType01() { var text = @"public class A { class B { } public static void F(B b) // CS0051 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 7, Column = 24 }); } [Fact] public void CS0051ERR_BadVisParamType02() { var text = @"class A { protected class P1 { } public class N { public void f(P1 p) { } protected void g(P1 p) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 7, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 8, Column = 24 }); } [Fact] public void CS0051ERR_BadVisParamType03() { var source = @"internal class A { } public class B<T> { public class C<U> { } } public class C1 { public void M(B<A> arg) { } } public class C2 { public void M(B<object>.C<A> arg) { } } public class C3 { public void M(B<A>.C<object> arg) { } } public class C4 { public void M(B<B<A>>.C<object> arg) { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (8,17): error CS0051: Inconsistent accessibility: parameter type 'B<A>' is less accessible than method 'C1.M(B<A>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C1.M(B<A>)", "B<A>").WithLocation(8, 17), // (12,17): error CS0051: Inconsistent accessibility: parameter type 'B<object>.C<A>' is less accessible than method 'C2.M(B<object>.C<A>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C2.M(B<object>.C<A>)", "B<object>.C<A>").WithLocation(12, 17), // (16,17): error CS0051: Inconsistent accessibility: parameter type 'B<A>.C<object>' is less accessible than method 'C3.M(B<A>.C<object>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C3.M(B<A>.C<object>)", "B<A>.C<object>").WithLocation(16, 17), // (20,17): error CS0051: Inconsistent accessibility: parameter type 'B<B<A>>.C<object>' is less accessible than method 'C4.M(B<B<A>>.C<object>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C4.M(B<B<A>>.C<object>)", "B<B<A>>.C<object>").WithLocation(20, 17)); } [Fact] public void CS0052ERR_BadVisFieldType() { var text = @"public class MyClass2 { public MyClass M; // CS0052 private class MyClass { } } public class MainClass { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisFieldType, Line = 3, Column = 20 }); } [Fact] public void CS0053ERR_BadVisPropertyType() { var text = @"internal interface InternalInterface { } public class PublicClass { } public class A { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } protected class B { public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } } } internal class C { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } protected class D { public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,30): error CS0053: Inconsistent accessibility: property return type 'InternalInterface' is less accessible than property 'A.Q' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "Q").WithArguments("A.Q", "InternalInterface").WithLocation(8, 30), // (9,28): error CS0053: Inconsistent accessibility: property return type 'A.ProtectedStruct' is less accessible than property 'A.R' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "R").WithArguments("A.R", "A.ProtectedStruct").WithLocation(9, 28), // (10,25): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("A.S", "A.PrivateClass").WithLocation(10, 25), // (13,30): error CS0053: Inconsistent accessibility: property return type 'A.ProtectedStruct' is less accessible than property 'A.V' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "V").WithArguments("A.V", "A.ProtectedStruct").WithLocation(13, 30), // (14,27): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("A.W", "A.PrivateClass").WithLocation(14, 27), // (18,34): error CS0053: Inconsistent accessibility: property return type 'InternalInterface' is less accessible than property 'A.B.Q' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "Q").WithArguments("A.B.Q", "InternalInterface").WithLocation(18, 34), // (20,29): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.B.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("A.B.S", "A.PrivateClass").WithLocation(20, 29), // (24,31): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.B.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("A.B.W", "A.PrivateClass").WithLocation(24, 31), // (33,28): error CS0053: Inconsistent accessibility: property return type 'C.ProtectedStruct' is less accessible than property 'C.R' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "R").WithArguments("C.R", "C.ProtectedStruct").WithLocation(33, 28), // (34,24): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("C.S", "C.PrivateClass").WithLocation(34, 25), // (37,30): error CS0053: Inconsistent accessibility: property return type 'C.ProtectedStruct' is less accessible than property 'C.V' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "V").WithArguments("C.V", "C.ProtectedStruct").WithLocation(37, 30), // (38,27): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("C.W", "C.PrivateClass").WithLocation(38, 27), // (44,29): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.D.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("C.D.S", "C.PrivateClass").WithLocation(44, 29), // (48,31): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.D.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("C.D.W", "C.PrivateClass").WithLocation(48, 31)); } [Fact] public void CS0054ERR_BadVisIndexerReturn() { var text = @"internal interface InternalInterface { } public class PublicClass { } public class A { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } protected class B { public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } } } internal class C { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } protected class D { public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,30): error CS0054: Inconsistent accessibility: indexer return type 'InternalInterface' is less accessible than indexer 'A.this[object]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[object]", "InternalInterface").WithLocation(8, 30), // (9,28): error CS0054: Inconsistent accessibility: indexer return type 'A.ProtectedStruct' is less accessible than indexer 'A.this[string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[string]", "A.ProtectedStruct").WithLocation(9, 28), // (10,25): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[double]", "A.PrivateClass").WithLocation(10, 25), // (13,30): error CS0054: Inconsistent accessibility: indexer return type 'A.ProtectedStruct' is less accessible than indexer 'A.this[string, string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[string, string]", "A.ProtectedStruct").WithLocation(13, 30), // (14,27): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[double, double]", "A.PrivateClass").WithLocation(14, 27), // (18,34): error CS0054: Inconsistent accessibility: indexer return type 'InternalInterface' is less accessible than indexer 'A.B.this[object]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[object]", "InternalInterface").WithLocation(18, 34), // (20,29): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.B.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[double]", "A.PrivateClass").WithLocation(20, 29), // (24,31): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.B.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[double, double]", "A.PrivateClass").WithLocation(24, 31), // (33,28): error CS0054: Inconsistent accessibility: indexer return type 'C.ProtectedStruct' is less accessible than indexer 'C.this[string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[string]", "C.ProtectedStruct").WithLocation(33, 28), // (34,24): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[double]", "C.PrivateClass").WithLocation(34, 25), // (37,30): error CS0054: Inconsistent accessibility: indexer return type 'C.ProtectedStruct' is less accessible than indexer 'C.this[string, string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[string, string]", "C.ProtectedStruct").WithLocation(37, 30), // (38,27): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[double, double]", "C.PrivateClass").WithLocation(38, 27), // (44,29): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.D.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.D.this[double]", "C.PrivateClass").WithLocation(44, 29), // (48,31): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.D.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.D.this[double, double]", "C.PrivateClass").WithLocation(48, 31)); } [Fact] public void CS0055ERR_BadVisIndexerParam() { var text = @"class MyClass //defaults to private accessibility { } public class MyClass2 { public int this[MyClass myClass] // CS0055 { get { return 0; } } } public class MyClass3 { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisIndexerParam, Line = 7, Column = 16 }); } [Fact] public void CS0056ERR_BadVisOpReturn() { var text = @"class MyClass { } public class A { public static implicit operator MyClass(A a) // CS0056 { return new MyClass(); } public static void Main() { } }"; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (7,28): error CS0056: Inconsistent accessibility: return type 'MyClass' is less accessible than operator 'A.implicit operator MyClass(A)' // public static implicit operator MyClass(A a) // CS0056 Diagnostic(ErrorCode.ERR_BadVisOpReturn, "MyClass").WithArguments("A.implicit operator MyClass(A)", "MyClass") ); } [Fact] public void CS0057ERR_BadVisOpParam() { var text = @"class MyClass //defaults to private accessibility { } public class MyClass2 { public static implicit operator MyClass2(MyClass iii) // CS0057 { return new MyClass2(); } public static void Main() { } }"; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (7,37): error CS0057: Inconsistent accessibility: parameter type 'MyClass' is less accessible than operator 'MyClass2.implicit operator MyClass2(MyClass)' // public static implicit operator MyClass2(MyClass iii) // CS0057 Diagnostic(ErrorCode.ERR_BadVisOpParam, "MyClass2").WithArguments("MyClass2.implicit operator MyClass2(MyClass)", "MyClass")); } [Fact] public void CS0058ERR_BadVisDelegateReturn() { var text = @"class MyClass { } public delegate MyClass MyClassDel(); // CS0058 public class A { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisDelegateReturn, Line = 5, Column = 25 }); } [WorkItem(542005, "DevDiv")] [Fact] public void CS0058ERR_BadVisDelegateReturn02() { var text = @" public class Outer { protected class Test { } public delegate Test MyDelegate(); }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,26): error CS0058: Inconsistent accessibility: return type 'Outer.Test' is less accessible than delegate 'Outer.MyDelegate' // public delegate Test MyDelegate(); Diagnostic(ErrorCode.ERR_BadVisDelegateReturn, "MyDelegate").WithArguments("Outer.MyDelegate", "Outer.Test").WithLocation(5, 26) ); } [Fact] public void CS0059ERR_BadVisDelegateParam() { var text = @" class MyClass {} //defaults to internal accessibility public delegate void MyClassDel(MyClass myClass); // CS0059 "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (3,22): error CS0059: Inconsistent accessibility: parameter type 'MyClass' is less accessible than delegate 'MyClassDel' // public delegate void MyClassDel(MyClass myClass); // CS0059 Diagnostic(ErrorCode.ERR_BadVisDelegateParam, "MyClassDel").WithArguments("MyClassDel", "MyClass") ); } [Fact] public void CS0060ERR_BadVisBaseClass() { var text = @" namespace NS { internal class MyBase { } public class MyClass : MyBase { } public class Outer { private class MyBase { } protected class MyClass : MyBase { } protected class MyBase01 { } protected internal class MyClass01 : MyBase { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 6, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 11, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 14, Column = 34 }); } [WorkItem(539511, "DevDiv")] [Fact] public void CS0060ERR_BadVisBaseClass02() { var text = @" public class A<T> { public class B<S> : A<B<D>.C> { public class C { } } protected class D { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 4, Column = 18 }); } [WorkItem(539512, "DevDiv")] [Fact] public void CS0060ERR_BadVisBaseClass03() { var text = @" public class A { protected class B { protected class C { } } } internal class F : A { private class D : B { public class E : C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 14, Column = 22 }); } [WorkItem(539546, "DevDiv")] [Fact] public void CS0060ERR_BadVisBaseClass04() { var text = @" public class A<T> { private class B : A<B.C> { private class C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 4, Column = 19 }); } [WorkItem(539562, "DevDiv")] [Fact] public void CS0060ERR_BadVisBaseClass05() { var text = @" class A<T> { class B : A<B> { public class C : B { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(539950, "DevDiv")] [Fact] public void CS0060ERR_BadVisBaseClass06() { var text = @" class A : C<E.F> { public class B { public class D { protected class F { } } } } class C<T> { } class E : A.B.D { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // E.F is inaccessible where written; cascaded ERR_BadVisBaseClass is therefore suppressed new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 2, Column = 15 }); } [Fact] public void CS0060ERR_BadVisBaseClass07() { var source = @"internal class A { } public class B<T> { public class C<U> { } } public class C1 : B<A> { } public class C2 : B<object>.C<A> { } public class C3 : B<A>.C<object> { } public class C4 : B<B<A>>.C<object> { }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (6,14): error CS0060: Inconsistent accessibility: base class 'B<A>' is less accessible than class 'C1' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "B<A>").WithLocation(6, 14), // (7,14): error CS0060: Inconsistent accessibility: base class 'B<object>.C<A>' is less accessible than class 'C2' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C2").WithArguments("C2", "B<object>.C<A>").WithLocation(7, 14), // (8,14): error CS0060: Inconsistent accessibility: base class 'B<A>.C<object>' is less accessible than class 'C3' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C3").WithArguments("C3", "B<A>.C<object>").WithLocation(8, 14), // (9,14): error CS0060: Inconsistent accessibility: base class 'B<B<A>>.C<object>' is less accessible than class 'C4' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C4").WithArguments("C4", "B<B<A>>.C<object>").WithLocation(9, 14)); } [Fact] public void CS0060ERR_BadVisBaseClass08() { var source = @"public class A { internal class B { public interface C { } } } public class B<T> : A { } public class C : B<A.B.C> { }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (9,14): error CS0060: Inconsistent accessibility: base class 'B<A.B.C>' is less accessible than class 'C' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("C", "B<A.B.C>").WithLocation(9, 14)); } [Fact] public void CS0061ERR_BadVisBaseInterface() { var text = @"internal interface A { } public interface AA : A { } // CS0061 // OK public interface B { } internal interface BB : B { } internal interface C { } internal interface CC : C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseInterface, Line = 2, Column = 18 }); } [Fact] public void CS0065ERR_EventNeedsBothAccessors() { var text = @"using System; public delegate void Eventhandler(object sender, int e); public class MyClass { public event EventHandler E1 { } // CS0065, public event EventHandler E2 { add { } } // CS0065, public event EventHandler E3 { remove { } } // CS0065, } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,31): error CS0065: 'MyClass.E1': event property must have both add and remove accessors // public event EventHandler E1 { } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("MyClass.E1"), // (6,31): error CS0065: 'MyClass.E2': event property must have both add and remove accessors // public event EventHandler E2 { add { } } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E2").WithArguments("MyClass.E2"), // (7,31): error CS0065: 'MyClass.E3': event property must have both add and remove accessors // public event EventHandler E3 { remove { } } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E3").WithArguments("MyClass.E3")); } [WorkItem(542570, "DevDiv")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface01() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,22): error CS0065: 'i1.myevent': event property must have both add and remove accessors Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "myevent").WithArguments("i1.myevent")); } [WorkItem(542570, "DevDiv")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface02() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add; remove; } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,35): error CS0073: An add or remove accessor must have a body Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";"), // (6,43): error CS0073: An add or remove accessor must have a body Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";"), // NOTE: dev10 doesn't report these cascading errors, but they seem more // informative than the parser errors above. // (6,32): error CS0069: An event in an interface cannot have add or remove accessors Diagnostic(ErrorCode.ERR_EventPropertyInInterface, "add"), // (6,37): error CS0069: An event in an interface cannot have add or remove accessors Diagnostic(ErrorCode.ERR_EventPropertyInInterface, "remove")); } [WorkItem(542570, "DevDiv")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface03() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add {} remove {} } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,32): error CS0069: An event in an interface cannot have add or remove accessors Diagnostic(ErrorCode.ERR_EventPropertyInInterface, "add"), // (5,39): error CS0069: An event in an interface cannot have add or remove accessors Diagnostic(ErrorCode.ERR_EventPropertyInInterface, "remove")); } [WorkItem(542570, "DevDiv")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface04() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add {} } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,32): error CS0069: An event in an interface cannot have add or remove accessors Diagnostic(ErrorCode.ERR_EventPropertyInInterface, "add")); } [Fact] public void CS0066ERR_EventNotDelegate() { var text = @" public class C { public event C Click; // CS0066 } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,20): error CS0066: 'C.Click': event must be of a delegate type // public event C Click; // CS0066 Diagnostic(ErrorCode.ERR_EventNotDelegate, "Click").WithArguments("C.Click"), // (4,20): warning CS0067: The event 'C.Click' is never used // public event C Click; // CS0066 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Click").WithArguments("C.Click")); } [Fact] public void CS0068ERR_InterfaceEventInitializer() { var text = @" delegate void MyDelegate(); interface I { event MyDelegate d = new MyDelegate(M.f); // CS0068 } class M { event MyDelegate d = new MyDelegate(M.f); public static void f() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,22): error CS0068: 'I.d': event in interface cannot have initializer // event MyDelegate d = new MyDelegate(M.f); // CS0068 Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "d").WithArguments("I.d")); } [Fact] public void CS0072ERR_CantOverrideNonEvent() { var text = @"delegate void MyDelegate(); class Test1 { public virtual event MyDelegate MyEvent; public virtual void VMeth() { } } class Test2 : Test1 { public override event MyDelegate VMeth // CS0072 { add { VMeth += value; } remove { VMeth -= value; } } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (13,38): error CS0072: 'Test2.VMeth': cannot override; 'Test1.VMeth()' is not an event // public override event MyDelegate VMeth // CS0072 Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "VMeth").WithArguments("Test2.VMeth", "Test1.VMeth()"), // (5,37): warning CS0067: The event 'Test1.MyEvent' is never used // public virtual event MyDelegate MyEvent; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test1.MyEvent")); } [Fact] public void CS0074ERR_AbstractEventInitializer() { var text = @" delegate void D(); abstract class Test { public abstract event D e = null; // CS0074 } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,29): error CS0074: 'Test.e': abstract event cannot have initializer // public abstract event D e = null; // CS0074 Diagnostic(ErrorCode.ERR_AbstractEventInitializer, "e").WithArguments("Test.e")); } [Fact] public void CS0076ERR_ReservedEnumerator() { var text = @"enum E { value__ } enum F { A, B, value__ } enum G { X = 0, value__ = 1, Z = value__ + 1 } enum H { Value__ } // no error class C { E value__; // no error static void M() { F value__; // no error } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (1,10): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum E { value__ } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (2,16): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum F { A, B, value__ } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (3,17): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum G { X = 0, value__ = 1, Z = value__ + 1 } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (10,11): warning CS0168: The variable 'value__' is declared but never used // F value__; // no error Diagnostic(ErrorCode.WRN_UnreferencedVar, "value__").WithArguments("value__"), // (7,7): warning CS0169: The field 'C.value__' is never used // E value__; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "value__").WithArguments("C.value__") ); } /// <summary> /// Currently parser error 1001, 1003. Is that good enough? /// </summary> [Fact()] public void CS0081ERR_TypeParamMustBeIdentifier01() { var text = @"namespace NS { class C { int F<int>() { } // CS0081 } }"; // Triage decision was made to have this be a parse error as the grammar specifies it as such. CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,11): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "int"), // (5,11): error CS1003: Syntax error, '>' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(">", "int"), // (5,11): error CS1003: Syntax error, '(' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments("(", "int"), // (5,14): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, ">"), // (5,14): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, ">").WithArguments(",", ">"), // (5,9): error CS0161: 'NS.C.F<>(int)': not all code paths return a value // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_ReturnExpected, "F").WithArguments("NS.C.F<>(int)")); } [Fact] public void CS0082ERR_MemberReserved01() { CreateCompilationWithMscorlib( @"class C { public void set_P(int i) { } public int P { get; set; } public int get_P() { return 0; } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C").WithLocation(4, 20), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "C").WithLocation(4, 25)); } [Fact] public void CS0082ERR_MemberReserved02() { CreateCompilationWithMscorlib( @"class A { public void set_P(int i) { } } partial class B : A { public int P { get { return 0; } set { } } } partial class B { partial void get_P(); public void set_P() { } } partial class B { partial void get_P() { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "B").WithLocation(9, 9)); } [Fact] public void CS0082ERR_MemberReserved03() { CreateCompilationWithMscorlib( @"abstract class C { public abstract object P { get; } protected abstract object Q { set; } internal object R { get; set; } protected internal object S { get { return null; } } private object T { set { } } object U { get { return null; } set { } } object get_P() { return null; } void set_P(object value) { } private object get_Q() { return null; } private void set_Q(object value) { } protected internal object get_R() { return null; } protected internal void set_R(object value) { } internal object get_S() { return null; } internal void set_S(object value) { } protected object get_T() { return null; } protected void set_T(object value) { } public object get_U() { return null; } public void set_U(object value) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C").WithLocation(3, 32), Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("set_P", "C").WithLocation(3, 28), Diagnostic(ErrorCode.ERR_MemberReserved, "Q").WithArguments("get_Q", "C").WithLocation(4, 31), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(4, 35), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_R", "C").WithLocation(5, 25), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_R", "C").WithLocation(5, 30), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_S", "C").WithLocation(6, 35), Diagnostic(ErrorCode.ERR_MemberReserved, "S").WithArguments("set_S", "C").WithLocation(6, 31), Diagnostic(ErrorCode.ERR_MemberReserved, "T").WithArguments("get_T", "C").WithLocation(7, 20), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_T", "C").WithLocation(7, 24), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_U", "C").WithLocation(8, 16), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_U", "C").WithLocation(8, 37)); } [Fact] public void CS0082ERR_MemberReserved04() { CreateCompilationWithMscorlibAndSystemCore( @"class A<T, U> { public T P { get; set; } // CS0082 public U Q { get; set; } // no error public U R { get; set; } // no error public void set_P(T t) { } public void set_Q(object o) { } public void set_R(T t) { } } class B : A<object, object> { } class C { public dynamic P { get; set; } // CS0082 public dynamic Q { get; set; } // CS0082 public object R { get; set; } // CS0082 public object S { get; set; } // CS0082 public void set_P(object o) { } public void set_Q(dynamic o) { } public void set_R(object o) { } public void set_S(dynamic o) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "A<T, U>").WithLocation(3, 23), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "C").WithLocation(15, 29), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(16, 29), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_R", "C").WithLocation(17, 28), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_S", "C").WithLocation(18, 28)); } [Fact] public void CS0082ERR_MemberReserved05() { CreateCompilationWithMscorlib( @"class C { object P { get; set; } object Q { get; set; } object R { get; set; } object[] S { get; set; } public object get_P(object o) { return null; } // CS0082 public void set_P() { } public void set_P(ref object o) { } public void get_Q() { } // CS0082 public object set_Q(object o) { return null; } // CS0082 public object set_Q(out object o) { o = null; return null; } void set_S(params object[] args) { } // CS0082 } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_Q", "C").WithLocation(4, 16), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(4, 21), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_S", "C").WithLocation(6, 23)); } [Fact] public void CS0082ERR_MemberReserved06() { // No errors for explicit interface implementation. CreateCompilationWithMscorlib( @"interface I { int get_P(); void set_P(int o); } class C : I { public int P { get; set; } int I.get_P() { return 0; } void I.set_P(int o) { } } ") .VerifyDiagnostics(); } [WorkItem(539770, "DevDiv")] [Fact] public void CS0082ERR_MemberReserved07() { // No errors for explicit interface implementation. CreateCompilationWithMscorlib( @"class C { public object P { get { return null; } } object get_P() { return null; } void set_P(object value) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C"), Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("set_P", "C")); } [Fact] public void CS0082ERR_MemberReserved08() { CreateCompilationWithMscorlib( @"class C { public event System.Action E; void add_E(System.Action value) { } void remove_E(System.Action value) { } } ") .VerifyDiagnostics( // (3,32): error CS0082: Type 'C' already reserves a member called 'add_E' with the same parameter types // public event System.Action E; Diagnostic(ErrorCode.ERR_MemberReserved, "E").WithArguments("add_E", "C"), // (3,32): error CS0082: Type 'C' already reserves a member called 'remove_E' with the same parameter types // public event System.Action E; Diagnostic(ErrorCode.ERR_MemberReserved, "E").WithArguments("remove_E", "C"), // (3,32): warning CS0067: The event 'C.E' is never used // public event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0082ERR_MemberReserved09() { CreateCompilationWithMscorlib( @"class C { public event System.Action E { add { } remove { } } void add_E(System.Action value) { } void remove_E(System.Action value) { } } ") .VerifyDiagnostics( // (3,36): error CS0082: Type 'C' already reserves a member called 'add_E' with the same parameter types // public event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_MemberReserved, "add").WithArguments("add_E", "C"), // (3,44): error CS0082: Type 'C' already reserves a member called 'remove_E' with the same parameter types // public event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_MemberReserved, "remove").WithArguments("remove_E", "C")); } [Fact] public void CS0100ERR_DuplicateParamName01() { var text = @"namespace NS { interface IFoo { void M1(byte b, sbyte b); } struct S { public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } } } "; var comp = CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,31): error CS0100: The parameter name 'b' is a duplicate // void M1(byte b, sbyte b); Diagnostic(ErrorCode.ERR_DuplicateParamName, "b").WithArguments("b").WithLocation(5, 31), // (10,45): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 45), // (10,59): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 59), // (10,77): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 77), // (10,82): error CS0229: Ambiguity between 'object' and 'ref string' // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_AmbigMember, "p").WithArguments("object", "ref string").WithLocation(10, 82) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0101ERR_DuplicateNameInNS01() { var text = @"namespace NS { struct Test { } class Test { } interface Test { } namespace NS1 { interface A<T, V> { } class A<T, V> { } class A<T, V> { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 5, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 10, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 11, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0101ERR_DuplicateNameInNS02() { var text = @"namespace NS { interface IFoo<T, V> { } class IFoo<T, V> { } struct SS { } public class SS { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 7, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0101ERR_DuplicateNameInNS03() { var text = @"namespace NS { interface IFoo<T, V> { } interface IFoo<T, V> { } struct SS { } public struct SS { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 7, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0101ERR_DuplicateNameInNS04() { var text = @"namespace NS { partial class Foo<T, V> { } // no error, because ""partial"" partial class Foo<T, V> { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0102ERR_DuplicateNameInClass01() { var text = @"class A { int n = 0; long n = 1; } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (4,10): error CS0102: The type 'A' already contains a definition for 'n' // long n = 1; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "n").WithArguments("A", "n"), // (3,9): warning CS0414: The field 'A.n' is assigned but its value is never used // int n = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "n").WithArguments("A.n"), // (4,10): warning CS0414: The field 'A.n' is assigned but its value is never used // long n = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "n").WithArguments("A.n") ); var classA = comp.SourceModule.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol; var ns = classA.GetMembers("n"); Assert.Equal(2, ns.Length); foreach (var n in ns) { Assert.Equal(TypeKind.Struct, (n as FieldSymbol).Type.TypeKind); } } [Fact] public void CS0102ERR_DuplicateNameInClass02() { CreateCompilationWithMscorlib( @"namespace NS { class C { interface I<T, U> { } interface I<T, U> { } struct S { } public struct S { } } struct S<X> { X x; C x; } } ") .VerifyDiagnostics( // (6,19): error CS0102: The type 'NS.C' already contains a definition for 'I' // interface I<T, U> { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("NS.C", "I"), // (9,23): error CS0102: The type 'NS.C' already contains a definition for 'S' // public struct S { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("NS.C", "S"), // (14,11): error CS0102: The type 'NS.S<X>' already contains a definition for 'x' // C x; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x").WithArguments("NS.S<X>", "x"), // (13,11): warning CS0169: The field 'NS.S<X>.x' is never used // X x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("NS.S<X>.x"), // (14,11): warning CS0169: The field 'NS.S<X>.x' is never used // C x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("NS.S<X>.x") ); // Dev10 miss this with previous errors } [Fact] public void CS0102ERR_DuplicateNameInClass03() { CreateCompilationWithMscorlib( @"namespace NS { class C { interface I<T> { } class I<U> { } struct S { } class S { } enum E { } interface E { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("NS.C", "I").WithLocation(6, 15), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("NS.C", "S").WithLocation(8, 15), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("NS.C", "E").WithLocation(10, 19)); } [Fact] public void CS0104ERR_AmbigContext01() { var text = @"namespace n1 { public interface IFoo<T> { } class A { } } namespace n3 { using n1; using n2; namespace n2 { public interface IFoo<V> { } public class A { } } public class C<X> : IFoo<X> { } struct S { A a; } }"; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (16,25): error CS0104: 'IFoo<X>' is an ambiguous reference between 'n1.IFoo<T>' and 'n3.n2.IFoo<V>' // public class C<X> : IFoo<X> Diagnostic(ErrorCode.ERR_AmbigContext, "IFoo<X>").WithArguments("IFoo<X>", "n1.IFoo<T>", "n3.n2.IFoo<V>"), // (22,9): error CS0104: 'A' is an ambiguous reference between 'n1.A' and 'n3.n2.A' // A a; Diagnostic(ErrorCode.ERR_AmbigContext, "A").WithArguments("A", "n1.A", "n3.n2.A"), // (22,11): warning CS0169: The field 'n3.S.a' is never used // A a; Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("n3.S.a") ); var ns3 = comp.SourceModule.GlobalNamespace.GetMember<NamespaceSymbol>("n3"); var classC = ns3.GetMember<NamedTypeSymbol>("C"); var classCInterface = classC.Interfaces.Single(); Assert.Equal("IFoo", classCInterface.Name); Assert.Equal(TypeKind.Error, classCInterface.TypeKind); var structS = ns3.GetMember<NamedTypeSymbol>("S"); var structSField = structS.GetMember<FieldSymbol>("a"); Assert.Equal("A", structSField.Type.Name); Assert.Equal(TypeKind.Error, structSField.Type.TypeKind); } [Fact] public void CS0106ERR_BadMemberFlag01() { var text = @"namespace MyNamespace { interface I { void m(); static public void f(); // CS0106 } public class MyClass { virtual ushort field; public void I.m() // CS0106 { } } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,28): error CS0106: The modifier 'static' is not valid for this item // static public void f(); // CS0106 Diagnostic(ErrorCode.ERR_BadMemberFlag, "f").WithArguments("static"), // (6,28): error CS0106: The modifier 'public' is not valid for this item // static public void f(); // CS0106 Diagnostic(ErrorCode.ERR_BadMemberFlag, "f").WithArguments("public"), // (11,24): error CS0106: The modifier 'virtual' is not valid for this item // virtual ushort field; Diagnostic(ErrorCode.ERR_BadMemberFlag, "field").WithArguments("virtual"), // (12,23): error CS0106: The modifier 'public' is not valid for this item // public void I.m() // CS0106 Diagnostic(ErrorCode.ERR_BadMemberFlag, "m").WithArguments("public"), // (12,21): error CS0540: 'MyNamespace.MyClass.MyNamespace.I.m()': containing type does not implement interface 'MyNamespace.I' // public void I.m() // CS0106 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I").WithArguments("MyNamespace.MyClass.MyNamespace.I.m()", "MyNamespace.I"), // (11,24): warning CS0169: The field 'MyNamespace.MyClass.field' is never used // virtual ushort field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("MyNamespace.MyClass.field") ); } [Fact] public void CS0106ERR_BadMemberFlag02() { var text = @"interface I { public static int P1 { get; } abstract int P2 { static set; } int P4 { new abstract get; } int P5 { static set; } int P6 { sealed get; } } class C { public int P1 { virtual get { return 0; } } internal int P2 { static set { } } static int P3 { new get { return 0; } } int P4 { sealed get { return 0; } } protected internal object P5 { get { return null; } extern set; } public extern object P6 { get; } // no error } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 3, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 3, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 4, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 4, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 5, Column = 27 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 5, Column = 27 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 6, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 7, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 11, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 12, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 13, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 14, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 15, Column = 64 }, new ErrorDescription { Code = (int)ErrorCode.WRN_ExternMethodNoImplementation, Line = 16, Column = 31, IsWarning = true }); } [WorkItem(539584, "DevDiv")] [Fact] public void CS0106ERR_BadMemberFlag03() { var text = @" class C { sealed private C() { } new abstract C(object o); public virtual C(C c) { } protected internal override C(int i, int j) { } volatile const int x = 1; } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,20): error CS0106: The modifier 'sealed' is not valid for this item // sealed private C() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("sealed"), // (5,18): error CS0106: The modifier 'abstract' is not valid for this item // new abstract C(object o); Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("abstract"), // (5,18): error CS0106: The modifier 'new' is not valid for this item // new abstract C(object o); Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("new"), // (6,20): error CS0106: The modifier 'virtual' is not valid for this item // public virtual C(C c) { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("virtual"), // (7,33): error CS0106: The modifier 'override' is not valid for this item // protected internal override C(int i, int j) { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("override"), // (8,24): error CS0106: The modifier 'volatile' is not valid for this item // volatile const int x = 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("volatile") ); } [Fact] public void CS0106ERR_BadMemberFlag04() { var text = @" class C { static int this[int x] { set { } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 4, Column = 16 }); } [Fact] public void CS0111ERR_MemberAlreadyExists01() { var text = @"class A { void Test() { } public static void Test() { } // CS0111 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_MemberAlreadyExists, Line = 4, Column = 24 }); } [Fact] public void CS0111ERR_MemberAlreadyExists02() { var compilation = CreateCompilationWithMscorlib( @"static class S { internal static void E<T>(this T t, object o) where T : new() { } internal static void E<T>(this T t, object o) where T : class { } internal static void E<U>(this U u, object o) { } }", references: new[] { SystemCoreRef }); compilation.VerifyDiagnostics( // (4,26): error CS0111: Type 'S' already defines a member called 'E' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "E").WithArguments("E", "S").WithLocation(4, 26), // (5,26): error CS0111: Type 'S' already defines a member called 'E' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "E").WithArguments("E", "S").WithLocation(5, 26)); } [Fact] public void CS0111ERR_MemberAlreadyExists03() { var compilation = CreateCompilationWithMscorlib( @"class C { object this[object o] { get { return null; } set { } } object this[int x] { get { return null; } } int this[int y] { set { } } object this[object o] { get { return null; } set { } } } interface I { object this[int x, int y] { get; set; } I this[int a, int b] { get; } I this[int a, int b] { set; } I this[object a, object b] { get; } }"); compilation.VerifyDiagnostics( // (5,9): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C").WithLocation(5, 9), // (6,12): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C").WithLocation(6, 12), // (11,7): error CS0111: Type 'I' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "I").WithLocation(11, 7), // (12,7): error CS0111: Type 'I' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "I").WithLocation(12, 7)); } [Fact] public void CS0111ERR_MemberAlreadyExists04() { var compilation = CreateCompilationWithMscorlib( @" using AliasForI = I; public interface I { int this[int x] { get; set; } } public interface J { int this[int x] { get; set; } } public class C : I, J { int I.this[int x] { get { return 0; } set { } } int AliasForI.this[int x] { get { return 0; } set { } } //CS0111 int J.this[int x] { get { return 0; } set { } } //fine public int this[int x] { get { return 0; } set { } } //fine } "); compilation.VerifyDiagnostics( // (16,19): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types // int AliasForI.this[int x] { get { return 0; } set { } } //CS0111 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C")); } /// <summary> /// Method signature comparison should ignore constraints. /// </summary> [Fact] public void CS0111ERR_MemberAlreadyExists05() { var compilation = CreateCompilationWithMscorlib( @"class C { void M<T>(T t) where T : new() { } void M<U>(U u) where U : struct { } void M<T>(T t) where T : C { } } interface I<T> { void M<U>(); void M<U>() where U : T; }"); compilation.VerifyDiagnostics( // (4,10): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(4, 10), // (5,10): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(5, 10), // (10,10): error CS0111: Type 'I<T>' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "I<T>").WithLocation(10, 10)); } [Fact] public void CS0112ERR_StaticNotVirtual01() { var text = @"namespace MyNamespace { abstract public class MyClass { public abstract void MyMethod(); } public class MyClass2 : MyClass { override public static void MyMethod() // CS0112, remove static keyword { } public static int Main() { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticNotVirtual, Line = 9, Column = 37 }); } [Fact] public void CS0112ERR_StaticNotVirtual02() { var text = @"abstract class A { protected abstract object P { get; } } class B : A { protected static override object P { get { return null; } } public static virtual object Q { get; } internal static abstract object R { get; set; } } "; var tree = Parse(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); CreateCompilationWithMscorlib(tree).VerifyDiagnostics( // (7,38): error CS0112: A static member 'B.P' cannot be marked as override, virtual, or abstract // protected static override object P { get { return null; } } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P").WithArguments("B.P").WithLocation(7, 38), // (8,34): error CS0112: A static member 'B.Q' cannot be marked as override, virtual, or abstract // public static virtual object Q { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "Q").WithArguments("B.Q").WithLocation(8, 34), // (9,37): error CS0112: A static member 'B.R' cannot be marked as override, virtual, or abstract // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "R").WithArguments("B.R").WithLocation(9, 37), // (9,41): error CS0513: 'B.R.get' is abstract but it is contained in non-abstract class 'B' // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("B.R.get", "B").WithLocation(9, 41), // (9,46): error CS0513: 'B.R.set' is abstract but it is contained in non-abstract class 'B' // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("B.R.set", "B").WithLocation(9, 46)); } [Fact] public void CS0112ERR_StaticNotVirtual03() { var text = @"abstract class A { protected abstract event System.Action P; } abstract class B : A { protected static override event System.Action P; public static virtual event System.Action Q; internal static abstract event System.Action R; } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticNotVirtual, Line = 7, Column = 51 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticNotVirtual, Line = 8, Column = 47 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticNotVirtual, Line = 9, Column = 50 }); } [Fact] public void CS0113ERR_OverrideNotNew01() { var text = @"namespace MyNamespace { abstract public class MyClass { public abstract void MyMethod(); public abstract void MyMethod(int x); public virtual void MyMethod(int x, long j) { } } public class MyClass2 : MyClass { override new public void MyMethod() // CS0113, remove new keyword { } virtual override public void MyMethod(int x) // CS0113, remove virtual keyword { } virtual override public void MyMethod(int x, long j) // CS0113, remove virtual keyword { } public static int Main() { return 0; } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 14, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 17, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 20, Column = 38 }); } [Fact] public void CS0113ERR_OverrideNotNew02() { var text = @"abstract class A { protected abstract object P { get; } internal virtual object Q { get; set; } } class B : A { protected new override object P { get { return null; } } internal virtual override object Q { get; set; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 8, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 9, Column = 38 }); } [Fact] public void CS0113ERR_OverrideNotNew03() { var text = @"abstract class A { protected abstract event System.Action P; internal virtual event System.Action Q; } class B : A { protected new override event System.Action P; internal virtual override event System.Action Q; } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (9,51): error CS0113: A member 'B.Q' marked as override cannot be marked as new or virtual // internal virtual override event System.Action Q; Diagnostic(ErrorCode.ERR_OverrideNotNew, "Q").WithArguments("B.Q"), // (8,48): error CS0113: A member 'B.P' marked as override cannot be marked as new or virtual // protected new override event System.Action P; Diagnostic(ErrorCode.ERR_OverrideNotNew, "P").WithArguments("B.P"), // (8,48): warning CS0067: The event 'B.P' is never used // protected new override event System.Action P; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P").WithArguments("B.P"), // (9,51): warning CS0067: The event 'B.Q' is never used // internal virtual override event System.Action Q; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Q").WithArguments("B.Q")); } [Fact] public void CS0115ERR_OverrideNotExpected() { var text = @"namespace MyNamespace { abstract public class MyClass1 { public abstract int f(); } abstract public class MyClass2 { public override int f() // CS0115 { return 0; } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 10, Column = 29 }); } /// <summary> /// Some? /// </summary> [Fact] public void CS0118ERR_BadSKknown01() { var text = @"namespace NS { namespace Foo {} internal struct S { void Foo(Foo f) {} } class Bar { Foo foundNamespaceInsteadOfType; } public class A : Foo {} }"; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (7,18): error CS0118: 'Foo' is a namespace but is used like a type // void Foo(Foo f) {} Diagnostic(ErrorCode.ERR_BadSKknown, "Foo").WithArguments("Foo", "namespace", "type"), // (12,9): error CS0118: 'Foo' is a namespace but is used like a type // Foo foundNamespaceInsteadOfType; Diagnostic(ErrorCode.ERR_BadSKknown, "Foo").WithArguments("Foo", "namespace", "type"), // (15,22): error CS0118: 'Foo' is a namespace but is used like a type // public class A : Foo {} Diagnostic(ErrorCode.ERR_BadSKknown, "Foo").WithArguments("Foo", "namespace", "type"), // (12,13): warning CS0169: The field 'NS.Bar.foundNamespaceInsteadOfType' is never used // Foo foundNamespaceInsteadOfType; Diagnostic(ErrorCode.WRN_UnreferencedField, "foundNamespaceInsteadOfType").WithArguments("NS.Bar.foundNamespaceInsteadOfType") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var baseType = ns.GetTypeMembers("A").Single().BaseType; Assert.Equal("Foo", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); Assert.Null(baseType.BaseType); var type2 = ns.GetTypeMembers("Bar").Single() as NamedTypeSymbol; var mem1 = type2.GetMembers("foundNamespaceInsteadOfType").Single() as FieldSymbol; Assert.Equal("Foo", mem1.Type.Name); Assert.Equal(TypeKind.Error, mem1.Type.TypeKind); var type3 = ns.GetTypeMembers("S").Single() as NamedTypeSymbol; var mem2 = type3.GetMembers("Foo").Single() as MethodSymbol; var param = mem2.Parameters[0]; Assert.Equal("Foo", param.Type.Name); Assert.Equal(TypeKind.Error, param.Type.TypeKind); } [WorkItem(538147, "DevDiv")] [Fact] public void CS0118ERR_BadSKknown02() { var text = @" class Test { static void Main() { B B = null; if (B == B) {} } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadSKknown, Line = 6, Column = 10 }); } [Fact] public void CS0119ERR_BadSKunknown01() { var text = @"namespace NS { using System; public class Test { public static void F() { } public static int Main() { Console.WriteLine(F.x); return NS(); } } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (10,31): error CS0119: 'NS.Test.F()' is a method, which is not valid in the given context // Console.WriteLine(F.x); Diagnostic(ErrorCode.ERR_BadSKunknown, "F").WithArguments("NS.Test.F()", "method"), // (11,20): error CS0118: 'NS' is a namespace but is used like a variable // return NS(); Diagnostic(ErrorCode.ERR_BadSKknown, "NS").WithArguments("NS", "namespace", "variable") ); } [Fact, WorkItem(538214, "DevDiv")] public void CS0119ERR_BadSKunknown02() { var text = @"namespace N1 { class Test { static void Main() { double x = -5d; int y = (global::System.Int32) +x; short z = (System.Int16) +x; } } } "; // Roslyn gives same error twice CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,22): error CS0119: 'int' is a type, which is not valid in the given context // int y = (global::System.Int32) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (8,22): error CS0119: 'int' is a type, which is not valid in the given context // int y = (global::System.Int32) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (9,24): error CS0119: 'short' is a type, which is not valid in the given context // short z = (System.Int16) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Int16").WithArguments("short", "type"), // (9,24): error CS0119: 'short' is a type, which is not valid in the given context // short z = (System.Int16) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Int16").WithArguments("short", "type") ); } [Fact] public void CS0132ERR_StaticConstParam01() { var text = @"namespace NS { struct S { static S(string s) { } } public class clx { static clx(params long[] ary) { } static clx(ref int n) { } } public class cly : clx { static cly() { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 5, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 10, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 11, Column = 16 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(539627, "DevDiv")] [Fact] public void CS0136ERR_LocalIllegallyOverrides() { // See comments in NameCollisionTests.cs for commentary on this error. var text = @" class MyClass { public MyClass(int a) { long a; // 0136 } public long MyMeth(string x) { long x = 1; // 0136 return x; } public byte MyProp { set { int value; // 0136 } } } "; CreateCompilationWithMscorlib(text). VerifyDiagnostics( Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "a").WithArguments("a"), Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a"), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x"), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value"), Diagnostic(ErrorCode.WRN_UnreferencedVar, "value").WithArguments("value") ); } [Fact] public void CS0136ERR_LocalIllegallyOverrides02() { // See comments in NameCollisionTests.cs for commentary on this error. var text = @"class C { public static void Main() { foreach (var x in ""abc"") { int x = 1 ; System.Console.WriteLine(x); } } } "; CreateCompilationWithMscorlib(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x")); } [Fact] public void CS0138ERR_BadUsingNamespace01() { var text = @"using System.Object; namespace NS { using NS.S; struct S {} }"; var comp = CreateCompilationWithMscorlib(Parse(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); comp.VerifyDiagnostics( // (1,7): error CS0138: A using namespace directive can only be applied to namespaces; 'object' is a type not a namespace // using System.Object; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System.Object").WithArguments("object"), // (5,11): error CS0138: A using namespace directive can only be applied to namespaces; 'NS.S' is a type not a namespace // using NS.S; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "NS.S").WithArguments("NS.S"), // (1,1): info CS8019: Unnecessary using directive. // using System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Object;"), // (5,5): info CS8019: Unnecessary using directive. // using NS.S; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NS.S;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Roslyn has 3 extra CS0146, Neal said it's per spec /// </summary> [Fact] public void CS0146ERR_CircularBase01() { var text = @"namespace NS { class A : B { } class B : A { } public class AA : BB { } public class BB : CC { } public class CC : DD { } public class DD : BB { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 3, Column = 11 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 7, Column = 18 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 8, Column = 18 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 9, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var baseType = (NamedTypeSymbol)ns.GetTypeMembers("A").Single().BaseType; Assert.Null(baseType.BaseType); Assert.Equal("B", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); baseType = (NamedTypeSymbol)ns.GetTypeMembers("DD").Single().BaseType; Assert.Null(baseType.BaseType); Assert.Equal("BB", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); baseType = (NamedTypeSymbol)ns.GetTypeMembers("BB").Single().BaseType; Assert.Null(baseType.BaseType); Assert.Equal("CC", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); } [Fact] public void CS0146ERR_CircularBase02() { var text = @"public interface C<T> { } public class D : C<D.Q> { private class Q { } // accessible in base clause } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(4169, "DevDiv_Projects/Roslyn")] [Fact] public void CS0146ERR_CircularBase03() { var text = @" class A : object, A.IC { protected interface IC { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(4169, "DevDiv_Projects/Roslyn")] [Fact] public void CS0146ERR_CircularBase04() { var text = @" class A : object, I<A.IC> { protected interface IC { } } interface I<T> { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0179ERR_ExternHasBody01() { var text = @" namespace NS { public class C { extern C() { } extern void M1() { } extern int M2() => 1; extern object P1 { get { return null; } set { } } extern int P2 => 1; extern event System.Action E { add { } remove { } } extern static public int operator + (C c1, C c2) { return 1; } extern static public int operator - (C c1, C c2) => 1; } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (6,16): error CS0179: 'C.C()' cannot be extern and declare a body // extern C() { } Diagnostic(ErrorCode.ERR_ExternHasBody, "C").WithArguments("NS.C.C()").WithLocation(6, 16), // (7,21): error CS0179: 'C.M1()' cannot be extern and declare a body // extern void M1() { } Diagnostic(ErrorCode.ERR_ExternHasBody, "M1").WithArguments("NS.C.M1()").WithLocation(7, 21), // (8,20): error CS0179: 'C.M2()' cannot be extern and declare a body // extern int M2() => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "M2").WithArguments("NS.C.M2()").WithLocation(8, 20), // (9,28): error CS0179: 'C.P1.get' cannot be extern and declare a body // extern object P1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("NS.C.P1.get").WithLocation(9, 28), // (9,49): error CS0179: 'C.P1.set' cannot be extern and declare a body // extern object P1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("NS.C.P1.set").WithLocation(9, 49), // (10,26): error CS0179: 'C.P2.get' cannot be extern and declare a body // extern int P2 => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "1").WithArguments("NS.C.P2.get").WithLocation(10, 26), // (11,40): error CS0179: 'C.E.add' cannot be extern and declare a body // extern event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("NS.C.E.add").WithLocation(11, 40), // (11,48): error CS0179: 'C.E.remove' cannot be extern and declare a body // extern event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("NS.C.E.remove").WithLocation(11, 48), // (12,43): error CS0179: 'C.operator +(C, C)' cannot be extern and declare a body // extern static public int operator + (C c1, C c2) { return 1; } Diagnostic(ErrorCode.ERR_ExternHasBody, "+").WithArguments("NS.C.operator +(NS.C, NS.C)").WithLocation(12, 43), // (13,43): error CS0179: 'C.operator -(C, C)' cannot be extern and declare a body // extern static public int operator - (C c1, C c2) => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "-").WithArguments("NS.C.operator -(NS.C, NS.C)").WithLocation(13, 43)); } [Fact] public void CS0180ERR_AbstractAndExtern01() { CreateCompilationWithMscorlib( @"abstract class X { public abstract extern void M(); public extern abstract int P { get; } // If a body is provided for an abstract extern method, // Dev10 reports CS0180, but does not report CS0179/CS0500. public abstract extern void N(int i) { } public extern abstract object Q { set { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M").WithArguments("X.M()").WithLocation(3, 33), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P").WithArguments("X.P").WithLocation(4, 32), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "N").WithArguments("X.N(int)").WithLocation(7, 33), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "Q").WithArguments("X.Q").WithLocation(8, 35)); } [WorkItem(527618, "DevDiv")] [Fact] public void CS0180ERR_AbstractAndExtern02() { CreateCompilationWithMscorlib( @"abstract class C { public extern abstract void M(); public extern abstract object P { set; } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M").WithArguments("C.M()"), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P").WithArguments("C.P")); } [Fact] public void CS0180ERR_AbstractAndExtern03() { CreateCompilationWithMscorlib( @"class C { public extern abstract event System.Action E; } ") .VerifyDiagnostics( // (3,48): error CS0180: 'C.E' cannot be both extern and abstract // public extern abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E").WithArguments("C.E")); } [Fact] public void CS0181ERR_BadAttributeParamType_Dynamic() { var text = @" using System; public class C<T> { public enum D { A } } [A1] // Dev11 error public class A1 : Attribute { public A1(dynamic i = null) { } } [A2] // Dev11 ok (bug) public class A2 : Attribute { public A2(dynamic[] i = null) { } } [A3] // Dev11 error (bug) public class A3 : Attribute { public A3(C<dynamic>.D i = 0) { } } [A4] // Dev11 ok public class A4 : Attribute { public A4(C<dynamic>.D[] i = null) { } } "; CreateCompilationWithMscorlibAndSystemCore(text).VerifyDiagnostics( // (6,2): error CS0181: Attribute constructor parameter 'i' has type 'dynamic', which is not a valid attribute parameter type // [A1] // Dev11 error Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A1").WithArguments("i", "dynamic"), // (12,2): error CS0181: Attribute constructor parameter 'i' has type 'dynamic[]', which is not a valid attribute parameter type // [A2] // Dev11 ok Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A2").WithArguments("i", "dynamic[]")); } [Fact] public void CS0182ERR_BadAttributeArgument() { var text = @"public class MyClass { static string s = ""Test""; [System.Diagnostics.ConditionalAttribute(s)] // CS0182 void NonConstantArgumentToConditional() { } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,46): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [System.Diagnostics.ConditionalAttribute(s)] // CS0182 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s"), // (3,19): warning CS0414: The field 'MyClass.s' is assigned but its value is never used // static string s = "Test"; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "s").WithArguments("MyClass.s")); } [Fact] public void CS0214ERR_UnsafeNeeded() { var text = @"public struct S { public int a; } public class MyClass { public static void Test() { S s = new S(); S* s2 = &s; // CS0214 s2->a = 3; // CS0214 s.a = 0; } // OK unsafe public static void Test2() { S s = new S(); S* s2 = &s; s2->a = 3; s.a = 0; } } "; // NOTE: only first in scope is reported. CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // S* s2 = &s; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "S*"), // (11,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // S* s2 = &s; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&s"), // (12,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s2->a = 3; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s2")); } [Fact] public void CS0214ERR_UnsafeNeeded02() { var text = @"unsafe struct S { public fixed int x[10]; } class Program { static void Main() { S s; s.x[1] = s.x[2]; } }"; // NOTE: only first in scope is reported. CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s.x[1] = s.x[2]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s.x"), // (11,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s.x[1] = s.x[2]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s.x")); } [Fact] public void CS0214ERR_UnsafeNeeded03() { var text = @"public struct S { public fixed int buf[10]; } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public fixed int buf[10]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "buf[10]")); } [Fact] public void CS0215ERR_OpTFRetType() { var text = @"class MyClass { public static int operator true(MyClass MyInt) // CS0215 { return 1; } public static int operator false(MyClass MyInt) // CS0215 { return 1; } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,32): error CS0215: The return type of operator True or False must be bool // public static int operator true(MyClass MyInt) // CS0215 Diagnostic(ErrorCode.ERR_OpTFRetType, "true"), // (8,32): error CS0215: The return type of operator True or False must be bool // public static int operator false(MyClass MyInt) // CS0215 Diagnostic(ErrorCode.ERR_OpTFRetType, "false") ); } [Fact] public void CS0216ERR_OperatorNeedsMatch() { var text = @"class MyClass { // Missing operator false public static bool operator true(MyClass MyInt) // CS0216 { return true; } // Missing matching operator > -- parameter types must match. public static bool operator < (MyClass x, int y) { return false; } // Missing matching operator < -- parameter types must match. public static bool operator > (MyClass x, double y) { return false; } // Missing matching operator >= -- return types must match. public static MyClass operator <=(MyClass x, MyClass y) { return x; } // Missing matching operator <= -- return types must match. public static bool operator >=(MyClass x, MyClass y) { return true; } // Missing operator != public static bool operator ==(MyClass x, MyClass y) { return true; } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (1,7): warning CS0660: 'MyClass' defines operator == or operator != but does not override Object.Equals(object o) // class MyClass Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "MyClass").WithArguments("MyClass"), // (1,7): warning CS0661: 'MyClass' defines operator == or operator != but does not override Object.GetHashCode() // class MyClass Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "MyClass").WithArguments("MyClass"), // (4,33): error CS0216: The operator 'MyClass.operator true(MyClass)' requires a matching operator 'false' to also be defined // public static bool operator true(MyClass MyInt) // CS0216 Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("MyClass.operator true(MyClass)", "false"), // (7,33): error CS0216: The operator 'MyClass.operator <(MyClass, int)' requires a matching operator '>' to also be defined // public static bool operator < (MyClass x, int y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "<").WithArguments("MyClass.operator <(MyClass, int)", ">"), // (10,33): error CS0216: The operator 'MyClass.operator >(MyClass, double)' requires a matching operator '<' to also be defined // public static bool operator > (MyClass x, double y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, ">").WithArguments("MyClass.operator >(MyClass, double)", "<"), // (13,36): error CS0216: The operator 'MyClass.operator <=(MyClass, MyClass)' requires a matching operator '>=' to also be defined // public static MyClass operator <=(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "<=").WithArguments("MyClass.operator <=(MyClass, MyClass)", ">="), // (16,33): error CS0216: The operator 'MyClass.operator >=(MyClass, MyClass)' requires a matching operator '<=' to also be defined // public static bool operator >=(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, ">=").WithArguments("MyClass.operator >=(MyClass, MyClass)", "<="), // (19,33): error CS0216: The operator 'MyClass.operator ==(MyClass, MyClass)' requires a matching operator '!=' to also be defined // public static bool operator ==(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "==").WithArguments("MyClass.operator ==(MyClass, MyClass)", "!=") ); } [Fact] public void CS0216ERR_OperatorNeedsMatch_NoErrorForDynamicObject() { string source = @" using System.Collections.Generic; class C { public static object operator >(C p1, dynamic p2) { return null; } public static dynamic operator <(C p1, object p2) { return null; } public static dynamic operator >=(C p1, dynamic p2) { return null; } public static object operator <=(C p1, object p2) { return null; } public static List<object> operator ==(C p1, dynamic[] p2) { return null; } public static List<dynamic> operator !=(C p1, object[] p2) { return null; } public override bool Equals(object o) { return false; } public override int GetHashCode() { return 1; } } "; CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0218ERR_MustHaveOpTF() { // Note that the wording of this error has changed. var text = @" public class MyClass { public static MyClass operator &(MyClass f1, MyClass f2) { return new MyClass(); } public static void Main() { MyClass f = new MyClass(); MyClass i = f && f; // CS0218, requires operators true and false } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (12,21): error CS0218: In order to be applicable as a short circuit operator, the declaring type 'MyClass' of user-defined operator 'MyClass.operator &(MyClass, MyClass)' must declare operator true and operator false. // MyClass i = f && f; // CS0218, requires operators true and false Diagnostic(ErrorCode.ERR_MustHaveOpTF, "f && f").WithArguments("MyClass.operator &(MyClass, MyClass)", "MyClass") ); } [Fact] public void CS0224ERR_BadVarargs01() { var text = @"namespace NS { class C { public static void F<T>(T x, __arglist) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 5, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0224ERR_BadVarargs02() { var text = @"class C { C(object o, __arglist) { } // no error void M(__arglist) { } // no error } abstract class C<T> { C(object o) { } // no error C(__arglist) { } void M(object o, __arglist) { } internal abstract object F(__arglist); } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 9, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 10, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 11, Column = 30 }); } [Fact] public void CS0225ERR_ParamsMustBeArray01() { var text = @" using System.Collections.Generic; public class A { struct S { internal List<string> Bar(string s1, params List<string> s2) { return s2; } } public static void Foo(params int a) {} public static int Main() { Foo(1); return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ParamsMustBeArray, Line = 8, Column = 46 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParamsMustBeArray, Line = 13, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol; // TODO... } [Fact] public void CS0227ERR_IllegalUnsafe() { var text = @"public class MyClass { unsafe public static void Main() // CS0227 { } } "; var c = CreateCompilationWithMscorlib(text, options: TestOptions.ReleaseDll.WithAllowUnsafe(false)); c.VerifyDiagnostics( // (3,31): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe public static void Main() // CS0227 Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Main").WithLocation(3, 31)); } [Fact] public void CS0234ERR_DottedTypeNameNotFoundInNS() { var text = @"using NA = N.A; using NB = C<N.B<object>>; namespace N { } class C<T> { NA a; NB b; N.C<N.D> c; }"; CreateCompilationWithMscorlib(text, references: new[] { SystemCoreRef }).VerifyDiagnostics( // (1,14): error CS0234: The type or namespace name 'A' does not exist in the namespace 'N' (are you missing an assembly reference?) // using NA = N.A; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "A").WithArguments("A", "N"), // (2,16): error CS0234: The type or namespace name 'B<object>' does not exist in the namespace 'N' (are you missing an assembly reference?) // using NB = C<N.B<object>>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "B<object>").WithArguments("B<object>", "N"), // (8,7): error CS0234: The type or namespace name 'C<N.D>' does not exist in the namespace 'N' (are you missing an assembly reference?) // N.C<N.D> c; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "C<N.D>").WithArguments("C<N.D>", "N"), // (8,11): error CS0234: The type or namespace name 'D' does not exist in the namespace 'N' (are you missing an assembly reference?) // N.C<N.D> c; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "D").WithArguments("D", "N"), // (6,8): warning CS0169: The field 'C<T>.a' is never used // NA a; Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("C<T>.a"), // (7,8): warning CS0169: The field 'C<T>.b' is never used // NB b; Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b"), // (8,14): warning CS0169: The field 'C<T>.c' is never used // N.C<N.D> c; Diagnostic(ErrorCode.WRN_UnreferencedField, "c").WithArguments("C<T>.c")); } [Fact] public void CS0238ERR_SealedNonOverride01() { var text = @"abstract class MyClass { public abstract void f(); } class MyClass2 : MyClass { public static void Main() { } public sealed void f() // CS0238 { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedNonOverride, Line = 12, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 12, Column = 24, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 6, Column = 7 }); } [Fact] public void CS0238ERR_SealedNonOverride02() { var text = @"interface I { sealed void M(); sealed object P { get; } } "; //we're diverging from Dev10 - it's a little silly to report two errors saying the same modifier isn't allowed DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 3, Column = 17 }, //new ErrorDescription { Code = (int)ErrorCode.ERR_SealedNonOverride, Line = 3, Column = 17 }, //Dev10 //new ErrorDescription { Code = (int)ErrorCode.ERR_SealedNonOverride, Line = 4, Column = 19 }, //Dev10 new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 4, Column = 19 }); } [Fact] public void CS0238ERR_SealedNonOverride03() { var text = @"class B { sealed int P { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedNonOverride, Line = 3, Column = 16 }); } [Fact] public void CS0238ERR_SealedNonOverride04() { var text = @"class B { sealed event System.Action E; } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,32): error CS0238: 'B.E' cannot be sealed because it is not an override // sealed event System.Action E; Diagnostic(ErrorCode.ERR_SealedNonOverride, "E").WithArguments("B.E"), // (3,32): warning CS0067: The event 'B.E' is never used // sealed event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B.E")); } [Fact] public void CS0239ERR_CantOverrideSealed() { var text = @"abstract class MyClass { public abstract void f(); } class MyClass2 : MyClass { public static void Main() { } public override sealed void f() { } } class MyClass3 : MyClass2 { public override void f() // CS0239 { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 19, Column = 26 }); } [Fact()] public void CS0243ERR_ConditionalOnOverride() { var text = @"public class MyClass { public virtual void M() { } } public class MyClass2 : MyClass { [System.Diagnostics.ConditionalAttribute(""MySymbol"")] // CS0243 public override void M() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,6): error CS0243: The Conditional attribute is not valid on 'MyClass2.M()' because it is an override method // [System.Diagnostics.ConditionalAttribute("MySymbol")] // CS0243 Diagnostic(ErrorCode.ERR_ConditionalOnOverride, @"System.Diagnostics.ConditionalAttribute(""MySymbol"")").WithArguments("MyClass2.M()").WithLocation(8, 6)); } [Fact] public void CS0246ERR_SingleTypeNameNotFound01() { var text = @"namespace NS { interface IFoo : INotExist {} // Extra CS0527 interface IBar { string M(ref NoType p1, out NoType p2, params NOType[] ary); } class A : CNotExist {} struct S { public const NoType field = 123; private NoType M() { return null; } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 20 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 51 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 8, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 11, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 12, Column = 14 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("IFoo").Single() as NamedTypeSymbol; // bug: expected 1 but error symbol // Assert.Equal(1, type1.Interfaces.Count()); var type2 = ns.GetTypeMembers("IBar").Single() as NamedTypeSymbol; var mem1 = type2.GetMembers().First() as MethodSymbol; //ErrorTypes now appear as though they are declared in the global namespace. Assert.Equal("System.String NS.IBar.M(ref NoType p1, out NoType p2, params NOType[] ary)", mem1.ToTestDisplayString()); var param = mem1.Parameters[0] as ParameterSymbol; var ptype = param.Type; Assert.Equal(RefKind.Ref, param.RefKind); Assert.Equal(TypeKind.Error, ptype.TypeKind); Assert.Equal("NoType", ptype.Name); var type3 = ns.GetTypeMembers("A").Single() as NamedTypeSymbol; var base1 = type3.BaseType; Assert.Null(base1.BaseType); Assert.Equal(TypeKind.Error, base1.TypeKind); Assert.Equal("CNotExist", base1.Name); var type4 = ns.GetTypeMembers("S").Single() as NamedTypeSymbol; var mem2 = type4.GetMembers("field").First() as FieldSymbol; Assert.Equal(TypeKind.Error, mem2.Type.TypeKind); Assert.Equal("NoType", mem2.Type.Name); var mem3 = type4.GetMembers("M").Single() as MethodSymbol; Assert.Equal(TypeKind.Error, mem3.ReturnType.TypeKind); Assert.Equal("NoType", mem3.ReturnType.Name); } [WorkItem(537882, "DevDiv")] [Fact] public void CS0246ERR_SingleTypeNameNotFound02() { var text = @"using NoExistNS1; namespace NS { using NoExistNS2; // No error for this one class Test { static int Main() { return 1; } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (1,7): error CS0246: The type or namespace name 'NoExistNS1' could not be found (are you missing a using directive or an assembly reference?) // using NoExistNS1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NoExistNS1").WithArguments("NoExistNS1"), // (5,11): error CS0246: The type or namespace name 'NoExistNS2' could not be found (are you missing a using directive or an assembly reference?) // using NoExistNS2; // No error for this one Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NoExistNS2").WithArguments("NoExistNS2"), // (1,1): info CS8019: Unnecessary using directive. // using NoExistNS1; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NoExistNS1;"), // (5,5): info CS8019: Unnecessary using directive. // using NoExistNS2; // No error for this one Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NoExistNS2;")); } [Fact] public void CS0246ERR_SingleTypeNameNotFound03() { var text = @"[Attribute] class C { } "; // (1,2): error CS0246: The type or namespace name 'Attribute' could not be found (are you missing a using directive or an assembly reference?) var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 1, Column = 2 }); } [Fact] public void CS0246ERR_SingleTypeNameNotFound04() { var text = @"class AAttribute : System.Attribute { } class BAttribute : System.Attribute { } [A][@B] class C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 5 }); } [Fact] public void CS0246ERR_SingleTypeNameNotFound05() { var text = @"class C { static void Main(string[] args) { System.Console.WriteLine(typeof(s)); // Invalid } } "; CreateCompilationWithMscorlib(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "s").WithArguments("s")); } [WorkItem(543791, "DevDiv")] [Fact] public void CS0246ERR_SingleTypeNameNotFound06() { var text = @"class C { public static Nada x = null, y = null; } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,19): error CS0246: The type or namespace name 'Nada' could not be found (are you missing a using directive or an assembly reference?) // public static Nada x = null, y = null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nada").WithArguments("Nada") ); } [Fact] public void CS0249ERR_OverrideFinalizeDeprecated() { var text = @"class MyClass { protected override void Finalize() // CS0249 { } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,29): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (3,29): error CS0249: Do not override object.Finalize. Instead, provide a destructor. Diagnostic(ErrorCode.ERR_OverrideFinalizeDeprecated, "Finalize")); } [Fact] public void CS0260ERR_MissingPartial01() { var text = @"namespace NS { public class C // CS0260 { partial struct S { } struct S { } // CS0260 } public partial class C {} public partial class C {} partial interface I {} interface I { } // CS0260 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 3, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 6, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 13, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0261ERR_PartialTypeKindConflict01() { var text = @"namespace NS { partial class A { } partial class A { } partial struct A { } // CS0261 partial interface A { } // CS0261 partial class B { } partial struct B<T> { } partial interface B<T, U> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialTypeKindConflict, Line = 5, Column = 20 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialTypeKindConflict, Line = 6, Column = 23 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0262ERR_PartialModifierConflict01() { var text = @"namespace NS { public partial interface I { } internal partial interface I { } partial interface I { } class A { internal partial class C { } protected partial class C {} private partial struct S { } internal partial struct S { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialModifierConflict, Line = 3, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialModifierConflict, Line = 9, Column = 32 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialModifierConflict, Line = 12, Column = 32 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0263ERR_PartialMultipleBases01() { var text = @"namespace NS { class B1 { } class B2 { } partial class C : B1 // CS0263 - is the base class B1 or B2? { } partial class C : B2 { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMultipleBases, Line = 5, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("C").Single() as NamedTypeSymbol; var base1 = type1.BaseType; Assert.Null(base1.BaseType); Assert.Equal(TypeKind.Error, base1.TypeKind); Assert.Equal("B1", base1.Name); } [Fact] public void ERRMixed_BaseAnalysisMishmash() { var text = @"namespace NS { public interface I { } public class C { } public class D { } public struct S { } public struct N0 : object, NS.C { } public class N1 : C, D { } public struct N2 : C, D { } public class N3 : I, C { } public partial class N4 : C { } public partial class N4 : D { } class N5<T> : C, D { } class N6<T> : C, T { } class N7<T> : T, C { } interface N8 : I, I { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 8, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 8, Column = 32 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 10, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 11, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 11, Column = 27 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 12, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMultipleBases, Line = 13, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 16, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 17, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 18, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 18, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 20, Column = 23 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0264ERR_PartialWrongTypeParams01() { var text = @"namespace NS { public partial class C<T1> // CS0264.cs { } partial class C<T2> { partial struct S<X> { } // CS0264.cs partial struct S<T2> { } } internal partial interface IFoo<T, V> { } // CS0264.cs partial interface IFoo<T, U> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 3, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 9, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 13, Column = 32 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("C").Single() as NamedTypeSymbol; Assert.Equal(1, type1.TypeParameters.Length); var param = type1.TypeParameters[0]; // Assert.Equal(TypeKind.Error, param.TypeKind); // this assert it incorrect: it is definitely a type parameter Assert.Equal("T1", param.Name); } [Fact] public void PartialMethodRenameTypeParameters() { var text = @"namespace NS { public partial class MyClass { partial void F<T, U>(T t) where T : class; partial void F<U, T>(U u) where U : class {} } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("MyClass").Single() as NamedTypeSymbol; Assert.Equal(0, type1.TypeParameters.Length); var f = type1.GetMembers("F").Single() as MethodSymbol; Assert.Equal(2, f.TypeParameters.Length); var param1 = f.TypeParameters[0]; var param2 = f.TypeParameters[1]; Assert.Equal("T", param1.Name); Assert.Equal("U", param2.Name); } [Fact] public void CS0265ERR_PartialWrongConstraints01() { var text = @"interface IA<T> { } interface IB { } // Different constraints. partial class A1<T> where T : struct { } partial class A1<T> where T : class { } partial class A2<T, U> where T : struct where U : IA<T> { } partial class A2<T, U> where T : class where U : IB { } partial class A3<T> where T : IA<T> { } partial class A3<T> where T : IA<IA<T>> { } partial interface A4<T> where T : struct, IB { } partial interface A4<T> where T : class, IB { } partial struct A5<T> where T : IA<T>, new() { } partial struct A5<T> where T : IA<T>, new() { } partial struct A5<T> where T : IB, new() { } // Additional constraints. partial class B1<T> where T : new() { } partial class B1<T> where T : class, new() { } partial class B2<T, U> where T : IA<T> { } partial class B2<T, U> where T : IB, IA<T> { } // Missing constraints. partial interface C1<T> where T : class, new() { } partial interface C1<T> where T : new() { } partial struct C2<T, U> where U : IB, IA<T> { } partial struct C2<T, U> where U : IA<T> { } // Same constraints, different order. partial class D1<T> where T : IA<T>, IB { } partial class D1<T> where T : IB, IA<T> { } partial class D1<T> where T : IA<T>, IB { } partial class D2<T, U, V> where V : T, U { } partial class D2<T, U, V> where V : U, T { } // Different constraint clauses. partial class E1<T, U> where U : T { } partial class E1<T, U> where T : class { } partial class E1<T, U> where U : T { } partial class E2<T, U> where U : IB { } partial class E2<T, U> where T : IA<U> { } partial class E2<T, U> where T : IA<U> { } // Additional constraint clause. partial class F1<T> { } partial class F1<T> { } partial class F1<T> where T : class { } partial class F2<T> { } partial class F2<T, U> where T : class { } partial class F2<T, U> where T : class where U : T { } // Missing constraint clause. partial interface G1<T> where T : class { } partial interface G1<T> { } partial struct G2<T, U> where T : class where U : T { } partial struct G2<T, U> where T : class { } partial struct G2<T, U> { } // Same constraint clauses, different order. partial class H1<T, U> where T : class where U : T { } partial class H1<T, U> where T : class where U : T { } partial class H1<T, U> where U : T where T : class { } partial class H2<T, U, V> where U : IB where T : IA<V> { } partial class H2<T, U, V> where T : IA<V> where U : IB { }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,15): error CS0265: Partial declarations of 'A1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A1").WithArguments("A1<T>", "T").WithLocation(4, 15), // (6,15): error CS0265: Partial declarations of 'A2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A2").WithArguments("A2<T, U>", "T").WithLocation(6, 15), // (6,15): error CS0265: Partial declarations of 'A2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A2").WithArguments("A2<T, U>", "U").WithLocation(6, 15), // (8,15): error CS0265: Partial declarations of 'A3<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A3").WithArguments("A3<T>", "T").WithLocation(8, 15), // (10,19): error CS0265: Partial declarations of 'A4<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A4").WithArguments("A4<T>", "T").WithLocation(10, 19), // (12,16): error CS0265: Partial declarations of 'A5<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A5").WithArguments("A5<T>", "T").WithLocation(12, 16), // (16,15): error CS0265: Partial declarations of 'B1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B1").WithArguments("B1<T>", "T").WithLocation(16, 15), // (18,15): error CS0265: Partial declarations of 'B2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B2").WithArguments("B2<T, U>", "T").WithLocation(18, 15), // (21,19): error CS0265: Partial declarations of 'C1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C1").WithArguments("C1<T>", "T").WithLocation(21, 19), // (23,16): error CS0265: Partial declarations of 'C2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C2").WithArguments("C2<T, U>", "U").WithLocation(23, 16), // (32,15): error CS0265: Partial declarations of 'E1<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E1").WithArguments("E1<T, U>", "T").WithLocation(32, 15), // (32,15): error CS0265: Partial declarations of 'E1<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E1").WithArguments("E1<T, U>", "U").WithLocation(32, 15), // (35,15): error CS0265: Partial declarations of 'E2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E2").WithArguments("E2<T, U>", "T").WithLocation(35, 15), // (35,15): error CS0265: Partial declarations of 'E2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E2").WithArguments("E2<T, U>", "U").WithLocation(35, 15), // (35,15): error CS0265: Partial declarations of 'E2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E2").WithArguments("E2<T, U>", "T").WithLocation(35, 15), // (35,15): error CS0265: Partial declarations of 'E2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E2").WithArguments("E2<T, U>", "U").WithLocation(35, 15), // (43,15): error CS0265: Partial declarations of 'F2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "F2").WithArguments("F2<T, U>", "U").WithLocation(43, 15), // (48,16): error CS0265: Partial declarations of 'G2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "G2").WithArguments("G2<T, U>", "U").WithLocation(48, 16)); } [Fact] public void CS0265ERR_PartialWrongConstraints02() { var text = @"using NIA = N.IA; using NIBA = N.IB<N.IA>; using NIBAC = N.IB<N.A.IC>; using NA1 = N.A; using NA2 = N.A; namespace N { interface IA { } interface IB<T> { } class A { internal interface IC { } } partial class B1<T> where T : A, IB<IA> { } partial class B1<T> where T : N.A, N.IB<N.IA> { } partial class B1<T> where T : NA1, NIBA { } partial class B2<T> where T : NA1, IB<A.IC> { } partial class B2<T> where T : NA2, NIBAC { } partial class B3<T> where T : IB<A> { } partial class B3<T> where T : NIBA { } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (19,19): error CS0265: Partial declarations of 'N.B3<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B3").WithArguments("N.B3<T>", "T").WithLocation(19, 19), // (1,1): info CS8019: Unnecessary using directive. // using NIA = N.IA; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NIA = N.IA;").WithLocation(1, 1)); } /// <summary> /// Class1.dll: error CS0268: Imported type 'C1' is invalid. It contains a circular base class dependency. /// </summary> [Fact()] public void CS0268ERR_ImportedCircularBase01() { var text = @"namespace NS { public class C3 : C1 { } public interface I3 : I1 { } } "; var ref1 = TestReferences.SymbolsTests.CyclicInheritance.Class1; var ref2 = TestReferences.SymbolsTests.CyclicInheritance.Class2; var comp = CreateCompilationWithMscorlib(text, new[] { ref1, ref2 }); comp.VerifyDiagnostics( // (3,23): error CS0268: Imported type 'C2' is invalid. It contains a circular base class dependency. // public class C3 : C1 { } Diagnostic(ErrorCode.ERR_ImportedCircularBase, "C1").WithArguments("C2", "C1"), // (4,22): error CS0268: Imported type 'I2' is invalid. It contains a circular base class dependency. // public interface I3 : I1 { } Diagnostic(ErrorCode.ERR_ImportedCircularBase, "I3").WithArguments("I2", "I1") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0273ERR_InvalidPropertyAccessMod() { var text = @"class C { public object P1 { get; public set; } // CS0273 public object P2 { get; internal set; } public object P3 { get; protected set; } public object P4 { get; protected internal set; } public object P5 { get; private set; } internal object Q1 { public get; set; } // CS0273 internal object Q2 { internal get; set; } // CS0273 internal object Q3 { protected get; set; } // CS0273 internal object Q4 { protected internal get; set; } // CS0273 internal object Q5 { private get; set; } protected object R1 { get { return null; } public set { } } // CS0273 protected object R2 { get { return null; } internal set { } } // CS0273 protected object R3 { get { return null; } protected set { } } // CS0273 protected object R4 { get { return null; } protected internal set { } } // CS0273 protected object R5 { get { return null; } private set { } } protected internal object S1 { get { return null; } public set { } } // CS0273 protected internal object S2 { get { return null; } internal set { } } protected internal object S3 { get { return null; } protected set { } } protected internal object S4 { get { return null; } protected internal set { } } // CS0273 protected internal object S5 { get { return null; } private set { } } private object T1 { public get; set; } // CS0273 private object T2 { internal get; set; } // CS0273 private object T3 { protected get; set; } // CS0273 private object T4 { protected internal get; set; } // CS0273 private object T5 { private get; set; } // CS0273 object U1 { public get; set; } // CS0273 object U2 { internal get; set; } // CS0273 object U3 { protected get; set; } // CS0273 object U4 { protected internal get; set; } // CS0273 object U5 { private get; set; } // CS0273 } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,36): error CS0273: The accessibility modifier of the 'C.P1.set' accessor must be more restrictive than the property or indexer 'C.P1' // public object P1 { get; public set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.P1.set", "C.P1"), // (8,33): error CS0273: The accessibility modifier of the 'C.Q1.get' accessor must be more restrictive than the property or indexer 'C.Q1' // internal object Q1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q1.get", "C.Q1"), // (9,35): error CS0273: The accessibility modifier of the 'C.Q2.get' accessor must be more restrictive than the property or indexer 'C.Q2' // internal object Q2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q2.get", "C.Q2"), // (10,36): error CS0273: The accessibility modifier of the 'C.Q3.get' accessor must be more restrictive than the property or indexer 'C.Q3' // internal object Q3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q3.get", "C.Q3"), // (11,45): error CS0273: The accessibility modifier of the 'C.Q4.get' accessor must be more restrictive than the property or indexer 'C.Q4' // internal object Q4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q4.get", "C.Q4"), // (13,55): error CS0273: The accessibility modifier of the 'C.R1.set' accessor must be more restrictive than the property or indexer 'C.R1' // protected object R1 { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R1.set", "C.R1"), // (14,57): error CS0273: The accessibility modifier of the 'C.R2.set' accessor must be more restrictive than the property or indexer 'C.R2' // protected object R2 { get { return null; } internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R2.set", "C.R2"), // (15,58): error CS0273: The accessibility modifier of the 'C.R3.set' accessor must be more restrictive than the property or indexer 'C.R3' // protected object R3 { get { return null; } protected set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R3.set", "C.R3"), // (16,67): error CS0273: The accessibility modifier of the 'C.R4.set' accessor must be more restrictive than the property or indexer 'C.R4' // protected object R4 { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R4.set", "C.R4"), // (18,64): error CS0273: The accessibility modifier of the 'C.S1.set' accessor must be more restrictive than the property or indexer 'C.S1' // protected internal object S1 { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.S1.set", "C.S1"), // (21,76): error CS0273: The accessibility modifier of the 'C.S4.set' accessor must be more restrictive than the property or indexer 'C.S4' // protected internal object S4 { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.S4.set", "C.S4"), // (23,32): error CS0273: The accessibility modifier of the 'C.T1.get' accessor must be more restrictive than the property or indexer 'C.T1' // private object T1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T1.get", "C.T1"), // (24,34): error CS0273: The accessibility modifier of the 'C.T2.get' accessor must be more restrictive than the property or indexer 'C.T2' // private object T2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T2.get", "C.T2"), // (25,35): error CS0273: The accessibility modifier of the 'C.T3.get' accessor must be more restrictive than the property or indexer 'C.T3' // private object T3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T3.get", "C.T3"), // (26,44): error CS0273: The accessibility modifier of the 'C.T4.get' accessor must be more restrictive than the property or indexer 'C.T4' // private object T4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T4.get", "C.T4"), // (27,33): error CS0273: The accessibility modifier of the 'C.T5.get' accessor must be more restrictive than the property or indexer 'C.T5' // private object T5 { private get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T5.get", "C.T5"), // (28,24): error CS0273: The accessibility modifier of the 'C.U1.get' accessor must be more restrictive than the property or indexer 'C.U1' // object U1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U1.get", "C.U1"), // (29,26): error CS0273: The accessibility modifier of the 'C.U2.get' accessor must be more restrictive than the property or indexer 'C.U2' // object U2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U2.get", "C.U2"), // (30,27): error CS0273: The accessibility modifier of the 'C.U3.get' accessor must be more restrictive than the property or indexer 'C.U3' // object U3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U3.get", "C.U3"), // (31,36): error CS0273: The accessibility modifier of the 'C.U4.get' accessor must be more restrictive than the property or indexer 'C.U4' // object U4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U4.get", "C.U4"), // (32,25): error CS0273: The accessibility modifier of the 'C.U5.get' accessor must be more restrictive than the property or indexer 'C.U5' // object U5 { private get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U5.get", "C.U5")); } [Fact] public void CS0273ERR_InvalidPropertyAccessMod_Indexers() { var text = @"class C { public object this[int x, int y, double z] { get { return null; } public set { } } // CS0273 public object this[int x, double y, int z] { get { return null; } internal set { } } public object this[int x, double y, double z] { get { return null; } protected set { } } public object this[double x, int y, int z] { get { return null; } protected internal set { } } public object this[double x, int y, double z] { get { return null; } private set { } } internal object this[int x, int y, char z] { public get { return null; } set { } } // CS0273 internal object this[int x, char y, int z] { internal get { return null; } set { } } // CS0273 internal object this[int x, char y, char z] { protected get { return null; } set { } } // CS0273 internal object this[char x, int y, int z] { protected internal get { return null; } set { } } // CS0273 internal object this[char x, int y, char z] { private get { return null; } set { } } protected object this[int x, int y, long z] { get { return null; } public set { } } // CS0273 protected object this[int x, long y, int z] { get { return null; } internal set { } } // CS0273 protected object this[int x, long y, long z] { get { return null; } protected set { } } // CS0273 protected object this[long x, int y, int z] { get { return null; } protected internal set { } } // CS0273 protected object this[long x, int y, long z] { get { return null; } private set { } } protected internal object this[int x, int y, float z] { get { return null; } public set { } } // CS0273 protected internal object this[int x, float y, int z] { get { return null; } internal set { } } protected internal object this[int x, float y, float z] { get { return null; } protected set { } } protected internal object this[float x, int y, int z] { get { return null; } protected internal set { } } // CS0273 protected internal object this[float x, int y, float z] { get { return null; } private set { } } private object this[int x, int y, string z] { public get { return null; } set { } } // CS0273 private object this[int x, string y, int z] { internal get { return null; } set { } } // CS0273 private object this[int x, string y, string z] { protected get { return null; } set { } } // CS0273 private object this[string x, int y, int z] { protected internal get { return null; } set { } } // CS0273 private object this[string x, int y, string z] { private get { return null; } set { } } // CS0273 object this[int x, int y, object z] { public get { return null; } set { } } // CS0273 object this[int x, object y, int z] { internal get { return null; } set { } } // CS0273 object this[int x, object y, object z] { protected get { return null; } set { } } // CS0273 object this[object x, int y, int z] { protected internal get { return null; } set { } } // CS0273 object this[object x, int y, object z] { private get { return null; } set { } } // CS0273 } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,78): error CS0273: The accessibility modifier of the 'C.this[int, int, double].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, double]' // public object this[int x, int y, double z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, double].set", "C.this[int, int, double]"), // (8,57): error CS0273: The accessibility modifier of the 'C.this[int, int, char].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, char]' // internal object this[int x, int y, char z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, char].get", "C.this[int, int, char]"), // (9,59): error CS0273: The accessibility modifier of the 'C.this[int, char, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, char, int]' // internal object this[int x, char y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, char, int].get", "C.this[int, char, int]"), // (10,61): error CS0273: The accessibility modifier of the 'C.this[int, char, char].get' accessor must be more restrictive than the property or indexer 'C.this[int, char, char]' // internal object this[int x, char y, char z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, char, char].get", "C.this[int, char, char]"), // (11,69): error CS0273: The accessibility modifier of the 'C.this[char, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[char, int, int]' // internal object this[char x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[char, int, int].get", "C.this[char, int, int]"), // (13,79): error CS0273: The accessibility modifier of the 'C.this[int, int, long].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, long]' // protected object this[int x, int y, long z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, long].set", "C.this[int, int, long]"), // (14,81): error CS0273: The accessibility modifier of the 'C.this[int, long, int].set' accessor must be more restrictive than the property or indexer 'C.this[int, long, int]' // protected object this[int x, long y, int z] { get { return null; } internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, long, int].set", "C.this[int, long, int]"), // (15,83): error CS0273: The accessibility modifier of the 'C.this[int, long, long].set' accessor must be more restrictive than the property or indexer 'C.this[int, long, long]' // protected object this[int x, long y, long z] { get { return null; } protected set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, long, long].set", "C.this[int, long, long]"), // (16,91): error CS0273: The accessibility modifier of the 'C.this[long, int, int].set' accessor must be more restrictive than the property or indexer 'C.this[long, int, int]' // protected object this[long x, int y, int z] { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[long, int, int].set", "C.this[long, int, int]"), // (18,89): error CS0273: The accessibility modifier of the 'C.this[int, int, float].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, float]' // protected internal object this[int x, int y, float z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, float].set", "C.this[int, int, float]"), // (21,101): error CS0273: The accessibility modifier of the 'C.this[float, int, int].set' accessor must be more restrictive than the property or indexer 'C.this[float, int, int]' // protected internal object this[float x, int y, int z] { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[float, int, int].set", "C.this[float, int, int]"), // (23,58): error CS0273: The accessibility modifier of the 'C.this[int, int, string].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, string]' // private object this[int x, int y, string z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, string].get", "C.this[int, int, string]"), // (24,60): error CS0273: The accessibility modifier of the 'C.this[int, string, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, string, int]' // private object this[int x, string y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, string, int].get", "C.this[int, string, int]"), // (25,64): error CS0273: The accessibility modifier of the 'C.this[int, string, string].get' accessor must be more restrictive than the property or indexer 'C.this[int, string, string]' // private object this[int x, string y, string z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, string, string].get", "C.this[int, string, string]"), // (26,70): error CS0273: The accessibility modifier of the 'C.this[string, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[string, int, int]' // private object this[string x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[string, int, int].get", "C.this[string, int, int]"), // (27,62): error CS0273: The accessibility modifier of the 'C.this[string, int, string].get' accessor must be more restrictive than the property or indexer 'C.this[string, int, string]' // private object this[string x, int y, string z] { private get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[string, int, string].get", "C.this[string, int, string]"), // (28,50): error CS0273: The accessibility modifier of the 'C.this[int, int, object].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, object]' // object this[int x, int y, object z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, object].get", "C.this[int, int, object]"), // (29,52): error CS0273: The accessibility modifier of the 'C.this[int, object, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, object, int]' // object this[int x, object y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, object, int].get", "C.this[int, object, int]"), // (30,56): error CS0273: The accessibility modifier of the 'C.this[int, object, object].get' accessor must be more restrictive than the property or indexer 'C.this[int, object, object]' // object this[int x, object y, object z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, object, object].get", "C.this[int, object, object]"), // (31,62): error CS0273: The accessibility modifier of the 'C.this[object, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[object, int, int]' // object this[object x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[object, int, int].get", "C.this[object, int, int]"), // (32,54): error CS0273: The accessibility modifier of the 'C.this[object, int, object].get' accessor must be more restrictive than the property or indexer 'C.this[object, int, object]' // object this[object x, int y, object z] { private get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[object, int, object].get", "C.this[object, int, object]")); } [Fact] public void CS0274ERR_DuplicatePropertyAccessMods() { var text = @"class C { public int P { protected get; internal set; } internal object Q { private get { return null; } private set { } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.P' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "P").WithArguments("C.P"), // (4,21): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.Q' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "Q").WithArguments("C.Q")); } [Fact] public void CS0274ERR_DuplicatePropertyAccessMods_Indexer() { var text = @"class C { public int this[int x] { protected get { return 0; } internal set { } } internal object this[object x] { private get { return null; } private set { } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.this[int]' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("C.this[int]"), // (4,21): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.this[object]' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("C.this[object]")); } [Fact] public void CS0275ERR_PropertyAccessModInInterface() { CreateCompilationWithMscorlib( @"interface I { object P { get; } // no error int Q { private get; set; } // CS0275 object R { get; internal set; } // CS0275 } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PropertyAccessModInInterface, "get").WithArguments("I.Q.get"), Diagnostic(ErrorCode.ERR_PropertyAccessModInInterface, "set").WithArguments("I.R.set")); } [Fact] public void CS0275ERR_PropertyAccessModInInterface_Indexer() { CreateCompilationWithMscorlib( @"interface I { object this[int x] { get; } // no error int this[char x] { private get; set; } // CS0275 object this[string x] { get; internal set; } // CS0275 } ") .VerifyDiagnostics( // (4,32): error CS0275: 'I.this[char].get': accessibility modifiers may not be used on accessors in an interface Diagnostic(ErrorCode.ERR_PropertyAccessModInInterface, "get").WithArguments("I.this[char].get"), // (5,43): error CS0275: 'I.this[string].set': accessibility modifiers may not be used on accessors in an interface Diagnostic(ErrorCode.ERR_PropertyAccessModInInterface, "set").WithArguments("I.this[string].set")); } [WorkItem(538620, "DevDiv")] [Fact] public void CS0276ERR_AccessModMissingAccessor() { var text = @"class A { public virtual object P { get; protected set; } } class B : A { public override object P { protected set { } } // no error public object Q { private set { } } // CS0276 protected internal object R { internal get { return null; } } // CS0276 } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,19): error CS0276: 'B.Q': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "Q").WithArguments("B.Q"), // (9,31): error CS0276: 'B.R': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "R").WithArguments("B.R")); } [Fact] public void CS0276ERR_AccessModMissingAccessor_Indexer() { var text = @"class A { public virtual object this[int x] { get { return null; } protected set { } } } class B : A { public override object this[int x] { protected set { } } // no error public object this[char x] { private set { } } // CS0276 protected internal object this[string x] { internal get { return null; } } // CS0276 } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,19): error CS0276: 'B.this[char]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("B.this[char]"), // (9,31): error CS0276: 'B.this[string]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("B.this[string]")); } [Fact] public void CS0277ERR_UnimplementedInterfaceAccessor() { var text = @"public interface MyInterface { int Property { get; set; } } public class MyClass : MyInterface // CS0277 { public int Property { get { return 0; } protected set { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceAccessor, Line = 10, Column = 24 }); } [Fact(Skip = "530901"), WorkItem(530901, "DevDiv")] public void CS0281ERR_FriendRefNotEqualToThis() { //sn -k CS0281.snk //sn -i CS0281.snk CS0281.snk //sn -pc CS0281.snk key.publickey //sn -tp key.publickey //csc /target:library /keyfile:CS0281.snk class1.cs //csc /target:library /keyfile:CS0281.snk /reference:class1.dll class2.cs //csc /target:library /keyfile:CS0281.snk /reference:class2.dll /out:class1.dll program.cs var text1 = @"public class A { }"; var tree1 = SyntaxFactory.ParseCompilationUnit(text1); var text2 = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Class1 , PublicKey=abc"")] class B : A { } "; var tree2 = SyntaxFactory.ParseCompilationUnit(text2); var text3 = @"using System.Runtime.CompilerServices; [assembly: System.Reflection.AssemblyVersion(""3"")] [assembly: System.Reflection.AssemblyCulture(""en-us"")] [assembly: InternalsVisibleTo(""MyServices, PublicKeyToken=aaabbbcccdddeee"")] class C : B { } public class A { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text3, new ErrorDescription { Code = (int)ErrorCode.ERR_FriendRefNotEqualToThis, Line = 10, Column = 14 }); } /// <summary> /// Some? /// </summary> [Fact] public void CS0305ERR_BadArity01() { var text = @"namespace NS { interface I<T, V> { } struct S<T> : I<T> { } class C<T> { } public class Test { //public static int Main() //{ // C c = new C(); // Not in Dev10 // return 1; //} I<T, V, U> M<T, V, U>() { return null; } public I<int> field; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 5, Column = 19 }, //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 13, Column = 13 }, // Dev10 miss this due to other errors //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 13, Column = 23 }, // Dev10 miss this due to other errors new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 17, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 18, Column = 16 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0306ERR_BadTypeArgument01() { var source = @"using System; class C<T> { static void F<U>() { } static void M(object o) { new C<int*>(); new C<ArgIterator>(); new C<RuntimeArgumentHandle>(); new C<TypedReference>(); F<int*>(); o.E<object, ArgIterator>(); Action a; a = F<RuntimeArgumentHandle>; a = o.E<T, TypedReference>; Console.WriteLine(typeof(TypedReference?)); Console.WriteLine(typeof(Nullable<TypedReference>)); } } static class S { internal static void E<T, U>(this object o) { } } "; CreateCompilationWithMscorlib(source, references: new[] { SystemCoreRef }).VerifyDiagnostics( // (7,15): error CS0306: The type 'int*' may not be used as a type argument // new C<int*>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*"), // (8,15): error CS0306: The type 'System.ArgIterator' may not be used as a type argument // new C<ArgIterator>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "ArgIterator").WithArguments("System.ArgIterator"), // (9,15): error CS0306: The type 'System.RuntimeArgumentHandle' may not be used as a type argument // new C<RuntimeArgumentHandle>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle"), // (10,15): error CS0306: The type 'System.TypedReference' may not be used as a type argument // new C<TypedReference>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference"), // (11,9): error CS0306: The type 'int*' may not be used as a type argument // F<int*>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "F<int*>").WithArguments("int*"), // (12,9): error CS0306: The type 'System.ArgIterator' may not be used as a type argument // o.E<object, ArgIterator>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "o.E<object, ArgIterator>").WithArguments("System.ArgIterator"), // (14,13): error CS0306: The type 'System.RuntimeArgumentHandle' may not be used as a type argument // a = F<RuntimeArgumentHandle>; Diagnostic(ErrorCode.ERR_BadTypeArgument, "F<RuntimeArgumentHandle>").WithArguments("System.RuntimeArgumentHandle"), // (15,13): error CS0306: The type 'System.TypedReference' may not be used as a type argument // a = o.E<T, TypedReference>; Diagnostic(ErrorCode.ERR_BadTypeArgument, "o.E<T, TypedReference>").WithArguments("System.TypedReference"), // (16,34): error CS0306: The type 'System.TypedReference' may not be used as a type argument // Console.WriteLine(typeof(TypedReference?)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference?").WithArguments("System.TypedReference"), // (17,43): error CS0306: The type 'System.TypedReference' may not be used as a type argument // Console.WriteLine(typeof(Nullable<TypedReference>)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference")); } /// <summary> /// Bad type arguments for aliases should be reported at the /// alias declaration rather than at the use. (Note: This differs /// from Dev10 which reports errors at the use, with no errors /// reported if there are no uses of the alias.) /// </summary> [Fact] public void CS0306ERR_BadTypeArgument02() { var source = @"using COfObject = C<object>; using COfIntPtr = C<int*>; using COfArgIterator = C<System.ArgIterator>; // unused class C<T> { static void F<U>() { } static void M() { new COfIntPtr(); COfObject.F<int*>(); COfIntPtr.F<object>(); } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (2,7): error CS0306: The type 'int*' may not be used as a type argument Diagnostic(ErrorCode.ERR_BadTypeArgument, "COfIntPtr").WithArguments("int*").WithLocation(2, 7), // (3,7): error CS0306: The type 'System.ArgIterator' may not be used as a type argument Diagnostic(ErrorCode.ERR_BadTypeArgument, "COfArgIterator").WithArguments("System.ArgIterator").WithLocation(3, 7), // (10,9): error CS0306: The type 'int*' may not be used as a type argument Diagnostic(ErrorCode.ERR_BadTypeArgument, "COfObject.F<int*>").WithArguments("int*").WithLocation(10, 9), // (3,1): info CS8019: Unnecessary using directive. // using COfArgIterator = C<System.ArgIterator>; // unused Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using COfArgIterator = C<System.ArgIterator>;").WithLocation(3, 1)); } [WorkItem(538157, "DevDiv")] [Fact] public void CS0307ERR_TypeArgsNotAllowed() { var text = @"namespace NS { public class Test<T> { internal object field; public int P { get { return 1; } } public static int Main() { Test<int> t = new NS<T>.Test<int>(); var v = t.field<string>; int p = t.P<int>(); if (v == v | p == p | t == t) {} return 1; } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (10,31): error CS0307: The namespace 'NS' cannot be used with type arguments // Test<int> t = new NS<T>.Test<int>(); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "NS<T>").WithArguments("NS", "namespace"), // (11,23): error CS0307: The field 'NS.Test<int>.field' cannot be used with type arguments // var v = t.field<string>; Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "field<string>").WithArguments("NS.Test<int>.field", "field"), // (12,23): error CS0307: The property 'NS.Test<int>.P' cannot be used with type arguments // int p = t.P<int>(); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<int>").WithArguments("NS.Test<int>.P", "property"), // (13,17): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "v == v"), // (13,26): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "p == p"), // (13,35): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t == t"), // (5,25): warning CS0649: Field 'NS.Test<T>.field' is never assigned to, and will always have its default value null // internal object field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Test<T>.field", "null") ); } [WorkItem(542296, "DevDiv")] [Fact] public void CS0307ERR_TypeArgsNotAllowed_02() { var text = @" public class Test { public int Fld; public int Func() { return (int)(Fld<int>); } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (7,22): error CS0307: The field 'Test.Fld' cannot be used with type arguments // return (int)(Fld<int>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Fld<int>").WithArguments("Test.Fld", "field") ); } [Fact] public void CS0307ERR_TypeArgsNotAllowed_03() { var text = @"class C<T, U> where T : U<T>, new() { static object M() { return new T<U>(); } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (1,25): error CS0307: The type parameter 'U' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "U<T>").WithArguments("U", "type parameter").WithLocation(1, 25), // (5,20): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<U>").WithArguments("T", "type parameter").WithLocation(5, 20)); } [Fact] public void CS0308ERR_HasNoTypeVars01() { var text = @"namespace NS { public class Test { public static string F() { return null; } protected void FF(string s) { } public static int Main() { new Test().FF<string, string>(F<int>()); return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 10, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 10, Column = 43 }); } [WorkItem(540090, "DevDiv")] [Fact] public void CS0308ERR_HasNoTypeVars02() { var text = @" public class NormalType { public static class M2 { public static int F1 = 1; } public static void Test() { int i; i = M2<int>.F1; } public static int Main() { return -1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 8, Column = 13 }); } [Fact] public void CS0400ERR_GlobalSingleTypeNameNotFound01() { var text = @"namespace NS { public class Test { public static int Main() { // global::D d = new global::D(); return 1; } } struct S { global::G field; } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (14,17): error CS0400: The type or namespace name 'G' could not be found in the global namespace (are you missing an assembly reference?) // global::G field; Diagnostic(ErrorCode.ERR_GlobalSingleTypeNameNotFound, "G").WithArguments("G", "<global namespace>"), // (14,19): warning CS0169: The field 'NS.S.field' is never used // global::G field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.S.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0405ERR_DuplicateBound() { var source = @"interface IA { } interface IB { } class A { } class B { } class C<T, U> where T : IA, IB, IA where U : A, IA, A { void M<V>() where V : U, IA, U { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (6,23): error CS0405: Duplicate constraint 'IA' for type parameter 'T' Diagnostic(ErrorCode.ERR_DuplicateBound, "IA").WithArguments("IA", "T").WithLocation(6, 23), // (7,22): error CS0405: Duplicate constraint 'A' for type parameter 'U' Diagnostic(ErrorCode.ERR_DuplicateBound, "A").WithArguments("A", "U").WithLocation(7, 22), // (9,34): error CS0405: Duplicate constraint 'U' for type parameter 'V' Diagnostic(ErrorCode.ERR_DuplicateBound, "U").WithArguments("U", "V").WithLocation(9, 34)); } [Fact] public void CS0406ERR_ClassBoundNotFirst() { var source = @"interface I { } class A { } class B { } class C<T, U> where T : I, A where U : A, B { void M<V>() where V : U, A, B { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (5,18): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(5, 18), // (6,18): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(6, 18), // (8,30): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(8, 30), // (8,33): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(8, 33)); } [Fact] public void CS0409ERR_DuplicateConstraintClause() { var source = @"interface I<T> where T : class where T : struct { void M<U, V>() where U : new() where V : class where U : class where U : I<T>; }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,11): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "T").WithArguments("T").WithLocation(3, 11), // (8,15): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(8, 15), // (9,15): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(9, 15)); } [Fact] public void CS0415ERR_BadIndexerNameAttr() { var text = @"using System; using System.Runtime.CompilerServices; public interface IA { int this[int index] { get; set; } } public class A : IA { [IndexerName(""Item"")] // CS0415 int IA.this[int index] { get { return 0; } set { } } [IndexerName(""Item"")] // CS0415 int P { get; set; } [IndexerName(""Item"")] // CS0592 int f; [IndexerName(""Item"")] // CS0592 void M() { } [IndexerName(""Item"")] // CS0592 event Action E; [IndexerName(""Item"")] // CS0592 class C { } [IndexerName(""Item"")] // CS0592 struct S { } [IndexerName(""Item"")] // CS0592 delegate void D(); } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (15,6): error CS0415: The 'IndexerName' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, "IndexerName").WithArguments("IndexerName"), // (22,6): error CS0415: The 'IndexerName' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, "IndexerName").WithArguments("IndexerName"), // (26,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (29,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (32,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (35,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (38,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (41,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (27,9): warning CS0169: The field 'A.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("A.f"), // (33,18): warning CS0067: The event 'A.E' is never used Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("A.E")); } [Fact] public void CS0415ERR_BadIndexerNameAttr_Alias() { var text = @" using Alias = System.Runtime.CompilerServices.IndexerNameAttribute; public interface IA { int this[int index] { get; set; } } public class A : IA { [ Alias(""Item"")] // CS0415 int IA.this[int index] { get { return 0; } set { } } } "; var compilation = CreateCompilationWithMscorlib(text); // NOTE: uses attribute name from syntax. compilation.VerifyDiagnostics( // (11,6): error CS0415: The 'Alias' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, @"Alias").WithArguments("Alias")); // Note: invalid attribute had no effect on metadata name. var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetProperty("IA." + WellKnownMemberNames.Indexer); Assert.Equal("IA.Item", indexer.MetadataName); } [Fact] public void CS0416ERR_AttrArgWithTypeVars() { var text = @"public class MyAttribute : System.Attribute { public MyAttribute(System.Type t) { } } class G<T> { [MyAttribute(typeof(G<T>))] // CS0416 public void F() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AttrArgWithTypeVars, Line = 10, Column = 18 }); } [Fact] public void CS0418ERR_AbstractSealedStatic01() { var text = @"namespace NS { public abstract static class C // CS0418 { internal abstract sealed class CC { private static abstract sealed class CCC // CS0418, 0441 { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 3, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 5, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 7, Column = 50 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedStaticClass, Line = 7, Column = 50 }); } [Fact] public void CS0423ERR_ComImportWithImpl() { var text = @"using System.Runtime.InteropServices; [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class ImageProperties { public static void Main() // CS0423 { ImageProperties i = new ImageProperties(); } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,24): error CS0423: Since 'ImageProperties' has the ComImport attribute, 'ImageProperties.Main()' must be extern or abstract // public static void Main() // CS0423 Diagnostic(ErrorCode.ERR_ComImportWithImpl, "Main").WithArguments("ImageProperties.Main()", "ImageProperties").WithLocation(5, 24)); } [Fact] public void CS0424ERR_ComImportWithBase() { var text = @"using System.Runtime.InteropServices; public class A { } [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class B : A { } // CS0424 error "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,7): error CS0424: 'B': a class with the ComImport attribute cannot specify a base class // class B : A { } // CS0424 error Diagnostic(ErrorCode.ERR_ComImportWithBase, "B").WithArguments("B").WithLocation(5, 7)); } [WorkItem(856187, "DevDiv")] [WorkItem(866093, "DevDiv")] [Fact] public void CS0424ERR_ComImportWithInitializers() { var text = @" using System.Runtime.InteropServices; [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class B { public static int X = 5; public int Y = 5; public const decimal D = 5; public const int Yconst = 5; } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (7,25): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public static int X = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(7, 25), // (9,28): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public const decimal D = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(9, 28), // (8,18): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public int Y = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(8, 18) ); } [Fact] public void CS0425ERR_ImplBadConstraints01() { var source = @"interface IA<T> { } interface IB { } interface I { // Different constraints: void A1<T>() where T : struct; void A2<T, U>() where T : struct where U : IA<T>; void A3<T>() where T : IA<T>; void A4<T, U>() where T : struct, IA<T>; // Additional constraints: void B1<T>(); void B2<T>() where T : new(); void B3<T, U>() where T : IA<T>; // Missing constraints. void C1<T>() where T : class; void C2<T>() where T : class, new(); void C3<T, U>() where U : IB, IA<T>; // Same constraints, different order. void D1<T>() where T : IA<T>, IB; void D2<T, U, V>() where V : T, U; // Different constraint clauses. void E1<T, U>() where U : T; // Additional constraint clause. void F1<T, U>() where T : class; // Missing constraint clause. void G1<T, U>() where T : class where U : T; // Same constraint clauses, different order. void H1<T, U>() where T : class where U : T; void H2<T, U>() where T : class where U : T; void H3<T, U, V>() where V : class where U : IB where T : IA<V>; // Different type parameter names. void K1<T, U>() where T : class where U : T; void K2<T, U>() where T : class where U : T; } class C : I { // Different constraints: public void A1<T>() where T : class { } public void A2<T, U>() where T : struct where U : IB { } public void A3<T>() where T : IA<IA<T>> { } public void A4<T, U>() where T : struct, IA<U> { } // Additional constraints: public void B1<T>() where T : new() { } public void B2<T>() where T : class, new() { } public void B3<T, U>() where T : IB, IA<T> { } // Missing constraints. public void C1<T>() { } public void C2<T>() where T : class { } public void C3<T, U>() where U : IA<T> { } // Same constraints, different order. public void D1<T>() where T : IB, IA<T> { } public void D2<T, U, V>() where V : U, T { } // Different constraint clauses. public void E1<T, U>() where T : class { } // Additional constraint clause. public void F1<T, U>() where T : class where U : T { } // Missing constraint clause. public void G1<T, U>() where T : class { } // Same constraint clauses, different order. public void H1<T, U>() where U : T where T : class { } public void H2<T, U>() where U : class where T : U { } public void H3<T, U, V>() where T : IA<V> where U : IB where V : class { } // Different type parameter names. public void K1<U, T>() where T : class where U : T { } public void K2<T1, T2>() where T1 : class where T2 : T1 { } }"; // Note: Errors are reported on A1, A2, ... rather than A1<T>, A2<T, U>, ... See bug #9396. CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (38,17): error CS0425: The constraints for type parameter 'T' of method 'C.A1<T>()' must match the constraints for type parameter 'T' of interface method 'I.A1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A1").WithArguments("T", "C.A1<T>()", "T", "I.A1<T>()").WithLocation(38, 17), // (39,17): error CS0425: The constraints for type parameter 'U' of method 'C.A2<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.A2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A2").WithArguments("U", "C.A2<T, U>()", "U", "I.A2<T, U>()").WithLocation(39, 17), // (40,17): error CS0425: The constraints for type parameter 'T' of method 'C.A3<T>()' must match the constraints for type parameter 'T' of interface method 'I.A3<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A3").WithArguments("T", "C.A3<T>()", "T", "I.A3<T>()").WithLocation(40, 17), // (41,17): error CS0425: The constraints for type parameter 'T' of method 'C.A4<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.A4<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A4").WithArguments("T", "C.A4<T, U>()", "T", "I.A4<T, U>()").WithLocation(41, 17), // (43,17): error CS0425: The constraints for type parameter 'T' of method 'C.B1<T>()' must match the constraints for type parameter 'T' of interface method 'I.B1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B1").WithArguments("T", "C.B1<T>()", "T", "I.B1<T>()").WithLocation(43, 17), // (44,17): error CS0425: The constraints for type parameter 'T' of method 'C.B2<T>()' must match the constraints for type parameter 'T' of interface method 'I.B2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B2").WithArguments("T", "C.B2<T>()", "T", "I.B2<T>()").WithLocation(44, 17), // (45,17): error CS0425: The constraints for type parameter 'T' of method 'C.B3<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.B3<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B3").WithArguments("T", "C.B3<T, U>()", "T", "I.B3<T, U>()").WithLocation(45, 17), // (47,17): error CS0425: The constraints for type parameter 'T' of method 'C.C1<T>()' must match the constraints for type parameter 'T' of interface method 'I.C1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C1").WithArguments("T", "C.C1<T>()", "T", "I.C1<T>()").WithLocation(47, 17), // (48,17): error CS0425: The constraints for type parameter 'T' of method 'C.C2<T>()' must match the constraints for type parameter 'T' of interface method 'I.C2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C2").WithArguments("T", "C.C2<T>()", "T", "I.C2<T>()").WithLocation(48, 17), // (49,17): error CS0425: The constraints for type parameter 'U' of method 'C.C3<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.C3<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C3").WithArguments("U", "C.C3<T, U>()", "U", "I.C3<T, U>()").WithLocation(49, 17), // (54,17): error CS0425: The constraints for type parameter 'T' of method 'C.E1<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.E1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "E1").WithArguments("T", "C.E1<T, U>()", "T", "I.E1<T, U>()").WithLocation(54, 17), // (54,17): error CS0425: The constraints for type parameter 'U' of method 'C.E1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.E1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "E1").WithArguments("U", "C.E1<T, U>()", "U", "I.E1<T, U>()").WithLocation(54, 17), // (56,17): error CS0425: The constraints for type parameter 'U' of method 'C.F1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.F1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "F1").WithArguments("U", "C.F1<T, U>()", "U", "I.F1<T, U>()").WithLocation(56, 17), // (58,17): error CS0425: The constraints for type parameter 'U' of method 'C.G1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.G1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "G1").WithArguments("U", "C.G1<T, U>()", "U", "I.G1<T, U>()").WithLocation(58, 17), // (61,17): error CS0425: The constraints for type parameter 'T' of method 'C.H2<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.H2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "H2").WithArguments("T", "C.H2<T, U>()", "T", "I.H2<T, U>()").WithLocation(61, 17), // (61,17): error CS0425: The constraints for type parameter 'U' of method 'C.H2<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.H2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "H2").WithArguments("U", "C.H2<T, U>()", "U", "I.H2<T, U>()").WithLocation(61, 17), // (64,17): error CS0425: The constraints for type parameter 'U' of method 'C.K1<U, T>()' must match the constraints for type parameter 'T' of interface method 'I.K1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "K1").WithArguments("U", "C.K1<U, T>()", "T", "I.K1<T, U>()").WithLocation(64, 17), // (64,17): error CS0425: The constraints for type parameter 'T' of method 'C.K1<U, T>()' must match the constraints for type parameter 'U' of interface method 'I.K1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "K1").WithArguments("T", "C.K1<U, T>()", "U", "I.K1<T, U>()").WithLocation(64, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints02() { var source = @"interface IA<T> { } interface IB { } interface I<T> { void M1<U, V>() where U : T where V : IA<T>; void M2<U>() where U : T, new(); } class C1 : I<IB> { public void M1<U, V>() where U : IB where V : IA<IB> { } public void M2<U>() where U : I<IB> { } } class C2<T, U> : I<IA<U>> { public void M1<X, Y>() where Y : IA<IA<U>> where X : IA<U> { } public void M2<X>() where X : T, new() { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (11,17): error CS0425: The constraints for type parameter 'U' of method 'C1.M2<U>()' must match the constraints for type parameter 'U' of interface method 'I<IB>.M2<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("U", "C1.M2<U>()", "U", "I<IB>.M2<U>()").WithLocation(11, 17), // (16,17): error CS0425: The constraints for type parameter 'X' of method 'C2<T, U>.M2<X>()' must match the constraints for type parameter 'U' of interface method 'I<IA<U>>.M2<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("X", "C2<T, U>.M2<X>()", "U", "I<IA<U>>.M2<U>()").WithLocation(16, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints03() { var source = @"interface IA { } class B { } interface I1<T> { void M<U>() where U : struct, T; } class C1<T> : I1<T> where T : struct { public void M<U>() where U : T { } } interface I2<T> { void M<U>() where U : class, T; } class C2 : I2<B> { public void M<U>() where U : B { } } class C2<T> : I2<T> where T : class { public void M<U>() where U : T { } } interface I3<T> { void M<U>() where U : T, new(); } class C3 : I3<B> { public void M<U>() where U : B { } } class C3<T> : I3<T> where T : new() { public void M<U>() where U : T { } } interface I4<T> { void M<U>() where U : T, IA; } class C4 : I4<IA> { public void M<U>() where U : IA { } } class C4<T> : I4<T> where T : IA { public void M<U>() where U : T { } } interface I5<T> { void M<U>() where U : B, T; } class C5 : I5<B> { public void M<U>() where U : B { } } class C5<T> : I5<T> where T : B { public void M<U>() where U : T { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (9,17): error CS0425: The constraints for type parameter 'U' of method 'C1<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I1<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C1<T>.M<U>()", "U", "I1<T>.M<U>()").WithLocation(9, 17), // (9,19): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(9, 19), // (17,17): error CS0425: The constraints for type parameter 'U' of method 'C2.M<U>()' must match the constraints for type parameter 'U' of interface method 'I2<B>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C2.M<U>()", "U", "I2<B>.M<U>()").WithLocation(17, 17), // (21,17): error CS0425: The constraints for type parameter 'U' of method 'C2<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I2<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C2<T>.M<U>()", "U", "I2<T>.M<U>()").WithLocation(21, 17), // (29,17): error CS0425: The constraints for type parameter 'U' of method 'C3.M<U>()' must match the constraints for type parameter 'U' of interface method 'I3<B>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C3.M<U>()", "U", "I3<B>.M<U>()").WithLocation(29, 17), // (33,17): error CS0425: The constraints for type parameter 'U' of method 'C3<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I3<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C3<T>.M<U>()", "U", "I3<T>.M<U>()").WithLocation(33, 17), // (45,17): error CS0425: The constraints for type parameter 'U' of method 'C4<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I4<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C4<T>.M<U>()", "U", "I4<T>.M<U>()").WithLocation(45, 17), // (57,17): error CS0425: The constraints for type parameter 'U' of method 'C5<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I5<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C5<T>.M<U>()", "U", "I5<T>.M<U>()").WithLocation(57, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints04() { var source = @"interface IA { void M1<T>(); void M2<T, U>() where U : T; } interface IB { void M1<T>() where T : IB; void M2<X, Y>(); } abstract class C : IA, IB { public abstract void M1<T>(); public abstract void M2<X, Y>(); }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (14,26): error CS0425: The constraints for type parameter 'Y' of method 'C.M2<X, Y>()' must match the constraints for type parameter 'U' of interface method 'IA.M2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("Y", "C.M2<X, Y>()", "U", "IA.M2<T, U>()").WithLocation(14, 26), // (13,26): error CS0425: The constraints for type parameter 'T' of method 'C.M1<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "C.M1<T>()", "T", "IB.M1<T>()").WithLocation(13, 26)); } [Fact] public void CS0425ERR_ImplBadConstraints05() { var source = @"interface I<T> { } class C { } interface IA<T, U> { void A1<V>() where V : T, I<T>; void A2<V>() where V : T, U, I<T>, I<U>; } interface IB<T> { void B1<U>() where U : C; void B2<U, V>() where U : C, T, V; } class A<T, U> { // More constraints than IA<T, U>.A1<V>(). public void A1<V>() where V : T, U, I<T>, I<U> { } // Fewer constraints than IA<T, U>.A2<V>(). public void A2<V>() where V : T, I<T> { } } class B<T> { // More constraints than IB<T>.B1<U>(). public void B1<U>() where U : C, T { } // Fewer constraints than IB<T>.B2<U, V>(). public void B2<U, V>() where U : T, V { } } class A1<T> : A<T, T>, IA<T, T> { } class A2<T, U> : A<T, U>, IA<T, U> { } class B1 : B<C>, IB<C> { } class B2<T> : B<T>, IB<T> { }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (30,7): error CS0425: The constraints for type parameter 'V' of method 'A<T, U>.A1<V>()' must match the constraints for type parameter 'V' of interface method 'IA<T, U>.A1<V>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A2").WithArguments("V", "A<T, U>.A1<V>()", "V", "IA<T, U>.A1<V>()").WithLocation(30, 7), // (30,7): error CS0425: The constraints for type parameter 'V' of method 'A<T, U>.A2<V>()' must match the constraints for type parameter 'V' of interface method 'IA<T, U>.A2<V>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A2").WithArguments("V", "A<T, U>.A2<V>()", "V", "IA<T, U>.A2<V>()").WithLocation(30, 7), // (36,7): error CS0425: The constraints for type parameter 'U' of method 'B<T>.B1<U>()' must match the constraints for type parameter 'U' of interface method 'IB<T>.B1<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B2").WithArguments("U", "B<T>.B1<U>()", "U", "IB<T>.B1<U>()").WithLocation(36, 7), // (36,7): error CS0425: The constraints for type parameter 'U' of method 'B<T>.B2<U, V>()' must match the constraints for type parameter 'U' of interface method 'IB<T>.B2<U, V>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B2").WithArguments("U", "B<T>.B2<U, V>()", "U", "IB<T>.B2<U, V>()").WithLocation(36, 7)); } [Fact] public void CS0425ERR_ImplBadConstraints06() { var source = @"using NIA1 = N.IA; using NIA2 = N.IA; using NA1 = N.A; using NA2 = N.A; namespace N { interface IA { } class A { } } interface IB { void M1<T>() where T : N.A, N.IA; void M2<T>() where T : NA1, NIA1; } abstract class B1 : IB { public abstract void M1<T>() where T : NA1, NIA1; public abstract void M2<T>() where T : NA2, NIA2; } abstract class B2 : IB { public abstract void M1<T>() where T : NA1; public abstract void M2<T>() where T : NIA2; }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (22,26): error CS0425: The constraints for type parameter 'T' of method 'B2.M1<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "B2.M1<T>()", "T", "IB.M1<T>()").WithLocation(22, 26), // (23,26): error CS0425: The constraints for type parameter 'T' of method 'B2.M2<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("T", "B2.M2<T>()", "T", "IB.M2<T>()").WithLocation(23, 26)); } [Fact] public void CS0426ERR_DottedTypeNameNotFoundInAgg01() { var text = @"namespace NS { public class C { public interface I { } } struct S { } public class Test { C.I.x field; // CS0426 void M(S.s p) { } // CS0426 public static int Main() { // C.A a; // CS0426 return 1; } } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (14,18): error CS0426: The type name 's' does not exist in the type 'NS.S' // void M(S.s p) { } // CS0426 Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "s").WithArguments("s", "NS.S"), // (13,13): error CS0426: The type name 'x' does not exist in the type 'NS.C.I' // C.I.x field; // CS0426 Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "x").WithArguments("x", "NS.C.I"), // (13,15): warning CS0169: The field 'NS.Test.field' is never used // C.I.x field; // CS0426 Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.Test.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0426ERR_DottedTypeNameNotFoundInAgg02() { var text = @"class A<T> { A<T>.T F = default(A<T>.T); } class B : A<object> { B.T F = default(B.T); }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,10): error CS0426: The type name 'T' does not exist in the type 'A<T>' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "A<T>").WithLocation(3, 10), // (3,29): error CS0426: The type name 'T' does not exist in the type 'A<T>' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "A<T>").WithLocation(3, 29), // (7,7): error CS0426: The type name 'T' does not exist in the type 'B' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "B").WithLocation(7, 7), // (7,23): error CS0426: The type name 'T' does not exist in the type 'B' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "B").WithLocation(7, 23)); } [Fact] public void CS0430ERR_BadExternAlias() { var text = @"extern alias MyType; // CS0430 public class Test { public static void Main() {} } public class MyClass { } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (1,14): error CS0430: The extern alias 'MyType' was not specified in a /reference option // extern alias MyType; // CS0430 Diagnostic(ErrorCode.ERR_BadExternAlias, "MyType").WithArguments("MyType"), // (1,1): info CS8020: Unused extern alias. // extern alias MyType; // CS0430 Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias MyType;")); } [Fact] public void CS0432ERR_AliasNotFound() { var text = @"class C { public class A { } } class E : C::A { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AliasNotFound, Line = 6, Column = 11 }); } /// <summary> /// Import - same name class from lib1 and lib2 /// </summary> [Fact] public void CS0433ERR_SameFullNameAggAgg01() { var text = @"namespace NS { class Test { Class1 var; void M(Class1 p) {} } } "; var ref1 = TestReferences.SymbolsTests.V1.MTTestLib1.dll; // this is not related to this test, but need by lib2 (don't want to add a new dll resource) var ref2 = TestReferences.SymbolsTests.MultiModule.Assembly; // Roslyn give CS0104 for now var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference> { ref1, ref2 }); comp.VerifyDiagnostics( // (6,16): error CS0433: The type 'Class1' exists in both 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // void M(Class1 p) {} Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "Class1").WithArguments("MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1", "MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,9): error CS0433: The type 'Class1' exists in both 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // Class1 var; Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "Class1").WithArguments("MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1", "MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,16): warning CS0169: The field 'NS.Test.var' is never used // Class1 var; Diagnostic(ErrorCode.WRN_UnreferencedField, "var").WithArguments("NS.Test.var")); text = @" class Class1 { } class Test { Class1 var; } "; comp = CreateCompilationWithMscorlib(new SyntaxTree[] { Parse(text, "foo.cs") }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // foo.cs(8,5): warning CS0436: The type 'Class1' in 'foo.cs' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'foo.cs'. // Class1 var; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("foo.cs", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // foo.cs(8,12): warning CS0169: The field 'Test.var' is never used // Class1 var; Diagnostic(ErrorCode.WRN_UnreferencedField, "var").WithArguments("Test.var") ); } /// <summary> /// import - lib1: namespace A { namespace B { .class C {}.. }} /// vs. lib2: Namespace A { class B { class C{} } }} - use C /// </summary> [Fact] public void CS0434ERR_SameFullNameNsAgg01() { var text = @" namespace NS { public class Test { public static void Main() { // var v = new N1.N2.A(); } void M(N1.N2.A p) { } } } "; var ref1 = TestReferences.DiagnosticTests.ErrTestLib11.dll; var ref2 = TestReferences.DiagnosticTests.ErrTestLib02.dll; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new List<MetadataReference> { ref1, ref2 }, // new ErrorDescription { Code = (int)ErrorCode.ERR_SameFullNameNsAgg, Line = 9, Column = 28 }, // Dev10 one error new ErrorDescription { Code = (int)ErrorCode.ERR_SameFullNameNsAgg, Line = 12, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact()] [WorkItem(568953, "DevDiv")] public void CS0438ERR_SameFullNameThisAggThisNs01() // I (Neal Gafter) was not able to reproduce this in Dev10 using the batch compiler, but the Dev10 // background compiler will emit this diagnostic (along with one other) for this code: // namespace NS { // namespace A { } // public class A { } // } // class B : NS.A { } //Compiling the scenario below using the native compiler gives CS0438 for me (Ed). { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0438 } } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0438 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact()] [WorkItem(568953, "DevDiv")] public void CS0438ERR_SameFullNameThisAggThisNs02() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0438 } } class Util { public class A {} } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0438 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "DevDiv")] public void CS0438ERR_SameFullNameThisAggThisNs03() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "DevDiv")] public void CS0438ERR_SameFullNameThisAggThisNs04() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "DevDiv")] public void CS0438ERR_SameFullNameThisAggThisNs05() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "DevDiv")] public void CS0438ERR_SameFullNameThisAggThisNs06() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); } } class Util {} } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "DevDiv")] public void CS0436WRN_SameFullNameThisAggAgg_01() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, emitOptions: TestEmitters.CCI, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0436: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, emitOptions: TestEmitters.CCI, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0436: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [Fact()] [WorkItem(568953, "DevDiv")] public void CS0436WRN_SameFullNameThisAggAgg_02() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, emitOptions: TestEmitters.CCI, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,43): warning CS0436: The type 'NS.Util.A' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util.A' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "A").WithArguments("ErrTestMod02.netmodule", "NS.Util.A", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util.A") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, emitOptions: TestEmitters.CCI, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,43): warning CS0436: The type 'NS.Util.A' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util.A' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "A").WithArguments("ErrTestMod02.netmodule", "NS.Util.A", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util.A") ); } [Fact()] [WorkItem(568953, "DevDiv")] public void CS0435WRN_SameFullNameThisNsAgg_01() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, emitOptions: TestEmitters.CCI, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,38): warning CS0435: The namespace 'NS.Util' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("ErrTestMod02.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, emitOptions: TestEmitters.CCI, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,38): warning CS0435: The namespace 'NS.Util' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("ErrTestMod02.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [Fact()] [WorkItem(568953, "DevDiv")] public void CS0437WRN_SameFullNameThisAggNs_01() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, emitOptions: TestEmitters.CCI, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0437: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported namespace 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, emitOptions: TestEmitters.CCI, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0437: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported namespace 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_01() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_02() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { class A {} } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_03() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { class A {} } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), }); comp.VerifyDiagnostics( // (15,15): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_04() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); } } namespace Util { class A<T> {} } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), }); CompileAndVerify(comp, emitOptions: TestEmitters.CCI).VerifyDiagnostics(); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_05() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_06() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_07() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_08() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_09() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_10() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_11() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_12() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_13() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util"), // Test.cs(9,38): warning CS0435: The namespace 'NS.Util' in 'Test.cs' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'Test.cs'. // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("Test.cs", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util"), // Test.cs(9,38): warning CS0435: The namespace 'NS.Util' in 'Test.cs' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'Test.cs'. // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("Test.cs", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_14() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilationWithMscorlib(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_15() { var mod3Source = @" namespace NS { namespace Util { public class A {} } } "; var mod3Ref = CreateCompilationWithMscorlib(mod3Source, options: TestOptions.ReleaseModule, assemblyName: "ErrTestMod03").EmitToImageReference(); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), mod3Ref }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), s_mod1.GetReference(), mod3Ref }); //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), mod3Ref, s_mod1.GetReference() }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); } [Fact()] [WorkItem(530676, "DevDiv")] public void CS0101ERR_DuplicateNameInNS_16() { var mod3Source = @" namespace NS { internal class Util { public class A {} } }"; var mod3Ref = CreateCompilationWithMscorlib(mod3Source, options: TestOptions.ReleaseModule, assemblyName: "ErrTestMod03").EmitToImageReference(); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), mod3Ref }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod01.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod2.GetReference(), s_mod1.GetReference(), mod3Ref }); //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { s_mod1.GetReference(), mod3Ref, s_mod2.GetReference() }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod01.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); } [Fact()] [WorkItem(641639, "DevDiv")] public void Bug641639() { var ModuleA01 = @" class A01 { public static int AT = (new { field = 1 }).field; } "; var ModuleA01Ref = CreateCompilationWithMscorlib(ModuleA01, options: TestOptions.ReleaseModule, assemblyName: "ModuleA01").EmitToImageReference(); var ModuleB01 = @" class B01{ public static int AT = (new { field = 2 }).field; } "; var ModuleB01Ref = CreateCompilationWithMscorlib(ModuleB01, options: TestOptions.ReleaseModule, assemblyName: "ModuleB01").EmitToImageReference(); var text = @" class Test { static void Main() { System.Console.WriteLine(""{0} + {1} = {2}"", A01.AT, A01.AT, B01.AT); A01.AT = B01.AT; System.Console.WriteLine(""{0} = {1}"", A01.AT, B01.AT); } } "; var comp = CreateCompilationWithMscorlib(text, new List<MetadataReference>() { ModuleA01Ref, ModuleB01Ref }, TestOptions.ReleaseExe); Assert.Equal(1, comp.Assembly.Modules[1].GlobalNamespace.GetTypeMembers("<ModuleA01>f__AnonymousType0", 1).Length); Assert.Equal(1, comp.Assembly.Modules[2].GlobalNamespace.GetTypeMembers("<ModuleB01>f__AnonymousType0", 1).Length); CompileAndVerify(comp, expectedOutput: @"1 + 1 = 2 2 = 2", emitOptions: TestEmitters.RefEmitBug); } [Fact] public void NameCollisionWithAddedModule_01() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module ITest20Mod.netmodule // MVID: {53AFCDC2-985A-43AE-928E-89B4A4017344} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00EC0000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ITest20<T> { } // end of class ITest20 "; ImmutableArray<Byte> ilBytes; using (var reference = SharedCompilationUtils.IlasmTempAssembly(ilSource, appendDefaultHeader: false)) { ilBytes = ReadFromFile(reference.Path); } var moduleRef = ModuleMetadata.CreateFromImage(ilBytes).GetReference(); var source = @" interface ITest20 {} "; var compilation = CreateCompilationWithMscorlib(source, new List<MetadataReference>() { moduleRef }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8004: Type 'ITest20<T>' exported from module 'ITest20Mod.netmodule' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration).WithArguments("ITest20<T>", "ITest20Mod.netmodule") ); } [Fact] public void NameCollisionWithAddedModule_02() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module mod_1_1.netmodule // MVID: {98479031-F5D1-443D-AF73-CF21159C1BCF} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00D30000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ns.c1<T> { } .class interface public abstract auto ansi c2<T> { } .class interface public abstract auto ansi ns.C3<T> { } .class interface public abstract auto ansi C4<T> { } .class interface public abstract auto ansi NS1.c5<T> { } "; ImmutableArray<Byte> ilBytes; using (var reference = SharedCompilationUtils.IlasmTempAssembly(ilSource, appendDefaultHeader: false)) { ilBytes = ReadFromFile(reference.Path); } var moduleRef1 = ModuleMetadata.CreateFromImage(ilBytes).GetReference(); var mod2Source = @" namespace ns { public interface c1 {} public interface c3 {} } public interface c2 {} public interface c4 {} namespace ns1 { public interface c5 {} } "; var moduleRef2 = CreateCompilationWithMscorlib(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "mod_1_2").EmitToImageReference(); var compilation = CreateCompilationWithMscorlib("", new List<MetadataReference>() { moduleRef1, moduleRef2 }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8005: Type 'c2' exported from module 'mod_1_2.netmodule' conflicts with type 'c2<T>' exported from module 'mod_1_1.netmodule'. Diagnostic(ErrorCode.ERR_ExportedTypesConflict).WithArguments("c2", "mod_1_2.netmodule", "c2<T>", "mod_1_1.netmodule"), // error CS8005: Type 'ns.c1' exported from module 'mod_1_2.netmodule' conflicts with type 'ns.c1<T>' exported from module 'mod_1_1.netmodule'. Diagnostic(ErrorCode.ERR_ExportedTypesConflict).WithArguments("ns.c1", "mod_1_2.netmodule", "ns.c1<T>", "mod_1_1.netmodule") ); } [Fact] public void NameCollisionWithAddedModule_03() { var forwardedTypesSource = @" public class CF1 {} namespace ns { public class CF2 { } } public class CF3<T> {} "; var forwardedTypes1 = CreateCompilationWithMscorlib(forwardedTypesSource, options: TestOptions.ReleaseDll, assemblyName: "ForwardedTypes1"); var forwardedTypes1Ref = new CSharpCompilationReference(forwardedTypes1); var forwardedTypes2 = CreateCompilationWithMscorlib(forwardedTypesSource, options: TestOptions.ReleaseDll, assemblyName: "ForwardedTypes2"); var forwardedTypes2Ref = new CSharpCompilationReference(forwardedTypes2); var forwardedTypesModRef = CreateCompilationWithMscorlib(forwardedTypesSource, options: TestOptions.ReleaseModule, assemblyName: "forwardedTypesMod"). EmitToImageReference(); var modSource = @" [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF1))] [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(ns.CF2))] "; var module1_FT1_Ref = CreateCompilationWithMscorlib(modSource, options: TestOptions.ReleaseModule, assemblyName: "module1_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var module2_FT1_Ref = CreateCompilationWithMscorlib(modSource, options: TestOptions.ReleaseModule, assemblyName: "module2_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var module3_FT2_Ref = CreateCompilationWithMscorlib(modSource, options: TestOptions.ReleaseModule, assemblyName: "module3_FT2", references: new MetadataReference[] { forwardedTypes2Ref }). EmitToImageReference(); var module4_Ref = CreateCompilationWithMscorlib("[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF3<int>))]", options: TestOptions.ReleaseModule, assemblyName: "module4_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var compilation = CreateCompilationWithMscorlib(forwardedTypesSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8006: Forwarded type 'ns.CF2' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("ns.CF2"), // error CS8006: Forwarded type 'CF1' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("CF1") ); compilation = CreateCompilationWithMscorlib(modSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); // Exported types in .Net modules cause PEVerify to fail. CompileAndVerify(compilation, emitOptions: TestEmitters.RefEmitBug, verify: false).VerifyDiagnostics(); compilation = CreateCompilationWithMscorlib("[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF3<byte>))]", new List<MetadataReference>() { module4_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); CompileAndVerify(compilation, emitOptions: TestEmitters.RefEmitBug, verify: false).VerifyDiagnostics(); compilation = CreateCompilationWithMscorlib(modSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes2Ref, new CSharpCompilationReference(forwardedTypes1, aliases: ImmutableArray.Create("FT1")) }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8007: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // error CS8007: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") ); compilation = CreateCompilationWithMscorlib( @" extern alias FT1; [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(FT1::CF1))] [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(FT1::ns.CF2))] ", new List<MetadataReference>() { forwardedTypesModRef, new CSharpCompilationReference(forwardedTypes1, ImmutableArray.Create("FT1")) }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule"), // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule") ); compilation = CreateCompilationWithMscorlib("", new List<MetadataReference>() { forwardedTypesModRef, module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule"), // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule") ); compilation = CreateCompilationWithMscorlib("", new List<MetadataReference>() { module1_FT1_Ref, forwardedTypesModRef, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule"), // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule") ); compilation = CreateCompilationWithMscorlib("", new List<MetadataReference>() { module1_FT1_Ref, module2_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); CompileAndVerify(compilation, emitOptions: TestEmitters.RefEmitBug, verify: false).VerifyDiagnostics(); compilation = CreateCompilationWithMscorlib("", new List<MetadataReference>() { module1_FT1_Ref, module3_FT2_Ref, forwardedTypes1Ref, forwardedTypes2Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8007: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // error CS8007: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") ); } [Fact] public void CS0441ERR_SealedStaticClass01() { var text = @"namespace NS { static sealed class Test { public static int Main() { return 1; } } sealed static class StaticClass : Test //verify 'sealed' works { } static class Derived : StaticClass //verify 'sealed' works { // Test tst = new Test(); //verify 'static' works } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (3,25): error CS0441: 'NS.Test': a class cannot be both static and sealed Diagnostic(ErrorCode.ERR_SealedStaticClass, "Test").WithArguments("NS.Test"), // (11,25): error CS0441: 'NS.StaticClass': a class cannot be both static and sealed Diagnostic(ErrorCode.ERR_SealedStaticClass, "StaticClass").WithArguments("NS.StaticClass"), //CONSIDER: Dev10 skips these cascading errors // (11,39): error CS0713: Static class 'NS.StaticClass' cannot derive from type 'NS.Test'. Static classes must derive from object. Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "Test").WithArguments("NS.StaticClass", "NS.Test"), // (15,28): error CS0713: Static class 'NS.Derived' cannot derive from type 'NS.StaticClass'. Static classes must derive from object. Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "StaticClass").WithArguments("NS.Derived", "NS.StaticClass")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0442ERR_PrivateAbstractAccessor() { DiagnosticsUtils.TestDiagnosticsExact( @"abstract class MyClass { public abstract int P { get; private set; } // CS0442 protected abstract object Q { private get; set; } // CS0442 internal virtual object R { private get; set; } // no error } ", "'set' error CS0442: 'MyClass.P.set': abstract properties cannot have private accessors", "'get' error CS0442: 'MyClass.Q.get': abstract properties cannot have private accessors"); } [Fact] public void CS0448ERR_BadIncDecRetType() { // Note that the wording of this error message has changed slightly from the native compiler. var text = @"public struct S { public static S? operator ++(S s) { return new S(); } // CS0448 public static S? operator --(S s) { return new S(); } // CS0448 }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,31): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // public static S? operator ++(S s) { return new S(); } // CS0448 Diagnostic(ErrorCode.ERR_BadIncDecRetType, "++"), // (4,31): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // public static S? operator --(S s) { return new S(); } // CS0448 Diagnostic(ErrorCode.ERR_BadIncDecRetType, "--")); } [Fact] public void CS0450ERR_RefValBoundWithClass() { var source = @"interface I { } class A { } class B<T> { } class C<T1, T2, T3, T4, T5, T6, T7> where T1 : class, I where T2 : struct, I where T3 : class, A where T4 : struct, B<T5> where T6 : class, T5 where T7 : struct, T5 { }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (7,23): error CS0450: 'A': cannot specify both a constraint class and the 'class' or 'struct' constraint Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "A").WithArguments("A").WithLocation(7, 23), // (8, 24): error CS0450: 'B<T5>': cannot specify both a constraint class and the 'class' or 'struct' constraint Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "B<T5>").WithArguments("B<T5>").WithLocation(8, 24)); } [Fact] public void CS0452ERR_RefConstraintNotSatisfied() { var source = @"interface I { } class A { } class B<T> where T : class { } class C { static void F<U>() where U : class { } static void M1<T>() { new B<T>(); F<T>(); } static void M2<T>() where T : class { new B<T>(); F<T>(); } static void M3<T>() where T : struct { new B<T>(); F<T>(); } static void M4<T>() where T : new() { new B<T>(); F<T>(); } static void M5<T>() where T : I { new B<T>(); F<T>(); } static void M6<T>() where T : A { new B<T>(); F<T>(); } static void M7<T, U>() where T : U { new B<T>(); F<T>(); } static void M8() { new B<int?>(); F<int?>(); } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (9,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(9, 15), // (10,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>() Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(10, 9), // (19,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(19, 15), // (20,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(20, 9), // (24,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(24, 15), // (25,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(25, 9), // (29,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(29, 15), // (30,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(30, 9), // (39,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(39, 15), // (40,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(40, 9), // (44,15): error CS0452: The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int?").WithArguments("B<T>", "T", "int?").WithLocation(44, 15), // (45,9): error CS0452: The type 'int?' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<int?>").WithArguments("C.F<U>()", "U", "int?").WithLocation(45, 9)); } [Fact] public void CS0453ERR_ValConstraintNotSatisfied01() { var source = @"interface I { } class A { } class B<T> where T : struct { } class C { static void F<U>() where U : struct { } static void M1<T>() { new B<T>(); F<T>(); } static void M2<T>() where T : class { new B<T>(); F<T>(); } static void M3<T>() where T : struct { new B<T>(); F<T>(); } static void M4<T>() where T : new() { new B<T>(); F<T>(); } static void M5<T>() where T : I { new B<T>(); F<T>(); } static void M6<T>() where T : A { new B<T>(); F<T>(); } static void M7<T, U>() where T : U { new B<T>(); F<T>(); } static void M8() { new B<int?>(); F<int?>(); } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (9,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(9, 15), // (10,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(10, 9), // (14,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(14, 15), // (15,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(15, 9), // (24,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(24, 15), // (25,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(25, 9), // (29,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(29, 15), // (30,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(30, 9), // (34,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(34, 15), // (35,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(35, 9), // (39,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(39, 15), // (40,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(40, 9), // (44,15): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "int?").WithArguments("B<T>", "T", "int?").WithLocation(44, 15), // (45,9): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<int?>").WithArguments("C.F<U>()", "U", "int?").WithLocation(45, 9)); } [Fact] public void CS0453ERR_ValConstraintNotSatisfied02() { var source = @"abstract class A<X, Y> { internal static void F<U>() where U : struct { } internal abstract void M<U>() where U : X, Y; } class B1 : A<int?, object> { internal override void M<U>() { F<U>(); } } class B2 : A<object, int?> { internal override void M<U>() { F<U>(); } } class B3 : A<object, int> { internal override void M<U>() { F<U>(); } } class B4<T> : A<object, T> { internal override void M<U>() { F<U>(); } } class B5<T> : A<object, T> where T : struct { internal override void M<U>() { F<U>(); } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (10,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<int?, object>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<int?, object>.F<U>()", "U", "U").WithLocation(10, 9), // (17,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<object, int?>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<object, int?>.F<U>()", "U", "U").WithLocation(17, 9), // (31,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<object, T>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<object, T>.F<U>()", "U", "U").WithLocation(31, 9)); } [Fact] public void CS0454ERR_CircularConstraint01() { var source = @"class A<T> where T : T { } class B<T, U, V> where V : T where U : V where T : U { } delegate void D<T1, T2, T3>() where T1 : T3 where T2 : T2 where T3 : T1;"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (1,9): error CS0454: Circular constraint dependency involving 'T' and 'T' Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(1, 9), // (4,9): error CS0454: Circular constraint dependency involving 'T' and 'V' Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "V").WithLocation(4, 9), // (10,17): error CS0454: Circular constraint dependency involving 'T1' and 'T3' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T3").WithLocation(10, 17), // (10,21): error CS0454: Circular constraint dependency involving 'T2' and 'T2' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T2").WithLocation(10, 21)); } [Fact] public void CS0454ERR_CircularConstraint02() { var source = @"interface I { void M<T, U, V>() where T : V, new() where U : class, V where V : U; } class A<T> { } class B<T, U> where T : U where U : A<U>, U { }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,18): error CS0454: Circular constraint dependency involving 'V' and 'U' Diagnostic(ErrorCode.ERR_CircularConstraint, "V").WithArguments("V", "U").WithLocation(3, 18), // (9,12): error CS0454: Circular constraint dependency involving 'U' and 'U' Diagnostic(ErrorCode.ERR_CircularConstraint, "U").WithArguments("U", "U").WithLocation(9, 12)); } [Fact] public void CS0454ERR_CircularConstraint03() { var source = @"interface I<T1, T2, T3, T4, T5> where T1 : T2, T4 where T2 : T3 where T3 : T1 where T4 : T5 where T5 : T1 { } class C<T1, T2, T3, T4, T5> where T1 : T2, T3 where T2 : T3, T4 where T3 : T4, T5 where T5 : T2, T3 { } struct S<T1, T2, T3, T4, T5> where T4 : T1 where T5 : T2 where T1 : T3 where T2 : T4 where T3 : T5 { } delegate void D<T1, T2, T3, T4>() where T1 : T2 where T2 : T3, T4 where T3 : T4 where T4 : T2;"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (1,13): error CS0454: Circular constraint dependency involving 'T1' and 'T3' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T3").WithLocation(1, 13), // (1,13): error CS0454: Circular constraint dependency involving 'T1' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T5").WithLocation(1, 13), // (9,13): error CS0454: Circular constraint dependency involving 'T2' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T5").WithLocation(9, 13), // (9,17): error CS0454: Circular constraint dependency involving 'T3' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T3").WithArguments("T3", "T5").WithLocation(9, 17), // (16,10): error CS0454: Circular constraint dependency involving 'T1' and 'T4' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T4").WithLocation(16, 10), // (24,21): error CS0454: Circular constraint dependency involving 'T2' and 'T4' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T4").WithLocation(24, 21)); } [Fact] public void CS0454ERR_CircularConstraint04() { var source = @"interface I<T> where U : U { } class C<T, U> where T : U where U : class where U : T { }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (2,11): error CS0699: 'I<T>' does not define type parameter 'U' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "I<T>").WithLocation(2, 11), // (8,11): error CS0409: A constraint clause has already been specified for type parameter 'U'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(8, 11)); } [Fact] public void CS0455ERR_BaseConstraintConflict01() { var source = @"class A<T> { } class B : A<int> { } class C<T, U> where T : B, U where U : A<int> { } class D<T, U> where T : A<T> where U : B, T { }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (8,12): error CS0455: Type parameter 'U' inherits conflicting constraints 'A<T>' and 'B' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "A<T>", "B").WithLocation(8, 12)); } [Fact] public void CS0455ERR_BaseConstraintConflict02() { var source = @"class A<T> { internal virtual void M1<U>() where U : struct, T { } internal virtual void M2<U>() where U : class, T { } } class B1 : A<object> { internal override void M1<U>() { } internal override void M2<U>() { } } class B2 : A<int> { internal override void M1<U>() { } internal override void M2<U>() { } } class B3 : A<string> { internal override void M1<U>() { } internal override void M2<U>() { } } class B4 : A<int?> { internal override void M1<T>() { } internal override void M2<X>() { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (14,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'int' and 'class' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "int", "class").WithLocation(14, 31), // (18,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'string' and 'System.ValueType' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "string", "System.ValueType").WithLocation(18, 31), // (18,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'System.ValueType' and 'struct' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "System.ValueType", "struct").WithLocation(18, 31), // (23,31): error CS0455: Type parameter 'T' inherits conflicting constraints 'int?' and 'struct' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "T").WithArguments("T", "int?", "struct").WithLocation(23, 31), // (24,31): error CS0455: Type parameter 'X' inherits conflicting constraints 'int?' and 'class' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "X").WithArguments("X", "int?", "class").WithLocation(24, 31)); } [Fact] public void CS0456ERR_ConWithValCon() { var source = @"class A<T, U> where T : struct where U : T { } class B<T> where T : struct { void M<U>() where U : T { } struct S<U> where U : T { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (1,12): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(1, 12), // (8,12): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(8, 12), // (9,14): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(9, 14)); } [Fact] public void CS0462ERR_AmbigOverride() { var text = @"class C<T> { public virtual void F(T t) {} public virtual void F(int t) {} } class D : C<int> { public override void F(int t) {} // CS0462 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_MultipleRuntimeOverrideMatches, Line = 3, Column = 24, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigOverride, Line = 9, Column = 25 }); } [Fact] public void CS0466ERR_ExplicitImplParams() { var text = @"interface I { void M1(params int[] a); void M2(int[] a); } class C1 : I { //implicit implementations can add or remove 'params' public virtual void M1(int[] a) { } public virtual void M2(params int[] a) { } } class C2 : I { //explicit implementations can remove but not add 'params' void I.M1(int[] a) { } void I.M2(params int[] a) { } //CS0466 } class C3 : C1 { //overrides can add or remove 'params' public override void M1(params int[] a) { } public override void M2(int[] a) { } } class C4 : C1 { //hiding methods can add or remove 'params' public new void M1(params int[] a) { } public new void M2(int[] a) { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (18,12): error CS0466: 'C2.I.M2(params int[])' should not have a params parameter since 'I.M2(int[])' does not Diagnostic(ErrorCode.ERR_ExplicitImplParams, "M2").WithArguments("C2.I.M2(params int[])", "I.M2(int[])")); } [Fact] public void CS0470ERR_MethodImplementingAccessor() { var text = @"interface I { int P { get; } } class MyClass : I { public int get_P() { return 0; } // CS0470 public int P2 { get { return 0; } } // OK } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 6, Column = 17 }, //Dev10 doesn't include this new ErrorDescription { Code = (int)ErrorCode.ERR_MethodImplementingAccessor, Line = 8, Column = 16 }); } [Fact] public void CS0500ERR_AbstractHasBody01() { var text = @"namespace NS { abstract public class clx { abstract public void M1() { } internal abstract object M2() { return null; } protected abstract internal void M3(sbyte p) { } public abstract object P { get { return null; } set { } } public abstract event System.Action E { add { } remove { } } } // class clx } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractHasBody, Line = 5, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractHasBody, Line = 6, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractHasBody, Line = 7, Column = 42 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractHasBody, Line = 8, Column = 36 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractHasBody, Line = 8, Column = 57 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractHasBody, Line = 9, Column = 49 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractHasBody, Line = 9, Column = 57 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0501ERR_ConcreteMissingBody01() { var text = @" namespace NS { public class clx<T> { public void M1(T t); internal V M2<V>(); protected internal void M3(sbyte p); public static int operator+(clx<T> c); } // class clx } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (7,21): error CS0501: 'NS.clx<T>.M1(T)' must declare a body because it is not marked abstract, extern, or partial // public void M1(T t); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M1").WithArguments("NS.clx<T>.M1(T)"), // (8,20): error CS0501: 'NS.clx<T>.M2<V>()' must declare a body because it is not marked abstract, extern, or partial // internal V M2<V>(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M2").WithArguments("NS.clx<T>.M2<V>()"), // (9,33): error CS0501: 'NS.clx<T>.M3(sbyte)' must declare a body because it is not marked abstract, extern, or partial // protected internal void M3(sbyte p); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M3").WithArguments("NS.clx<T>.M3(sbyte)"), // (10,35): error CS0501: 'NS.clx<T>.operator +(NS.clx<T>)' must declare a body because it is not marked abstract, extern, or partial // public static int operator+(clx<T> c); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("NS.clx<T>.operator +(NS.clx<T>)")); } [Fact] public void CS0501ERR_ConcreteMissingBody02() { var text = @"abstract class C { public int P { get; set { } } public int Q { get { return 0; } set; } public extern object R { get; } // no error protected abstract object S { set; } // no error } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,20): error CS0501: 'C.P.get' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C.P.get"), // (4,38): error CS0501: 'C.Q.set' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C.Q.set"), // (5,30): warning CS0626: Method, operator, or accessor 'C.R.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("C.R.get")); } [Fact] public void CS0501ERR_ConcreteMissingBody03() { var source = @"class C { public C(); internal abstract C(C c); extern public C(object o); // no error }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()"), // (4,23): error CS0106: The modifier 'abstract' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("abstract"), // (5,19): warning CS0824: Constructor 'C.C(object)' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "C").WithArguments("C.C(object)")); } [Fact] public void CS0502ERR_AbstractAndSealed01() { var text = @"namespace NS { abstract public class clx { abstract public void M1(); abstract protected void M2<T>(T t); internal abstract object P { get; } abstract public event System.Action E; } // class clx abstract public class cly : clx { abstract sealed override public void M1(); abstract sealed override protected void M2<T>(T t); internal abstract sealed override object P { get; } public abstract sealed override event System.Action E; } // class cly } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 13, Column = 46 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 14, Column = 49 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 15, Column = 50 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 16, Column = 61 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0503ERR_AbstractNotVirtual01() { var text = @"namespace NS { abstract public class clx { abstract virtual internal void M1(); abstract virtual protected void M2<T>(T t); virtual abstract public object P { get; set; } virtual abstract public event System.Action E; } // class clx } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractNotVirtual, Line = 5, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractNotVirtual, Line = 6, Column = 41 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractNotVirtual, Line = 7, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractNotVirtual, Line = 8, Column = 53 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0504ERR_StaticConstant() { var text = @"namespace x { abstract public class clx { static const int i = 0; // CS0504, cannot be both static and const abstract public void f(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstant, Line = 5, Column = 26 }); } [Fact] public void CS0505ERR_CantOverrideNonFunction() { var text = @"public class clx { public int i; } public class cly : clx { public override int i() { return 0; } // CS0505 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonFunction, Line = 8, Column = 24 }); } [Fact] public void CS0506ERR_CantOverrideNonVirtual() { var text = @"namespace MyNameSpace { abstract public class ClassX { public int f() { return 0; } } public class ClassY : ClassX { public override int f() // CS0506 { return 0; } public static int Main() { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 13, Column = 29 }); } private static string s_typeWithMixedProperty = @" .class public auto ansi beforefieldinit Base_VirtGet_Set extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance int32 get_Prop() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } .method public hidebysig specialname instance void set_Prop(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } .property instance int32 Prop() { .get instance int32 Base_VirtGet_Set::get_Prop() .set instance void Base_VirtGet_Set::set_Prop(int32) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit Base_Get_VirtSet extends [mscorlib]System.Object { .method public hidebysig specialname instance int32 get_Prop() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } .method public hidebysig specialname newslot virtual instance void set_Prop(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } .property instance int32 Prop() { .get instance int32 Base_Get_VirtSet::get_Prop() .set instance void Base_Get_VirtSet::set_Prop(int32) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } } "; [WorkItem(543263, "DevDiv")] [Fact] public void CS0506ERR_CantOverrideNonVirtual_Imported() { var text = @" class Derived1 : Base_Get_VirtSet { public override int Prop { get { return base.Prop; } set { base.Prop = value; } } } class Derived2 : Base_VirtGet_Set { public override int Prop { get { return base.Prop; } set { base.Prop = value; } } } "; var comp = CreateCompilationWithCustomILSource(text, s_typeWithMixedProperty); comp.VerifyDiagnostics( // (4,25): error CS0506: 'Derived2.Prop.set': cannot override inherited member 'Base_VirtGet_Set.Prop.set' because it is not marked virtual, abstract, or override // get { return base.Prop; } Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "get").WithArguments("Derived1.Prop.get", "Base_Get_VirtSet.Prop.get"), // (16,9): error CS0506: 'Derived2.Prop.set': cannot override inherited member 'Base_VirtGet_Set.Prop.set' because it is not marked virtual, abstract, or override // set { base.Prop = value; } Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "set").WithArguments("Derived2.Prop.set", "Base_VirtGet_Set.Prop.set")); } [WorkItem(543263, "DevDiv")] [Fact] public void CS0506ERR_CantOverrideNonVirtual_Imported_NO_ERROR() { var text = @" class Derived1 : Base_Get_VirtSet { public override int Prop { set { base.Prop = value; } } } class Derived2 : Base_VirtGet_Set { public override int Prop { get { return base.Prop; } } } "; var comp = CreateCompilationWithCustomILSource(text, s_typeWithMixedProperty); comp.VerifyDiagnostics(); } [WorkItem(539586, "DevDiv")] [Fact] public void CS0506ERR_CantOverrideNonVirtual02() { var text = @"public class BaseClass { public virtual int Test() { return 1; } } public class BaseClass2 : BaseClass { public static int Test() // Warning CS0114 { return 1; } } public class MyClass : BaseClass2 { public override int Test() // Error CS0506 { return 2; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 11, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 19, Column = 25 }); } [Fact] public void CS0507ERR_CantChangeAccessOnOverride() { var text = @"abstract public class clx { virtual protected void f() { } } public class cly : clx { public override void f() { } // CS0507 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 8, Column = 26 }); } [Fact] public void CS0508ERR_CantChangeReturnTypeOnOverride() { var text = @"abstract public class Clx { public int i = 0; abstract public int F(); } public class Cly : Clx { public override double F() { return 0.0; // CS0508 } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 9, Column = 28 }); } [WorkItem(540325, "DevDiv")] [Fact] public void CS0508ERR_CantChangeReturnTypeOnOverride2() { // When the overriding and overridden methods differ in their generic method // type parameter names, the error message should state what the return type // type should be on the overriding method using its type parameter names, // rather than using the return type of the overridden method. var text = @" class G { internal virtual T GM<T>(T t) { return t; } } class GG : G { internal override void GM<V>(V v) { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,24): error CS0508: 'GG.GM<V>(V)': return type must be 'V' to match overridden member 'G.GM<T>(T)' // internal override void GM<V>(V v) { } Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GM").WithArguments("GG.GM<V>(V)", "G.GM<T>(T)", "V") ); } [Fact] public void CS0509ERR_CantDeriveFromSealedType01() { DiagnosticsUtils.TestDiagnostics( @"namespace NS { public struct stx { } public sealed class clx {} public class cly : clx {} public class clz : stx { } } ", "'cly' error CS0509: 'cly': cannot derive from sealed type 'clx'", "'clz' error CS0509: 'clz': cannot derive from sealed type 'stx'"); } [Fact] public void CS0509ERR_CantDeriveFromSealedType02() { DiagnosticsUtils.TestDiagnostics( @"namespace N1 { enum E { A, B } } namespace N2 { class C : N1.E { } class D : System.Int32 { } class E : int { } } ", "'C' error CS0509: 'C': cannot derive from sealed type 'E'", "'D' error CS0509: 'D': cannot derive from sealed type 'int'", "'E' error CS0509: 'E': cannot derive from sealed type 'int'"); } [Fact] public void CS0513ERR_AbstractInConcreteClass01() { DiagnosticsUtils.TestDiagnostics( @"namespace NS { public class clx { abstract public void M1(); internal abstract object M2(); protected abstract internal void M3(sbyte p); public abstract object P { get; set; } } } ", "'M1' error CS0513: 'clx.M1()' is abstract but it is contained in non-abstract class 'clx'", "'M2' error CS0513: 'clx.M2()' is abstract but it is contained in non-abstract class 'clx'", "'M3' error CS0513: 'clx.M3(sbyte)' is abstract but it is contained in non-abstract class 'clx'", "'get' error CS0513: 'clx.P.get' is abstract but it is contained in non-abstract class 'clx'", "'set' error CS0513: 'clx.P.set' is abstract but it is contained in non-abstract class 'clx'"); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" class C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,41): error CS0513: 'C.E' is abstract but it is contained in non-abstract class 'C' // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("C.E", "C"), // (5,39): error CS0513: 'C.this[int].get' is abstract but it is contained in non-abstract class 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.this[int].get", "C"), // (5,44): error CS0513: 'C.this[int].set' is abstract but it is contained in non-abstract class 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.this[int].set", "C")); } [Fact] public void CS0515ERR_StaticConstructorWithAccessModifiers01() { var text = @"namespace NS { static public class clx { private static clx() { } class C<T, V> { internal static C() { } } } public class clz { public static clz() { } struct S { internal static S() { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 5, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 9, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 15, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 19, Column = 29 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Some - /nostdlib - no mscorlib /// </summary> [Fact] public void CS0518ERR_PredefinedTypeNotFound01() { var text = @"namespace NS { class Test { static int Main() { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,11): error CS0518: Predefined type 'System.Object' is not defined or imported // class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Object"), // (5,16): error CS0518: Predefined type 'System.Int32' is not defined or imported // static int Main() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32"), // (7,20): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1").WithArguments("System.Int32"), // (3,11): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class Test Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("object", "0")); } //[Fact(Skip = "Bad test case")] //public void CS0520ERR_PredefinedTypeBadType() //{ // var text = @""; // var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription { Code = (int)ErrorCode.ERR_PredefinedTypeBadType, Line = 5, Column = 26 } // ); //} [Fact] public void CS0523ERR_StructLayoutCycle01() { var text = @"struct A { A F; // CS0523 } struct B { C F; // CS0523 C G; // no additional error } struct C { B G; // CS0523 } struct D<T> { D<D<object>> F; // CS0523 } struct E { F<E> F; // no error } class F<T> { E G; // no error } struct G { H<G> F; // CS0523 } struct H<T> { G G; // CS0523 } struct J { static J F; // no error } struct K { static L F; // no error } struct L { static K G; // no error } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (7,7): error CS0523: Struct member 'B.F' of type 'C' causes a cycle in the struct layout // C F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("B.F", "C").WithLocation(7, 7), // (12,7): error CS0523: Struct member 'C.G' of type 'B' causes a cycle in the struct layout // B G; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "G").WithArguments("C.G", "B").WithLocation(12, 7), // (16,18): error CS0523: Struct member 'D<T>.F' of type 'D<D<object>>' causes a cycle in the struct layout // D<D<object>> F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("D<T>.F", "D<D<object>>").WithLocation(16, 18), // (32,7): error CS0523: Struct member 'H<T>.G' of type 'G' causes a cycle in the struct layout // G G; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "G").WithArguments("H<T>.G", "G").WithLocation(32, 7), // (28,10): error CS0523: Struct member 'G.F' of type 'H<G>' causes a cycle in the struct layout // H<G> F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("G.F", "H<G>").WithLocation(28, 10), // (3,7): error CS0523: Struct member 'A.F' of type 'A' causes a cycle in the struct layout // A F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("A.F", "A").WithLocation(3, 7), // (16,18): warning CS0169: The field 'D<T>.F' is never used // D<D<object>> F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("D<T>.F").WithLocation(16, 18), // (32,7): warning CS0169: The field 'H<T>.G' is never used // G G; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("H<T>.G").WithLocation(32, 7), // (12,7): warning CS0169: The field 'C.G' is never used // B G; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("C.G").WithLocation(12, 7), // (40,14): warning CS0169: The field 'K.F' is never used // static L F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("K.F").WithLocation(40, 14), // (28,10): warning CS0169: The field 'G.F' is never used // H<G> F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("G.F").WithLocation(28, 10), // (8,7): warning CS0169: The field 'B.G' is never used // C G; // no additional error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("B.G").WithLocation(8, 7), // (36,14): warning CS0169: The field 'J.F' is never used // static J F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("J.F").WithLocation(36, 14), // (3,7): warning CS0169: The field 'A.F' is never used // A F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("A.F").WithLocation(3, 7), // (20,10): warning CS0169: The field 'E.F' is never used // F<E> F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("E.F").WithLocation(20, 10), // (44,14): warning CS0169: The field 'L.G' is never used // static K G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("L.G").WithLocation(44, 14), // (7,7): warning CS0169: The field 'B.F' is never used // C F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("B.F").WithLocation(7, 7), // (24,7): warning CS0169: The field 'F<T>.G' is never used // E G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("F<T>.G").WithLocation(24, 7) ); } [Fact] public void CS0523ERR_StructLayoutCycle02() { var text = @"struct A { A P { get; set; } // CS0523 A Q { get; set; } // no additional error } struct B { C P { get; set; } // CS0523 (no error in Dev10!) } struct C { B Q { get; set; } // CS0523 (no error in Dev10!) } struct D<T> { D<D<object>> P { get; set; } // CS0523 } struct E { F<E> P { get; set; } // no error } class F<T> { E Q { get; set; } // no error } struct G { H<G> P { get; set; } // CS0523 G Q; // no additional error } struct H<T> { G Q; // CS0523 } struct J { static J P { get; set; } // no error } struct K { static L P { get; set; } // no error } struct L { static K Q { get; set; } // no error } struct M { N P { get; set; } // no error } struct N { M Q // no error { get { return new M(); } set { } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,7): error CS0523: Struct member 'A.P' of type 'A' causes a cycle in the struct layout // A P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("A.P", "A"), // (8,7): error CS0523: Struct member 'B.P' of type 'C' causes a cycle in the struct layout // C P { get; set; } // CS0523 (no error in Dev10!) Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("B.P", "C"), // (12,7): error CS0523: Struct member 'C.Q' of type 'B' causes a cycle in the struct layout // B Q { get; set; } // CS0523 (no error in Dev10!) Diagnostic(ErrorCode.ERR_StructLayoutCycle, "Q").WithArguments("C.Q", "B"), // (16,18): error CS0523: Struct member 'D<T>.P' of type 'D<D<object>>' causes a cycle in the struct layout // D<D<object>> P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("D<T>.P", "D<D<object>>"), // (28,10): error CS0523: Struct member 'G.P' of type 'H<G>' causes a cycle in the struct layout // H<G> P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("G.P", "H<G>"), // (33,7): error CS0523: Struct member 'H<T>.Q' of type 'G' causes a cycle in the struct layout // G Q; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "Q").WithArguments("H<T>.Q", "G"), // (29,7): warning CS0169: The field 'G.Q' is never used // G Q; // no additional error Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("G.Q"), // (33,7): warning CS0169: The field 'H<T>.Q' is never used // G Q; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("H<T>.Q") ); } [WorkItem(540215, "DevDiv")] [Fact] public void CS0523ERR_StructLayoutCycle03() { // Static fields should not be considered when // determining struct cycles. (Note: Dev10 does // report these cases as errors though.) var text = @"struct A { B F; // no error } struct B { static A G; // no error } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,7): warning CS0169: The field 'A.F' is never used // B F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("A.F").WithLocation(3, 7), // (7,14): warning CS0169: The field 'B.G' is never used // static A G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("B.G").WithLocation(7, 14) ); } [WorkItem(541629, "DevDiv")] [Fact] public void CS0523ERR_StructLayoutCycle04() { var text = @"struct E { } struct X<T> { public T t; } struct Y { public X<Z> xz; } struct Z { public X<E> xe; public X<Y> xy; } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (9,17): error CS0523: Struct member 'Y.xz' of type 'X<Z>' causes a cycle in the struct layout // public X<Z> xz; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "xz").WithArguments("Y.xz", "X<Z>").WithLocation(9, 17), // (14,17): error CS0523: Struct member 'Z.xy' of type 'X<Y>' causes a cycle in the struct layout // public X<Y> xy; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "xy").WithArguments("Z.xy", "X<Y>").WithLocation(14, 17), // (9,17): warning CS0649: Field 'Y.xz' is never assigned to, and will always have its default value // public X<Z> xz; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xz").WithArguments("Y.xz", "").WithLocation(9, 17), // (14,17): warning CS0649: Field 'Z.xy' is never assigned to, and will always have its default value // public X<Y> xy; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xy").WithArguments("Z.xy", "").WithLocation(14, 17), // (5,14): warning CS0649: Field 'X<T>.t' is never assigned to, and will always have its default value // public T t; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "t").WithArguments("X<T>.t", "").WithLocation(5, 14), // (13,17): warning CS0649: Field 'Z.xe' is never assigned to, and will always have its default value // public X<E> xe; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xe").WithArguments("Z.xe", "").WithLocation(13, 17) ); } [WorkItem(541629, "DevDiv")] [Fact] public void CS0523ERR_StructLayoutCycle05() { var text = @"struct X<T> { public T t; } struct W<T> { X<W<W<T>>> x; }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,16): error CS0523: Struct member 'W<T>.x' of type 'X<W<W<T>>>' causes a cycle in the struct layout // X<W<W<T>>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("W<T>.x", "X<W<W<T>>>"), // (3,14): warning CS0649: Field 'X<T>.t' is never assigned to, and will always have its default value // public T t; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "t").WithArguments("X<T>.t", ""), // (8,16): warning CS0169: The field 'W<T>.x' is never used // X<W<W<T>>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("W<T>.x") ); } [Fact] public void CS0523ERR_StructLayoutCycle06() { var text = @"struct S1<T, U> { S1<object, object> F; } struct S2<T, U> { S2<U, T> F; } struct S3<T> { T F; } struct S4<T> { S3<S3<T>> F; }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,24): error CS0523: Struct member 'S1<T, U>.F' of type 'S1<object, object>' causes a cycle in the struct layout // S1<object, object> F; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("S1<T, U>.F", "S1<object, object>").WithLocation(3, 24), // (7,14): error CS0523: Struct member 'S2<T, U>.F' of type 'S2<U, T>' causes a cycle in the struct layout // S2<U, T> F; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("S2<T, U>.F", "S2<U, T>").WithLocation(7, 14), // (7,14): warning CS0169: The field 'S2<T, U>.F' is never used // S2<U, T> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S2<T, U>.F").WithLocation(7, 14), // (11,7): warning CS0169: The field 'S3<T>.F' is never used // T F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S3<T>.F").WithLocation(11, 7), // (15,15): warning CS0169: The field 'S4<T>.F' is never used // S3<S3<T>> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S4<T>.F").WithLocation(15, 15), // (3,24): warning CS0169: The field 'S1<T, U>.F' is never used // S1<object, object> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S1<T, U>.F").WithLocation(3, 24) ); } [WorkItem(872954)] [Fact] public void CS0523ERR_StructLayoutCycle07() { var text = @"struct S0<T> { static S0<T> x; } struct S1<T> { class C { } static S1<C> x; } struct S2<T> { struct S { } static S2<S> x; } struct S3<T> { interface I { } static S3<I> x; } struct S4<T> { delegate void D(); static S4<D> x; } struct S5<T> { enum E { } static S5<E> x; } struct S6<T> { static S6<T[]> x; }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,18): error CS0523: Struct member 'S1<T>.x' of type 'S1<S1<T>.C>' causes a cycle in the struct layout // static S1<C> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S1<T>.x", "S1<S1<T>.C>").WithLocation(8, 18), // (13,18): error CS0523: Struct member 'S2<T>.x' of type 'S2<S2<T>.S>' causes a cycle in the struct layout // static S2<S> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S2<T>.x", "S2<S2<T>.S>").WithLocation(13, 18), // (18,18): error CS0523: Struct member 'S3<T>.x' of type 'S3<S3<T>.I>' causes a cycle in the struct layout // static S3<I> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S3<T>.x", "S3<S3<T>.I>").WithLocation(18, 18), // (23,18): error CS0523: Struct member 'S4<T>.x' of type 'S4<S4<T>.D>' causes a cycle in the struct layout // static S4<D> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S4<T>.x", "S4<S4<T>.D>").WithLocation(23, 18), // (28,18): error CS0523: Struct member 'S5<T>.x' of type 'S5<S5<T>.E>' causes a cycle in the struct layout // static S5<E> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S5<T>.x", "S5<S5<T>.E>").WithLocation(28, 18), // (32,20): error CS0523: Struct member 'S6<T>.x' of type 'S6<T[]>' causes a cycle in the struct layout // static S6<T[]> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S6<T>.x", "S6<T[]>").WithLocation(32, 20), // (8,18): warning CS0169: The field 'S1<T>.x' is never used // static S1<C> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.x").WithLocation(8, 18), // (23,18): warning CS0169: The field 'S4<T>.x' is never used // static S4<D> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S4<T>.x").WithLocation(23, 18), // (18,18): warning CS0169: The field 'S3<T>.x' is never used // static S3<I> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S3<T>.x").WithLocation(18, 18), // (3,18): warning CS0169: The field 'S0<T>.x' is never used // static S0<T> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S0<T>.x").WithLocation(3, 18), // (13,18): warning CS0169: The field 'S2<T>.x' is never used // static S2<S> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S2<T>.x").WithLocation(13, 18), // (28,18): warning CS0169: The field 'S5<T>.x' is never used // static S5<E> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S5<T>.x").WithLocation(28, 18), // (32,20): warning CS0169: The field 'S6<T>.x' is never used // static S6<T[]> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S6<T>.x").WithLocation(32, 20)); } [Fact] public void CS0524ERR_InterfacesCannotContainTypes01() { var text = @"namespace NS { public interface IFoo { interface IBar { } public class cly {} struct S { } private enum E { zero, one } // internal delegate void MyDel(object p); // delegates not in scope yet } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCannotContainTypes, Line = 5, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCannotContainTypes, Line = 6, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCannotContainTypes, Line = 7, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCannotContainTypes, Line = 8, Column = 22 } // new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCannotContainTypes, // Line = 9, Column = 32 } ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0525ERR_InterfacesCantContainFields01() { var text = @"namespace NS { public interface IFoo { string field1; const ulong field2 = 0; public IFoo field3; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCantContainFields, Line = 5, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCantContainFields, Line = 6, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCantContainFields, Line = 7, Column = 21 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0526ERR_InterfacesCantContainConstructors01() { var text = @"namespace NS { public interface IFoo { public IFoo() {} internal IFoo(object p1, ref long p2) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCantContainConstructors, Line = 5, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCantContainConstructors, Line = 6, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0527ERR_NonInterfaceInInterfaceList01() { var text = @"namespace NS { class C { } public struct S : object, C { interface IFoo : C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 5, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 5, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 7, Column = 26 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0528ERR_DuplicateInterfaceInBaseList01() { var text = @"namespace NS { public interface IFoo {} public interface IBar { } public class C : IFoo, IFoo { } struct S : IBar, IFoo, IBar { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 5, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 8, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Extra errors - expected /// </summary> [Fact] public void CS0529ERR_CycleInInterfaceInheritance01() { var text = @"namespace NS { class AA : BB { } class BB : CC { } class CC : I3 { } interface I1 : I2 { } interface I2 : I3 { } interface I3 : I1 { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 7, Column = 15 }, // Extra new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 8, Column = 15 }, // Extra new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 9, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0531ERR_InterfaceMemberHasBody01() { var text = @"namespace NS { public interface IFoo { int M1() { return 0; } // CS0531 void M2<T>(T t) { } object P { get { return null; } } } interface IBar<T, V> { V M1(T t) { return default(V); } void M2(ref T t, out V v) { v = default(V); } T P { get { return default(T) } set { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 14, Column = 39 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceMemberHasBody, Line = 5, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceMemberHasBody, Line = 6, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceMemberHasBody, Line = 7, Column = 20 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceMemberHasBody, Line = 12, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceMemberHasBody, Line = 13, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceMemberHasBody, Line = 14, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceMemberHasBody, Line = 14, Column = 41 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void AbstractConstructor() { var text = @"namespace NS { public class C { abstract C(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 5, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void StaticFixed() { var text = @"unsafe struct S { public static fixed int x[10]; }"; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,29): error CS0106: The modifier 'static' is not valid for this item // public static fixed int x[10]; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("static")); } [WorkItem(895401, "DevDiv")] [Fact] public void VolatileFixed() { var text = @"unsafe struct S { public volatile fixed int x[10]; }"; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,29): error CS0106: The modifier 'volatile' is not valid for this item // public static fixed int x[10]; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("volatile")); } [WorkItem(895401, "DevDiv")] [Fact] public void ReadonlyConst() { var text = @" class C { private readonly int F1 = 123; private const int F2 = 123; private readonly const int F3 = 123; }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,32): error CS0106: The modifier 'readonly' is not valid for this item // private readonly const int F3 = 123; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F3").WithArguments("readonly"), // (4,26): warning CS0414: The field 'C.F1' is assigned but its value is never used // private readonly int F1 = 123; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F1").WithArguments("C.F1")); } [Fact] public void CS0533ERR_HidingAbstractMethod() { var text = @"namespace x { abstract public class a { abstract public void f(); abstract public void g(); } abstract public class b : a { new abstract public void f(); // CS0533 new abstract internal void g(); //fine since internal public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 11, Column = 34 }); } [WorkItem(539629, "DevDiv")] [Fact] public void CS0533ERR_HidingAbstractMethod02() { var text = @" abstract public class B1 { public abstract float foo { set; } } abstract class A1 : B1 { new protected enum foo { } // CS0533 abstract public class B2 { protected abstract void foo(); } abstract class A2 : B2 { new public delegate object foo(); // CS0533 } } namespace NS { abstract public class B3 { public abstract void foo(); } abstract class A3 : B3 { new protected double[] foo; // CS0533 } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (31,32): error CS0533: 'NS.A3.foo' hides inherited abstract member 'NS.B3.foo()' // new protected double[] foo; // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "foo").WithArguments("NS.A3.foo", "NS.B3.foo()"), // (9,24): error CS0533: 'A1.foo' hides inherited abstract member 'B1.foo' // new protected enum foo { } // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "foo").WithArguments("A1.foo", "B1.foo"), // (18,36): error CS0533: 'A1.A2.foo' hides inherited abstract member 'A1.B2.foo()' // new public delegate object foo(); // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "foo").WithArguments("A1.A2.foo", "A1.B2.foo()") ); } [WorkItem(540464, "DevDiv")] [Fact] public void CS0533ERR_HidingAbstractMethod03() { var text = @" public abstract class A { public abstract void f(); public abstract void g(); public abstract void h(); } public abstract class B : A { public override void g() { } } public abstract class C : B { public void h(int a) { } } public abstract class D: C { public new int f; // expected CS0533: 'C.f' hides inherited abstract member 'A.f()' public new int g; // no error public new int h; // no CS0533 here in Dev10, but I'm not sure why not. (VB gives error for this case) } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (18,16): error CS0533: 'D.f' hides inherited abstract member 'A.f()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "f").WithArguments("D.f", "A.f()")); } [WorkItem(539629, "DevDiv")] [Fact] public void CS0533ERR_HidingAbstractMethod_Combinations() { var text = @" abstract class Base { public abstract void M(); public abstract int P { get; set; } public abstract class C { } } abstract class Derived1 : Base { public new abstract void M(); public new abstract void P(); public new abstract void C(); } abstract class Derived2 : Base { public new abstract int M { get; set; } public new abstract int P { get; set; } public new abstract int C { get; set; } } abstract class Derived3 : Base { public new abstract class M { } public new abstract class P { } public new abstract class C { } } abstract class Derived4 : Base { public new void M() { } public new void P() { } public new void C() { } } abstract class Derived5 : Base { public new int M { get; set; } public new int P { get; set; } public new int C { get; set; } } abstract class Derived6 : Base { public new class M { } public new class P { } public new class C { } } abstract class Derived7 : Base { public new static void M() { } public new static int P { get; set; } public new static class C { } } abstract class Derived8 : Base { public new static int M = 1; public new static class P { }; public new const int C = 2; }"; // CONSIDER: dev10 reports each hidden accessor separately, but that seems silly CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (11,30): error CS0533: 'Derived1.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived1.M()", "Base.M()"), // (12,30): error CS0533: 'Derived1.P()' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived1.P()", "Base.P"), // (18,29): error CS0533: 'Derived2.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived2.M", "Base.M()"), // (19,29): error CS0533: 'Derived2.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived2.P", "Base.P"), // (25,31): error CS0533: 'Derived3.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived3.M", "Base.M()"), // (26,31): error CS0533: 'Derived3.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived3.P", "Base.P"), // (32,21): error CS0533: 'Derived4.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived4.M()", "Base.M()"), // (33,21): error CS0533: 'Derived4.P()' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived4.P()", "Base.P"), // (39,20): error CS0533: 'Derived5.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived5.M", "Base.M()"), // (40,20): error CS0533: 'Derived5.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived5.P", "Base.P"), // (46,22): error CS0533: 'Derived6.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived6.M", "Base.M()"), // (47,22): error CS0533: 'Derived6.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived6.P", "Base.P"), // (53,28): error CS0533: 'Derived7.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived7.M()", "Base.M()"), // (54,27): error CS0533: 'Derived7.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived7.P", "Base.P"), // (60,27): error CS0533: 'Derived8.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived8.M", "Base.M()"), // (61,20): error CS0533: 'Derived8.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived8.P", "Base.P")); } [WorkItem(539585, "DevDiv")] [Fact] public void CS0534ERR_UnimplementedAbstractMethod() { var text = @" abstract class A<T> { public abstract void M(T t); } abstract class B<T> : A<T> { public abstract void M(string s); } class C : B<string> // CS0534 { public override void M(string s) { } static void Main() { } } public abstract class Base<T> { public abstract void M(T t); public abstract void M(int i); } public class Derived : Base<int> // CS0534 { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 13, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 26, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 26, Column = 14 }); } [Fact] public void CS0535ERR_UnimplementedInterfaceMember() { var text = @"public interface A { void F(); } public class B : A { } // CS0535 A::F is not implemented "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 6, Column = 18 }); } [Fact] public void CS0537ERR_ObjectCantHaveBases() { var text = @"namespace System { public class Object : ICloneable { } }"; //compile without corlib, since otherwise this System.Object won't count as a special type CreateCompilation(text).VerifyDiagnostics( // (3,20): error CS0246: The type or namespace name 'ICloneable' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ICloneable").WithArguments("ICloneable"), // (3,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } //this should be the same as CS0537ERR_ObjectCantHaveBases, except without the second //error (about ICloneable not being defined) [Fact] public void CS0537ERR_ObjectCantHaveBases_OtherType() { var text = @"namespace System { public interface ICloneable { } public class Object : ICloneable { } }"; //compile without corlib, since otherwise this System.Object won't count as a special type CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } [WorkItem(538320, "DevDiv")] [Fact] public void CS0537ERR_ObjectCantHaveBases_WithMsCorlib() { var text = @"namespace System { public interface ICloneable { } public class Object : ICloneable { } }"; // When System.Object is defined in both source and metadata, dev10 favors // the source version and reports ERR_ObjectCantHaveBases. CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } [Fact] public void CS0538ERR_ExplicitInterfaceImplementationNotInterface() { var text = @"interface MyIFace { } public class MyClass { } class C : MyIFace { void MyClass.G() // CS0538, MyClass not an interface { } int MyClass.P { get { return 1; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, Line = 11, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, Line = 14, Column = 9 }); } [Fact] public void CS0539ERR_InterfaceMemberNotFound() { var text = @"namespace x { interface I { void m(); } public class clx : I { void I.x() // CS0539 { } void I.m() { } public static int Main() { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceMemberNotFound, Line = 10, Column = 14 }); } [Fact] public void CS0540ERR_ClassDoesntImplementInterface() { var text = @"interface I { void m(); } public class Clx { void I.m() { } // CS0540 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ClassDoesntImplementInterface, Line = 8, Column = 10 }); } [Fact] public void CS0541ERR_ExplicitInterfaceImplementationInNonClassOrStruct() { var text = @"namespace x { interface IFace { void F(); int P { set; } } interface IFace2 : IFace { void IFace.F(); // CS0541 int IFace.P { set; } //CS0541 } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (12,19): error CS0541: 'x.IFace2.P': explicit interface declaration can only be declared in a class or struct // int IFace.P { set; } //CS0541 Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationInNonClassOrStruct, "P").WithArguments("x.IFace2.P"), // (11,20): error CS0541: 'x.IFace2.F()': explicit interface declaration can only be declared in a class or struct // void IFace.F(); // CS0541 Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationInNonClassOrStruct, "F").WithArguments("x.IFace2.F()") ); } [Fact] public void CS0542ERR_MemberNameSameAsType01() { var comp = CreateCompilationWithMscorlib( @"namespace NS { class NS { } // no error interface IM { void IM(); } // no error interface IP { object IP { get; } } // no error enum A { A } // no error class B { enum B { } } class C { static void C() { } } class D { object D { get; set; } } class E { int D, E, F; } class F { class F { } } class G { struct G { } } class H { delegate void H(); } class L { class L<T> { } } class K<T> { class K { } } class M<T> { interface M<U> { } } class N { struct N<T, U> { } } struct O { enum O { } } struct P { void P() { } } struct Q { static object Q { get; set; } } struct R { object Q, R; } struct S { class S { } } struct T { interface T { } } struct U { struct U { } } struct V { delegate void V(); } struct W { class W<T> { } } struct X<T> { class X { } } struct Y<T> { interface Y<U> { } } struct Z { struct Z<T, U> { } } } "); comp.VerifyDiagnostics( // (7,20): error CS0542: 'B': member names cannot be the same as their enclosing type // class B { enum B { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "B").WithArguments("B"), // (8,27): error CS0542: 'C': member names cannot be the same as their enclosing type // class C { static void C() { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C"), // (9,22): error CS0542: 'D': member names cannot be the same as their enclosing type // class D { object D { get; set; } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "D").WithArguments("D"), // (10,22): error CS0542: 'E': member names cannot be the same as their enclosing type // class E { int D, E, F; } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("E"), // (11,21): error CS0542: 'F': member names cannot be the same as their enclosing type // class F { class F { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "F").WithArguments("F"), // (12,22): error CS0542: 'G': member names cannot be the same as their enclosing type // class G { struct G { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "G").WithArguments("G"), // (13,29): error CS0542: 'H': member names cannot be the same as their enclosing type // class H { delegate void H(); } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "H").WithArguments("H"), // (14,21): error CS0542: 'L': member names cannot be the same as their enclosing type // class L { class L<T> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "L").WithArguments("L"), // (15,24): error CS0542: 'K': member names cannot be the same as their enclosing type // class K<T> { class K { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "K").WithArguments("K"), // (16,28): error CS0542: 'M': member names cannot be the same as their enclosing type // class M<T> { interface M<U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "M").WithArguments("M"), // (17,22): error CS0542: 'N': member names cannot be the same as their enclosing type // class N { struct N<T, U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "N").WithArguments("N"), // (18,21): error CS0542: 'O': member names cannot be the same as their enclosing type // struct O { enum O { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "O").WithArguments("O"), // (19,21): error CS0542: 'P': member names cannot be the same as their enclosing type // struct P { void P() { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "P").WithArguments("P"), // (20,30): error CS0542: 'Q': member names cannot be the same as their enclosing type // struct Q { static object Q { get; set; } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Q").WithArguments("Q"), // (21,26): error CS0542: 'R': member names cannot be the same as their enclosing type // struct R { object Q, R; } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "R").WithArguments("R"), // (22,22): error CS0542: 'S': member names cannot be the same as their enclosing type // struct S { class S { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "S").WithArguments("S"), // (23,26): error CS0542: 'T': member names cannot be the same as their enclosing type // struct T { interface T { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "T").WithArguments("T"), // (24,23): error CS0542: 'U': member names cannot be the same as their enclosing type // struct U { struct U { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "U").WithArguments("U"), // (25,30): error CS0542: 'V': member names cannot be the same as their enclosing type // struct V { delegate void V(); } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "V").WithArguments("V"), // (26,22): error CS0542: 'W': member names cannot be the same as their enclosing type // struct W { class W<T> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "W").WithArguments("W"), // (27,25): error CS0542: 'X': member names cannot be the same as their enclosing type // struct X<T> { class X { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "X").WithArguments("X"), // (28,29): error CS0542: 'Y': member names cannot be the same as their enclosing type // struct Y<T> { interface Y<U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Y").WithArguments("Y"), // (29,23): error CS0542: 'Z': member names cannot be the same as their enclosing type // struct Z { struct Z<T, U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Z").WithArguments("Z"), // (10,19): warning CS0169: The field 'NS.E.D' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "D").WithArguments("NS.E.D"), // (10,22): warning CS0169: The field 'NS.E.E' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "E").WithArguments("NS.E.E"), // (10,25): warning CS0169: The field 'NS.E.F' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("NS.E.F"), // (21,23): warning CS0169: The field 'NS.R.Q' is never used // struct R { object Q, R; } Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("NS.R.Q"), // (21,26): warning CS0169: The field 'NS.R.R' is never used // struct R { object Q, R; } Diagnostic(ErrorCode.WRN_UnreferencedField, "R").WithArguments("NS.R.R")); } [Fact] public void CS0542ERR_MemberNameSameAsType02() { // No errors for names from explicit implementations. DiagnosticsUtils.TestDiagnostics( @"interface IM { void C(); } interface IP { object C { get; } } class C : IM, IP { void IM.C() { } object IP.C { get { return null; } } } "); } [Fact(), WorkItem(529156, "DevDiv")] public void CS0542ERR_MemberNameSameAsType03() { CreateCompilationWithMscorlib( @"class Item { public int this[int i] // CS0542 { get { return 0; } } } ").VerifyDiagnostics(); } [WorkItem(538633, "DevDiv")] [Fact] public void CS0542ERR_MemberNameSameAsType04() { var source = @"class get_P { object P { get; set; } // CS0542 } class set_P { object P { set { } } // CS0542 } interface get_Q { object Q { get; } } class C : get_Q { public object Q { get; set; } } interface IR { object R { get; set; } } class get_R : IR { public object R { get; set; } // CS0542 } class set_R : IR { object IR.R { get; set; } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,16): error CS0542: 'get_P': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_P").WithLocation(3, 16), // (7,16): error CS0542: 'set_P': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("set_P").WithLocation(7, 16), // (23,23): error CS0542: 'get_R': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_R").WithLocation(23, 23)); } [Fact] public void CS0542ERR_MemberNameSameAsType05() { var source = @"namespace N1 { class get_Item { object this[object o] { get { return null; } set { } } // CS0542 } class set_Item { object this[object o] { get { return null; } set { } } // CS0542 } } namespace N2 { interface I { object this[object o] { get; set; } } class get_Item : I { public object this[object o] { get { return null; } set { } } // CS0542 } class set_Item : I { object I.this[object o] { get { return null; } set { } } } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (5,33): error CS0542: 'get_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_Item").WithLocation(5, 33), // (9,54): error CS0542: 'set_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("set_Item").WithLocation(9, 54), // (20,40): error CS0542: 'get_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_Item").WithLocation(20, 40)); } /// <summary> /// Derived class with same name as base class /// property accessor metadata name. /// </summary> [Fact] public void CS0542ERR_MemberNameSameAsType06() { var source1 = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object B1() { } .method public abstract virtual instance void B2(object v) { } .property instance object P() { .get instance object A::B1() .set instance void A::B2(object v) } }"; var reference1 = CompileIL(source1); var source2 = @"class B0 : A { public override object P { get { return null; } set { } } } class B1 : A { public override object P { get { return null; } set { } } } class B2 : A { public override object P { get { return null; } set { } } } class get_P : A { public override object P { get { return null; } set { } } } class set_P : A { public override object P { get { return null; } set { } } }"; var compilation2 = CreateCompilationWithMscorlib(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (7,32): error CS0542: 'B1': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("B1").WithLocation(7, 32), // (11,53): error CS0542: 'B2': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("B2").WithLocation(11, 53)); } /// <summary> /// Derived class with same name as base class /// event accessor metadata name. /// </summary> [WorkItem(530385, "DevDiv")] [Fact] public void CS0542ERR_MemberNameSameAsType07() { var source1 = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance void B1(class [mscorlib]System.Action v) { } .method public abstract virtual instance void B2(class [mscorlib]System.Action v) { } .event [mscorlib]System.Action E { .addon instance void A::B1(class [mscorlib]System.Action); .removeon instance void A::B2(class [mscorlib]System.Action); } }"; var reference1 = CompileIL(source1); var source2 = @"using System; class B0 : A { public override event Action E; } class B1 : A { public override event Action E; } class B2 : A { public override event Action E; } class add_E : A { public override event Action E; } class remove_E : A { public override event Action E; }"; var compilation2 = CreateCompilationWithMscorlib(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,34): error CS0542: 'B1': member names cannot be the same as their enclosing type // public override event Action E; Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("B1").WithLocation(8, 34), // (12,34): error CS0542: 'B2': member names cannot be the same as their enclosing type // public override event Action E; Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("B2").WithLocation(12, 34), // (16,34): warning CS0067: The event 'add_E.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("add_E.E").WithLocation(16, 34), // (12,34): warning CS0067: The event 'B2.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B2.E").WithLocation(12, 34), // (8,34): warning CS0067: The event 'B1.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B1.E").WithLocation(8, 34), // (20,34): warning CS0067: The event 'remove_E.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("remove_E.E").WithLocation(20, 34), // (4,34): warning CS0067: The event 'B0.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B0.E").WithLocation(4, 34)); } [Fact] public void CS0544ERR_CantOverrideNonProperty() { var text = @"public class a { public int i; } public class b : a { public override int i// CS0544 { get { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonProperty, Line = 8, Column = 25 }); } [Fact] public void CS0545ERR_NoGetToOverride() { var text = @"public class a { public virtual int i { set { } } } public class b : a { public override int i { get { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoGetToOverride, Line = 13, Column = 9 }); } [WorkItem(539321, "DevDiv")] [Fact] public void CS0545ERR_NoGetToOverride_Regress() { var text = @"public class A { public virtual int P1 { private get; set; } public virtual int P2 { private get; set; } } public class C : A { public override int P1 { set { } } //fine public sealed override int P2 { set { } } //CS0546 since we can't see A.P2.set to override it as sealed } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (10,32): error CS0545: 'C.P2': cannot override because 'A.P2' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "P2").WithArguments("C.P2", "A.P2")); var classA = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var classAProp1 = classA.GetMember<PropertySymbol>("P1"); Assert.True(classAProp1.IsVirtual); Assert.True(classAProp1.SetMethod.IsVirtual); Assert.False(classAProp1.GetMethod.IsVirtual); //NB: non-virtual since private } [Fact] public void CS0546ERR_NoSetToOverride() { var text = @"public class a { public virtual int i { get { return 0; } } } public class b : a { public override int i { set { } // CS0546 error no set } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoSetToOverride, Line = 15, Column = 9 }); } [WorkItem(539321, "DevDiv")] [Fact] public void CS0546ERR_NoSetToOverride_Regress() { var text = @"public class A { public virtual int P1 { get; private set; } public virtual int P2 { get; private set; } } public class C : A { public override int P1 { get { return 0; } } //fine public sealed override int P2 { get { return 0; } } //CS0546 since we can't see A.P2.set to override it as sealed } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (10,32): error CS0546: 'C.P2': cannot override because 'A.P2' does not have an overridable set accessor Diagnostic(ErrorCode.ERR_NoSetToOverride, "P2").WithArguments("C.P2", "A.P2")); var classA = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var classAProp1 = classA.GetMember<PropertySymbol>("P1"); Assert.True(classAProp1.IsVirtual); Assert.True(classAProp1.GetMethod.IsVirtual); Assert.False(classAProp1.SetMethod.IsVirtual); //NB: non-virtual since private } [Fact] public void CS0547ERR_PropertyCantHaveVoidType() { var text = @"interface I { void P { get; set; } } class C { internal void P { set { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyCantHaveVoidType, Line = 3, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyCantHaveVoidType, Line = 7, Column = 19 }); } [Fact] public void CS0548ERR_PropertyWithNoAccessors() { var text = @"interface I { object P { } } abstract class A { public abstract object P { } } class B { internal object P { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 3, Column = 12 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 7, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 11, Column = 21 }); } [Fact] public void CS0548ERR_PropertyWithNoAccessors_Indexer() { var text = @"interface I { object this[int x] { } } abstract class A { public abstract object this[int x] { } } class B { internal object this[int x] { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 3, Column = 12 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 7, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 11, Column = 21 }); } [Fact] public void CS0549ERR_NewVirtualInSealed01() { var text = @"namespace NS { public sealed class Foo { public virtual void M1() { } internal virtual void M2<X>(X x) { } internal virtual int P1 { get; set; } } sealed class Bar<T> { internal virtual T M1(T t) { return t; } public virtual object P1 { get { return null; } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 5, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 6, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 7, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 7, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 12, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 13, Column = 36 }); } [Fact] public void CS0549ERR_NewVirtualInSealed02() { var text = @" public sealed class C { public virtual event System.Action E; public virtual event System.Action F { add { } remove { } } public virtual int this[int x] { get { return 0; } set { } } } "; // CONSIDER: it seems a little strange to report it on property accessors but on // events themselves. On the other hand, property accessors can have modifiers, // whereas event accessors cannot. CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,40): error CS0549: 'C.E' is a new virtual member in sealed class 'C' // public virtual event System.Action E; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "E").WithArguments("C.E", "C"), // (5,40): error CS0549: 'C.F' is a new virtual member in sealed class 'C' // public virtual event System.Action F { add { } remove { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "F").WithArguments("C.F", "C"), // (6,38): error CS0549: 'C.this[int].get' is a new virtual member in sealed class 'C' // public virtual int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "get").WithArguments("C.this[int].get", "C"), // (6,56): error CS0549: 'C.this[int].set' is a new virtual member in sealed class 'C' // public virtual int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "set").WithArguments("C.this[int].set", "C"), // (4,40): warning CS0067: The event 'C.E' is never used // public virtual event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0550ERR_ExplicitPropertyAddingAccessor() { var text = @"namespace x { interface ii { int i { get; } } public class a : ii { int ii.i { get { return 0; } set { } // CS0550 no set in interface } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 19, Column = 13 }); } [Fact] public void CS0551ERR_ExplicitPropertyMissingAccessor() { var text = @"interface ii { int i { get; set; } } public class a : ii { int ii.i { set { } } // CS0551 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 10, Column = 18 }, //CONSIDER: dev10 suppresses this new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 12, Column = 12 }); } [Fact] public void CS0552ERR_ConversionWithInterface() { var text = @" public interface I { } public class C { public static implicit operator I(C c) // CS0552 { return null; } public static implicit operator C(I i) // CS0552 { return null; } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (7,37): error CS0552: 'C.implicit operator I(C)': user-defined conversions to or from an interface are not allowed // public static implicit operator I(C c) // CS0552 Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I").WithArguments("C.implicit operator I(C)"), // (11,37): error CS0552: 'C.implicit operator C(I)': user-defined conversions to or from an interface are not allowed // public static implicit operator C(I i) // CS0552 Diagnostic(ErrorCode.ERR_ConversionWithInterface, "C").WithArguments("C.implicit operator C(I)")); } [Fact] public void CS0553ERR_ConversionWithBase() { var text = @" public class B { } public class D : B { public static implicit operator B(D d) // CS0553 { return null; } } public struct C { public static implicit operator C?(object c) // CS0553 { return null; } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (5,37): error CS0553: 'D.implicit operator B(D)': user-defined conversions to or from a base class are not allowed // public static implicit operator B(D d) // CS0553 Diagnostic(ErrorCode.ERR_ConversionWithBase, "B").WithArguments("D.implicit operator B(D)"), // (12,37): error CS0553: 'C.implicit operator C?(object)': user-defined conversions to or from a base class are not allowed // public static implicit operator C?(object c) // CS0553 Diagnostic(ErrorCode.ERR_ConversionWithBase, "C?").WithArguments("C.implicit operator C?(object)")); } [Fact] public void CS0554ERR_ConversionWithDerived() { var text = @" public class B { public static implicit operator B(D d) // CS0554 { return null; } } public class D : B {} "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (4,37): error CS0554: 'B.implicit operator B(D)': user-defined conversions to or from a derived class are not allowed // public static implicit operator B(D d) // CS0554 Diagnostic(ErrorCode.ERR_ConversionWithDerived, "B").WithArguments("B.implicit operator B(D)") ); } [Fact] public void CS0555ERR_IdentityConversion() { var text = @" public class MyClass { public static implicit operator MyClass(MyClass aa) // CS0555 { return new MyClass(); } } public struct S { public static implicit operator S?(S s) { return s; } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (4,37): error CS0555: User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type // public static implicit operator MyClass(MyClass aa) // CS0555 Diagnostic(ErrorCode.ERR_IdentityConversion, "MyClass"), // (11,37): error CS0555: User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type // public static implicit operator S?(S s) { return s; } Diagnostic(ErrorCode.ERR_IdentityConversion, "S?") ); } [Fact] public void CS0556ERR_ConversionNotInvolvingContainedType() { var text = @" public class C { public static implicit operator int(string aa) // CS0556 { return 0; } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (4,37): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator int(string aa) // CS0556 Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int") ); } [Fact] public void CS0557ERR_DuplicateConversionInClass() { var text = @"namespace x { public class ii { public class iii { public static implicit operator int(iii aa) { return 0; } public static explicit operator int(iii aa) { return 0; } } } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (12,45): error CS0557: Duplicate user-defined conversion in type 'x.ii.iii' // public static explicit operator int(iii aa) Diagnostic(ErrorCode.ERR_DuplicateConversionInClass, "int").WithArguments("x.ii.iii") ); } [Fact] public void CS0558ERR_OperatorsMustBeStatic() { var text = @"namespace x { public class ii { public class iii { static implicit operator int(iii aa) // CS0558, add public { return 0; } } } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (7,35): error CS0558: User-defined operator 'x.ii.iii.implicit operator int(x.ii.iii)' must be declared static and public // static implicit operator int(iii aa) // CS0558, add public Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("x.ii.iii.implicit operator int(x.ii.iii)") ); } [Fact] public void CS0559ERR_BadIncDecSignature() { var text = @"public class iii { public static iii operator ++(int aa) // CS0559 { return null; } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (3,32): error CS0559: The parameter type for ++ or -- operator must be the containing type // public static iii operator ++(int aa) // CS0559 Diagnostic(ErrorCode.ERR_BadIncDecSignature, "++")); } [Fact] public void CS0562ERR_BadUnaryOperatorSignature() { var text = @"public class iii { public static iii operator +(int aa) // CS0562 { return null; } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (3,32): error CS0562: The parameter of a unary operator must be the containing type // public static iii operator +(int aa) // CS0562 Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "+") ); } [Fact] public void CS0563ERR_BadBinaryOperatorSignature() { var text = @"public class iii { public static int operator +(int aa, int bb) // CS0563 { return 0; } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (3,32): error CS0563: One of the parameters of a binary operator must be the containing type // public static int operator +(int aa, int bb) // CS0563 Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "+") ); } [Fact] public void CS0564ERR_BadShiftOperatorSignature() { var text = @" class C { public static int operator <<(C c1, C c2) // CS0564 { return 0; } public static int operator >>(int c1, int c2) // CS0564 { return 0; } static void Main() { } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (4,32): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static int operator <<(C c1, C c2) // CS0564 Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, "<<"), // (8,32): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static int operator >>(int c1, int c2) // CS0564 Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>") ); } [Fact] public void CS0567ERR_InterfacesCantContainOperators() { var text = @" interface IA { int operator +(int aa, int bb); // CS0567 } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (4,17): error CS0567: Interfaces cannot contain operators // int operator +(int aa, int bb); // CS0567 Diagnostic(ErrorCode.ERR_InterfacesCantContainOperators, "+") ); } [Fact] public void CS0568ERR_StructsCantContainDefaultConstructor01() { var text = @"namespace NS { public struct S1 { public S1() {} struct S2<T> { S2() { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ParameterlessStructCtorsMustBePublic, Line = 9, Column = 13 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0569ERR_CantOverrideBogusMethod() { var source1 = @".class abstract public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object get_sealed() { } .method public abstract virtual instance void set_sealed(object o) { } } .class abstract public B extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object get_abstract() { } .method public abstract virtual instance void set_abstract(object o) { } .method public virtual final instance void set_sealed(object o) { ret } .method public virtual final instance object get_sealed() { ldnull ret } // abstract get, sealed set .property instance object P() { .get instance object B::get_abstract() .set instance void B::set_sealed(object) } // sealed get, abstract set .property instance object Q() { .get instance object B::get_sealed() .set instance void B::set_abstract(object) } }"; var reference1 = CompileIL(source1); var source2 = @"class C : B { public override object P { get { return 0; } } public override object Q { set { } } }"; var compilation2 = CreateCompilationWithMscorlib(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (3,28): error CS0569: 'C.P': cannot override 'B.P' because it is not supported by the language Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "P").WithArguments("C.P", "B.P").WithLocation(3, 28), // (4,28): error CS0569: 'C.Q': cannot override 'B.Q' because it is not supported by the language Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Q").WithArguments("C.Q", "B.Q").WithLocation(4, 28)); } [Fact] public void CS8036ERR_FieldInitializerInStruct() { var text = @"namespace x { public class clx { public static void Main() { } } public struct cly { clx a = new clx(); // CS8036 int i = 7; // CS8036 const int c = 1; // no error static int s = 2; // no error } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (12,13): error CS0573: 'cly': cannot have instance property or field initializers in structs // clx a = new clx(); // CS8036 Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "a").WithArguments("x.cly").WithLocation(12, 13), // (13,13): error CS0573: 'cly': cannot have instance property or field initializers in structs // int i = 7; // CS8036 Diagnostic(ErrorCode.ERR_FieldInitializerInStruct, "i").WithArguments("x.cly").WithLocation(13, 13), // (13,13): warning CS0414: The field 'cly.i' is assigned but its value is never used // int i = 7; // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "i").WithArguments("x.cly.i").WithLocation(13, 13), // (15,20): warning CS0414: The field 'cly.s' is assigned but its value is never used // static int s = 2; // no error Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "s").WithArguments("x.cly.s").WithLocation(15, 20) ); } [Fact] public void InstanceCtorInsTructPre60() { var text = @"namespace x { public struct S1 { public S1() {} struct S2<T> { S2() { } } } } "; var comp = CreateCompilationWithMscorlib(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)); comp.VerifyDiagnostics( // (5,16): error CS8026: Feature 'struct instance parameterless constructors' is not available in C# 5. Please use language version 6 or greater. // public S1() {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "S1").WithArguments("struct instance parameterless constructors", "6").WithLocation(5, 16), // (9,13): error CS8075: Parameterless instance constructors in structs must be public // S2() { } Diagnostic(ErrorCode.ERR_ParameterlessStructCtorsMustBePublic, "S2").WithLocation(9, 13) ); } [Fact] public void CS0575ERR_OnlyClassesCanContainDestructors() { var text = @"namespace x { public struct iii { ~iii() // CS0575 { } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OnlyClassesCanContainDestructors, Line = 5, Column = 10 }); } [Fact] public void CS0576ERR_ConflictAliasAndMember01() { var text = @"namespace NS { class B { } } namespace NS { using System; using B = NS.B; class A { public static void Main(String[] args) { B b = null; if (b == b) {} } } struct S { B field; public void M(ref B p) { } } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (22,27): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // public void M(ref B p) { } Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (21,9): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // B field; Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (15,13): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // B b = null; if (b == b) {} Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (21,11): warning CS0169: The field 'NS.S.field' is never used // B field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.S.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(545463, "DevDiv")] [Fact] public void CS0576ERR_ConflictAliasAndMember02() { var source = @" namespace Globals.Errors.ResolveInheritance { using ConflictingAlias = BadUsingNamespace; public class ConflictingAlias { public class Nested { } } namespace BadUsingNamespace { public class UsingNotANamespace { } } class Cls1 : ConflictingAlias.UsingNotANamespace { } // Error class Cls2 : ConflictingAlias::UsingNotANamespace { } // OK class Cls3 : global::Globals.Errors.ResolveInheritance.ConflictingAlias.Nested { } // OK } "; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (12,18): error CS0576: Namespace 'Globals.Errors.ResolveInheritance' contains a definition conflicting with alias 'ConflictingAlias' // class Cls1 : ConflictingAlias.UsingNotANamespace { } // Error Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "ConflictingAlias").WithArguments("ConflictingAlias", "Globals.Errors.ResolveInheritance")); } [Fact] public void CS0577ERR_ConditionalOnSpecialMethod() { var text = @"interface I { void m(); } public class MyClass : I { [System.Diagnostics.Conditional(""a"")] // CS0577 void I.m() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,6): error CS0577: The Conditional attribute is not valid on 'MyClass.I.m()' because it is a constructor, destructor, operator, or explicit interface implementation // [System.Diagnostics.Conditional("a")] // CS0577 Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"System.Diagnostics.Conditional(""a"")").WithArguments("MyClass.I.m()").WithLocation(8, 6)); } [Fact] public void CS0578ERR_ConditionalMustReturnVoid() { var text = @"public class MyClass { [System.Diagnostics.ConditionalAttribute(""a"")] // CS0578 public int TestMethod() { return 0; } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,5): error CS0578: The Conditional attribute is not valid on 'MyClass.TestMethod()' because its return type is not void // [System.Diagnostics.ConditionalAttribute("a")] // CS0578 Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"System.Diagnostics.ConditionalAttribute(""a"")").WithArguments("MyClass.TestMethod()").WithLocation(3, 5)); } [Fact] public void CS0579ERR_DuplicateAttribute() { var text = @"class A : System.Attribute { } class B : System.Attribute { } [A, A] class C { } [B][A][B] class D { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateAttribute, Line = 3, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateAttribute, Line = 4, Column = 8 }); } [Fact, WorkItem(528872, "DevDiv")] public void CS0582ERR_ConditionalOnInterfaceMethod() { var text = @"using System.Diagnostics; interface MyIFace { [ConditionalAttribute(""DEBUG"")] // CS0582 void zz(); } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,5): error CS0582: The Conditional attribute is not valid on interface members // [ConditionalAttribute("DEBUG")] // CS0582 Diagnostic(ErrorCode.ERR_ConditionalOnInterfaceMethod, @"ConditionalAttribute(""DEBUG"")").WithLocation(4, 5)); } [Fact] public void CS0590ERR_OperatorCantReturnVoid() { var text = @" public class C { public static void operator +(C c1, C c2) { } public static implicit operator void(C c1) { } public static void operator +(C c) { } public static void operator >>(C c, int x) { } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (4,33): error CS0590: User-defined operators cannot return void // public static void operator +(C c1, C c2) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "+"), // (5,33): error CS0590: User-defined operators cannot return void // public static implicit operator void(C c1) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "void"), // (5,46): error CS1547: Keyword 'void' cannot be used in this context // public static implicit operator void(C c1) { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (6,33): error CS0590: User-defined operators cannot return void // public static void operator +(C c) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "+"), // (7,33): error CS0590: User-defined operators cannot return void // public static void operator >>(C c, int x) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, ">>") ); } [Fact] public void CS0591ERR_InvalidAttributeArgument() { var text = @"using System; [AttributeUsage(0)] // CS0591 class A : Attribute { } [AttributeUsageAttribute(0)] // CS0591 class B : Attribute { }"; var compilation = CreateCompilationWithMscorlib(text); compilation.VerifyDiagnostics( // (2,17): error CS0591: Invalid value for argument to 'AttributeUsage' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "0").WithArguments("AttributeUsage").WithLocation(2, 17), // (4,26): error CS0591: Invalid value for argument to 'AttributeUsageAttribute' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "0").WithArguments("AttributeUsageAttribute").WithLocation(4, 26)); } [Fact] public void CS0592ERR_AttributeOnBadSymbolType() { var text = @"using System; [AttributeUsage(AttributeTargets.Interface)] public class MyAttribute : Attribute { } [MyAttribute] // Generates CS0592 because MyAttribute is not valid for a class. public class A { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AttributeOnBadSymbolType, Line = 8, Column = 2 }); } [Fact()] public void CS0596ERR_ComImportWithoutUuidAttribute() { var text = @"using System.Runtime.InteropServices; namespace x { [ComImport] // CS0596 public class a { } public class b { public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ComImportWithoutUuidAttribute, Line = 5, Column = 6 }); } // CS0599: not used [Fact] public void CS0601ERR_DllImportOnInvalidMethod() { var text = @" using System.Runtime.InteropServices; public class C { [DllImport(""KERNEL32.DLL"")] extern int Foo(); // CS0601 [DllImport(""KERNEL32.DLL"")] static void Bar() { } // CS0601 } "; CreateCompilationWithMscorlib(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport"), // (9,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport")); } /// <summary> /// Dev10 doesn't report this error, but emits invalid metadata. /// When the containing type is being loaded TypeLoadException is thrown by the CLR. /// </summary> [Fact] public void CS7042ERR_DllImportOnGenericMethod() { var text = @" using System.Runtime.InteropServices; public class C<T> { class X { [DllImport(""KERNEL32.DLL"")] static extern void Bar(); } } public class C { [DllImport(""KERNEL32.DLL"")] static extern void Bar<T>(); } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,10): error CS7042: cannot be applied to a method that is generic or contained in a generic type. Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport"), // (15,6): error CS7042: cannot be applied to a method that is generic or contained in a generic type. Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport")); } // CS0609ERR_NameAttributeOnOverride -> BreakChange [Fact] public void CS0610ERR_FieldCantBeRefAny() { var text = @"public class MainClass { System.TypedReference i; // CS0610 public static void Main() { } System.TypedReference Prop { get; set; } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,5): error CS0610: Field or property cannot be of type 'System.TypedReference' // System.TypedReference Prop { get; set; } Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference"), // (3,5): error CS0610: Field or property cannot be of type 'System.TypedReference' // System.TypedReference i; // CS0610 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference"), // (3,27): warning CS0169: The field 'MainClass.i' is never used // System.TypedReference i; // CS0610 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("MainClass.i") ); } [Fact] public void CS0616ERR_NotAnAttributeClass() { var text = @"[CMyClass] // CS0616 public class CMyClass {} "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NotAnAttributeClass, Line = 1, Column = 2 }); } [Fact] public void CS0616ERR_NotAnAttributeClass2() { var text = @"[CMyClass] // CS0616 public class CMyClassAttribute {} "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NotAnAttributeClass, Line = 1, Column = 2 }); } [Fact] public void CS0617ERR_BadNamedAttributeArgument() { var text = @"using System; [AttributeUsage(AttributeTargets.Class)] public class MyClass : Attribute { public MyClass(int sName) { Bad = sName; Bad2 = -1; } public readonly int Bad; public int Bad2; } [MyClass(5, Bad = 0)] class Class1 { } // CS0617 [MyClass(5, Bad2 = 0)] class Class2 { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadNamedAttributeArgument, Line = 16, Column = 13 }); } [Fact] public void CS0620ERR_IndexerCantHaveVoidType() { var text = @"class MyClass { public static void Main() { MyClass test = new MyClass(); } void this[int intI] // CS0620, return type cannot be void { get { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IndexerCantHaveVoidType, Line = 8, Column = 10 }); } [Fact] public void CS0621ERR_VirtualPrivate01() { var text = @"namespace x { class Foo { private virtual void vf() { } } public class Bar<T> { private virtual void M1(T t) { } virtual V M2<V>(T t); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 5, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 9, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 10, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("x").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0621ERR_VirtualPrivate02() { DiagnosticsUtils.TestDiagnostics( @"abstract class A { abstract object P { get; } } class B { private virtual object Q { get; set; } } ", "'P' error CS0621: 'A.P': virtual or abstract members cannot be private", "'Q' error CS0621: 'B.Q': virtual or abstract members cannot be private"); } [Fact] public void CS0621ERR_VirtualPrivate03() { var text = @"namespace x { abstract class Foo { private virtual void M1<T>(T x) { } private abstract int P { get; set; } } class Bar { private override void M1<T>(T a) { } private override int P { set { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 5, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 6, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 10, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 11, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 10, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 11, Column = 30 }); } [Fact] public void CS0621ERR_VirtualPrivate04() { var text = @" class C { virtual private event System.Action E; } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,41): error CS0621: 'C.E': virtual or abstract members cannot be private // virtual private event System.Action E; Diagnostic(ErrorCode.ERR_VirtualPrivate, "E").WithArguments("C.E"), // (4,41): warning CS0067: The event 'C.E' is never used // virtual private event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } // CS0625: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors [Fact] public void CS0629ERR_InterfaceImplementedByConditional() { var text = @"interface MyInterface { void MyMethod(); } public class MyClass : MyInterface { [System.Diagnostics.Conditional(""debug"")] public void MyMethod() // CS0629, remove the Conditional attribute { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceImplementedByConditional, Line = 9, Column = 17 }); } [Fact] public void CS0633ERR_BadArgumentToAttribute() { var text = @"#define DEBUG using System.Diagnostics; public class Test { [Conditional(""DEB+UG"")] // CS0633 public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,18): error CS0633: The argument to the 'Conditional' attribute must be a valid identifier // [Conditional("DEB+UG")] // CS0633 Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""DEB+UG""").WithArguments("Conditional").WithLocation(5, 18)); } [Fact] public void CS0633ERR_BadArgumentToAttribute_IndexerNameAttribute() { var text = @" using System.Runtime.CompilerServices; class A { [IndexerName(null)] int this[int x] { get { return 0; } set { } } } class B { [IndexerName("""")] int this[int x] { get { return 0; } set { } } } class C { [IndexerName("" "")] int this[int x] { get { return 0; } set { } } } class D { [IndexerName(""1"")] int this[int x] { get { return 0; } set { } } } class E { [IndexerName(""!"")] int this[int x] { get { return 0; } set { } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, "null").WithArguments("IndexerName"), // (10,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""""").WithArguments("IndexerName"), // (15,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @""" """).WithArguments("IndexerName"), // (20,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""1""").WithArguments("IndexerName"), // (25,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""!""").WithArguments("IndexerName")); } // CS0636: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors // CS0637: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors [Fact] public void CS0641ERR_AttributeUsageOnNonAttributeClass() { var text = @"using System; [AttributeUsage(AttributeTargets.Method)] class A { } [System.AttributeUsageAttribute(AttributeTargets.Class)] class B { }"; var compilation = CreateCompilationWithMscorlib(text); compilation.VerifyDiagnostics( // (2,2): error CS0641: Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "AttributeUsage").WithArguments("AttributeUsage").WithLocation(2, 2), // (4,2): error CS0641: Attribute 'System.AttributeUsageAttribute' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "System.AttributeUsageAttribute").WithArguments("System.AttributeUsageAttribute").WithLocation(4, 2)); } [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument() { var text = @"using System; [AttributeUsage(AttributeTargets.Class)] public class MyAttribute : Attribute { public MyAttribute() { } public int x; } [MyAttribute(x = 5, x = 6)] // CS0643, error setting x twice class MyClass { } public class MainClass { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNamedAttributeArgument, Line = 13, Column = 21 }); } [WorkItem(540923, "DevDiv")] [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument02() { var text = @"using System; [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] class MyAtt : Attribute { } [MyAtt] public class Test { public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (2,39): error CS0643: 'AllowMultiple' duplicate named attribute argument // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_DuplicateNamedAttributeArgument, "AllowMultiple = false").WithArguments("AllowMultiple").WithLocation(2, 39), // (2,2): error CS7036: There is no argument given that corresponds to the required formal parameter 'validOn' of 'System.AttributeUsageAttribute.AttributeUsageAttribute(System.AttributeTargets)' // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AttributeUsage(AllowMultiple = true, AllowMultiple = false)").WithArguments("validOn", "System.AttributeUsageAttribute.AttributeUsageAttribute(System.AttributeTargets)").WithLocation(2, 2)); } [Fact] public void CS0644ERR_DeriveFromEnumOrValueType() { DiagnosticsUtils.TestDiagnostics( @"using System; namespace N { class C : Enum { } class D : ValueType { } class E : Delegate { } static class F : MulticastDelegate { } static class G : Array { } } ", "'C' error CS0644: 'C' cannot derive from special class 'Enum'", "'D' error CS0644: 'D' cannot derive from special class 'ValueType'", "'E' error CS0644: 'E' cannot derive from special class 'Delegate'", "'F' error CS0644: 'F' cannot derive from special class 'MulticastDelegate'", "'G' error CS0644: 'G' cannot derive from special class 'Array'"); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType() { var text = @"[System.Reflection.DefaultMemberAttribute(""x"")] // CS0646 class MyClass { public int this[int index] // an indexer { get { return 0; } } public int x = 0; } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultMemberOnIndexedType, Line = 1, Column = 2 }); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType02() { var text = @" using System.Reflection; interface I { int this[int x] { set; } } [DefaultMember(""X"")] class Program : I { int I.this[int x] { set { } } //doesn't count as an indexer for CS0646 }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics(); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType03() { var text = @" using System.Reflection; [DefaultMember(""This is definitely not a valid member name *#&#*"")] class Program { }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics(); } [Fact] public void CS0653ERR_AbstractAttributeClass() { var text = @"using System; public abstract class MyAttribute : Attribute { } [My] // CS0653 class MyClass { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAttributeClass, Line = 7, Column = 2 }); } [Fact] public void CS0655ERR_BadNamedAttributeArgumentType() { var text = @"using System; class MyAttribute : Attribute { public decimal d = 0; public int e = 0; } [My(d = 0)] // CS0655 class C { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadNamedAttributeArgumentType, Line = 9, Column = 5 }); } [Fact] public void CS0655ERR_BadNamedAttributeArgumentType_Dynamic() { var text = @" using System; public class C<T> { public enum D { A } } [A1(P = null)] // Dev11 error public class A1 : Attribute { public A1() { } public dynamic P { get; set; } } [A2(P = null)] // Dev11 ok (bug) public class A2 : Attribute { public A2() { } public dynamic[] P { get; set; } } [A3(P = 0)] // Dev11 error (bug) public class A3 : Attribute { public A3() { } public C<dynamic>.D P { get; set; } } [A4(P = null)] // Dev11 ok public class A4 : Attribute { public A4() { } public C<dynamic>.D[] P { get; set; } } "; CreateCompilationWithMscorlibAndSystemCore(text).VerifyDiagnostics( // (6,5): error CS0655: 'P' is not a valid named attribute argument because it is not a valid attribute parameter type // [A1(P = null)] // Dev11 error Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "P").WithArguments("P"), // (13,5): error CS0655: 'P' is not a valid named attribute argument because it is not a valid attribute parameter type // [A2(P = null)] // Dev11 ok (bug) Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "P").WithArguments("P")); } [Fact] public void CS0656ERR_MissingPredefinedMember() { var text = @"namespace System { public class Object { } public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct SByte { } public struct UInt32 { } public struct UInt64 { } public struct Char { } public struct Boolean { } public struct UInt16 { } public struct UIntPtr { } public struct IntPtr { } public class Delegate { } public class String { public int Length { get { return 10; } } } public class MulticastDelegate { } public class Array { } public class Exception { } public class Type { } public class ValueType { } public class Enum { } public interface IEnumerable { } public interface IDisposable { } public class Attribute { } public class ParamArrayAttribute { } public struct Void { } public struct RuntimeFieldHandle { } public struct RuntimeTypeHandle { } namespace Collections { public interface IEnumerable { } public interface IEnumerator { } } namespace Runtime { namespace InteropServices { public class OutAttribute { } } namespace CompilerServices { public class RuntimeHelpers { } } } namespace Reflection { public class DefaultMemberAttribute { } } public class Test { public unsafe static int Main() { string str = ""This is my test string""; fixed (char* ptr = str) { if (*(ptr + str.Length) != '\0') return 1; } return 0; } } }"; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyEmitDiagnostics( // (70,32): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RuntimeHelpers.get_OffsetToStringData' // fixed (char* ptr = str) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "str").WithArguments("System.Runtime.CompilerServices.RuntimeHelpers", "get_OffsetToStringData")); } // CS0662: see AttributeTests.InOutAttributes_Errors [Fact] public void CS0663ERR_OverloadRefOut01() { var text = @"namespace NS { public interface IFoo<T> { void M(T t); void M(ref T t); void M(out T t); } internal class CFoo { private struct SFoo { void M<T>(T t) { } void M<T>(ref T t) { } void M<T>(out T t) { } } public int RetInt(byte b, out int i) { return i; } public int RetInt(byte b, ref int j) { return 3; } public int RetInt(byte b, int k) { return 4; } } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (7,14): error CS0663: 'NS.IFoo<T>' cannot define overloaded methods that differ only on ref and out Diagnostic(ErrorCode.ERR_OverloadRefOut, "M").WithArguments("NS.IFoo<T>"), // (24,20): error CS0663: 'NS.CFoo' cannot define overloaded methods that differ only on ref and out Diagnostic(ErrorCode.ERR_OverloadRefOut, "RetInt").WithArguments("NS.CFoo"), // (16,18): error CS0663: 'NS.CFoo.SFoo' cannot define overloaded methods that differ only on ref and out Diagnostic(ErrorCode.ERR_OverloadRefOut, "M").WithArguments("NS.CFoo.SFoo"), // Dev10 stops after reporting the overload problems. However, it produces the errors below once those problems are fixed. // (21,20): error CS0269: Use of unassigned out parameter 'i' Diagnostic(ErrorCode.ERR_UseDefViolationOut, "i").WithArguments("i"), // (21,13): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method Diagnostic(ErrorCode.ERR_ParamUnassigned, "return i;").WithArguments("i"), // (16,18): error CS0177: The out parameter 't' must be assigned to before control leaves the current method Diagnostic(ErrorCode.ERR_ParamUnassigned, "M").WithArguments("t")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0666ERR_ProtectedInStruct01() { var text = @"namespace NS { internal struct S1<T, V> { protected T field; protected internal void M(T t, V v) { } protected object P { get { return null; } } // Dev10 no error protected event System.Action E; struct S2 { protected void M1<X>(X p) { } protected internal R M2<X, R>(ref X p, R r) { return r; } protected internal object Q { get; set; } // Dev10 no error protected event System.Action E; } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,21): error CS0666: 'NS.S1<T, V>.field': new protected member declared in struct // protected T field; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "field").WithArguments("NS.S1<T, V>.field"), // (7,26): error CS0666: 'NS.S1<T, V>.P': new protected member declared in struct // protected object P { get { return null; } } // Dev10 no error Diagnostic(ErrorCode.ERR_ProtectedInStruct, "P").WithArguments("NS.S1<T, V>.P"), // (8,39): error CS0666: 'NS.S1<T, V>.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("NS.S1<T, V>.E"), // (6,33): error CS0666: 'NS.S1<T, V>.M(T, V)': new protected member declared in struct // protected internal void M(T t, V v) { } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M").WithArguments("NS.S1<T, V>.M(T, V)"), // (14,39): error CS0666: 'NS.S1<T, V>.S2.Q': new protected member declared in struct // protected internal object Q { get; set; } // Dev10 no error Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Q").WithArguments("NS.S1<T, V>.S2.Q"), // (15,43): error CS0666: 'NS.S1<T, V>.S2.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("NS.S1<T, V>.S2.E"), // (12,28): error CS0666: 'NS.S1<T, V>.S2.M1<X>(X)': new protected member declared in struct // protected void M1<X>(X p) { } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M1").WithArguments("NS.S1<T, V>.S2.M1<X>(X)"), // (13,34): error CS0666: 'NS.S1<T, V>.S2.M2<X, R>(ref X, R)': new protected member declared in struct // protected internal R M2<X, R>(ref X p, R r) { return r; } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M2").WithArguments("NS.S1<T, V>.S2.M2<X, R>(ref X, R)"), // (5,21): warning CS0649: Field 'NS.S1<T, V>.field' is never assigned to, and will always have its default value // protected T field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.S1<T, V>.field", ""), // (8,39): warning CS0067: The event 'NS.S1<T, V>.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.S1<T, V>.E"), // (15,43): warning CS0067: The event 'NS.S1<T, V>.S2.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.S1<T, V>.S2.E") ); } [Fact] public void CS0666ERR_ProtectedInStruct02() { var text = @"struct S { protected object P { get { return null; } } public int Q { get; protected set; } } struct C<T> { protected internal T P { get; protected set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 4, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 8, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 8, Column = 45 }); } [Fact] public void CS0666ERR_ProtectedInStruct03() { var text = @" struct S { protected event System.Action E; protected event System.Action F { add { } remove { } } protected int this[int x] { get { return 0; } set { } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,35): error CS0666: 'S.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("S.E"), // (5,35): error CS0666: 'S.F': new protected member declared in struct // protected event System.Action F { add { } remove { } } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "F").WithArguments("S.F"), // (6,19): error CS0666: 'S.this[int]': new protected member declared in struct // protected int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "this").WithArguments("S.this[int]"), // (4,35): warning CS0067: The event 'S.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("S.E")); } [Fact] public void CS0668ERR_InconsistentIndexerNames() { var text = @" using System.Runtime.CompilerServices; class IndexerClass { [IndexerName(""IName1"")] public int this[int index] // indexer declaration { get { return index; } set { } } [IndexerName(""IName2"")] public int this[string s] // CS0668, change IName2 to IName1 { get { return int.Parse(s); } set { } } void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InconsistentIndexerNames, Line = 19, Column = 16 }); } [Fact] public void CS0668ERR_InconsistentIndexerNames02() { var text = @" using System.Runtime.CompilerServices; class IndexerClass { public int this[int[] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from no attribute to A public int this[int[,] index] { get { return 0; } set { } } // transition from A to no attribute public int this[int[,,] index] { get { return 0; } set { } } [IndexerName(""B"")] // transition from no attribute to B public int this[int[,,,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from B to A public int this[int[,,,,] index] { get { return 0; } set { } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (9,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (12,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (15,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (18,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } /// <summary> /// Same as 02, but with an explicit interface implementation between each pair. /// </summary> [Fact] public void CS0668ERR_InconsistentIndexerNames03() { var text = @" using System.Runtime.CompilerServices; interface I { int this[int[] index] { get; set; } int this[int[,] index] { get; set; } int this[int[,,] index] { get; set; } int this[int[,,,] index] { get; set; } int this[int[,,,,] index] { get; set; } int this[int[,,,,,] index] { get; set; } } class IndexerClass : I { int I.this[int[] index] { get { return 0; } set { } } public int this[int[] index] { get { return 0; } set { } } int I.this[int[,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from no attribute to A public int this[int[,] index] { get { return 0; } set { } } int I.this[int[,,] index] { get { return 0; } set { } } // transition from A to no attribute public int this[int[,,] index] { get { return 0; } set { } } int I.this[int[,,,] index] { get { return 0; } set { } } [IndexerName(""B"")] // transition from no attribute to B public int this[int[,,,] index] { get { return 0; } set { } } int I.this[int[,,,,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from B to A public int this[int[,,,,] index] { get { return 0; } set { } } int I.this[int[,,,,,] index] { get { return 0; } set { } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (23,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (28,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (33,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (38,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } [Fact()] public void CS0669ERR_ComImportWithUserCtor() { var text = @"using System.Runtime.InteropServices; [ComImport, Guid(""00000000-0000-0000-0000-000000000001"")] class TestClass { TestClass() // CS0669, delete constructor to resolve { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,5): error CS0669: A class with the ComImport attribute cannot have a user-defined constructor // TestClass() // CS0669, delete constructor to resolve Diagnostic(ErrorCode.ERR_ComImportWithUserCtor, "TestClass").WithLocation(5, 5)); } [Fact] public void CS0670ERR_FieldCantHaveVoidType01() { var text = @"namespace NS { public class Foo { void Field2 = 0; public void Field1; public struct SFoo { void Field1; internal void Field2; } } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (5,9): error CS0670: Field cannot have void type // void Field2 = 0; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (6,16): error CS0670: Field cannot have void type // public void Field1; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (10,13): error CS0670: Field cannot have void type // void Field1; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (11,22): error CS0670: Field cannot have void type // internal void Field2; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (5,23): error CS0029: Cannot implicitly convert type 'int' to 'void' // void Field2 = 0; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "void"), // (10,18): warning CS0169: The field 'NS.Foo.SFoo.Field1' is never used // void Field1; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field1").WithArguments("NS.Foo.SFoo.Field1"), // (11,27): warning CS0649: Field 'NS.Foo.SFoo.Field2' is never assigned to, and will always have its default value // internal void Field2; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("NS.Foo.SFoo.Field2", "") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0673ERR_SystemVoid01() { var source = @"namespace NS { using System; interface IFoo<T> { Void M(T t); } class Foo { extern Void GetVoid(); struct SFoo : IFoo<Void> { } } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IFoo<Void>").WithArguments("NS.Foo.SFoo", "NS.IFoo<System.Void>.M(System.Void)"), Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "GetVoid").WithArguments("NS.Foo.GetVoid()")); } [Fact] public void CS0674ERR_ExplicitParamArray() { var text = @"using System; public class MyClass { public static void UseParams([ParamArray] int[] list) // CS0674 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitParamArray, Line = 4, Column = 35 }); } [Fact] public void CS0677ERR_VolatileStruct() { var text = @"class TestClass { private volatile long i; // CS0677 public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,27): error CS0677: 'TestClass.i': a volatile field cannot be of the type 'long' // private volatile long i; // CS0677 Diagnostic(ErrorCode.ERR_VolatileStruct, "i").WithArguments("TestClass.i", "long"), // (3,27): warning CS0169: The field 'TestClass.i' is never used // private volatile long i; // CS0677 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("TestClass.i") ); } [Fact] public void CS0677ERR_VolatileStruct_TypeParameter() { var text = @" class C1<T> { volatile T f; // CS0677 } class C2<T> where T : class { volatile T f; } class C3<T> where T : struct { volatile T f; // CS0677 } class C4<T> where T : C1<int> { volatile T f; } interface I { } class C5<T> where T : I { volatile T f; // CS0677 } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,16): error CS0677: 'C1<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C1<T>.f", "T"), // (14,16): error CS0677: 'C3<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C3<T>.f", "T"), // (26,16): error CS0677: 'C5<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C5<T>.f", "T"), // (4,16): warning CS0169: The field 'C1<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C1<T>.f"), // (9,16): warning CS0169: The field 'C2<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C2<T>.f"), // (14,16): warning CS0169: The field 'C3<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C3<T>.f"), // (19,16): warning CS0169: The field 'C4<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C4<T>.f"), // (26,16): warning CS0169: The field 'C5<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C5<T>.f")); } [Fact] public void CS0678ERR_VolatileAndReadonly() { var text = @"class TestClass { private readonly volatile int i; // CS0678 public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,35): error CS0678: 'TestClass.i': a field cannot be both volatile and readonly // private readonly volatile int i; // CS0678 Diagnostic(ErrorCode.ERR_VolatileAndReadonly, "i").WithArguments("TestClass.i"), // (3,35): warning CS0169: The field 'TestClass.i' is never used // private readonly volatile int i; // CS0678 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("TestClass.i")); } [Fact] public void CS0681ERR_AbstractField01() { var text = @"namespace NS { class Foo<T> { public abstract T field; struct SFoo { abstract internal Foo<object> field; } } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (6,27): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // public abstract T field; Diagnostic(ErrorCode.ERR_AbstractField, "field"), // (10,43): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract internal Foo<object> field; Diagnostic(ErrorCode.ERR_AbstractField, "field"), // (6,27): warning CS0649: Field 'NS.Foo<T>.field' is never assigned to, and will always have its default value // public abstract T field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Foo<T>.field", ""), // (10,43): warning CS0649: Field 'NS.Foo<T>.SFoo.field' is never assigned to, and will always have its default value null // abstract internal Foo<object> field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Foo<T>.SFoo.field", "null") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(546447, "DevDiv")] [Fact] public void CS0682ERR_BogusExplicitImpl() { var source1 = @".class interface public abstract I { .method public abstract virtual instance object get_P() { } .method public abstract virtual instance void set_P(object& v) { } .property instance object P() { .get instance object I::get_P() .set instance void I::set_P(object& v) } .method public abstract virtual instance void add_E(class [mscorlib]System.Action v) { } .method public abstract virtual instance void remove_E(class [mscorlib]System.Action& v) { } .event [mscorlib]System.Action E { .addon instance void I::add_E(class [mscorlib]System.Action v); .removeon instance void I::remove_E(class [mscorlib]System.Action& v); } }"; var reference1 = CompileIL(source1); var source2 = @"using System; class C1 : I { object I.get_P() { return null; } void I.set_P(ref object v) { } void I.add_E(Action v) { } void I.remove_E(ref Action v) { } } class C2 : I { object I.P { get { return null; } set { } } event Action I.E { add { } remove { } } }"; var compilation2 = CreateCompilationWithMscorlib(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (11,14): error CS0682: 'C2.I.P' cannot implement 'I.P' because it is not supported by the language Diagnostic(ErrorCode.ERR_BogusExplicitImpl, "P").WithArguments("C2.I.P", "I.P").WithLocation(11, 14), // (16,20): error CS0682: 'C2.I.E' cannot implement 'I.E' because it is not supported by the language Diagnostic(ErrorCode.ERR_BogusExplicitImpl, "E").WithArguments("C2.I.E", "I.E").WithLocation(16, 20)); } [Fact] public void CS0683ERR_ExplicitMethodImplAccessor() { var text = @"interface IExample { int Test { get; } } class CExample : IExample { int IExample.get_Test() { return 0; } // CS0683 int IExample.Test { get { return 0; } } // correct } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitMethodImplAccessor, Line = 8, Column = 18 }); } [Fact] public void CS0685ERR_ConditionalWithOutParam() { var text = @"namespace NS { using System.Diagnostics; class Test { [Conditional(""DEBUG"")] void Debug(out int i) // CS0685 { i = 1; } [Conditional(""TRACE"")] void Trace(ref string p1, out string p2) // CS0685 { p2 = p1; } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (7,10): error CS0685: Conditional member 'NS.Test.Debug(out int)' cannot have an out parameter // [Conditional("DEBUG")] Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""DEBUG"")").WithArguments("NS.Test.Debug(out int)").WithLocation(7, 10), // (13,10): error CS0685: Conditional member 'NS.Test.Trace(ref string, out string)' cannot have an out parameter // [Conditional("TRACE")] Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""TRACE"")").WithArguments("NS.Test.Trace(ref string, out string)").WithLocation(13, 10)); } [Fact] public void CS0686ERR_AccessorImplementingMethod() { var text = @"interface I { int get_P(); } class C : I { public int P { get { return 1; } // CS0686 } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AccessorImplementingMethod, Line = 10, Column = 9 }); } [Fact] public void CS0689ERR_DerivingFromATyVar01() { var text = @"namespace NS { interface IFoo<T, V> : V { } internal class A<T> : T // CS0689 { protected struct S : T { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 3, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 7, Column = 27 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 9, Column = 30 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0692ERR_DuplicateTypeParameter() { var source = @"class C<T, T> where T : class { void M<U, V, U>() where U : new() { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (1,12): error CS0692: Duplicate type parameter 'T' Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(1, 12), // (4,18): error CS0692: Duplicate type parameter 'U' Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U").WithLocation(4, 18)); } [Fact] public void CS0693WRN_TypeParameterSameAsOuterTypeParameter01() { var text = @"namespace NS { interface IFoo<T, V> { void M<T>(); } public struct S<T> { public class Outer<T, V> { class Inner<T> // CS0693 { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 5, Column = 16, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 10, Column = 28, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 12, Column = 25, IsWarning = true }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0694ERR_TypeVariableSameAsParent01() { var text = @"namespace NS { interface IFoo { void M<M>(M m); } class C<C> { public struct S<T, S> { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_TypeVariableSameAsParent, Line = 5, Column = 16 }, // Dev10 not report this if there next 2 errors new ErrorDescription { Code = (int)ErrorCode.ERR_TypeVariableSameAsParent, Line = 8, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.ERR_TypeVariableSameAsParent, Line = 10, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations() { // Note: more detailed unification tests are in TypeUnificationTests.cs var text = @"interface I<T> { } class G1<T1, T2> : I<T1>, I<T2> { } // CS0695 class G2<T1, T2> : I<int>, I<T2> { } // CS0695 class G3<T1, T2> : I<int>, I<short> { } // fine class G4<T1, T2> : I<I<T1>>, I<T1> { } // fine class G5<T1, T2> : I<I<T1>>, I<T2> { } // CS0695 interface I2<T> : I<T> { } class G6<T1, T2> : I<T1>, I2<T2> { } // CS0695 "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 3, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 5, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 11, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 15, Column = 7 }); } [WorkItem(539517, "DevDiv")] [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations2() { var text = @" interface I<T, S> { } class A<T, S> : I<I<T, T>, T>, I<I<T, S>, S> { } // CS0695 "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 4, Column = 7 }); } [WorkItem(539518, "DevDiv")] [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations3() { var text = @" class A<T, S> { class B : A<B, B> { } interface IA { } interface IB : B.IA, B.B.IA { } // fine } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0698ERR_GenericDerivingFromAttribute01() { var text = @"class C<T> : System.Attribute // CS0698 { } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (1,14): error CS0698: A generic type cannot derive from 'System.Attribute' because it is an attribute class Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "System.Attribute").WithArguments("System.Attribute").WithLocation(1, 14)); } [Fact] public void CS0698ERR_GenericDerivingFromAttribute02() { var text = @"class A : System.Attribute { } class B<T> : A { } class C<T> { class B : A { } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (2,14): error CS0698: A generic type cannot derive from 'A' because it is an attribute class Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "A").WithArguments("A").WithLocation(2, 14), // (5,15): error CS0698: A generic type cannot derive from 'A' because it is an attribute class Diagnostic(ErrorCode.ERR_GenericDerivingFromAttribute, "A").WithArguments("A").WithLocation(5, 15)); } [Fact] public void CS0699ERR_TyVarNotFoundInConstraint() { var source = @"struct S<T> where T : class where U : struct { void M<U, V>() where T : new() where W : class { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,11): error CS0699: 'S<T>' does not define type parameter 'U' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "S<T>").WithLocation(3, 11), // (6,15): error CS0699: 'S<T>.M<U, V>()' does not define type parameter 'T' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "T").WithArguments("T", "S<T>.M<U, V>()").WithLocation(6, 15), // (7,15): error CS0699: 'S<T>.M<U, V>()' does not define type parameter 'W' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "W").WithArguments("W", "S<T>.M<U, V>()").WithLocation(7, 15)); } [Fact] public void CS0701ERR_BadBoundType() { var source = @"delegate void D(); enum E { } struct S { } sealed class A<T> { } class C { void M1<T>() where T : string { } void M2<T>() where T : D { } void M3<T>() where T : E { } void M4<T>() where T : S { } void M5<T>() where T : A<T> { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (7,28): error CS0701: 'string' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "string").WithArguments("string").WithLocation(7, 28), // (8,28): error CS0701: 'D' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "D").WithArguments("D").WithLocation(8, 28), // (9,28): error CS0701: 'E' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "E").WithArguments("E").WithLocation(9, 28), // (10,28): error CS0701: 'S' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "S").WithArguments("S").WithLocation(10, 28), // (11,28): error CS0701: 'A<T>' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "A<T>").WithArguments("A<T>").WithLocation(11, 28)); } [Fact] public void CS0702ERR_SpecialTypeAsBound() { var source = @"using System; interface IA<T> where T : object { } interface IB<T> where T : System.Object { } interface IC<T, U> where T : ValueType where U : Enum { } interface ID<T> where T : Array { } interface IE<T, U> where T : Delegate where U : MulticastDelegate { }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (2,27): error CS0702: Constraint cannot be special class 'object' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object").WithArguments("object").WithLocation(2, 27), // (3,27): error CS0702: Constraint cannot be special class 'object' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object").WithArguments("object").WithLocation(3, 27), // (4,30): error CS0702: Constraint cannot be special class 'System.ValueType' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "ValueType").WithArguments("System.ValueType").WithLocation(4, 30), // (4,50): error CS0702: Constraint cannot be special class 'System.Enum' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "Enum").WithArguments("System.Enum").WithLocation(4, 50), // (5,27): error CS0702: Constraint cannot be special class 'System.Array' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "Array").WithArguments("System.Array").WithLocation(5, 27), // (6,30): error CS0702: Constraint cannot be special class 'System.Delegate' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "Delegate").WithArguments("System.Delegate").WithLocation(6, 30), // (6,49): error CS0702: Constraint cannot be special class 'System.MulticastDelegate' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "MulticastDelegate").WithArguments("System.MulticastDelegate").WithLocation(6, 49)); } [Fact] public void CS0703ERR_BadVisBound01() { var source = @"public class C1 { protected interface I<T> { } internal class A<T> { } public delegate void D<T>() where T : A<T>, I<T>; } public class C2 : C1 { protected struct S<T, U, V> where T : I<A<T>> where U : I<I<U>> where V : A<A<V>> { } internal void M<T, U, V>() where T : A<I<T>> where U : I<I<U>> where V : A<A<V>> { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (5,26): error CS0703: Inconsistent accessibility: constraint type 'C1.A<T>' is less accessible than 'C1.D<T>' Diagnostic(ErrorCode.ERR_BadVisBound, "D").WithArguments("C1.D<T>", "C1.A<T>").WithLocation(5, 26), // (5,26): error CS0703: Inconsistent accessibility: constraint type 'C1.I<T>' is less accessible than 'C1.D<T>' Diagnostic(ErrorCode.ERR_BadVisBound, "D").WithArguments("C1.D<T>", "C1.I<T>").WithLocation(5, 26), // (13,19): error CS0703: Inconsistent accessibility: constraint type 'C1.A<C1.I<T>>' is less accessible than 'C2.M<T, U, V>()' Diagnostic(ErrorCode.ERR_BadVisBound, "M").WithArguments("C2.M<T, U, V>()", "C1.A<C1.I<T>>").WithLocation(13, 19), // (13,19): error CS0703: Inconsistent accessibility: constraint type 'C1.I<C1.I<U>>' is less accessible than 'C2.M<T, U, V>()' Diagnostic(ErrorCode.ERR_BadVisBound, "M").WithArguments("C2.M<T, U, V>()", "C1.I<C1.I<U>>").WithLocation(13, 19), // (9,22): error CS0703: Inconsistent accessibility: constraint type 'C1.I<C1.A<T>>' is less accessible than 'C2.S<T, U, V>' Diagnostic(ErrorCode.ERR_BadVisBound, "S").WithArguments("C2.S<T, U, V>", "C1.I<C1.A<T>>").WithLocation(9, 22), // (9,22): error CS0703: Inconsistent accessibility: constraint type 'C1.A<C1.A<V>>' is less accessible than 'C2.S<T, U, V>' Diagnostic(ErrorCode.ERR_BadVisBound, "S").WithArguments("C2.S<T, U, V>", "C1.A<C1.A<V>>").WithLocation(9, 22)); } [Fact] public void CS0703ERR_BadVisBound02() { var source = @"internal interface IA<T> { } public interface IB<T, U> { } public class A { public partial class B<T, U> { } public partial class B<T, U> where U : IB<U, IA<T>> { } public partial class B<T, U> where U : IB<U, IA<T>> { } } public partial class C { public partial void M<T>() where T : IA<T>; public partial void M<T>() where T : IA<T> { } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (6,26): error CS0703: Inconsistent accessibility: constraint type 'IB<U, IA<T>>' is less accessible than 'A.B<T, U>' Diagnostic(ErrorCode.ERR_BadVisBound, "B").WithArguments("A.B<T, U>", "IB<U, IA<T>>").WithLocation(6, 26), // (11,25): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M").WithLocation(11, 25), // (12,25): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "M").WithLocation(12, 25), // (11,25): error CS0703: Inconsistent accessibility: constraint type 'IA<T>' is less accessible than 'C.M<T>()' Diagnostic(ErrorCode.ERR_BadVisBound, "M").WithArguments("C.M<T>()", "IA<T>").WithLocation(11, 25), // (12,25): error CS0703: Inconsistent accessibility: constraint type 'IA<T>' is less accessible than 'C.M<T>()' Diagnostic(ErrorCode.ERR_BadVisBound, "M").WithArguments("C.M<T>()", "IA<T>").WithLocation(12, 25)); } [Fact] public void CS0708ERR_InstanceMemberInStaticClass01() { var text = @"namespace NS { public static class Foo { int i; void M() { } internal object P { get; set; } event System.Action E; } static class Bar<T> { T field; T M(T x) { return x; } int Q { get { return 0; } } event System.Action<T> E; } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (5,13): error CS0708: 'NS.Foo.i': cannot declare instance members in a static class // int i; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "i").WithArguments("NS.Foo.i"), // (7,25): error CS0708: 'NS.Foo.P': cannot declare instance members in a static class // internal object P { get; set; } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "P").WithArguments("NS.Foo.P"), // (8,29): error CS0708: 'E': cannot declare instance members in a static class // event System.Action E; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "E").WithArguments("E"), // (6,14): error CS0708: 'M': cannot declare instance members in a static class // void M() { } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "M").WithArguments("M"), // (13,11): error CS0708: 'NS.Bar<T>.field': cannot declare instance members in a static class // T field; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "field").WithArguments("NS.Bar<T>.field"), // (15,13): error CS0708: 'NS.Bar<T>.Q': cannot declare instance members in a static class // int Q { get { return 0; } } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "Q").WithArguments("NS.Bar<T>.Q"), // (16,32): error CS0708: 'E': cannot declare instance members in a static class // event System.Action<T> E; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "E").WithArguments("E"), // (16,32): warning CS0067: The event 'NS.Bar<T>.E' is never used // event System.Action<T> E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.Bar<T>.E"), // (8,29): warning CS0067: The event 'NS.Foo.E' is never used // event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.Foo.E"), // (14,11): error CS0708: 'M': cannot declare instance members in a static class // T M(T x) { return x; } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "M").WithArguments("M"), // (5,13): warning CS0169: The field 'NS.Foo.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("NS.Foo.i"), // (13,11): warning CS0169: The field 'NS.Bar<T>.field' is never used // T field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.Bar<T>.field")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0709ERR_StaticBaseClass01() { var text = @"namespace NS { public static class Base { } public class Derived : Base { } static class Base1<T, V> { } sealed class Seal<T> : Base1<T, short> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticBaseClass, Line = 7, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticBaseClass, Line = 15, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0710ERR_ConstructorInStaticClass01() { var text = @"namespace NS { public static class C { public C() {} C(string s) { } static class D<T, V> { internal D() { } internal D(params sbyte[] ary) { } } static C() { } // no error } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 5, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 10, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 11, Column = 22 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0711ERR_DestructorInStaticClass() { var text = @"public static class C { ~C() // CS0711 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DestructorInStaticClass, Line = 3, Column = 6 }); } [Fact] public void CS0712ERR_InstantiatingStaticClass() { var text = @" static class C { static void Main() { C c = new C(); //CS0712 } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,9): error CS0723: Cannot declare a variable of static type 'C' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "C").WithArguments("C"), // (6,15): error CS0712: Cannot create an instance of the static class 'C' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new C()").WithArguments("C")); } [Fact] public void CS0713ERR_StaticDerivedFromNonObject01() { DiagnosticsUtils.TestDiagnostics( @"namespace NS { public class Base { } public static class Derived : Base { } class Base1<T, V> { } static class D<V> : Base1<string, V> { } } ", "'Base' error CS0713: Static class 'Derived' cannot derive from type 'Base'. Static classes must derive from object.", "'Base1<string, V>' error CS0713: Static class 'D<V>' cannot derive from type 'Base1<string, V>'. Static classes must derive from object."); } [Fact] public void CS0713ERR_StaticDerivedFromNonObject02() { DiagnosticsUtils.TestDiagnostics( @"delegate void A(); struct B { } static class C : A { } static class D : B { } ", "'A' error CS0713: Static class 'C' cannot derive from type 'A'. Static classes must derive from object.", "'B' error CS0713: Static class 'D' cannot derive from type 'B'. Static classes must derive from object."); } [Fact] public void CS0714ERR_StaticClassInterfaceImpl01() { var text = @"namespace NS { interface I { } public static class C : I { } interface IFoo<T, V> { } static class D<V> : IFoo<string, V> { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (7,29): error CS0714: 'NS.C': static classes cannot implement interfaces Diagnostic(ErrorCode.ERR_StaticClassInterfaceImpl, "I").WithArguments("NS.C", "NS.I"), // (15,25): error CS0714: 'NS.D<V>': static classes cannot implement interfaces Diagnostic(ErrorCode.ERR_StaticClassInterfaceImpl, "IFoo<string, V>").WithArguments("NS.D<V>", "NS.IFoo<string, V>")); } [Fact] public void CS0715ERR_OperatorInStaticClass() { var text = @" public static class C { public static C operator +(C c) // CS0715 { return c; } } "; // Note that Roslyn produces these three errors. The native compiler // produces only the first. We might consider suppressing the additional // "cascading" errors in Roslyn. CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,30): error CS0715: 'C.operator +(C)': static classes cannot contain user-defined operators // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_OperatorInStaticClass, "+").WithArguments("C.operator +(C)"), // (4,30): error CS0721: 'C': static types cannot be used as parameters // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "+").WithArguments("C"), // (4,19): error CS0722: 'C': static types cannot be used as return types // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "C").WithArguments("C") ); } [Fact] public void CS0716ERR_ConvertToStaticClass() { var text = @" static class C { static void M(object o) { M((C)o); M((C)new object()); M((C)null); M((C)1); M((C)""a""); } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)o").WithArguments("C"), // (7,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)new object()").WithArguments("C"), // (8,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)null").WithArguments("C"), // (9,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)1").WithArguments("C"), // (10,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)\"a\"").WithArguments("C")); } [Fact] public void CS7023ERR_StaticInIsAsOrIs() { // BREAKING CHANGE: The C# specification states that it is always illegal // BREAKING CHANGE: to use a static type with "is" and "as". The native // BREAKING CHANGE: compiler allows it in some cases; Roslyn does not. var text = @" static class C { static void M(object o) { M(o as C); // legal in native M(new object() as C); // legal in native M(null as C); // legal in native M(1 as C); M(""a"" as C); M(o is C); // legal in native, no warning M(new object() is C); // legal in native, no warning M(null is C); // legal in native, warns M(1 is C); // legal in native, warns M(""a"" is C); // legal in native, warns } } "; var comp = CreateCompilationWithMscorlib(text); // these diagnostics correspond to those produced by the native compiler. comp.VerifyDiagnostics( // (9,11): error CS0039: Cannot convert type 'int' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // M(1 as C); Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "1 as C").WithArguments("int", "C").WithLocation(9, 11), // (10,11): error CS0039: Cannot convert type 'string' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // M("a" as C); Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, @"""a"" as C").WithArguments("string", "C").WithLocation(10, 11), // (14,11): warning CS0184: The given expression is never of the provided ('C') type // M(null is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null is C").WithArguments("C").WithLocation(14, 11), // (15,11): warning CS0184: The given expression is never of the provided ('C') type // M(1 is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is C").WithArguments("C").WithLocation(15, 11), // (16,11): warning CS0184: The given expression is never of the provided ('C') type // M("a" is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, @"""a"" is C").WithArguments("C").WithLocation(16, 11) ); // in strict mode we also diagnose "is" and "as" operators with a static type. comp = comp.WithOptions(comp.Options.WithFeatures(new string[] { "strict" }.ToImmutableArray())); comp.VerifyDiagnostics( // In the native compiler these three produce no errors. Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "o as C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "new object() as C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "null as C").WithArguments("C"), // In the native compiler these two produce: // error CS0039: Cannot convert type 'int' to 'C' via a reference conversion, boxing conversion, // unboxing conversion, wrapping conversion, or null type conversion Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "1 as C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "\"a\" as C").WithArguments("C"), // In the native compiler these two produce no errors: Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "o is C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "new object() is C").WithArguments("C"), // In the native compiler these three produce: // warning CS0184: The given expression is never of the provided ('C') type Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "null is C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "1 is C").WithArguments("C"), Diagnostic(ErrorCode.ERR_StaticInAsOrIs, "\"a\" is C").WithArguments("C") ); } [Fact] public void CS0717ERR_ConstraintIsStaticClass() { var source = @"static class A { } class B { internal static class C { } } delegate void D<T, U>() where T : A where U : B.C;"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (4,15): error CS0717: 'A': static classes cannot be used as constraints Diagnostic(ErrorCode.ERR_ConstraintIsStaticClass, "A").WithArguments("A").WithLocation(4, 15), // (5,15): error CS0717: 'B.C': static classes cannot be used as constraints Diagnostic(ErrorCode.ERR_ConstraintIsStaticClass, "B.C").WithArguments("B.C").WithLocation(5, 15)); } [Fact] public void CS0718ERR_GenericArgIsStaticClass01() { var text = @"interface I<T> { } class C<T> { internal static void M() { } } static class S { static void M<T>() { I<S> i = null; C<S> c = null; C<S>.M(); M<S>(); object o = typeof(I<S>); } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (10,11): error CS0718: 'S': static types cannot be used as type arguments Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(10, 11), // (11,11): error CS0718: 'S': static types cannot be used as type arguments Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(11, 11), // (12,11): error CS0718: 'S': static types cannot be used as type arguments Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(12, 11), // (13,9): error CS0718: 'S': static types cannot be used as type arguments Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(13, 11), // (14,29): error CS0718: 'S': static types cannot be used as type arguments Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(14, 29), // (10,14): warning CS0219: The variable 'i' is assigned but its value is never used // I<S> i = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i"), // (11,14): warning CS0219: The variable 'c' is assigned but its value is never used // C<S> c = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c") ); } [Fact] public void CS0719ERR_ArrayOfStaticClass01() { var text = @"namespace NS { public static class C { } static class D<T> { } class Test { public static int Main() { var ca = new C[] { null }; var cd = new D<long>[9]; return 1; } } } "; // The native compiler produces two errors for "C[] X;" -- that C cannot be used // as the element type of an array, and that C[] is not a legal type for // a local because it is static. This seems unnecessary, redundant and wrong. // I've eliminated the second error; the first is sufficient to diagnose the issue. var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayOfStaticClass, Line = 14, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayOfStaticClass, Line = 15, Column = 26 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void ERR_VarDeclIsStaticClass02() { // The native compiler produces two errors for "C[] X;" -- that C cannot be used // as the element type of an array, and that C[] is not a legal type for // a field because it is static. This seems unnecessary, redundant and wrong. // I've eliminated the second error; the first is sufficient to diagnose the issue. var text = @"namespace NS { public static class C { } static class D<T> { } class Test { C[] X; C Y; D<int> Z; } }"; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (12,9): error CS0719: 'NS.C': array elements cannot be of static type // C[] X; Diagnostic(ErrorCode.ERR_ArrayOfStaticClass, "C").WithArguments("NS.C"), // (13,11): error CS0723: Cannot declare a variable of static type 'NS.C' // C Y; Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "Y").WithArguments("NS.C"), // (14,16): error CS0723: Cannot declare a variable of static type 'NS.D<int>' // D<int> Z; Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "Z").WithArguments("NS.D<int>"), // (12,13): warning CS0169: The field 'NS.Test.X' is never used // C[] X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("NS.Test.X"), // (13,11): warning CS0169: The field 'NS.Test.Y' is never used // C Y; Diagnostic(ErrorCode.WRN_UnreferencedField, "Y").WithArguments("NS.Test.Y"), // (14,16): warning CS0169: The field 'NS.Test.Z' is never used // D<int> Z; Diagnostic(ErrorCode.WRN_UnreferencedField, "Z").WithArguments("NS.Test.Z")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0720ERR_IndexerInStaticClass() { var text = @"public static class Test { public int this[int index] // CS0720 { get { return 1; } set {} } static void Main() {} } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IndexerInStaticClass, Line = 3, Column = 16 }); } [Fact] public void CS0721ERR_ParameterIsStaticClass01() { var text = @"namespace NS { public static class C { } public static class D<T> { } interface IFoo<T> { void M(D<T> d); // Dev10 no error? } class Test { public void F(C p) // CS0721 { } struct S { object M<T>(D<T> p1) // CS0721 { return null; } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription { Code = (int)ErrorCode.ERR_ParameterIsStaticClass, Line = 12, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParameterIsStaticClass, Line = 16, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParameterIsStaticClass, Line = 22, Column = 20 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0721ERR_ParameterIsStaticClass02() { var source = @"static class S { } class C { S P { set { } } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (4,11): error CS0721: 'S': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("S").WithLocation(4, 11)); } [Fact] public void CS0722ERR_ReturnTypeIsStaticClass01() { var source = @"namespace NS { public static class C { } public static class D<T> { } interface IFoo<T> { D<T> M(); // Dev10 no error? } class Test { extern public C F(); // CS0722 // { // return default(C); // } struct S { extern D<sbyte> M(); // CS0722 // { // return default(D<sbyte>); // } } } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (16,25): error CS0722: 'NS.C': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "F").WithArguments("NS.C").WithLocation(16, 25), // (23,29): error CS0722: 'NS.D<sbyte>': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "M").WithArguments("NS.D<sbyte>").WithLocation(23, 29), // (16,25): warning CS0626: Method, operator, or accessor 'NS.Test.F()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "F").WithArguments("NS.Test.F()").WithLocation(16, 25), // (23,29): warning CS0626: Method, operator, or accessor 'NS.Test.S.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("NS.Test.S.M()").WithLocation(23, 29)); } [Fact] public void CS0722ERR_ReturnTypeIsStaticClass02() { var source = @"static class S { } class C { S P { get { return null; } } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (4,11): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("S").WithLocation(4, 11)); } [WorkItem(530434, "DevDiv")] [Fact(Skip = "530434")] public void CS0722ERR_ReturnTypeIsStaticClass03() { var source = @"static class S { } class C { public abstract S F(); public abstract S P { get; } public abstract S Q { set; } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (4,23): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "F").WithArguments("S").WithLocation(4, 23), // (4,23): error CS0513: 'C.F()' is abstract but it is contained in non-abstract class 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "F").WithArguments("C.F()", "C").WithLocation(4, 23), // (5,27): error CS0513: 'C.P.get' is abstract but it is contained in non-abstract class 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.P.get", "C").WithLocation(5, 27), // (6,27): error CS0513: 'C.Q.set' is abstract but it is contained in non-abstract class 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.Q.set", "C").WithLocation(6, 27), // (5,27): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("S").WithLocation(5, 27), // (6,27): error CS0721: 'S': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("S").WithLocation(6, 27)); } [WorkItem(546540, "DevDiv")] [Fact] public void CS0722ERR_ReturnTypeIsStaticClass04() { var source = @"static class S1 { } static class S2 { } class C { public static S1 operator-(C c) { return null; } public static implicit operator S2(C c) { return null; } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (5,19): error CS0722: 'S1': static types cannot be used as return types // public static S1 operator-(C c) Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S1").WithArguments("S1"), // (9,37): error CS0722: 'S2': static types cannot be used as return types // public static implicit operator S2(C c) { return null; } Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S2").WithArguments("S2") ); } [Fact] public void CS0729ERR_ForwardedTypeInThisAssembly() { var csharp = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(Test))] public class Test { } "; CreateCompilationWithMscorlib(csharp).VerifyDiagnostics( // (4,12): error CS0729: Type 'Test' is defined in this assembly, but a type forwarder is specified for it // [assembly: TypeForwardedTo(typeof(Test))] Diagnostic(ErrorCode.ERR_ForwardedTypeInThisAssembly, "TypeForwardedTo(typeof(Test))").WithArguments("Test")); } [Fact] public void CS0730ERR_ForwardedTypeIsNested() { var text1 = @"public class C { public class CC { } } "; var text2 = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(C.CC))]"; var comp1 = CreateCompilationWithMscorlib(text1); var compRef1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib(text2, new MetadataReference[] { compRef1 }); comp2.VerifyDiagnostics( // (4,12): error CS0730: Cannot forward type 'C.CC' because it is a nested type of 'C' // [assembly: TypeForwardedTo(typeof(C.CC))] Diagnostic(ErrorCode.ERR_ForwardedTypeIsNested, "TypeForwardedTo(typeof(C.CC))").WithArguments("C.CC", "C")); } // See TypeForwarders.Cycle1, etc. //[Fact] //public void CS0731ERR_CycleInTypeForwarder() [Fact] public void CS0735ERR_InvalidFwdType() { var csharp = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(string[]))] [assembly: TypeForwardedTo(typeof(System.Int32*))] "; CreateCompilationWithMscorlib(csharp).VerifyDiagnostics( // (4,12): error CS0735: Invalid type specified as an argument for TypeForwardedTo attribute // [assembly: TypeForwardedTo(typeof(string[]))] Diagnostic(ErrorCode.ERR_InvalidFwdType, "TypeForwardedTo(typeof(string[]))"), // (5,12): error CS0735: Invalid type specified as an argument for TypeForwardedTo attribute // [assembly: TypeForwardedTo(typeof(System.Int32*))] Diagnostic(ErrorCode.ERR_InvalidFwdType, "TypeForwardedTo(typeof(System.Int32*))")); } [Fact] public void CS0736ERR_CloseUnimplementedInterfaceMemberStatic() { var text = @"namespace CS0736 { interface ITest { int testMethod(int x); } class Program : ITest // CS0736 { public static int testMethod(int x) { return 0; } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 8, Column = 21 }); } [Fact] public void CS0737ERR_CloseUnimplementedInterfaceMemberNotPublic() { var text = @"interface ITest { int Return42(); } struct Struct1 : ITest // CS0737 { int Return42() { return (42); } } public class Test { public static void Main(string[] args) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 6, Column = 18 }); } [Fact] public void CS0738ERR_CloseUnimplementedInterfaceMemberWrongReturnType() { var text = @" interface ITest { int TestMethod(); } public class Test : ITest { public void TestMethod() { } // CS0738 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 7, Column = 21 }); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_1() { var text = @"[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(int))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(int))] namespace cs0739 { class Program { static void Main(string[] args) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateTypeForwarder, Line = 2, Column = 12 }); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_2() { var csharp = @" using System.Collections.Generic; using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(System.Int32))] [assembly: TypeForwardedTo(typeof(int))] [assembly: TypeForwardedTo(typeof(List<string>))] [assembly: TypeForwardedTo(typeof(List<System.String>))] "; CreateCompilationWithMscorlib(csharp).VerifyDiagnostics( // (6,12): error CS0739: 'int' duplicate TypeForwardedToAttribute // [assembly: TypeForwardedTo(typeof(int))] Diagnostic(ErrorCode.ERR_DuplicateTypeForwarder, "TypeForwardedTo(typeof(int))").WithArguments("int"), // (9,12): error CS0739: 'System.Collections.Generic.List<string>' duplicate TypeForwardedToAttribute // [assembly: TypeForwardedTo(typeof(List<System.String>))] Diagnostic(ErrorCode.ERR_DuplicateTypeForwarder, "TypeForwardedTo(typeof(List<System.String>))").WithArguments("System.Collections.Generic.List<string>")); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_3() { var csharp = @" using System.Collections.Generic; using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(List<int>))] [assembly: TypeForwardedTo(typeof(List<char>))] [assembly: TypeForwardedTo(typeof(List<>))] "; CreateCompilationWithMscorlib(csharp).VerifyDiagnostics(); } [Fact] public void CS0750ERR_PartialMethodInvalidModifier() { var text = @" public class Base { protected virtual void PartG() { } protected void PartH() { } protected virtual void PartI() { } } public partial class C : Base { public partial void PartA(); private partial void PartB(); protected partial void PartC(); internal partial void PartD(); virtual partial void PartE(); abstract partial void PartF(); override partial void PartG(); new partial void PartH(); sealed override partial void PartI(); [System.Runtime.InteropServices.DllImport(""none"")] extern partial void PartJ(); public static int Main() { return 1; } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (19,25): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartA"), // (20,26): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartB"), // (21,28): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartC"), // (22,27): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartD"), // (23,26): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartE"), // (24,27): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartF"), // (25,27): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartG"), // (26,22): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartH"), // (27,34): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartI"), // (29,25): error CS0750: A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartJ"), // (28,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "System.Runtime.InteropServices.DllImport")); } [Fact] public void CS0751ERR_PartialMethodOnlyInPartialClass() { var text = @" public class C { partial void Part(); // CS0751 public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodOnlyInPartialClass, Line = 5, Column = 18 }); } [Fact] public void CS0752ERR_PartialMethodCannotHaveOutParameters() { var text = @" namespace NS { public partial class C { partial void F(out int x); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodCannotHaveOutParameters, Line = 7, Column = 22 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0753ERR_PartialMethodOnlyMethods() { var text = @" partial class C { partial int f; partial object P { get { return null; } } partial int this[int index] { get { return index; } } partial void M(); } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (5,17): error CS0753: Only methods, classes, structs, or interfaces may be partial // partial int f; Diagnostic(ErrorCode.ERR_PartialMethodOnlyMethods, "f"), // (6,20): error CS0753: Only methods, classes, structs, or interfaces may be partial // partial object P { get { return null; } } Diagnostic(ErrorCode.ERR_PartialMethodOnlyMethods, "P"), // (7,17): error CS0753: Only methods, classes, structs, or interfaces may be partial // partial int this[int index] Diagnostic(ErrorCode.ERR_PartialMethodOnlyMethods, "this"), // (5,17): warning CS0169: The field 'C.f' is never used // partial int f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C.f")); } [Fact] public void CS0754ERR_PartialMethodNotExplicit() { var text = @" public interface IF { void Part(); } public partial class C : IF { partial void IF.Part(); //CS0754 public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodNotExplicit, Line = 8, Column = 21 }); } [Fact] public void CS0755ERR_PartialMethodExtensionDifference() { var text = @"static partial class C { static partial void M1(this object o); static partial void M1(object o) { } static partial void M2(object o) { } static partial void M2(this object o); }"; var reference = SystemCoreRef; CreateCompilationWithMscorlib(text, references: new[] { reference }).VerifyDiagnostics( // (4,25): error CS0755: Both partial method declarations must be extension methods or neither may be an extension method Diagnostic(ErrorCode.ERR_PartialMethodExtensionDifference, "M1").WithLocation(4, 25), // (5,25): error CS0755: Both partial method declarations must be extension methods or neither may be an extension method Diagnostic(ErrorCode.ERR_PartialMethodExtensionDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0756ERR_PartialMethodOnlyOneLatent() { var text = @" public partial class C { partial void Part(); partial void Part(); // CS0756 public static int Main() { return 1; } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,18): error CS0756: A partial method may not have multiple defining declarations // partial void Part(); // CS0756 Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneLatent, "Part").WithLocation(5, 18)); } [Fact] public void CS0757ERR_PartialMethodOnlyOneActual() { var text = @" public partial class C { partial void Part(); partial void Part() { } partial void Part() // CS0757 { } public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodOnlyOneActual, Line = 8, Column = 18 }); } [Fact] public void CS0758ERR_PartialMethodParamsDifference() { var text = @"partial class C { partial void M1(params object[] args); partial void M1(object[] args) { } partial void M2(int n, params object[] args) { } partial void M2(int n, object[] args); }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,18): error CS0758: Both partial method declarations must use a parameter array or neither may use a parameter array Diagnostic(ErrorCode.ERR_PartialMethodParamsDifference, "M1").WithLocation(4, 18), // (5,18): error CS0758: Both partial method declarations must use a parameter array or neither may use a parameter array Diagnostic(ErrorCode.ERR_PartialMethodParamsDifference, "M2").WithLocation(5, 18)); } [Fact] public void CS0759ERR_PartialMethodMustHaveLatent() { var text = @"partial class C { partial void M1() { } partial void M2(); }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M1()' Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M1").WithArguments("C.M1()").WithLocation(3, 18)); } [WorkItem(542703, "DevDiv")] [Fact] public void CS0759ERR_PartialMethodMustHaveLatent_02() { var text = @"using System; static partial class EExtensionMethod { static partial void M(this Array a); } static partial class EExtensionMethod { static partial void M() { } } "; var reference = SystemCoreRef; CreateCompilationWithMscorlib(text, references: new[] { reference }).VerifyDiagnostics( // (9,25): error CS0759: No defining declaration found for implementing declaration of partial method'EExtensionMethod.M()' Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("EExtensionMethod.M()").WithLocation(9, 25)); } [Fact] public void CS0761ERR_PartialMethodInconsistentConstraints01() { var source = @"interface IA<T> { } interface IB { } partial class C<X> { // Different constraints: partial void A1<T>() where T : struct; partial void A2<T, U>() where T : struct where U : IA<T>; partial void A3<T>() where T : IA<T>; partial void A4<T, U>() where T : struct, IA<T>; // Additional constraints: partial void B1<T>(); partial void B2<T>() where T : X, new(); partial void B3<T, U>() where T : IA<T>; // Missing constraints. partial void C1<T>() where T : class; partial void C2<T>() where T : class, new(); partial void C3<T, U>() where U : IB, IA<T>; // Same constraints, different order. partial void D1<T>() where T : IA<T>, IB { } partial void D2<T, U, V>() where V : T, U, X { } // Different constraint clauses. partial void E1<T, U>() where U : T { } // Additional constraint clause. partial void F1<T, U>() where T : class { } // Missing constraint clause. partial void G1<T, U>() where T : class where U : T { } // Same constraint clauses, different order. partial void H1<T, U>() where T : class where U : T { } partial void H2<T, U>() where T : class where U : T { } partial void H3<T, U, V>() where V : class where U : IB where T : IA<V> { } // Different type parameter names. partial void K1<T, U>() where T : class where U : IA<T> { } partial void K2<T, U>() where T : class where U : T, IA<U> { } } partial class C<X> { // Different constraints: partial void A1<T>() where T : class { } partial void A2<T, U>() where T : struct where U : IB { } partial void A3<T>() where T : IA<IA<T>> { } partial void A4<T, U>() where T : struct, IA<U> { } // Additional constraints: partial void B1<T>() where T : new() { } partial void B2<T>() where T : class, X, new() { } partial void B3<T, U>() where T : IB, IA<T> { } // Missing constraints. partial void C1<T>() { } partial void C2<T>() where T : class { } partial void C3<T, U>() where U : IA<T> { } // Same constraints, different order. partial void D1<T>() where T : IB, IA<T>; partial void D2<T, U, V>() where V : U, X, T; // Different constraint clauses. partial void E1<T, U>() where T : class; // Additional constraint clause. partial void F1<T, U>() where T : class where U : T; // Missing constraint clause. partial void G1<T, U>() where T : class; // Same constraint clauses, different order. partial void H1<T, U>() where U : T where T : class; partial void H2<T, U>() where U : class where T : U; partial void H3<T, U, V>() where T : IA<V> where U : IB where V : class; // Different type parameter names. partial void K1<U, T>() where T : class where U : IA<T>; partial void K2<T1, T2>() where T1 : class where T2 : T1, IA<T2>; }"; // Note: Errors are reported on A1, A2, ... rather than A1<T>, A2<T, U>, ... See bug #9396. CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (38,18): error CS0761: Partial method declarations of 'C<X>.A1<T>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A1").WithArguments("C<X>.A1<T>()").WithLocation(38, 18), // (39,18): error CS0761: Partial method declarations of 'C<X>.A2<T, U>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A2").WithArguments("C<X>.A2<T, U>()").WithLocation(39, 18), // (40,18): error CS0761: Partial method declarations of 'C<X>.A3<T>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A3").WithArguments("C<X>.A3<T>()").WithLocation(40, 18), // (41,18): error CS0761: Partial method declarations of 'C<X>.A4<T, U>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A4").WithArguments("C<X>.A4<T, U>()").WithLocation(41, 18), // (43,18): error CS0761: Partial method declarations of 'C<X>.B1<T>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B1").WithArguments("C<X>.B1<T>()").WithLocation(43, 18), // (44,18): error CS0761: Partial method declarations of 'C<X>.B2<T>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B2").WithArguments("C<X>.B2<T>()").WithLocation(44, 18), // (45,18): error CS0761: Partial method declarations of 'C<X>.B3<T, U>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B3").WithArguments("C<X>.B3<T, U>()").WithLocation(45, 18), // (47,18): error CS0761: Partial method declarations of 'C<X>.C1<T>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C1").WithArguments("C<X>.C1<T>()").WithLocation(47, 18), // (48,18): error CS0761: Partial method declarations of 'C<X>.C2<T>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C2").WithArguments("C<X>.C2<T>()").WithLocation(48, 18), // (49,18): error CS0761: Partial method declarations of 'C<X>.C3<T, U>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C3").WithArguments("C<X>.C3<T, U>()").WithLocation(49, 18), // (22,18): error CS0761: Partial method declarations of 'C<X>.E1<T, U>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "E1").WithArguments("C<X>.E1<T, U>()").WithLocation(22, 18), // (24,18): error CS0761: Partial method declarations of 'C<X>.F1<T, U>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "F1").WithArguments("C<X>.F1<T, U>()").WithLocation(24, 18), // (26,18): error CS0761: Partial method declarations of 'C<X>.G1<T, U>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "G1").WithArguments("C<X>.G1<T, U>()").WithLocation(26, 18), // (29,18): error CS0761: Partial method declarations of 'C<X>.H2<T, U>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "H2").WithArguments("C<X>.H2<T, U>()").WithLocation(29, 18), // (32,18): error CS0761: Partial method declarations of 'C<X>.K1<T, U>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "K1").WithArguments("C<X>.K1<T, U>()").WithLocation(32, 18)); } [Fact] public void CS0761ERR_PartialMethodInconsistentConstraints02() { var source = @"using NIA = N.IA; using NIBA = N.IB<N.IA>; using NIBAC = N.IB<N.A.IC>; using NA = N.A; namespace N { interface IA { } interface IB<T> { } class A { internal interface IC { } } partial class C { partial void M1<T>() where T : A, NIBA; partial void M2<T>() where T : NA, IB<IA>; partial void M3<T, U>() where U : NIBAC; partial void M4<T, U>() where T : U, NIA; } partial class C { partial void M1<T>() where T : N.A, IB<IA> { } partial void M2<T>() where T : A, NIBA { } partial void M3<T, U>() where U : N.IB<A.IC> { } partial void M4<T, U>() where T : NIA { } } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (25,22): error CS0761: Partial method declarations of 'N.C.M4<T, U>()' have inconsistent type parameter constraints Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "M4").WithArguments("N.C.M4<T, U>()").WithLocation(25, 22)); } [Fact] public void CS0763ERR_PartialMethodStaticDifference() { var text = @"partial class C { static partial void M1(); partial void M1() { } static partial void M2() { } partial void M2(); }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,18): error CS0763: Both partial method declarations must be static or neither may be static Diagnostic(ErrorCode.ERR_PartialMethodStaticDifference, "M1").WithLocation(4, 18), // (5,25): error CS0763: Both partial method declarations must be static or neither may be static Diagnostic(ErrorCode.ERR_PartialMethodStaticDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0764ERR_PartialMethodUnsafeDifference() { var text = @"partial class C { unsafe partial void M1(); partial void M1() { } unsafe partial void M2() { } partial void M2(); }"; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,18): error CS0764: Both partial method declarations must be unsafe or neither may be unsafe Diagnostic(ErrorCode.ERR_PartialMethodUnsafeDifference, "M1").WithLocation(4, 18), // (5,25): error CS0764: Both partial method declarations must be unsafe or neither may be unsafe Diagnostic(ErrorCode.ERR_PartialMethodUnsafeDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0766ERR_PartialMethodMustReturnVoid() { var text = @" public partial class C { partial int Part(); // CS0766 partial int Part() //CS0766 { return 1; } public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodMustReturnVoid, Line = 5, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodMustReturnVoid, Line = 6, Column = 17 }); } [Fact] public void CS0767ERR_ExplicitImplCollisionOnRefOut() { var text = @"interface IFace<T> { void Foo(ref T x); void Foo(out int x); } class A : IFace<int> { void IFace<int>.Foo(ref int x) { } void IFace<int>.Foo(out int x) { x = 0; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitImplCollisionOnRefOut, Line = 1, Column = 11 }, //error for IFace<int, int>.Foo(ref int) new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitImplCollisionOnRefOut, Line = 1, Column = 11 } //error for IFace<int, int>.Foo(out int) ); } [Fact] public void CS0825ERR_TypeVarNotFound01() { var text = @"namespace NS { class Test { static var myStaticField; extern private var M(); void MM(ref var v) { } } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (6,24): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // extern private var M(); Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (7,21): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // void MM(ref var v) { } Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (5,16): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // static var myStaticField; Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (6,28): warning CS0626: Method, operator, or accessor 'NS.Test.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern private var M(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("NS.Test.M()"), // (5,20): warning CS0169: The field 'NS.Test.myStaticField' is never used // static var myStaticField; Diagnostic(ErrorCode.WRN_UnreferencedField, "myStaticField").WithArguments("NS.Test.myStaticField") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0842ERR_ExplicitLayoutAndAutoImplementedProperty() { var text = @" using System.Runtime.InteropServices; namespace TestNamespace { [StructLayout(LayoutKind.Explicit)] struct Str { public int Num // CS0842 { get; set; } static int Main() { return 1; } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (9,20): error CS0842: 'TestNamespace.Str.Num': Automatically implemented properties cannot be used inside a type marked with StructLayout(LayoutKind.Explicit) Diagnostic(ErrorCode.ERR_ExplicitLayoutAndAutoImplementedProperty, "Num").WithArguments("TestNamespace.Str.Num")); } [Fact] [WorkItem(1032724)] public void CS0842ERR_ExplicitLayoutAndAutoImplementedProperty_Bug1032724() { var text = @" using System.Runtime.InteropServices; namespace TestNamespace { [StructLayout(LayoutKind.Explicit)] struct Str { public static int Num { get; set; } static int Main() { return 1; } } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics(); } [Fact] public void CS0851ERR_OverloadRefOutCtor() { var text = @"namespace TestNamespace { class MyClass { public MyClass(ref int num) { } public MyClass(out int num) { num = 1; } } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,17): error CS0851: Cannot define overloaded constructor 'TestNamespace.MyClass' because it differs from another constructor only on ref and out Diagnostic(ErrorCode.ERR_OverloadRefOutCtor, "MyClass").WithArguments("TestNamespace.MyClass")); } [Fact] public void CS1014ERR_GetOrSetExpected() { DiagnosticsUtils.TestDiagnostics( @"partial class C { public object P { partial get; set; } object Q { get { return 0; } add { } } } ", "'partial' error CS1014: A get or set accessor expected", "'add' error CS1014: A get or set accessor expected"); } [Fact] public void CS1057ERR_ProtectedInStatic01() { var text = @"namespace NS { public static class B { protected static object field = null; internal protected static void M() {} } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 5, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 6, Column = 40 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CanNotDeclareProtectedPropertyInStaticClass() { const string text = @" static class B { protected static int X { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 33 }); } [Fact] public void CanNotDeclareProtectedInternalPropertyInStaticClass() { const string text = @" static class B { internal static protected int X { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 37 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 42 }); } [Fact] public void CanNotDeclarePropertyWithProtectedInternalAccessorInStaticClass() { const string text = @" static class B { public static int X { get; protected internal set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic }); } /// <summary> /// variance /// </summary> [Fact] public void CS1067ERR_PartialWrongTypeParamsVariance01() { var text = @"namespace NS { //combinations partial interface I1<in T> { } partial interface I1<out T> { } partial interface I2<in T> { } partial interface I2<T> { } partial interface I3<T> { } partial interface I3<out T> { } //no duplicate errors partial interface I4<T, U> { } partial interface I4<out T, out U> { } //prefer over CS0264 partial interface I5<S> { } partial interface I5<out T> { } //no error after CS0264 partial interface I6<R, in T> { } partial interface I6<S, out T> { } //no error since arities don't match partial interface I7<T> { } partial interface I7<in T, U> { } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,23): error CS1067: Partial declarations of 'NS.I1<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I1").WithArguments("NS.I1<T>"), // (7,23): error CS1067: Partial declarations of 'NS.I2<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I2").WithArguments("NS.I2<T>"), // (10,23): error CS1067: Partial declarations of 'NS.I3<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I3").WithArguments("NS.I3<T>"), // (14,23): error CS1067: Partial declarations of 'NS.I4<T, U>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I4").WithArguments("NS.I4<T, U>"), // (18,23): error CS1067: Partial declarations of 'NS.I5<S>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I5").WithArguments("NS.I5<S>"), // (22,23): error CS0264: Partial declarations of 'NS.I6<R, T>' must have the same type parameter names in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParams, "I6").WithArguments("NS.I6<R, T>")); } [Fact] public void CS1100ERR_BadThisParam() { var text = @"static class Test { static void ExtMethod(int i, this Foo1 c) // CS1100 { } } class Foo1 { }"; var compilation = CreateCompilationWithMscorlib(text); compilation.VerifyDiagnostics( // (3,34): error CS1100: Method 'ExtMethod' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("ExtMethod").WithLocation(3, 34)); } [Fact] public void CS1103ERR_BadTypeforThis01() { // Note that the dev11 compiler does not report error CS0721, that C cannot be used as a parameter type. // This appears to be a shortcoming of the dev11 compiler; there is no good reason to not report the error. var reference = SystemCoreRef; var compilation = CreateCompilationWithMscorlib( @"static class C { static void M1(this Unknown u) { } static void M2(this C c) { } static void M3(this dynamic d) { } static void M4(this dynamic[] d) { } }", references: new[] { reference }); compilation.VerifyDiagnostics( // (3,25): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown"), // (4,17): error CS0721: 'C': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M2").WithArguments("C"), // (5,25): error CS1103: The first parameter of an extension method cannot be of type 'dynamic' Diagnostic(ErrorCode.ERR_BadTypeforThis, "dynamic").WithArguments("dynamic")); } [Fact] public void CS1103ERR_BadTypeforThis02() { CreateCompilationWithMscorlib( @"public static class Extensions { public unsafe static char* Test(this char* charP) { return charP; } // CS1103 } ", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadTypeforThis, "char*").WithArguments("char*").WithLocation(3, 42)); } [Fact] public void CS1105ERR_BadExtensionMeth() { var text = @"public class Extensions { public void Test<T>(this System.String s) { } //CS1105 } "; var reference = SystemCoreRef; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new List<MetadataReference> { reference }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadExtensionAgg, Line = 1, Column = 14 }); } [Fact] public void CS1106ERR_BadExtensionAgg01() { var reference = SystemCoreRef; var compilation = CreateCompilationWithMscorlib( @"class A { static void M(this object o) { } } class B { static void M<T>(this object o) { } } static class C<T> { static void M(this object o) { } } static class D<T> { static void M<U>(this object o) { } } struct S { static void M(this object o) { } } struct T { static void M<U>(this object o) { } } struct U<T> { static void M(this object o) { } }", references: new[] { reference }); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadExtensionAgg, "A").WithLocation(1, 7), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "B").WithLocation(5, 7), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "C").WithLocation(9, 14), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "D").WithLocation(13, 14), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "S").WithLocation(17, 8), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "T").WithLocation(21, 8), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "U").WithLocation(25, 8)); } [WorkItem(528256, "DevDiv")] [Fact()] public void CS1106ERR_BadExtensionAgg02() { CreateCompilationWithMscorlib( @"interface I { static void M(this object o); }") .VerifyDiagnostics( // (1,11): error CS1106: Extension method must be defined in a non-generic static class // interface I Diagnostic(ErrorCode.ERR_BadExtensionAgg, "I").WithLocation(1, 11), // (3,17): error CS0106: The modifier 'static' is not valid for this item // static void M(this object o); Diagnostic(ErrorCode.ERR_BadMemberFlag, "M").WithArguments("static").WithLocation(3, 17)); } [Fact] public void CS1109ERR_ExtensionMethodsDecl() { var reference = SystemCoreRef; var compilation = CreateCompilationWithMscorlib( @"class A { static class C { static void M(this object o) { } } } static class B { static class C { static void M(this object o) { } } } struct S { static class C { static void M(this object o) { } } }", references: new[] { reference }); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(5, 21), Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(12, 21), Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(19, 21)); } [Fact] public void CS1110ERR_ExtensionAttrNotFound() { //Extension method cannot be declared without a reference to System.Core.dll var source = @"static class A { public static void M1(this object o) { } public static void M2(this string s, this object o) { } public static void M3(this dynamic d) { } } class B { public static void M4(this object o) { } }"; var compilation = CreateCompilationWithMscorlib(source); compilation.VerifyDiagnostics( // (3,27): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(3, 27), // (4,27): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(4, 27), // (4,42): error CS1100: Method 'M2' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("M2").WithLocation(4, 42), // (5,32): error CS1103: The first parameter of an extension method cannot be of type 'dynamic' Diagnostic(ErrorCode.ERR_BadTypeforThis, "dynamic").WithArguments("dynamic").WithLocation(5, 32), // (5,32): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference? Diagnostic(ErrorCode.ERR_DynamicAttributeMissing, "dynamic").WithArguments("System.Runtime.CompilerServices.DynamicAttribute").WithLocation(5, 32), // (7,7): error CS1106: Extension methods must be defined in a non-generic static class Diagnostic(ErrorCode.ERR_BadExtensionAgg, "B").WithLocation(7, 7)); } [Fact] public void CS1112ERR_ExplicitExtension() { var source = @"using System.Runtime.CompilerServices; [System.Runtime.CompilerServices.ExtensionAttribute] static class A { static void M(object o) { } } static class B { [Extension] static void M() { } [ExtensionAttribute] static void M(this object o) { } [Extension] static object P { [Extension] get { return null; } } [Extension(0)] static object F; }"; var compilation = CreateCompilationWithMscorlib(source, references: new[] { SystemCoreRef }); compilation.VerifyDiagnostics( // (2,2): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [System.Runtime.CompilerServices.ExtensionAttribute] Diagnostic(ErrorCode.ERR_ExplicitExtension, "System.Runtime.CompilerServices.ExtensionAttribute"), // (9,6): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension"), // (11,6): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [ExtensionAttribute] Diagnostic(ErrorCode.ERR_ExplicitExtension, "ExtensionAttribute"), // (13,6): error CS0592: Attribute 'Extension' is not valid on this declaration type. It is only valid on 'assembly, class, method' declarations. // [Extension] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Extension").WithArguments("Extension", "assembly, class, method"), // (16,10): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension"), // (19,6): error CS1729: 'System.Runtime.CompilerServices.ExtensionAttribute' does not contain a constructor that takes 1 arguments // [Extension(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Extension(0)").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute", "1"), // (20,19): warning CS0169: The field 'B.F' is never used // static object F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("B.F")); } [Fact] public void CS1509ERR_ImportNonAssembly() { //CSC /TARGET:library /reference:class1.netmodule text.CS var text = @"class Test { public static int Main() { return 1; } }"; var ref1 = AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(display: "NetModule.mod"); CreateCompilationWithMscorlib(text, new[] { ref1 }).VerifyDiagnostics( // error CS1509: The referenced file 'NetModule.mod' is not an assembly Diagnostic(ErrorCode.ERR_ImportNonAssembly).WithArguments(@"NetModule.mod")); } [Fact] public void CS1527ERR_NoNamespacePrivate1() { var text = @"private class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 15 } //pos = the class name ); } [Fact] public void CS1527ERR_NoNamespacePrivate2() { var text = @"protected class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 17 } //pos = the class name ); } [Fact] public void CS1527ERR_NoNamespacePrivate3() { var text = @"protected internal class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 26 } //pos = the class name ); } [Fact] public void CS1537ERR_DuplicateAlias1() { var text = @"using A = System; using A = System; namespace NS { using O = System.Object; using O = System.Object; }"; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (2,7): error CS1537: The using alias 'A' appeared previously in this namespace // using A = System; Diagnostic(ErrorCode.ERR_DuplicateAlias, "A").WithArguments("A"), // (7,11): error CS1537: The using alias 'O' appeared previously in this namespace // using O = System.Object; Diagnostic(ErrorCode.ERR_DuplicateAlias, "O").WithArguments("O"), // (1,1): info CS8019: Unnecessary using directive. // using A = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = System;"), // (2,1): info CS8019: Unnecessary using directive. // using A = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = System;"), // (6,5): info CS8019: Unnecessary using directive. // using O = System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using O = System.Object;"), // (7,5): info CS8019: Unnecessary using directive. // using O = System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using O = System.Object;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [WorkItem(537684, "DevDiv")] [Fact] public void CS1537ERR_DuplicateAlias2() { var text = @"namespace namespace1 { class A { } } namespace namespace2 { class B { } } namespace NS { using ns = namespace1; using ns = namespace2; using System; class C : ns.A { } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (14,11): error CS1537: The using alias 'ns' appeared previously in this namespace // using ns = namespace2; Diagnostic(ErrorCode.ERR_DuplicateAlias, "ns").WithArguments("ns"), // (14,5): info CS8019: Unnecessary using directive. // using ns = namespace2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using ns = namespace2;"), // (15,5): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetMembers("C").Single() as NamedTypeSymbol; var b = type1.BaseType; } [Fact] public void CS1537ERR_DuplicateAlias3() { var text = @"using X = System; using X = ABC.X<int>;"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (2,7): error CS1537: The using alias 'X' appeared previously in this namespace // using X = ABC.X<int>; Diagnostic(ErrorCode.ERR_DuplicateAlias, "X").WithArguments("X"), // (1,1): info CS8019: Unnecessary using directive. // using X = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = System;"), // (2,1): info CS8019: Unnecessary using directive. // using X = ABC.X<int>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = ABC.X<int>;")); } [WorkItem(539125, "DevDiv")] [Fact] public void CS1542ERR_AddModuleAssembly() { //CSC /addmodule:cs1542.dll /TARGET:library text1.cs var text = @"public class Foo : IFoo { public void M0() { } }"; var ref1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.CorLibrary.NoMsCorLibRef).GetReference(display: "NoMsCorLibRef.mod"); CreateCompilationWithMscorlib(text, references: new[] { ref1 }).VerifyDiagnostics( // error CS1542: 'NoMsCorLibRef.mod' cannot be added to this assembly because it already is an assembly Diagnostic(ErrorCode.ERR_AddModuleAssembly).WithArguments(@"NoMsCorLibRef.mod"), // (1,20): error CS0246: The type or namespace name 'IFoo' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IFoo").WithArguments("IFoo")); } [Fact, WorkItem(544910, "DevDiv")] public void CS1599ERR_MethodReturnCantBeRefAny() { var text = @" using System; interface I { ArgIterator M(); // 1599 } class C { public delegate TypedReference Test1(); // 1599 public RuntimeArgumentHandle Test2() // 1599 { return default(RuntimeArgumentHandle); } // The native compiler does not catch this one; Roslyn does. public static ArgIterator operator +(C c1, C c2) // 1599 { return default(ArgIterator); } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,5): error CS1599: Method or delegate cannot return type 'System.ArgIterator' // ArgIterator M(); // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator"), // (11,12): error CS1599: Method or delegate cannot return type 'System.RuntimeArgumentHandle' // public RuntimeArgumentHandle Test2() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle"), // (17,19): error CS1599: Method or delegate cannot return type 'System.ArgIterator' // public static ArgIterator operator +(C c1, C c2) // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator"), // (9,21): error CS1599: Method or delegate cannot return type 'System.TypedReference' // public delegate TypedReference Test1(); // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "TypedReference").WithArguments("System.TypedReference") ); } [Fact, WorkItem(544910, "DevDiv")] public void CS1601ERR_MethodArgCantBeRefAny() { // We've changed the text of the error message from // CS1601: Method or delegate parameter cannot be of type 'ref System.TypedReference' // to // CS1601: Cannot make reference to variable of type 'System.TypedReference' // because we use this error message at both the call site and the declaration. // The new wording makes sense in both uses; the former only makes sense at // the declaration site. var text = @" using System; class MyClass { delegate void D(ref TypedReference t1); // CS1601 public void Test1(ref TypedReference t2, RuntimeArgumentHandle r3) // CS1601 { var x = __makeref(r3); // CS1601 } public void Test2(out ArgIterator t4) // CS1601 { t4 = default(ArgIterator); } MyClass(ref RuntimeArgumentHandle r5) {} // CS1601 } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,23): error CS1601: Cannot make reference to variable of type 'System.TypedReference' // public void Test1(ref TypedReference t2, RuntimeArgumentHandle r3) // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref TypedReference t2").WithArguments("System.TypedReference"), // (11,23): error CS1601: Cannot make reference to variable of type 'System.ArgIterator' // public void Test2(out ArgIterator t4) // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out ArgIterator t4").WithArguments("System.ArgIterator"), // (16,13): error CS1601: Cannot make reference to variable of type 'System.RuntimeArgumentHandle' // MyClass(ref RuntimeArgumentHandle r5) {} // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref RuntimeArgumentHandle r5").WithArguments("System.RuntimeArgumentHandle"), // (5,21): error CS1601: Cannot make reference to variable of type 'System.TypedReference' // delegate void D(ref TypedReference t1); // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref TypedReference t1").WithArguments("System.TypedReference"), // (8,17): error CS1601: Cannot make reference to variable of type 'System.RuntimeArgumentHandle' // var x = __makeref(r3); // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "__makeref(r3)").WithArguments("System.RuntimeArgumentHandle") ); } [WorkItem(542003, "DevDiv")] [Fact] public void CS1608ERR_CantUseRequiredAttribute() { var text = @"using System.Runtime.CompilerServices; [RequiredAttribute(typeof(object))] class ClassMain { }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,2): error CS1608: The Required attribute is not permitted on C# types // [RequiredAttribute(typeof(object))] Diagnostic(ErrorCode.ERR_CantUseRequiredAttribute, "RequiredAttribute").WithLocation(3, 2)); } [Fact] public void CS1614ERR_AmbiguousAttribute() { var text = @"using System; class A : Attribute { } class AAttribute : Attribute { } [A][@A][AAttribute] class C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigousAttribute, Line = 4, Column = 2 }); } [Fact] public void CS0214ERR_RequiredInUnsafeContext() { var text = @"struct C { public fixed int ab[10]; // CS0214 } "; var comp = CreateCompilationWithMscorlib(text, options: TestOptions.ReleaseDll); // (3,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public fixed string ab[10]; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "ab[10]"); } [Fact] public void CS1642ERR_FixedNotInStruct() { var text = @"unsafe class C { fixed int a[10]; // CS1642 }"; var comp = CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (3,15): error CS1642: Fixed size buffer fields may only be members of structs // fixed int a[10]; // CS1642 Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a")); } [Fact] public void CS1663ERR_IllegalFixedType() { var text = @"unsafe struct C { fixed string ab[10]; // CS1663 }"; var comp = CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (3,11): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // fixed string ab[10]; // CS1663 Diagnostic(ErrorCode.ERR_IllegalFixedType, "string")); } [WorkItem(545353, "DevDiv")] [Fact] public void CS1664ERR_FixedOverflow() { // set Allow unsafe code = true var text = @"public unsafe struct C { unsafe private fixed long test_1[1073741825]; }"; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,38): error CS1664: Fixed size buffer of length '1073741825' and type 'long' is too big // unsafe private fixed long test_1[1073741825]; Diagnostic(ErrorCode.ERR_FixedOverflow, "1073741825").WithArguments("1073741825", "long")); } [WorkItem(545353, "DevDiv")] [Fact] public void CS1665ERR_InvalidFixedArraySize() { var text = @"unsafe struct S { public unsafe fixed int A[0]; // CS1665 } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,31): error CS1665: Fixed size buffers must have a length greater than zero // public unsafe fixed int A[0]; // CS1665 Diagnostic(ErrorCode.ERR_InvalidFixedArraySize, "0")); } [WorkItem(546922, "DevDiv")] [Fact] public void CS1665ERR_InvalidFixedArraySizeNegative() { var text = @"unsafe struct S { public unsafe fixed int A[-1]; // CS1665 } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_InvalidFixedArraySize, "-1")); } [Fact()] public void CS0443ERR_InvalidFixedArraySizeNotSpecified() { var text = @"unsafe struct S { public unsafe fixed int A[]; // CS0443 } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,31): error CS0443: Syntax error; value expected // public unsafe fixed int A[]; // CS0443 Diagnostic(ErrorCode.ERR_ValueExpected, "]")); } [Fact] public void CS1003ERR_InvalidFixedArrayMultipleDimensions() { var text = @"unsafe struct S { public unsafe fixed int A[2,2]; // CS1003,CS1001 public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,33): error CS1002: ; expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_SemicolonExpected, "["), // (4,34): error CS1001: Identifier expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_IdentifierExpected, "2"), // (4,34): error CS1001: Identifier expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_IdentifierExpected, "2"), // (4,36): error CS1519: Invalid token ';' in class, struct, or interface member declaration // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";"), // (3,30): error CS7092: A fixed buffer may only have one dimension. // public unsafe fixed int A[2,2]; // CS1003,CS1001 Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[2,2]")); } [Fact] public void CS1642ERR_InvalidFixedBufferNested() { var text = @"unsafe struct S { unsafe class Err_OnlyOnInstanceInStructure { public fixed bool _bufferInner[10]; //Valid } public fixed bool _bufferOuter[10]; // error CS1642: Fixed size buffer fields may only be members of structs } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,31): error CS1642: Fixed size buffer fields may only be members of structs // public fixed bool _bufferInner[10]; //Valid Diagnostic(ErrorCode.ERR_FixedNotInStruct, "_bufferInner")); } [Fact] public void CS1642ERR_InvalidFixedBufferNested_2() { var text = @"unsafe class S { unsafe struct Err_OnlyOnInstanceInStructure { public fixed bool _bufferInner[10]; // Valid } public fixed bool _bufferOuter[10]; // error CS1642: Fixed size buffer fields may only be members of structs } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,31): error CS1642: Fixed size buffer fields may only be members of structs // public fixed bool _bufferOuter[10]; //Valid Diagnostic(ErrorCode.ERR_FixedNotInStruct, "_bufferOuter")); } [Fact] public void CS0133ERR_InvalidFixzedBufferCountFromField() { var text = @"unsafe struct s { public static int var1 = 10; public fixed bool _Type3[var1]; // error CS0133: The expression being assigned to '<Type>' must be constant } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,34): error CS0133: The expression being assigned to 's._Type3' must be constant // public fixed bool _Type3[var1]; // error CS0133: The expression being assigned to '<Type>' must be constant Diagnostic(ErrorCode.ERR_NotConstantExpression, "var1").WithArguments("s._Type3")); } [Fact] public void CS1663ERR_InvalidFixedBufferUsingGenericType() { var text = @"unsafe struct Err_FixedBufferDeclarationUsingGeneric<t> { public fixed t _Type1[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed t _Type1[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "t")); } [Fact] public void CS0029ERR_InvalidFixedBufferNonValidTypes() { var text = @"unsafe struct s { public fixed int _Type1[1.2]; // error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) public fixed int _Type2[true]; // error CS00029 public fixed int _Type3[""true""]; // error CS00029 public fixed int _Type4[System.Convert.ToInt32(@""1"")]; // error CS0133 } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,33): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // public fixed int _Type1[1.2]; // error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.2").WithArguments("double", "int"), // (4,33): error CS0029: Cannot implicitly convert type 'bool' to 'int' // public fixed int _Type2[true]; // error CS00029 Diagnostic(ErrorCode.ERR_NoImplicitConv, "true").WithArguments("bool", "int"), // (5,33): error CS0029: Cannot implicitly convert type 'string' to 'int' // public fixed int _Type3["true"]; // error CS00029 Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""true""").WithArguments("string", "int"), // (6,33): error CS0133: The expression being assigned to 's._Type4' must be constant // public fixed int _Type4[System.Convert.ToInt32(@"1")]; // error CS0133 Diagnostic(ErrorCode.ERR_NotConstantExpression, @"System.Convert.ToInt32(@""1"")").WithArguments("s._Type4")); } [Fact] public void CS0029ERR_InvalidFixedBufferNonValidTypesUserDefinedTypes() { var text = @"unsafe struct s { public fixed foo _bufferFoo[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double public fixed bar _bufferBar[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double } struct foo { public int ABC; } class bar { public bool ABC = true; } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed foo _bufferFoo[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "foo"), // (4,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed bar _bufferBar[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "bar"), // (9,20): warning CS0649: Field 'foo.ABC' is never assigned to, and will always have its default value 0 // public int ABC; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ABC").WithArguments("foo.ABC", "0")); } [Fact] public void C1666ERR_InvalidFixedBufferInUnfixedContext() { var text = @" unsafe struct s { private fixed ushort _e_res[4]; void Error_UsingFixedBuffersWiththis() { ushort c = this._e_res; } } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,24): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement. // ushort c = this._e_res; Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "this._e_res")); } [Fact] public void CS0029ERR_InvalidFixedBufferUsageInLocal() { //Some additional errors generated but the key ones from native are here. var text = @"unsafe struct s { //Use as local rather than field with unsafe on method // Incorrect usage of fixed buffers in method bodies try to use as a local static unsafe void Error_UseAsLocal() { //Invalid In Use as Local fixed bool _buffer[2]; // error CS1001: Identifier expected } } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,15): error CS1003: Syntax error, '(' expected // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_SyntaxError, "bool").WithArguments("(", "bool"), // (8,27): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_CStyleArray, "[2]"), // (8,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "2"), // (8,30): error CS1026: ) expected // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_CloseParenExpected, ";"), // (8,30): warning CS0642: Possible mistaken empty statement // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), // (8,20): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_BadFixedInitType, "_buffer[2]"), // (8,20): error CS0210: You must provide an initializer in a fixed or using statement declaration // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_FixedMustInit, "_buffer[2]")); } [Fact()] public void CS1667ERR_AttributeNotOnAccessor() { var text = @"using System; public class C { private int i; public int ObsoleteProperty { [Obsolete] // CS1667 get { return i; } [System.Diagnostics.Conditional(""Bernard"")] set { i = value; } } public static void Main() { } } "; var comp = CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,10): error CS1667: Attribute 'Obsolete' is not valid on property or event accessors. It is only valid on 'class, struct, enum, constructor, method, property, indexer, field, event, interface, delegate' declarations. // [Obsolete] // CS1667 Diagnostic(ErrorCode.ERR_AttributeNotOnAccessor, "Obsolete").WithArguments("System.ObsoleteAttribute", "class, struct, enum, constructor, method, property, indexer, field, event, interface, delegate"), // (10,10): error CS1667: Attribute 'System.Diagnostics.Conditional' is not valid on property or event accessors. It is only valid on 'class, method' declarations. // [System.Diagnostics.Conditional("Bernard")] Diagnostic(ErrorCode.ERR_AttributeNotOnAccessor, "System.Diagnostics.Conditional").WithArguments("System.Diagnostics.Conditional", "class, method") ); } [Fact] public void CS1689ERR_ConditionalOnNonAttributeClass() { var text = @"[System.Diagnostics.Conditional(""A"")] // CS1689 class MyClass {} "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (1,2): error CS1689: Attribute 'System.Diagnostics.Conditional' is only valid on methods or attribute classes // [System.Diagnostics.Conditional("A")] // CS1689 Diagnostic(ErrorCode.ERR_ConditionalOnNonAttributeClass, @"System.Diagnostics.Conditional(""A"")").WithArguments("System.Diagnostics.Conditional").WithLocation(1, 2)); } // CS1703ERR_DuplicateImport: See ReferenceManagerTests.CS1703ERR_DuplicateImport // CS1704ERR_DuplicateImportSimple: See ReferenceManagerTests.CS1704ERR_DuplicateImportSimple [Fact(Skip = "530901"), WorkItem(530901, "DevDiv")] public void CS1705ERR_AssemblyMatchBadVersion() { // compile with: /target:library /out:c:\\cs1705.dll /keyfile:mykey.snk var text1 = @"[assembly:System.Reflection.AssemblyVersion(""1.0"")] public class A { public void M1() {} public class N1 {} public void M2() {} public class N2 {} } public class C1 {} public class C2 {} "; var tree1 = SyntaxFactory.ParseCompilationUnit(text1); // compile with: /target:library /out:cs1705.dll /keyfile:mykey.snk var text2 = @"using System.Reflection; [assembly:AssemblyVersion(""2.0"")] public class A { public void M2() {} public class N2 {} public void M1() {} public class N1 {} } public class C2 {} public class C1 {} "; var tree2 = SyntaxFactory.ParseCompilationUnit(text2); // compile with: /target:library /r:A2=c:\\CS1705.dll /r:A1=CS1705.dll var text3 = @"extern alias A1; extern alias A2; using a1 = A1::A; using a2 = A2::A; using n1 = A1::A.N1; using n2 = A2::A.N2; public class Ref { public static a1 A1() { return new a1(); } public static a2 A2() { return new a2(); } public static A1::C1 M1() { return new A1::C1(); } public static A2::C2 M2() { return new A2::C2(); } public static n1 N1() { return new a1.N1(); } public static n2 N2() { return new a2.N2(); } } "; var tree3 = SyntaxFactory.ParseCompilationUnit(text3); // compile with: /reference:c:\\CS1705.dll /reference:CS1705_c.dll var text = @"class Tester { static void Main() { Ref.A1().M1(); Ref.A2().M2(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AssemblyMatchBadVersion, Line = 2, Column = 12 }); } [Fact] public void CS1715ERR_CantChangeTypeOnOverride() { var text = @"abstract public class Base { abstract public int myProperty { get; set; } } public class Derived : Base { int myField; public override double myProperty // CS1715 { get { return myField; } set { myField= 1; } } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 10, Column = 14 }, //Base.myProperty.get not impl new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 10, Column = 14 }, //Base.myProperty.set not impl // COMPARE: InheritanceBindingTests.TestNoPropertyToOverride new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeTypeOnOverride, Line = 13, Column = 28 } //key error, property type changed ); } [Fact] public void CS1716ERR_DoNotUseFixedBufferAttr() { var text = @" using System.Runtime.CompilerServices; public struct UnsafeStruct { [FixedBuffer(typeof(int), 4)] // CS1716 unsafe public int aField; } public class TestUnsafe { static void Main() { } } "; CreateCompilationWithMscorlib(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,6): error CS1716: Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead. // [FixedBuffer(typeof(int), 4)] // CS1716 Diagnostic(ErrorCode.ERR_DoNotUseFixedBufferAttr, "FixedBuffer").WithLocation(6, 6)); } [Fact] public void CS1721ERR_NoMultipleInheritance01() { var text = @"namespace NS { public class A { } public class B { } public class C : B { } public class MyClass : A, A { } // CS1721 public class MyClass2 : A, B { } // CS1721 public class MyClass3 : C, A { } // CS1721 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 6, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 7, Column = 32 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 8, Column = 32 }); } [Fact] public void CS1722ERR_BaseClassMustBeFirst01() { var text = @"namespace NS { public class A { } interface I { } interface IFoo<T> : I { } public class MyClass : I, A { } // CS1722 public class MyClass2 : A, I { } // OK class Test { class C : IFoo<int>, A , I { } // CS1722 } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 7, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 12, Column = 30 }); } [Fact(), WorkItem(530393, "DevDiv")] public void CS1724ERR_InvalidDefaultCharSetValue() { var text = @" using System.Runtime.InteropServices; [module: DefaultCharSetAttribute((CharSet)42)] // CS1724 class C { [DllImport(""F.Dll"")] extern static void FW1Named(); static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,34): error CS0591: Invalid value for argument to 'DefaultCharSetAttribute' attribute // [module: DefaultCharSetAttribute((CharSet)42)] // CS1724 Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "(CharSet)42").WithArguments("DefaultCharSetAttribute") ); } [Fact] public void CS1725ERR_FriendAssemblyBadArgs() { var text = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Test, Version=*"")] // ok [assembly: InternalsVisibleTo(""Test, PublicKeyToken=*"")] // ok [assembly: InternalsVisibleTo(""Test, Culture=*"")] // ok [assembly: InternalsVisibleTo(""Test, Retargetable=*"")] // ok [assembly: InternalsVisibleTo(""Test, ContentType=*"")] // ok [assembly: InternalsVisibleTo(""Test, Version=."")] // ok [assembly: InternalsVisibleTo(""Test, Version=.."")] // ok [assembly: InternalsVisibleTo(""Test, Version=..."")] // ok [assembly: InternalsVisibleTo(""Test, Version=1"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.*"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.1.*"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.1.1.*"")] // error [assembly: InternalsVisibleTo(""Test, ProcessorArchitecture=MSIL"")] // error [assembly: InternalsVisibleTo(""Test, CuLTure=EN"")] // error "; // Tested against Dev12 CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (12,12): error CS1725: Friend assembly reference 'Test, Version=1' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1"")").WithArguments("Test, Version=1").WithLocation(12, 12), // (13,12): error CS1725: Friend assembly reference 'Test, Version=1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.*"")").WithArguments("Test, Version=1.*").WithLocation(13, 12), // (14,12): error CS1725: Friend assembly reference 'Test, Version=1.1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.1.*"")").WithArguments("Test, Version=1.1.*").WithLocation(14, 12), // (15,12): error CS1725: Friend assembly reference 'Test, Version=1.1.1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.1.1.*"")").WithArguments("Test, Version=1.1.1.*").WithLocation(15, 12), // (16,12): error CS1725: Friend assembly reference 'Test, ProcessorArchitecture=MSIL' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, ProcessorArchitecture=MSIL"")").WithArguments("Test, ProcessorArchitecture=MSIL").WithLocation(16, 12), // (17,12): error CS1725: Friend assembly reference 'Test, CuLTure=EN' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, CuLTure=EN"")").WithArguments("Test, CuLTure=EN").WithLocation(17, 12)); } [Fact] public void CS1736ERR_DefaultValueMustBeConstant01() { var text = @"class A { static int Age; public void Foo(int Para1 = Age) { } } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (4,33): error CS1736: Default parameter value for 'Para1' must be a compile-time constant // public void Foo(int Para1 = Age) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Age").WithArguments("Para1"), // (3,16): warning CS0169: The field 'A.Age' is never used // static int Age; Diagnostic(ErrorCode.WRN_UnreferencedField, "Age").WithArguments("A.Age") ); } [Fact] public void CS1736ERR_DefaultValueMustBeConstant02() { var source = @"class C { object this[object x, object y = new C()] { get { return null; } set { } } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (3,38): error CS1736: Default parameter value for 'y' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new C()").WithArguments("y").WithLocation(3, 38)); } [Fact, WorkItem(542401, "DevDiv")] public void CS1736ERR_DefaultValueMustBeConstant_1() { var text = @" class NamedExample { static int y = 1; static void Main(string[] args) { } int CalculateBMI(int weight, int height = y) { return (weight * 703) / (height * height); } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (9,47): error CS1736: Default parameter value for 'height' must be a compile-time constant // int CalculateBMI(int weight, int height = y) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "y").WithArguments("height"), // (4,16): warning CS0414: The field 'NamedExample.y' is assigned but its value is never used // static int y = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "y").WithArguments("NamedExample.y") ); } [Fact] public void CS1737ERR_DefaultValueBeforeRequiredValue() { var text = @"class A { public void Foo(int Para1 = 1, int Para2) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1737, Line = 3, Column = 45 }); } [Fact] public void CS1741ERR_RefOutDefaultValue() { var text = @"class A { public void Foo(ref int Para1 = 1) { } public void Foo1(out int Para2 = 1) { Para2 = 2; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1741, Line = 3, Column = 21 }, new ErrorDescription { Code = 1741, Line = 5, Column = 22 }); } [Fact] public void CS1743ERR_DefaultValueForExtensionParameter() { var text = @"static class C { static void M1(object o = null) { } static void M2(this object o = null) { } static void M3(object o, this int i = 0) { } }"; var compilation = CreateCompilationWithMscorlib(text, references: new[] { SystemCoreRef }); compilation.VerifyDiagnostics( // (4,20): error CS1743: Cannot specify a default value for the 'this' parameter Diagnostic(ErrorCode.ERR_DefaultValueForExtensionParameter, "this").WithLocation(4, 20), // (5,30): error CS1100: Method 'M3' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("M3").WithLocation(5, 30)); } [Fact] public void CS1745ERR_DefaultValueUsedWithAttributes() { var text = @" using System.Runtime.InteropServices; class A { public void foo([OptionalAttribute]int p = 1) { } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,22): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public void foo([OptionalAttribute]int p = 1) Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "OptionalAttribute") ); } [Fact] public void CS1747ERR_NoPIAAssemblyMissingAttribute() { //csc program.cs /l:"C:\MissingPIAAttributes.dll var text = @"public class Test { static int Main(string[] args) { return 1; } }"; var ref1 = TestReferences.SymbolsTests.NoPia.Microsoft.VisualStudio.MissingPIAAttributes.WithEmbedInteropTypes(true); CreateCompilationWithMscorlib(text, references: new[] { ref1 }).VerifyDiagnostics( // error CS1747: Cannot embed interop types from assembly 'MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttribute).WithArguments("MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Runtime.InteropServices.GuidAttribute").WithLocation(1, 1), // error CS1759: Cannot embed interop types from assembly 'MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttributes).WithArguments("MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Runtime.InteropServices.ImportedFromTypeLibAttribute", "System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute").WithLocation(1, 1)); } [WorkItem(620366, "DevDiv")] [Fact] public void CS1748ERR_NoCanonicalView() { var textdll = @" using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTest"")] [assembly: Guid(""A55E0B17-2558-447D-B786-84682CBEF136"")] [assembly: BestFitMapping(false)] [ComImport, Guid(""E245C65D-2448-447A-B786-64682CBEF133"")] [TypeIdentifier(""E245C65D-2448-447A-B786-64682CBEF133"", ""IMyInterface"")] public interface IMyInterface { void Method(int n); } public delegate void DelegateWithInterface(IMyInterface value); public delegate void DelegateWithInterfaceArray(IMyInterface[] ary); public delegate IMyInterface DelegateRetInterface(); public delegate DelegateRetInterface DelegateRetDelegate(DelegateRetInterface d); "; var text = @" class Test { static void Main() { } public static void MyDelegate02(IMyInterface[] ary) { } } "; var comp1 = CreateCompilationWithMscorlib(textdll); var ref1 = new CSharpCompilationReference(comp1); CreateCompilationWithMscorlib(text, references: new MetadataReference[] { ref1 }).VerifyDiagnostics( // (7,37): error CS0246: The type or namespace name 'IMyInterface' could not be found (are you missing a using directive or an assembly reference?) // public static void MyDelegate02(IMyInterface[] ary) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IMyInterface").WithArguments("IMyInterface") ); } [Fact] public void CS1750ERR_NoConversionForDefaultParam() { var text = @"public class Generator { public void Show<T>(string msg = ""Number"", T value = null) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1750, Line = 3, Column = 50 }); } [Fact] public void CS1751ERR_DefaultValueForParamsParameter() { // The native compiler only produces one error here -- that // the default value on "params" is illegal. However it // seems reasonable to produce one error for each bad param. var text = @"class MyClass { public void M7(int i = null, params string[] values = ""test"") { } static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // 'i': A value of type '<null>' cannot be used as a default parameter because there are no standard conversions to type 'int' new ErrorDescription { Code = 1750, Line = 3, Column = 24 }, // 'params': error CS1751: Cannot specify a default value for a parameter array new ErrorDescription { Code = 1751, Line = 3, Column = 34 }); } [Fact] public void CS1754ERR_NoPIANestedType() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { public struct MyClass { public struct NestedClass { public string Name; } } } "; var text = @"public class Test { public static void Main() { var S = new NS.MyClass.NestedClass(); System.Console.Write(S); } } "; var comp = CreateCompilationWithMscorlib(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); CreateCompilationWithMscorlib(text, new[] { ref1 }).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoPIANestedType, "NestedClass").WithArguments("NS.MyClass.NestedClass")); } [Fact()] public void CS1755ERR_InvalidTypeIdentifierConstructor() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { [TypeIdentifier(""Foo2"", ""Bar2"")] public delegate void MyDel(); } "; var text = @" public class Test { event NS.MyDel e; public static void Main() { } } "; var comp = CreateCompilationWithMscorlib(textdll); var ref1 = new CSharpCompilationReference(comp); CreateCompilationWithMscorlib(text, new[] { ref1 }).VerifyDiagnostics( // (4,14): error CS0234: The type or namespace name 'MyDel' does not exist in the namespace 'NS' (are you missing an assembly reference?) // event NS.MyDel e; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "MyDel").WithArguments("MyDel", "NS"), // (4,20): warning CS0067: The event 'Test.e' is never used // event NS.MyDel e; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "e").WithArguments("Test.e")); //var comp1 = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(new List<string>() { text }, new List<MetadataReference>() { ref1 }, // new ErrorDescription { Code = 1755, Line = 4, Column = 14 }); } [Fact] public void CS1757ERR_InteropStructContainsMethods() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { public struct MyStuct { private int _age; public string Name; } } "; var text = @"public class Test { public static void Main() { NS.MyStuct S = new NS.MyStuct(); System.Console.Write(S); } } "; var comp = CreateCompilationWithMscorlib(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); var comp1 = CreateCompilationWithMscorlib(text, new[] { ref1 }); comp1.VerifyEmitDiagnostics( // (5,24): error CS1757: Embedded interop struct 'NS.MyStuct' can contain only public instance fields. // NS.MyStuct S = new NS.MyStuct(); Diagnostic(ErrorCode.ERR_InteropStructContainsMethods, "new NS.MyStuct()").WithArguments("NS.MyStuct")); } [Fact] public void CS1754ERR_NoPIANestedType_2() { //vbc /t:library PIA.vb //csc /l:PIA.dll Program.cs var textdll = @"Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib(""GeneralPIA.dll"")> <Assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedInterface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Interface InnerInterface End Interface End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedClass Class InnerClass End Class End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedStructure Structure InnerStructure End Structure End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedEnum Enum InnerEnum Value1 End Enum End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedDelegate Delegate Sub InnerDelegate() End Interface Public Structure NestedInterface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Interface InnerInterface End Interface End Structure Public Structure NestedClass Class InnerClass End Class End Structure Public Structure NestedStructure Structure InnerStructure End Structure End Structure Public Structure NestedEnum Enum InnerEnum Value1 End Enum End Structure Public Structure NestedDelegate Delegate Sub InnerDelegate() End Structure"; var text = @"public class Program { public static void Main() { INestedInterface.InnerInterface s1 = null; INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); INestedDelegate.InnerDelegate s5 = null; } }"; var vbcomp = VisualBasic.VisualBasicCompilation.Create( "Test", new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(textdll) }, new[] { MscorlibRef_v4_0_30316_17626 }, new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var ref1 = vbcomp.EmitToImageReference(embedInteropTypes: true); CreateCompilationWithMscorlib(text, new[] { ref1 }).VerifyDiagnostics( // (5,26): error CS1754: Type 'INestedInterface.InnerInterface' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedInterface.InnerInterface s1 = null; Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerInterface").WithArguments("INestedInterface.InnerInterface"), // (6,26): error CS1754: Type 'INestedStructure.InnerStructure' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerStructure").WithArguments("INestedStructure.InnerStructure"), // (6,71): error CS1754: Type 'INestedStructure.InnerStructure' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerStructure").WithArguments("INestedStructure.InnerStructure"), // (7,21): error CS1754: Type 'INestedEnum.InnerEnum' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerEnum").WithArguments("INestedEnum.InnerEnum"), // (7,56): error CS1754: Type 'INestedEnum.InnerEnum' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerEnum").WithArguments("INestedEnum.InnerEnum"), // (8,25): error CS1754: Type 'INestedDelegate.InnerDelegate' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedDelegate.InnerDelegate s5 = null; Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerDelegate").WithArguments("INestedDelegate.InnerDelegate"), // (5,41): warning CS0219: The variable 's1' is assigned but its value is never used // INestedInterface.InnerInterface s1 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s1").WithArguments("s1"), // (6,41): warning CS0219: The variable 's3' is assigned but its value is never used // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s3").WithArguments("s3"), // (7,31): warning CS0219: The variable 's4' is assigned but its value is never used // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s4").WithArguments("s4"), // (8,39): warning CS0219: The variable 's5' is assigned but its value is never used // INestedDelegate.InnerDelegate s5 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s5").WithArguments("s5")); } [Fact] public void CS1763ERR_NotNullRefDefaultParameter() { var text = @" public static class ErrorCode { // We do not allow constant conversions from string to object in a default parameter initializer static void M1(object x = ""hello"") {} // We do not allow boxing conversions to object in a default parameter initializer static void M2(System.ValueType y = 123) {} }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // (5,25): error CS1763: 'x' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null new ErrorDescription { Code = 1763, Line = 5, Column = 25 }, // (7,35): error CS1763: 'y' is of type 'System.ValueType'. A default parameter value of a reference type other than string can only be initialized with null new ErrorDescription { Code = 1763, Line = 7, Column = 35 }); } [WorkItem(619266, "DevDiv")] [Fact(Skip = "619266")] public void CS1768ERR_GenericsUsedInNoPIAType() { // add dll and make it embed var textdll = @"using System; using System.Collections.Generic; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace ClassLibrary3 { [ComImport, Guid(""b2496f7a-5d40-4abe-ad14-462f257a8ed5"")] public interface IFoo { IBar<string> foo(); } [ComImport, Guid(""b2496f7a-5d40-4abe-ad14-462f257a8ed6"")] public interface IBar<T> { List<IFoo> GetList(); } } "; var text = @" using System.Collections.Generic; using ClassLibrary3; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { IFoo x = (IFoo)new object(); } } class foo : IBar<string>, IFoo { public List<string> GetList() { throw new NotImplementedException(); } List<IFoo> IBar<string>.GetList() { throw new NotImplementedException(); } } } "; var comp = CreateCompilationWithMscorlib(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); CreateCompilationWithMscorlib(text, new[] { ref1 }).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_GenericsUsedInNoPIAType)); } [Fact] public void CS1770ERR_NoConversionForNubDefaultParam() { var text = @"using System; class MyClass { public enum E { None } // No error: public void Foo1(int? x = default(int)) { } public void Foo2(E? x = default(E)) { } public void Foo3(DateTime? x = default(DateTime?)) { } // Error: public void Foo(DateTime? x = default(DateTime)) { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1770, Line = 12, Column = 31 }); } [Fact] public void CS1908ERR_DefaultValueTypeMustMatch() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Bad([Optional] [DefaultParameterValue(""true"")] bool b); // CS1908 } "; CreateCompilationWithMscorlib(text, new[] { SystemRef }).VerifyDiagnostics( // (4,26): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue")); } // Dev10 reports CS1909: The DefaultValue attribute is not applicable on parameters of type '{0}'. // for parameters of type System.Type or array even though there is no reason why null couldn't be specified in DPV. // We report CS1910 if DPV has an argument of type System.Type or array like Dev10 does except for we do so instead // of CS1909 when non-null is passed. [Fact] public void CS1909ERR_DefaultValueBadValueType_Array_NoError() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(null)]int[] arr1); } "; // Dev10 reports CS1909, we don't CreateCompilationWithMscorlib(text, new[] { SystemRef }).VerifyDiagnostics(); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Array() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(new int[] { 1, 2 })]object a); void Test2([DefaultParameterValue(new int[] { 1, 2 })]int[] a); void Test3([DefaultParameterValue(new int[0])]int[] a); } "; // CS1910 CreateCompilationWithMscorlib(text, new[] { SystemRef }).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (5,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (6,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]")); } [Fact] public void CS1909ERR_DefaultValueBadValueType_Type_NoError() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(null)]System.Type t); } "; // Dev10 reports CS1909, we don't CreateCompilationWithMscorlib(text, new[] { SystemRef }).VerifyDiagnostics(); } [Fact] public void CS1910ERR_DefaultValueBadValue_Generics() { var text = @"using System.Runtime.InteropServices; public class C { } public interface ISomeInterface { void Test1<T>([DefaultParameterValue(null)]T t); // error void Test2<T>([DefaultParameterValue(null)]T t) where T : C; // OK void Test3<T>([DefaultParameterValue(null)]T t) where T : class; // OK void Test4<T>([DefaultParameterValue(null)]T t) where T : struct; // error } "; CreateCompilationWithMscorlib(text, new[] { SystemRef }).VerifyDiagnostics( // (6,20): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type // void Test1<T>([DefaultParameterValue(null)]T t); // error Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (9,20): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type // void Test4<T>([DefaultParameterValue(null)]T t) where T : struct; // error Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue")); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Type1() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(typeof(int))]object t); // CS1910 } "; CreateCompilationWithMscorlib(text, new[] { SystemRef }).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type")); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Type2() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(typeof(int))]System.Type t); // CS1910 } "; CreateCompilationWithMscorlib(text, new[] { SystemRef }).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type")); } [Fact] public void CS1961ERR_UnexpectedVariance() { var text = @"interface Foo<out T> { T Bar(); void Baz(T t); }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,14): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'Foo<T>.Baz(T)'. 'T' is covariant. // void Baz(T t); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("Foo<T>.Baz(T)", "T", "covariant", "contravariantly").WithLocation(4, 14)); } [Fact] public void CS1965ERR_DeriveFromDynamic() { var text = @"public class ErrorCode : dynamic { }"; CreateCompilationWithMscorlibAndSystemCore(text).VerifyDiagnostics( // (1,26): error CS1965: 'ErrorCode': cannot derive from the dynamic type Diagnostic(ErrorCode.ERR_DeriveFromDynamic, "dynamic").WithArguments("ErrorCode")); } [Fact, WorkItem(552740, "DevDiv")] public void CS1966ERR_DeriveFromConstructedDynamic() { var text = @" interface I<T> { } class C<T> { public enum D { } } class E1 : I<dynamic> {} class E2 : I<C<dynamic>.D*[]> {} "; CreateCompilationWithMscorlibAndSystemCore(text).VerifyDiagnostics( // (11,12): error CS1966: 'E2': cannot implement a dynamic interface 'I<C<dynamic>.D*[]>' // class E2 : I<C<dynamic>.D*[]> {} Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I<C<dynamic>.D*[]>").WithArguments("E2", "I<C<dynamic>.D*[]>"), // (10,12): error CS1966: 'E1': cannot implement a dynamic interface 'I<dynamic>' // class E1 : I<dynamic> {} Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I<dynamic>").WithArguments("E1", "I<dynamic>")); } [Fact] public void CS1967ERR_DynamicTypeAsBound() { var source = @"delegate void D<T>() where T : dynamic;"; CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (1,32): error CS1967: Constraint cannot be the dynamic type Diagnostic(ErrorCode.ERR_DynamicTypeAsBound, "dynamic")); } [Fact] public void CS1968ERR_ConstructedDynamicTypeAsBound() { var source = @"interface I<T> { } struct S<T> { internal delegate void D<U>(); } class A<T> { } class B<T, U> where T : A<S<T>.D<dynamic>>, I<dynamic[]> where U : I<S<dynamic>.D<T>> { }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (8,15): error CS1968: Constraint cannot be a dynamic type 'A<S<T>.D<dynamic>>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "A<S<T>.D<dynamic>>").WithArguments("A<S<T>.D<dynamic>>").WithLocation(8, 15), // (8,35): error CS1968: Constraint cannot be a dynamic type 'I<dynamic[]>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "I<dynamic[]>").WithArguments("I<dynamic[]>").WithLocation(8, 35), // (9,15): error CS1968: Constraint cannot be a dynamic type 'I<S<dynamic>.D<T>>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "I<S<dynamic>.D<T>>").WithArguments("I<S<dynamic>.D<T>>").WithLocation(9, 15)); } // Instead of CS1982 ERR_DynamicNotAllowedInAttribute we report CS0181 ERR_BadAttributeParamType [Fact] public void CS1982ERR_DynamicNotAllowedInAttribute_NoError() { var text = @" using System; public class C<T> { public enum D { A } } [A(T = typeof(dynamic[]))] // Dev11 reports error, but this should be ok [A(T = typeof(C<dynamic>))] [A(T = typeof(C<dynamic>[]))] [A(T = typeof(C<dynamic>.D[]))] [A(T = typeof(C<dynamic>.D*[]))] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] class A : Attribute { public Type T; } "; CreateCompilationWithMscorlibAndSystemCore(text).VerifyDiagnostics(); } [Fact] public void CS7021ERR_NamespaceNotAllowedInScript() { var text = @" namespace N1 { class A { public int Foo() { return 2; }} } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics(); } [Fact] public void ErrorTypeCandidateSymbols1() { var text = @" class A { public B n; }"; CSharpCompilation comp = CreateCompilationWithMscorlib(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.Type; Assert.Equal(SymbolKind.ErrorType, fieldType.Kind); Assert.Equal("B", fieldType.Name); var errorFieldType = (ErrorTypeSymbol)fieldType; Assert.Equal(CandidateReason.None, errorFieldType.CandidateReason); Assert.Equal(0, errorFieldType.CandidateSymbols.Length); } [Fact] public void ErrorTypeCandidateSymbols2() { var text = @" class C { private class B {} } class A : C { public B n; }"; CSharpCompilation comp = CreateCompilationWithMscorlib(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var classC = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("C").Single(); var classB = (NamedTypeSymbol)classC.GetTypeMembers("B").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.Type; Assert.Equal(SymbolKind.ErrorType, fieldType.Kind); Assert.Equal("B", fieldType.Name); var errorFieldType = (ErrorTypeSymbol)fieldType; Assert.Equal(CandidateReason.Inaccessible, errorFieldType.CandidateReason); Assert.Equal(1, errorFieldType.CandidateSymbols.Length); Assert.Equal(classB, errorFieldType.CandidateSymbols[0]); } [Fact] public void ErrorTypeCandidateSymbols3() { var text = @" using N1; using N2; namespace N1 { class B {} } namespace N2 { class B {} } class A : C { public B n; }"; CSharpCompilation comp = CreateCompilationWithMscorlib(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var ns1 = (NamespaceSymbol)comp.GlobalNamespace.GetMembers("N1").Single(); var ns2 = (NamespaceSymbol)comp.GlobalNamespace.GetMembers("N2").Single(); var classBinN1 = (NamedTypeSymbol)ns1.GetTypeMembers("B").Single(); var classBinN2 = (NamedTypeSymbol)ns2.GetTypeMembers("B").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.Type; Assert.Equal(SymbolKind.ErrorType, fieldType.Kind); Assert.Equal("B", fieldType.Name); var errorFieldType = (ErrorTypeSymbol)fieldType; Assert.Equal(CandidateReason.Ambiguous, errorFieldType.CandidateReason); Assert.Equal(2, errorFieldType.CandidateSymbols.Length); Assert.True((classBinN1 == errorFieldType.CandidateSymbols[0] && classBinN2 == errorFieldType.CandidateSymbols[1]) || (classBinN2 == errorFieldType.CandidateSymbols[0] && classBinN1 == errorFieldType.CandidateSymbols[1]), "CandidateSymbols must by N1.B and N2.B in some order"); } #endregion #region "Symbol Warning Tests" /// <summary> /// current error 104 /// </summary> [Fact] public void CS0105WRN_DuplicateUsing01() { var text = @"using System; using System; namespace Foo.Bar { class A { } } namespace testns { using Foo.Bar; using System; using Foo.Bar; class B : A { } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (2,7): warning CS0105: The using directive for 'System' appeared previously in this namespace // using System; Diagnostic(ErrorCode.WRN_DuplicateUsing, "System").WithArguments("System"), // (13,11): warning CS0105: The using directive for 'Foo.Bar' appeared previously in this namespace // using Foo.Bar; Diagnostic(ErrorCode.WRN_DuplicateUsing, "Foo.Bar").WithArguments("Foo.Bar"), // (1,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (12,5): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (13,5): info CS8019: Unnecessary using directive. // using Foo.Bar; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Foo.Bar;")); // TODO... // var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0108WRN_NewRequired01() { var text = @"using System; namespace x { public class clx { public int i = 1; } public class cly : clx { public static int i = 2; // CS0108, use the new keyword public static void Main() { Console.WriteLine(i); } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 12, Column = 27, IsWarning = true }); } [Fact] public void CS0108WRN_NewRequired02() { DiagnosticsUtils.TestDiagnosticsExact( @"class A { public static void P() { } public static void Q() { } public void R() { } public void S() { } public static int T { get; set; } public static int U { get; set; } public int V { get; set; } public int W { get; set; } } class B : A { public static int P { get; set; } // CS0108 public int Q { get; set; } // CS0108 public static int R { get; set; } // CS0108 public int S { get; set; } // CS0108 public static void T() { } // CS0108 public void U() { } // CS0108 public static void V() { } // CS0108 public void W() { } // CS0108 } ", "'P' warning CS0108: 'B.P' hides inherited member 'A.P()'. Use the new keyword if hiding was intended.", "'Q' warning CS0108: 'B.Q' hides inherited member 'A.Q()'. Use the new keyword if hiding was intended.", "'R' warning CS0108: 'B.R' hides inherited member 'A.R()'. Use the new keyword if hiding was intended.", "'S' warning CS0108: 'B.S' hides inherited member 'A.S()'. Use the new keyword if hiding was intended.", "'T' warning CS0108: 'B.T()' hides inherited member 'A.T'. Use the new keyword if hiding was intended.", "'U' warning CS0108: 'B.U()' hides inherited member 'A.U'. Use the new keyword if hiding was intended.", "'V' warning CS0108: 'B.V()' hides inherited member 'A.V'. Use the new keyword if hiding was intended.", "'W' warning CS0108: 'B.W()' hides inherited member 'A.W'. Use the new keyword if hiding was intended."); } [WorkItem(539624, "DevDiv")] [Fact] public void CS0108WRN_NewRequired03() { var text = @" class BaseClass { public int MyMeth(int intI) { return intI; } } class MyClass : BaseClass { public static int MyMeth(int intI) // CS0108 { return intI + 1; } } class SBase { protected static void M() {} } class DClass : SBase { protected void M() {} // CS0108 } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 13, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 26, Column = 20, IsWarning = true }); } [WorkItem(540459, "DevDiv")] [Fact] public void CS0108WRN_NewRequired04() { var text = @" class A { public void f() { } } class B: A { } class C : B { public int f = 3; //CS0108 } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (15,16): warning CS0108: 'C.f' hides inherited member 'A.f()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "f").WithArguments("C.f", "A.f()")); } [Fact] public void CS0108WRN_NewRequired05() { var text = @" class A { public static void SM1() { } public static void SM2() { } public static void SM3() { } public static void SM4() { } public void IM1() { } public void IM2() { } public void IM3() { } public void IM4() { } public static int SP1 { get; set; } public static int SP2 { get; set; } public static int SP3 { get; set; } public static int SP4 { get; set; } public int IP1 { get; set; } public int IP2 { get; set; } public int IP3 { get; set; } public int IP4 { get; set; } public static event System.Action SE1; public static event System.Action SE2; public static event System.Action SE3; public static event System.Action SE4; public event System.Action IE1{ add { } remove { } } public event System.Action IE2{ add { } remove { } } public event System.Action IE3{ add { } remove { } } public event System.Action IE4{ add { } remove { } } } class B : A { public static int SM1 { get; set; } //CS0108 public int SM2 { get; set; } //CS0108 public static event System.Action SM3; //CS0108 public event System.Action SM4{ add { } remove { } } //CS0108 public static int IM1 { get; set; } //CS0108 public int IM2 { get; set; } //CS0108 public static event System.Action IM3; //CS0108 public event System.Action IM4{ add { } remove { } } //CS0108 public static void SP1() { } //CS0108 public void SP2() { } //CS0108 public static event System.Action SP3; //CS0108 public event System.Action SP4{ add { } remove { } } //CS0108 public static void IP1() { } //CS0108 public void IP2() { } //CS0108 public static event System.Action IP3; //CS0108 public event System.Action IP4{ add { } remove { } } //CS0108 public static void SE1() { } //CS0108 public void SE2() { } //CS0108 public static int SE3 { get; set; } //CS0108 public int SE4 { get; set; } //CS0108 public static void IE1() { } //CS0108 public void IE2() { } //CS0108 public static int IE3 { get; set; } //CS0108 public int IE4 { get; set; } //CS0108 }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (36,23): warning CS0108: 'B.SM1' hides inherited member 'A.SM1()'. Use the new keyword if hiding was intended. // public static int SM1 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM1").WithArguments("B.SM1", "A.SM1()"), // (37,16): warning CS0108: 'B.SM2' hides inherited member 'A.SM2()'. Use the new keyword if hiding was intended. // public int SM2 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM2").WithArguments("B.SM2", "A.SM2()"), // (38,39): warning CS0108: 'B.SM3' hides inherited member 'A.SM3()'. Use the new keyword if hiding was intended. // public static event System.Action SM3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM3").WithArguments("B.SM3", "A.SM3()"), // (39,32): warning CS0108: 'B.SM4' hides inherited member 'A.SM4()'. Use the new keyword if hiding was intended. // public event System.Action SM4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM4").WithArguments("B.SM4", "A.SM4()"), // (41,23): warning CS0108: 'B.IM1' hides inherited member 'A.IM1()'. Use the new keyword if hiding was intended. // public static int IM1 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM1").WithArguments("B.IM1", "A.IM1()"), // (42,16): warning CS0108: 'B.IM2' hides inherited member 'A.IM2()'. Use the new keyword if hiding was intended. // public int IM2 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM2").WithArguments("B.IM2", "A.IM2()"), // (43,39): warning CS0108: 'B.IM3' hides inherited member 'A.IM3()'. Use the new keyword if hiding was intended. // public static event System.Action IM3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM3").WithArguments("B.IM3", "A.IM3()"), // (44,32): warning CS0108: 'B.IM4' hides inherited member 'A.IM4()'. Use the new keyword if hiding was intended. // public event System.Action IM4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM4").WithArguments("B.IM4", "A.IM4()"), // (46,24): warning CS0108: 'B.SP1()' hides inherited member 'A.SP1'. Use the new keyword if hiding was intended. // public static void SP1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP1").WithArguments("B.SP1()", "A.SP1"), // (47,17): warning CS0108: 'B.SP2()' hides inherited member 'A.SP2'. Use the new keyword if hiding was intended. // public void SP2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP2").WithArguments("B.SP2()", "A.SP2"), // (48,39): warning CS0108: 'B.SP3' hides inherited member 'A.SP3'. Use the new keyword if hiding was intended. // public static event System.Action SP3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP3").WithArguments("B.SP3", "A.SP3"), // (49,32): warning CS0108: 'B.SP4' hides inherited member 'A.SP4'. Use the new keyword if hiding was intended. // public event System.Action SP4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP4").WithArguments("B.SP4", "A.SP4"), // (51,24): warning CS0108: 'B.IP1()' hides inherited member 'A.IP1'. Use the new keyword if hiding was intended. // public static void IP1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP1").WithArguments("B.IP1()", "A.IP1"), // (52,17): warning CS0108: 'B.IP2()' hides inherited member 'A.IP2'. Use the new keyword if hiding was intended. // public void IP2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP2").WithArguments("B.IP2()", "A.IP2"), // (53,39): warning CS0108: 'B.IP3' hides inherited member 'A.IP3'. Use the new keyword if hiding was intended. // public static event System.Action IP3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP3").WithArguments("B.IP3", "A.IP3"), // (54,32): warning CS0108: 'B.IP4' hides inherited member 'A.IP4'. Use the new keyword if hiding was intended. // public event System.Action IP4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP4").WithArguments("B.IP4", "A.IP4"), // (56,24): warning CS0108: 'B.SE1()' hides inherited member 'A.SE1'. Use the new keyword if hiding was intended. // public static void SE1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE1").WithArguments("B.SE1()", "A.SE1"), // (57,17): warning CS0108: 'B.SE2()' hides inherited member 'A.SE2'. Use the new keyword if hiding was intended. // public void SE2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE2").WithArguments("B.SE2()", "A.SE2"), // (58,23): warning CS0108: 'B.SE3' hides inherited member 'A.SE3'. Use the new keyword if hiding was intended. // public static int SE3 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE3").WithArguments("B.SE3", "A.SE3"), // (59,16): warning CS0108: 'B.SE4' hides inherited member 'A.SE4'. Use the new keyword if hiding was intended. // public int SE4 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE4").WithArguments("B.SE4", "A.SE4"), // (61,24): warning CS0108: 'B.IE1()' hides inherited member 'A.IE1'. Use the new keyword if hiding was intended. // public static void IE1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE1").WithArguments("B.IE1()", "A.IE1"), // (62,17): warning CS0108: 'B.IE2()' hides inherited member 'A.IE2'. Use the new keyword if hiding was intended. // public void IE2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE2").WithArguments("B.IE2()", "A.IE2"), // (63,23): warning CS0108: 'B.IE3' hides inherited member 'A.IE3'. Use the new keyword if hiding was intended. // public static int IE3 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE3").WithArguments("B.IE3", "A.IE3"), // (64,16): warning CS0108: 'B.IE4' hides inherited member 'A.IE4'. Use the new keyword if hiding was intended. // public int IE4 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE4").WithArguments("B.IE4", "A.IE4"), // (53,39): warning CS0067: The event 'B.IP3' is never used // public static event System.Action IP3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "IP3").WithArguments("B.IP3"), // (25,39): warning CS0067: The event 'A.SE2' is never used // public static event System.Action SE2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE2").WithArguments("A.SE2"), // (26,39): warning CS0067: The event 'A.SE3' is never used // public static event System.Action SE3; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE3").WithArguments("A.SE3"), // (38,39): warning CS0067: The event 'B.SM3' is never used // public static event System.Action SM3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SM3").WithArguments("B.SM3"), // (27,39): warning CS0067: The event 'A.SE4' is never used // public static event System.Action SE4; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE4").WithArguments("A.SE4"), // (48,39): warning CS0067: The event 'B.SP3' is never used // public static event System.Action SP3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SP3").WithArguments("B.SP3"), // (24,39): warning CS0067: The event 'A.SE1' is never used // public static event System.Action SE1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE1").WithArguments("A.SE1"), // (43,39): warning CS0067: The event 'B.IM3' is never used // public static event System.Action IM3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "IM3").WithArguments("B.IM3")); } [WorkItem(539624, "DevDiv")] [Fact] public void CS0108WRN_NewRequired_Arity() { var text = @" class Class { public class T { } public class T<A> { } public class T<A, B> { } public class T<A, B, C> { } public void M() { } public void M<A>() { } public void M<A, B>() { } public void M<A, B, C>() { } public delegate void D(); public delegate void D<A>(); public delegate void D<A, B>(); public delegate void D<A, B, C>(); } class HideWithClass : Class { public class T { } public class T<A> { } public class T<A, B> { } public class T<A, B, C> { } public class M { } public class M<A> { } public class M<A, B> { } public class M<A, B, C> { } public class D { } public class D<A> { } public class D<A, B> { } public class D<A, B, C> { } } class HideWithMethod : Class { public void T() { } public void T<A>() { } public void T<A, B>() { } public void T<A, B, C>() { } public void M() { } public void M<A>() { } public void M<A, B>() { } public void M<A, B, C>() { } public void D() { } public void D<A>() { } public void D<A, B>() { } public void D<A, B, C>() { } } class HideWithDelegate : Class { public delegate void T(); public delegate void T<A>(); public delegate void T<A, B>(); public delegate void T<A, B, C>(); public delegate void M(); public delegate void M<A>(); public delegate void M<A, B>(); public delegate void M<A, B, C>(); public delegate void D(); public delegate void D<A>(); public delegate void D<A, B>(); public delegate void D<A, B, C>(); } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( /* HideWithClass */ // (22,18): warning CS0108: 'HideWithClass.T' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T", "Class.T"), // (23,18): warning CS0108: 'HideWithClass.T<A>' hides inherited member 'Class.T<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A>", "Class.T<A>"), // (24,18): warning CS0108: 'HideWithClass.T<A, B>' hides inherited member 'Class.T<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A, B>", "Class.T<A, B>"), // (25,18): warning CS0108: 'HideWithClass.T<A, B, C>' hides inherited member 'Class.T<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A, B, C>", "Class.T<A, B, C>"), // (27,18): warning CS0108: 'HideWithClass.M' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M", "Class.M()"), // (28,18): warning CS0108: 'HideWithClass.M<A>' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A>", "Class.M<A>()"), // (29,18): warning CS0108: 'HideWithClass.M<A, B>' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A, B>", "Class.M<A, B>()"), // (30,18): warning CS0108: 'HideWithClass.M<A, B, C>' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A, B, C>", "Class.M<A, B, C>()"), // (32,18): warning CS0108: 'HideWithClass.D' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D", "Class.D"), // (33,18): warning CS0108: 'HideWithClass.D<A>' hides inherited member 'Class.D<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A>", "Class.D<A>"), // (34,18): warning CS0108: 'HideWithClass.D<A, B>' hides inherited member 'Class.D<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A, B>", "Class.D<A, B>"), // (35,18): warning CS0108: 'HideWithClass.D<A, B, C>' hides inherited member 'Class.D<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A, B, C>", "Class.D<A, B, C>"), /* HideWithMethod */ // (40,17): warning CS0108: 'HideWithMethod.T()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T()", "Class.T"), // (41,17): warning CS0108: 'HideWithMethod.T<A>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A>()", "Class.T"), // (42,17): warning CS0108: 'HideWithMethod.T<A, B>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A, B>()", "Class.T"), // (43,17): warning CS0108: 'HideWithMethod.T<A, B, C>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A, B, C>()", "Class.T"), // (45,17): warning CS0108: 'HideWithMethod.M()' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M()", "Class.M()"), // (46,17): warning CS0108: 'HideWithMethod.M<A>()' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A>()", "Class.M<A>()"), // (47,17): warning CS0108: 'HideWithMethod.M<A, B>()' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A, B>()", "Class.M<A, B>()"), // (48,17): warning CS0108: 'HideWithMethod.M<A, B, C>()' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A, B, C>()", "Class.M<A, B, C>()"), // (50,17): warning CS0108: 'HideWithMethod.D()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D()", "Class.D"), // (51,17): warning CS0108: 'HideWithMethod.D<A>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A>()", "Class.D"), // (52,17): warning CS0108: 'HideWithMethod.D<A, B>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A, B>()", "Class.D"), // (53,17): warning CS0108: 'HideWithMethod.D<A, B, C>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A, B, C>()", "Class.D"), /* HideWithDelegate */ // (58,26): warning CS0108: 'HideWithDelegate.T' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T", "Class.T"), // (59,26): warning CS0108: 'HideWithDelegate.T<A>' hides inherited member 'Class.T<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A>", "Class.T<A>"), // (60,26): warning CS0108: 'HideWithDelegate.T<A, B>' hides inherited member 'Class.T<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A, B>", "Class.T<A, B>"), // (61,26): warning CS0108: 'HideWithDelegate.T<A, B, C>' hides inherited member 'Class.T<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A, B, C>", "Class.T<A, B, C>"), // (63,26): warning CS0108: 'HideWithDelegate.M' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M", "Class.M()"), // (64,26): warning CS0108: 'HideWithDelegate.M<A>' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A>", "Class.M<A>()"), // (65,26): warning CS0108: 'HideWithDelegate.M<A, B>' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A, B>", "Class.M<A, B>()"), // (66,26): warning CS0108: 'HideWithDelegate.M<A, B, C>' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A, B, C>", "Class.M<A, B, C>()"), // (68,26): warning CS0108: 'HideWithDelegate.D' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D", "Class.D"), // (69,26): warning CS0108: 'HideWithDelegate.D<A>' hides inherited member 'Class.D<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A>", "Class.D<A>"), // (70,26): warning CS0108: 'HideWithDelegate.D<A, B>' hides inherited member 'Class.D<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A, B>", "Class.D<A, B>"), // (71,26): warning CS0108: 'HideWithDelegate.D<A, B, C>' hides inherited member 'Class.D<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A, B, C>", "Class.D<A, B, C>")); } [Fact, WorkItem(546736, "DevDiv")] public void CS0108WRN_NewRequired_Partial() { var text = @" partial class Parent { partial void PM(int x); private void M(int x) { } partial class Child : Parent { partial void PM(int x); private void M(int x) { } } } partial class AnotherChild : Parent { partial void PM(int x); private void M(int x) { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_NewRequired, "PM").WithArguments("Parent.Child.PM(int)", "Parent.PM(int)"), Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("Parent.Child.M(int)", "Parent.M(int)")); } [Fact] public void CS0109WRN_NewNotRequired() { var text = @"namespace x { public class a { public int i; } public class b : a { public new int i; public new int j; // CS0109 public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewNotRequired, Line = 11, Column = 24, IsWarning = true }); } [Fact] public void CS0114WRN_NewOrOverrideExpected() { var text = @"abstract public class clx { public abstract void f(); } public class cly : clx { public void f() // CS0114, hides base class membe { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 8, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 6, Column = 14 } }); } [Fact] public void CS0282WRN_SequentialOnPartialClass() { var text = @" partial struct A { int i; } partial struct A { int j; } "; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (1,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'A'. To specify an ordering, all instance fields must be in the same declaration. // partial struct A Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "A").WithArguments("A"), // (3,9): warning CS0169: The field 'A.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("A.i"), // (7,9): warning CS0169: The field 'A.j' is never used // int j; Diagnostic(ErrorCode.WRN_UnreferencedField, "j").WithArguments("A.j")); } /// <summary> /// import - Lib: class A { class B {} } /// vs. curr: Namespace A { class B {} } - use B /// </summary> [Fact] public void CS0435WRN_SameFullNameThisNsAgg01() { var text = @"namespace CSFields { public class FFF { } } namespace SA { class Test { CSFields.FFF var = null; void M(CSFields.FFF p) { } } } "; // class CSFields { class FFF {}} var ref1 = TestReferences.SymbolsTests.Fields.CSFields.dll; var comp = CreateCompilationWithMscorlib(new List<string> { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (11,16): warning CS0435: The namespace 'CSFields' in '' conflicts with the imported type 'CSFields' in 'CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in ''. // void M(CSFields.FFF p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CSFields").WithArguments("", "CSFields", "CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CSFields"), // (10,9): warning CS0435: The namespace 'CSFields' in '' conflicts with the imported type 'CSFields' in 'CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in ''. // CSFields.FFF var = null; Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CSFields").WithArguments("", "CSFields", "CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CSFields"), // (10,22): warning CS0414: The field 'SA.Test.var' is assigned but its value is never used // CSFields.FFF var = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "var").WithArguments("SA.Test.var") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } /// <summary> /// import - Lib: class A {} vs. curr: class A { } /// </summary> [Fact] public void CS0436WRN_SameFullNameThisAggAgg01() { var text = @"class Class1 { } namespace SA { class Test { Class1 cls; void M(Class1 p) { } } } "; // Class1 var ref1 = TestReferences.SymbolsTests.V1.MTTestLib1.dll; // Roslyn gives CS1542 or CS0104 var comp = CreateCompilationWithMscorlib(new List<string> { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (8,16): warning CS0436: The type 'Class1' in '' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // void M(Class1 p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // (7,9): warning CS0436: The type 'Class1' in '' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // Class1 cls; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // (7,16): warning CS0169: The field 'SA.Test.cls' is never used // Class1 cls; Diagnostic(ErrorCode.WRN_UnreferencedField, "cls").WithArguments("SA.Test.cls")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } [Fact] [WorkItem(546077, "DevDiv")] public void MultipleSymbolDisambiguation() { var sourceRef1 = @" public class CCC { public class X { } } public class CNC { public class X { } } namespace NCC { public class X { } } namespace NNC { public class X { } } public class CCN { public class X { } } public class CNN { public class X { } } namespace NCN { public class X { } } namespace NNN { public class X { } } "; var sourceRef2 = @" public class CCC { public class X { } } namespace CNC { public class X { } } public class NCC{ public class X { } } namespace NNC { public class X { } } public class CCN { public class X { } } namespace CNN { public class X { } } public class NCN { public class X { } } namespace NNN { public class X { } } "; var sourceLib = @" public class CCC { public class X { } } namespace CCN { public class X { } } public class CNC { public class X { } } namespace CNN { public class X { } } public class NCC { public class X { } } namespace NCN { public class X { } } public class NNC { public class X { } } namespace NNN { public class X { } } internal class DC : CCC.X { } internal class DN : CCN.X { } internal class D3 : CNC.X { } internal class D4 : CNN.X { } internal class D5 : NCC.X { } internal class D6 : NCN.X { } internal class D7 : NNC.X { } internal class D8 : NNN.X { } "; var ref1 = CreateCompilationWithMscorlib(sourceRef1, assemblyName: "Ref1").VerifyDiagnostics(); var ref2 = CreateCompilationWithMscorlib(sourceRef2, assemblyName: "Ref2").VerifyDiagnostics(); var tree = Parse(sourceLib, filename: @"C:\lib.cs"); var lib = CreateCompilationWithMscorlib(tree, new MetadataReference[] { new CSharpCompilationReference(ref1), new CSharpCompilationReference(ref2), }); // In some cases we might order the symbols differently than Dev11 and thus reporting slightly different warnings. // E.g. (src:type, md:type, md:namespace) vs (src:type, md:namespace, md:type) // We report (type, type) ambiguity while Dev11 reports (type, namespace) ambiguity, but both are equally correct. // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. lib.VerifyDiagnostics( // C:\lib.cs(12,21): warning CS0435: The namespace 'CCN' in 'C:\lib.cs' conflicts with the imported type 'CCN' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CCN").WithArguments(@"C:\lib.cs", "CCN", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CCN"), // C:\lib.cs(16,21): warning CS0435: The namespace 'NCN' in 'C:\lib.cs' conflicts with the imported type 'NCN' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "NCN").WithArguments(@"C:\lib.cs", "NCN", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCN"), // C:\lib.cs(16,25): warning CS0436: The type 'NCN.X' in 'C:\lib.cs' conflicts with the imported type 'NCN.X' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "NCN.X", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCN.X"), // C:\lib.cs(11,21): warning CS0436: The type 'CCC' in 'C:\lib.cs' conflicts with the imported type 'CCC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "CCC").WithArguments(@"C:\lib.cs", "CCC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CCC"), // C:\lib.cs(15,21): warning CS0436: The type 'NCC' in 'C:\lib.cs' conflicts with the imported type 'NCC' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "NCC").WithArguments(@"C:\lib.cs", "NCC", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCC"), // C:\lib.cs(13,21): warning CS0436: The type 'CNC' in 'C:\lib.cs' conflicts with the imported type 'CNC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "CNC").WithArguments(@"C:\lib.cs", "CNC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNC"), // C:\lib.cs(14,21): warning CS0435: The namespace 'CNN' in 'C:\lib.cs' conflicts with the imported type 'CNN' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CNN").WithArguments(@"C:\lib.cs", "CNN", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNN"), // C:\lib.cs(14,25): warning CS0436: The type 'CNN.X' in 'C:\lib.cs' conflicts with the imported type 'CNN.X' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "CNN.X", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNN.X"), // C:\lib.cs(17,21): warning CS0437: The type 'NNC' in 'C:\lib.cs' conflicts with the imported namespace 'NNC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "NNC").WithArguments(@"C:\lib.cs", "NNC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NNC"), // C:\lib.cs(18,25): warning CS0436: The type 'NNN.X' in 'C:\lib.cs' conflicts with the imported type 'NNN.X' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "NNN.X", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NNN.X")); } [Fact] public void MultipleSourceSymbols1() { var sourceLib = @" public class C { } namespace C { } public class D : C { }"; // do not report lookup errors CreateCompilationWithMscorlib(sourceLib).VerifyDiagnostics( // error CS0101: The namespace '<global namespace>' already contains a definition for 'C' Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>")); } [Fact] public void MultipleSourceSymbols2() { var sourceRef1 = @" public class C { public class X { } } "; var sourceRef2 = @" namespace N { public class X { } } "; var sourceLib = @" public class C { public class X { } } namespace C { public class X { } } internal class D : C.X { } "; var ref1 = CreateCompilationWithMscorlib(sourceRef1, assemblyName: "Ref1").VerifyDiagnostics(); var ref2 = CreateCompilationWithMscorlib(sourceRef2, assemblyName: "Ref2").VerifyDiagnostics(); var tree = Parse(sourceLib, filename: @"C:\lib.cs"); var lib = CreateCompilationWithMscorlib(tree, new MetadataReference[] { new CSharpCompilationReference(ref1), new CSharpCompilationReference(ref2), }); // do not report lookup errors lib.VerifyDiagnostics( // C:\lib.cs(2,14): error CS0101: The namespace '<global namespace>' already contains a definition for 'C' Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>")); } [WorkItem(545725, "DevDiv")] [Fact] public void CS0436WRN_SameFullNameThisAggAgg02() { var text = @" namespace System { class Int32 { const Int32 MaxValue = null; static void Main() { Int32 x = System.Int32.MaxValue; } } } "; // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. CreateCompilationWithMscorlib(new SyntaxTree[] { Parse(text, "foo.cs") }).VerifyDiagnostics( // foo.cs(6,15): warning CS0436: The type 'System.Int32' in 'foo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'foo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Int32").WithArguments("foo.cs", "System.Int32", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "int"), // foo.cs(9,13): warning CS0436: The type 'System.Int32' in 'foo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'foo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Int32").WithArguments("foo.cs", "System.Int32", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "int"), // foo.cs(9,23): warning CS0436: The type 'System.Int32' in 'foo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'foo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "System.Int32").WithArguments("foo.cs", "System.Int32", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "int"), // foo.cs(9,19): warning CS0219: The variable 'x' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x")); } [WorkItem(538320, "DevDiv")] [Fact] public void CS0436WRN_SameFullNameThisAggAgg03() { var text = @"namespace System { class Object { static void Main() { Console.WriteLine(""hello""); } } class Foo : object {} class Bar : Object {} }"; // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. CreateCompilationWithMscorlib(new SyntaxTree[] { Parse(text, "foo.cs") }).VerifyDiagnostics( // foo.cs(11,17): warning CS0436: The type 'System.Object' in 'foo.cs' conflicts with the imported type 'object' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'foo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Object").WithArguments("foo.cs", "System.Object", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "object")); } /// <summary> /// import- Lib: namespace A { class B{} } vs. curr: class A { class B {} } /// </summary> [Fact] public void CS0437WRN_SameFullNameThisAggNs01() { var text = @"public class AppCS { public class App { } } namespace SA { class Test { AppCS.App app = null; void M(AppCS.App p) { } } } "; // this is not related to this test, but need by lib2 (don't want to add a new dll resource) var cs00 = TestReferences.MetadataTests.NetModule01.ModuleCS00; var cs01 = TestReferences.MetadataTests.NetModule01.ModuleCS01; var vb01 = TestReferences.MetadataTests.NetModule01.ModuleVB01; var ref1 = TestReferences.MetadataTests.NetModule01.AppCS; // Roslyn CS1542 var comp = CreateCompilationWithMscorlib(new List<string> { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (11,16): warning CS0437: The type 'AppCS' in '' conflicts with the imported namespace 'AppCS' in 'AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // void M(AppCS.App p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "AppCS").WithArguments("", "AppCS", "AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null", "AppCS"), // (10,9): warning CS0437: The type 'AppCS' in '' conflicts with the imported namespace 'AppCS' in 'AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // AppCS.App app = null; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "AppCS").WithArguments("", "AppCS", "AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null", "AppCS"), // (10,19): warning CS0414: The field 'SA.Test.app' is assigned but its value is never used // AppCS.App app = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "app").WithArguments("SA.Test.app")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } [WorkItem(545649, "DevDiv")] [Fact] public void CS0437WRN_SameFullNameThisAggNs02() { var source = @" using System; class System { } "; // NOTE: both mscorlib.dll and System.Core.dll define types in the System namespace. var compilation = CreateCompilationWithMscorlib( Parse(source, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)), new[] { SystemCoreRef }); compilation.VerifyDiagnostics( // (2,7): warning CS0437: The type 'System' in '' conflicts with the imported namespace 'System' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // using System; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "System").WithArguments("", "System", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System"), // (2,7): error CS0138: A using namespace directive can only be applied to namespaces; 'System' is a type not a namespace // using System; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System").WithArguments("System"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); } [Fact] public void CS0465WRN_FinalizeMethod() { var text = @" class A { protected virtual void Finalize() {} // CS0465 } abstract class B { public abstract void Finalize(); // CS0465 } abstract class C { protected int Finalize() {return 0;} // No Warning protected abstract void Finalize(int x); // No Warning protected virtual void Finalize<T>() { } // No Warning } class D : C { protected override void Finalize(int x) { } // No Warning protected override void Finalize<U>() { } // No Warning }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,27): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (9,25): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); } [Fact] public void CS0473WRN_ExplicitImplCollision() { var text = @"public interface ITest<T> { int TestMethod(int i); int TestMethod(T i); } public class ImplementingClass : ITest<int> { int ITest<int>.TestMethod(int i) // CS0473 { return i + 1; } public int TestMethod(int i) { return i - 1; } } class T { static int Main() { return 0; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ExplicitImplCollision, Line = 9, Column = 20, IsWarning = true }); } [Fact] public void CS0626WRN_ExternMethodNoImplementation01() { var source = @"class A : System.Attribute { } class B { extern void M(); extern object P1 { get; set; } extern static public bool operator !(B b); } class C { [A] extern void M(); [A] extern object P1 { get; set; } [A] extern static public bool operator !(C c); }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (4,17): warning CS0626: Method, operator, or accessor 'B.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("B.M()").WithLocation(4, 17), // (5,24): warning CS0626: Method, operator, or accessor 'B.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("B.P1.get").WithLocation(5, 24), // (5,29): warning CS0626: Method, operator, or accessor 'B.P1.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("B.P1.set").WithLocation(5, 29), // (6,40): warning CS0626: Method, operator, or accessor 'B.operator !(B)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "!").WithArguments("B.operator !(B)").WithLocation(6, 40), // (11,28): warning CS0626: Method, operator, or accessor 'C.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("C.P1.get").WithLocation(11, 28), // (11,33): warning CS0626: Method, operator, or accessor 'C.P1.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("C.P1.set").WithLocation(11, 33)); } [WorkItem(544660, "DevDiv")] [WorkItem(530324, "DevDiv")] [Fact] public void CS0626WRN_ExternMethodNoImplementation02() { var source = @"class A : System.Attribute { } delegate void D(); class C { extern event D E1; [A] extern event D E2; }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (5,20): warning CS0626: Method, operator, or accessor 'C.E1.add' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "E1").WithArguments("C.E1.add").WithLocation(5, 20), // (5,20): warning CS0626: Method, operator, or accessor 'C.E1.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "E1").WithArguments("C.E1.remove").WithLocation(5, 20), // (6,24): warning CS0626: Method, operator, or accessor 'C.E2.add' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "E2").WithArguments("C.E2.add").WithLocation(6, 24), // #15802 // (6,24): warning CS0626: Method, operator, or accessor 'C.E2.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "E2").WithArguments("C.E2.remove").WithLocation(6, 24)); // #15802 } [Fact] public void CS0628WRN_ProtectedInSealed01() { var text = @"namespace NS { sealed class Foo { protected int i = 0; protected internal void M() { } } sealed public class Bar<T> { internal protected void M1(T t) { } protected V M2<V>(T t) { return default(V); } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 5, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 6, Column = 33, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 11, Column = 33, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 12, Column = 21, IsWarning = true }); } [Fact] public void CS0628WRN_ProtectedInSealed02() { var text = @"sealed class C { protected object P { get { return null; } } public int Q { get; protected set; } } sealed class C<T> { internal protected T P { get; protected set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 3, Column = 22, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 4, Column = 35, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 8, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 8, Column = 45, IsWarning = true }); } [WorkItem(539588, "DevDiv")] [Fact] public void CS0628WRN_ProtectedInSealed03() { var text = @"abstract class C { protected abstract void M(); protected internal virtual int P { get { return 0; } } } sealed class D : C { protected override void M() { } protected internal override int P { get { return 0; } } protected void N() { } // CS0628 protected internal int Q { get { return 0; } } // CS0628 protected class Nested {} // CS0628 } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (13,21): warning CS0628: 'D.Nested': new protected member declared in sealed class // protected class Nested {} // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "Nested").WithArguments("D.Nested"), // (11,28): warning CS0628: 'D.Q': new protected member declared in sealed class // protected internal int Q { get { return 0; } } // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "Q").WithArguments("D.Q"), // (10,20): warning CS0628: 'D.N()': new protected member declared in sealed class // protected void N() { } // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "N").WithArguments("D.N()") ); } [Fact] public void CS0628WRN_ProtectedInSealed04() { var text = @" sealed class C { protected event System.Action E; } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,35): warning CS0628: 'C.E': new protected member declared in sealed class // protected event System.Action E; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "E").WithArguments("C.E"), // (4,35): warning CS0067: The event 'C.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0628WRN_ProtectedInSealed05() { const string text = @" abstract class C { protected C() { } } sealed class D : C { protected override D() { } protected D(byte b) { } protected internal D(short s) { } internal protected D(int i) { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (9,24): error CS0106: The modifier 'override' is not valid for this item // protected override D() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "D").WithArguments("override").WithLocation(9, 24), // (10,15): warning CS0628: 'D.D(byte)': new protected member declared in sealed class // protected D(byte b) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(byte)").WithLocation(10, 15), // (11,24): warning CS0628: 'D.D(short)': new protected member declared in sealed class // protected internal D(short s) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(short)").WithLocation(11, 24), // (12,24): warning CS0628: 'D.D(int)': new protected member declared in sealed class // internal protected D(int i) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(int)").WithLocation(12, 24)); } [Fact] public void CS0659WRN_EqualsWithoutGetHashCode() { var text = @"class Test { public override bool Equals(object o) { return true; } // CS0659 } // However the warning should NOT be produced if the Equals is not a 'real' override // of Equals. Neither of these should produce a warning: class Test2 { public new virtual bool Equals(object o) { return true; } } class Test3 : Test2 { public override bool Equals(object o) { return true; } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (1,7): warning CS0659: 'Test' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class Test Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "Test").WithArguments("Test") ); } [Fact] public void CS0660WRN_EqualityOpWithoutEquals() { var text = @" class TestBase { public new virtual bool Equals(object o) { return true; } } class Test : TestBase // CS0660 { public static bool operator ==(object o, Test t) { return true; } public static bool operator !=(object o, Test t) { return true; } // This does not count! public override bool Equals(object o) { return true; } public override int GetHashCode() { return 0; } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,7): warning CS0660: 'Test' defines operator == or operator != but does not override Object.Equals(object o) Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "Test").WithArguments("Test")); } [Fact] public void CS0660WRN_EqualityOpWithoutEquals_NoWarningWhenOveriddenWithDynamicParameter() { string source = @" public class C { public override bool Equals(dynamic o) { return false; } public static bool operator ==(C v1, C v2) { return true; } public static bool operator !=(C v1, C v2) { return false; } public override int GetHashCode() { return base.GetHashCode(); } }"; CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0661WRN_EqualityOpWithoutGetHashCode() { var text = @" class TestBase { // This does not count; it has to be overridden on Test. public override int GetHashCode() { return 123; } } class Test : TestBase // CS0661 { public static bool operator ==(object o, Test t) { return true; } public static bool operator !=(object o, Test t) { return true; } public override bool Equals(object o) { return true; } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (7,7): warning CS0659: 'Test' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class Test : TestBase // CS0661 Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "Test").WithArguments("Test"), // (7,7): warning CS0661: 'Test' defines operator == or operator != but does not override Object.GetHashCode() // class Test : TestBase // CS0661 Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "Test").WithArguments("Test") ); } [Fact()] public void CS0672WRN_NonObsoleteOverridingObsolete() { var text = @"class MyClass { [System.Obsolete] public virtual void ObsoleteMethod() { } } class MyClass2 : MyClass { public override void ObsoleteMethod() // CS0672 { } } class MainClass { static public void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NonObsoleteOverridingObsolete, Line = 11, Column = 26, IsWarning = true }); } [Fact()] public void CS0684WRN_CoClassWithoutComImport() { var text = @" using System.Runtime.InteropServices; [CoClass(typeof(C))] // CS0684 interface I { } class C { static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CoClassWithoutComImport, Line = 4, Column = 2, IsWarning = true }); } [Fact()] public void CS0809WRN_ObsoleteOverridingNonObsolete() { var text = @"public class Base { public virtual void Test1() { } } public class C : Base { [System.Obsolete()] public override void Test1() // CS0809 { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ObsoleteOverridingNonObsolete, Line = 10, Column = 26, IsWarning = true }); } [Fact] public void CS0824WRN_ExternCtorNoImplementation01() { var source = @"namespace NS { public class C<T> { extern C(); struct S { extern S(string s); } } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (5,16): warning CS0824: Constructor 'NS.C<T>.C()' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "C").WithArguments("NS.C<T>.C()").WithLocation(5, 16), // (9,20): warning CS0824: Constructor 'NS.C<T>.S.S(string)' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "S").WithArguments("NS.C<T>.S.S(string)").WithLocation(9, 20)); } [WorkItem(540859, "DevDiv")] [Fact] public void CS0824WRN_ExternCtorNoImplementation02() { var source = @"class A : System.Attribute { } class B { extern static B(); } class C { [A] extern static C(); }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (4,19): warning CS0824: Constructor 'B.B()' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(4, 19)); } [WorkItem(1084682, "DevDiv"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation03() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B(); } "; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(comp, verify: false, emitOptions: TestEmitters.RefEmitBug). VerifyDiagnostics( // (8,17): warning CS0824: Constructor 'B.B()' is marked external // public extern B(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(8, 17) ); Assert.True(verifier.TestData.Methods.Keys.Any(n => n.StartsWith("A..ctor"))); Assert.False(verifier.TestData.Methods.Keys.Any(n => n.StartsWith("B..ctor"))); // Haven't tried to emit it } [WorkItem(1084682, "DevDiv"), WorkItem(1036359, "DevDiv"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation04() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(); // error }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); // Dev12 : error CS1514: { expected // error CS1513: } expected comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(); // error Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "DevDiv"), WorkItem(1036359, "DevDiv"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation05() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(unknown); // error }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); // Dev12 : error CS1514: { expected // error CS1513: } expected comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(unknown); // error Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "DevDiv"), WorkItem(1036359, "DevDiv"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation06() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(1) {} }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(1) {} Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17), // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // public extern B() : base(1) {} Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "DevDiv"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation07() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() {} }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // public extern B() {} Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "DevDiv"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation08() { var source = @" public class B { private int x = 1; public extern B(); }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); comp.VerifyEmitDiagnostics( // (5,17): warning CS0824: Constructor 'B.B()' is marked external // public extern B(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(5, 17), // (4,15): warning CS0414: The field 'B.x' is assigned but its value is never used // private int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("B.x").WithLocation(4, 15) ); } [WorkItem(1084682, "DevDiv"), WorkItem(1036359, "DevDiv"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation09() { var source = @" public class A { public A() { } } public class B : A { static extern B() : base(); // error }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,23): error CS0514: 'B': static constructor cannot have an explicit 'this' or 'base' constructor call // static extern B() : base(); // error Diagnostic(ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall, "base").WithArguments("B").WithLocation(8, 23) ); } [WorkItem(1084682, "DevDiv"), WorkItem(1036359, "DevDiv"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation10() { var source = @" public class A { public A() { } } public class B : A { static extern B() : base() {} // error }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,23): error CS0514: 'B': static constructor cannot have an explicit 'this' or 'base' constructor call // static extern B() : base() {} // error Diagnostic(ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall, "base").WithArguments("B").WithLocation(8, 23), // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // static extern B() : base() {} // error Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation01() { // Slight change from the native compiler; in the native compiler the "int" gets the green squiggle. // This seems wrong; the error should either highlight the parameter "x" or the initializer " = 2". // I see no reason to highlight the "int". I've changed it to highlight the "x". var compilation = CreateCompilationWithMscorlib( @"interface IFace { int Foo(int x = 1); } class B : IFace { int IFace.Foo(int x = 2) { return 0; } }"); compilation.VerifyDiagnostics( // (7,23): error CS1066: The default value specified for parameter 'x' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "x").WithLocation(7, 23).WithArguments("x")); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation02() { var compilation = CreateCompilationWithMscorlib( @"interface I { object this[string index = null] { get; } //CS1066 object this[char c, char d] { get; } //CS1066 } class C : I { object I.this[string index = ""apple""] { get { return null; } } //CS1066 internal object this[int x, int y = 0] { get { return null; } } //fine object I.this[char c = 'c', char d = 'd'] { get { return null; } } //CS1066 x2 } "); compilation.VerifyDiagnostics( // (3,24): warning CS1066: The default value specified for parameter 'index' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "index").WithArguments("index"), // (7,26): warning CS1066: The default value specified for parameter 'index' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "index").WithArguments("index"), // (10,24): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (10,38): warning CS1066: The default value specified for parameter 'd' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "d").WithArguments("d")); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation03() { var compilation = CreateCompilationWithMscorlib( @" class C { public static C operator!(C c = null) { return c; } public static implicit operator int(C c = null) { return 0; } } "); compilation.VerifyDiagnostics( // (4,33): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // public static C operator!(C c = null) { return c; } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (5,43): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // public static implicit operator int(C c = null) { return 0; } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c") ); } // public void CS1698WRN_AssumedMatchThis() => Move to CommandLineTest [Fact] public void CS1699WRN_UseSwitchInsteadOfAttribute_RoslynWRN7033() { var text = @" [assembly:System.Reflection.AssemblyDelaySign(true)] // CS1699 "; // warning CS1699: Use command line option '/delaysign' or appropriate project settings instead of 'System.Reflection.AssemblyDelaySign' // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute, @"/delaysign").WithArguments(@"/delaysign", "System.Reflection.AssemblyDelaySign") // warning CS1607: Assembly generation -- Delay signing was requested, but no key was given CreateCompilationWithMscorlib(text).VerifyDiagnostics( // warning CS7033: Delay signing was specified and requires a public key, but no public key was specified Diagnostic(ErrorCode.WRN_DelaySignButNoKey) ); } [Fact(), WorkItem(544447, "DevDiv")] public void CS1700WRN_InvalidAssemblyName() { var text = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""' '"")] // ok [assembly: InternalsVisibleTo(""\t\r\n;a"")] // ok (whitespace escape) [assembly: InternalsVisibleTo(""\u1234;a"")] // ok (assembly name Unicode escape) [assembly: InternalsVisibleTo(""' a '"")] // ok [assembly: InternalsVisibleTo(""\u1000000;a"")] // invalid escape [assembly: InternalsVisibleTo(""a'b'c"")] // quotes in the middle [assembly: InternalsVisibleTo(""Test, PublicKey=Null"")] [assembly: InternalsVisibleTo(""Test, Bar"")] [assembly: InternalsVisibleTo(""Test, Version"")] [assembly: InternalsVisibleTo(""app2, Retargetable=f"")] // CS1700 "; // Tested against Dev12 CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,12): warning CS1700: Assembly reference 'a'b'c' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""a'b'c"")").WithArguments("a'b'c").WithLocation(8, 12), // (9,12): warning CS1700: Assembly reference 'Test, PublicKey=Null' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, PublicKey=Null"")").WithArguments("Test, PublicKey=Null").WithLocation(9, 12), // (10,12): warning CS1700: Assembly reference 'Test, Bar' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, Bar"")").WithArguments("Test, Bar").WithLocation(10, 12), // (11,12): warning CS1700: Assembly reference 'Test, Version' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, Version"")").WithArguments("Test, Version").WithLocation(11, 12), // (12,12): warning CS1700: Assembly reference 'app2, Retargetable=f' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""app2, Retargetable=f"")").WithArguments("app2, Retargetable=f").WithLocation(12, 12)); } // CS1701WRN_UnifyReferenceMajMin --> ReferenceManagerTests [Fact] public void CS1956WRN_MultipleRuntimeImplementationMatches() { var text = @"class Base<T, S> { public virtual int Test(out T x) // CS1956 { x = default(T); return 0; } public virtual int Test(ref S x) { return 1; } } interface IFace { int Test(out int x); } class Derived : Base<int, int>, IFace { static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_MultipleRuntimeImplementationMatches, Line = 9, Column = 24, IsWarning = true }); } [Fact] public void CS1957WRN_MultipleRuntimeOverrideMatches() { var text = @"class Base<TString> { public virtual void Test(TString s, out int x) { x = 0; } public virtual void Test(string s, ref int x) { } // CS1957 } class Derived : Base<string> { public override void Test(string s, ref int x) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_MultipleRuntimeOverrideMatches, Line = 8, Column = 25, IsWarning = true }); } [Fact] public void CS3000WRN_CLS_NoVarArgs() { var text = @" [assembly: System.CLSCompliant(true)] public class Test { public void AddABunchOfInts( __arglist) { } // CS3000 public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,17): warning CS3000: Methods with variable arguments are not CLS-compliant // public void AddABunchOfInts( __arglist) { } // CS3000 Diagnostic(ErrorCode.WRN_CLS_NoVarArgs, "AddABunchOfInts")); } [Fact] public void CS3001WRN_CLS_BadArgType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public void bad(ushort i) // CS3001 { } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,28): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void bad(ushort i) // CS3001 Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i").WithArguments("ushort")); } [Fact] public void CS3002WRN_CLS_BadReturnType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public ushort bad() // CS3002, public method { return ushort.MaxValue; } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,19): warning CS3002: Return type of 'a.bad()' is not CLS-compliant // public ushort bad() // CS3002, public method Diagnostic(ErrorCode.WRN_CLS_BadReturnType, "bad").WithArguments("a.bad()")); } [Fact] public void CS3003WRN_CLS_BadFieldPropType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public ushort a1; // CS3003, public variable public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,19): warning CS3003: Type of 'a.a1' is not CLS-compliant // public ushort a1; // CS3003, public variable Diagnostic(ErrorCode.WRN_CLS_BadFieldPropType, "a1").WithArguments("a.a1")); } [Fact] public void CS3005WRN_CLS_BadIdentifierCase() { var text = @"using System; [assembly: CLSCompliant(true)] public class a { public static int a1 = 0; public static int A1 = 1; // CS3005 public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (7,23): warning CS3005: Identifier 'a.A1' differing only in case is not CLS-compliant // public static int A1 = 1; // CS3005 Diagnostic(ErrorCode.WRN_CLS_BadIdentifierCase, "A1").WithArguments("a.A1")); } [Fact] public void CS3006WRN_CLS_OverloadRefOut() { var text = @"using System; [assembly: CLSCompliant(true)] public class MyClass { public void f(int i) { } public void f(ref int i) // CS3006 { } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (9,17): warning CS3006: Overloaded method 'MyClass.f(ref int)' differing only in ref or out, or in array rank, is not CLS-compliant // public void f(ref int i) // CS3006 Diagnostic(ErrorCode.WRN_CLS_OverloadRefOut, "f").WithArguments("MyClass.f(ref int)")); } [Fact] public void CS3007WRN_CLS_OverloadUnnamed() { var text = @"[assembly: System.CLSCompliant(true)] public struct S { public void F(int[][] array) { } public void F(byte[][] array) { } // CS3007 public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,17): warning CS3007: Overloaded method 'S.F(byte[][])' differing only by unnamed array types is not CLS-compliant // public void F(byte[][] array) { } // CS3007 Diagnostic(ErrorCode.WRN_CLS_OverloadUnnamed, "F").WithArguments("S.F(byte[][])")); } [Fact] public void CS3008WRN_CLS_BadIdentifier() { var text = @"using System; [assembly: CLSCompliant(true)] public class a { public static int _a = 0; // CS3008 public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (5,23): warning CS3008: Identifier '_a' is not CLS-compliant // public static int _a = 0; // CS3008 Diagnostic(ErrorCode.WRN_CLS_BadIdentifier, "_a").WithArguments("_a")); } [Fact] public void CS3009WRN_CLS_BadBase() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(false)] public class B { } public class C : B // CS3009 { public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (7,14): warning CS3009: 'C': base type 'B' is not CLS-compliant // public class C : B // CS3009 Diagnostic(ErrorCode.WRN_CLS_BadBase, "C").WithArguments("C", "B")); } [Fact] public void CS3010WRN_CLS_BadInterfaceMember() { var text = @"using System; [assembly: CLSCompliant(true)] public interface I { [CLSCompliant(false)] int M(); // CS3010 } public class C : I { public int M() { return 1; } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,9): warning CS3010: 'I.M()': CLS-compliant interfaces must have only CLS-compliant members // int M(); // CS3010 Diagnostic(ErrorCode.WRN_CLS_BadInterfaceMember, "M").WithArguments("I.M()")); } [Fact] public void CS3011WRN_CLS_NoAbstractMembers() { var text = @"using System; [assembly: CLSCompliant(true)] public abstract class I { [CLSCompliant(false)] public abstract int M(); // CS3011 } public class C : I { public override int M() { return 1; } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,25): warning CS3011: 'I.M()': only CLS-compliant members can be abstract // public abstract int M(); // CS3011 Diagnostic(ErrorCode.WRN_CLS_NoAbstractMembers, "M").WithArguments("I.M()")); } [Fact] public void CS3012WRN_CLS_NotOnModules() { var text = @"[module: System.CLSCompliant(true)] // CS3012 public class C { public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (1,10): warning CS3012: You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking // [module: System.CLSCompliant(true)] // CS3012 Diagnostic(ErrorCode.WRN_CLS_NotOnModules, "System.CLSCompliant(true)")); } [Fact] public void CS3013WRN_CLS_ModuleMissingCLS() { var netModule = CreateCompilation("", options: TestOptions.ReleaseModule, assemblyName: "lib").EmitToImageReference(expectedWarnings: new[] { Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion) }); CreateCompilationWithMscorlib("[assembly: System.CLSCompliant(true)]", new[] { netModule }).VerifyDiagnostics( // lib.netmodule: warning CS3013: Added modules must be marked with the CLSCompliant attribute to match the assembly Diagnostic(ErrorCode.WRN_CLS_ModuleMissingCLS)); } [Fact] public void CS3014WRN_CLS_AssemblyNotCLS() { var text = @"using System; // [assembly:CLSCompliant(true)] public class I { [CLSCompliant(true)] // CS3014 public void M() { } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,17): warning CS3014: 'I.M()' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute // public void M() Diagnostic(ErrorCode.WRN_CLS_AssemblyNotCLS, "M").WithArguments("I.M()")); } [Fact] public void CS3015WRN_CLS_BadAttributeType() { var text = @"using System; [assembly: CLSCompliant(true)] public class MyAttribute : Attribute { public MyAttribute(int[] ai) { } // CS3015 } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,14): warning CS3015: 'MyAttribute' has no accessible constructors which use only CLS-compliant types // public class MyAttribute : Attribute Diagnostic(ErrorCode.WRN_CLS_BadAttributeType, "MyAttribute").WithArguments("MyAttribute")); } [Fact] public void CS3016WRN_CLS_ArrayArgumentToAttribute() { var text = @"using System; [assembly: CLSCompliant(true)] [C(new int[] { 1, 2 })] // CS3016 public class C : Attribute { public C() { } public C(int[] a) { } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,2): warning CS3016: Arrays as attribute arguments is not CLS-compliant // [C(new int[] { 1, 2 })] // CS3016 Diagnostic(ErrorCode.WRN_CLS_ArrayArgumentToAttribute, "C(new int[] { 1, 2 })")); } [Fact] public void CS3017WRN_CLS_NotOnModules2() { var text = @"using System; [module: CLSCompliant(true)] [assembly: CLSCompliant(false)] // CS3017 class C { static void Main() { } } "; // NOTE: unlike dev11, roslyn assumes that [assembly:CLSCompliant(false)] means // "suppress all CLS diagnostics". CreateCompilationWithMscorlib(text).VerifyDiagnostics(); } [Fact] public void CS3018WRN_CLS_IllegalTrueInFalse() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(false)] public class Outer { [CLSCompliant(true)] // CS3018 public class Nested { } [CLSCompliant(false)] public class Nested3 { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (7,18): warning CS3018: 'Outer.Nested' cannot be marked as CLS-compliant because it is a member of non-CLS-compliant type 'Outer' // public class Nested { } Diagnostic(ErrorCode.WRN_CLS_IllegalTrueInFalse, "Nested").WithArguments("Outer.Nested", "Outer")); } [Fact] public void CS3019WRN_CLS_MeaninglessOnPrivateType() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(true)] // CS3019 class C { [CLSCompliant(false)] // CS3019 void Test() { } static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,7): warning CS3019: CLS compliance checking will not be performed on 'C' because it is not visible from outside this assembly // class C Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnPrivateType, "C").WithArguments("C"), // (7,10): warning CS3019: CLS compliance checking will not be performed on 'C.Test()' because it is not visible from outside this assembly // void Test() Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnPrivateType, "Test").WithArguments("C.Test()")); } [Fact] public void CS3021WRN_CLS_AssemblyNotCLS2() { var text = @"using System; [CLSCompliant(false)] // CS3021 public class C { public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (3,14): warning CS3021: 'C' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute // public class C Diagnostic(ErrorCode.WRN_CLS_AssemblyNotCLS2, "C").WithArguments("C")); } [Fact] public void CS3022WRN_CLS_MeaninglessOnParam() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(true)] public class C { public void F([CLSCompliant(true)] int i) { } public static void Main() { } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (6,20): warning CS3022: CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead. // public void F([CLSCompliant(true)] int i) Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnParam, "CLSCompliant(true)")); } [Fact] public void CS3023WRN_CLS_MeaninglessOnReturn() { var text = @"[assembly: System.CLSCompliant(true)] public class Test { [return: System.CLSCompliant(true)] // CS3023 public static int Main() { return 0; } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,14): warning CS3023: CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead. // [return: System.CLSCompliant(true)] // CS3023 Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnReturn, "System.CLSCompliant(true)")); } [Fact] public void CS3024WRN_CLS_BadTypeVar() { var text = @"[assembly: System.CLSCompliant(true)] [type: System.CLSCompliant(false)] public class TestClass // CS3024 { public ushort us; } [type: System.CLSCompliant(false)] public interface ITest // CS3024 { } public interface I<T> where T : TestClass { } public class TestClass_2<T> where T : ITest { } public class TestClass_3<T> : I<T> where T : TestClass { } public class TestClass_4<T> : TestClass_2<T> where T : ITest { } public class Test { public static int Main() { return 0; } } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (11,20): warning CS3024: Constraint type 'TestClass' is not CLS-compliant // public interface I<T> where T : TestClass Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("TestClass"), // (13,26): warning CS3024: Constraint type 'ITest' is not CLS-compliant // public class TestClass_2<T> where T : ITest Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("ITest"), // (17,26): warning CS3024: Constraint type 'ITest' is not CLS-compliant // public class TestClass_4<T> : TestClass_2<T> where T : ITest Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("ITest"), // (15,26): warning CS3024: Constraint type 'TestClass' is not CLS-compliant // public class TestClass_3<T> : I<T> where T : TestClass Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("TestClass")); } [Fact] public void CS3026WRN_CLS_VolatileField() { var text = @"[assembly: System.CLSCompliant(true)] public class Test { public volatile int v0 = 0; // CS3026 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CLS_VolatileField, Line = 4, Column = 25, IsWarning = true }); } [Fact] public void CS3027WRN_CLS_BadInterface() { var text = @"using System; [assembly: CLSCompliant(true)] public interface I1 { } [CLSCompliant(false)] public interface I2 { } public interface I : I1, I2 { } public class Foo { static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CLS_BadInterface, Line = 13, Column = 18, IsWarning = true }); } #endregion #region "Regressions or Mixed errors" [Fact] // bug 1985 public void ConstructWithErrors() { var text = @" class Base<T>{} class Derived : Base<NotFound>{}"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 22 }); var derived = comp.SourceModule.GlobalNamespace.GetTypeMembers("Derived").Single(); var Base = derived.BaseType; Assert.Equal(TypeKind.Class, Base.TypeKind); } [Fact] // bug 3045 public void AliasQualifiedName00() { var text = @"using NSA = A; namespace A { class Foo { } } namespace B { class Test { class NSA { public NSA(int Foo) { this.Foo = Foo; } int Foo; } static int Main() { NSA::Foo foo = new NSA::Foo(); // shouldn't error here foo = Xyzzy; return 0; } static NSA::Foo Xyzzy = null; // shouldn't error here } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); var b = comp.SourceModule.GlobalNamespace.GetMembers("B").Single() as NamespaceSymbol; var test = b.GetMembers("Test").Single() as NamedTypeSymbol; var nsa = test.GetMembers("NSA").Single() as NamedTypeSymbol; Assert.Equal(2, nsa.GetMembers().Length); } [WorkItem(538218, "DevDiv")] [Fact] public void RecursiveInterfaceLookup01() { var text = @"interface A<T> { } interface B : A<B.Garbage> { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DottedTypeNameNotFoundInAgg, Line = 2, Column = 19 }); var b = comp.SourceModule.GlobalNamespace.GetMembers("B").Single() as NamespaceSymbol; } [WorkItem(538150, "DevDiv")] [Fact] public void CS0102ERR_DuplicateNameInClass04() { var text = @" namespace NS { struct MyType { public class MyMeth { } public void MyMeth() { } public int MyMeth; } } "; var comp = CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (8,21): error CS0102: The type 'NS.MyType' already contains a definition for 'MyMeth' // public void MyMeth() { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "MyMeth").WithArguments("NS.MyType", "MyMeth"), // (9,20): error CS0102: The type 'NS.MyType' already contains a definition for 'MyMeth' // public int MyMeth; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "MyMeth").WithArguments("NS.MyType", "MyMeth"), // (9,20): warning CS0649: Field 'NS.MyType.MyMeth' is never assigned to, and will always have its default value 0 // public int MyMeth; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "MyMeth").WithArguments("NS.MyType.MyMeth", "0") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetMembers("MyType").Single() as NamedTypeSymbol; Assert.Equal(4, type1.GetMembers().Length); // constructor included } [Fact] public void CS0102ERR_DuplicateNameInClass05() { CreateCompilationWithMscorlib( @"class C { void P() { } int P { get { return 0; } } object Q { get; set; } void Q(int x, int y) { } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 9), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "Q").WithLocation(6, 10)); } [Fact] public void CS0102ERR_DuplicateNameInClass06() { CreateCompilationWithMscorlib( @"class C { private double get_P; // CS0102 private int set_P { get { return 0; } } // CS0102 void get_Q(object o) { } // no error class set_Q { } // CS0102 public int P { get; set; } object Q { get { return null; } } object R { set { } } enum get_R { } // CS0102 struct set_R { } // CS0102 }") .VerifyDiagnostics( // (7,20): error CS0102: The type 'C' already contains a definition for 'get_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("C", "get_P"), // (7,25): error CS0102: The type 'C' already contains a definition for 'set_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("C", "set_P"), // (8,12): error CS0102: The type 'C' already contains a definition for 'set_Q' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "set_Q"), // (9,12): error CS0102: The type 'C' already contains a definition for 'get_R' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "R").WithArguments("C", "get_R"), // (9,16): error CS0102: The type 'C' already contains a definition for 'set_R' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("C", "set_R"), // (3,20): warning CS0169: The field 'C.get_P' is never used // private double get_P; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("C.get_P")); } [Fact] public void CS0102ERR_DuplicateNameInClass07() { CreateCompilationWithMscorlib( @"class C { public int P { get { return 0; } set { } } public bool P { get { return false; } } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(8, 17)); } [WorkItem(538616, "DevDiv")] [Fact] public void CS0102ERR_DuplicateNameInClass08() { var text = @" class A<T> { void T() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInClass, Line = 4, Column = 10 }); } [WorkItem(538917, "DevDiv")] [Fact] public void CS0102ERR_DuplicateNameInClass09() { var text = @" class A<T> { class T<S> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInClass, Line = 4, Column = 11 }); } [WorkItem(538634, "DevDiv")] [Fact] public void CS0102ERR_DuplicateNameInClass10() { var text = @"class C<A, B, D, E, F, G> { object A; void B() { } object D { get; set; } class E { } struct F { } enum G { } }"; var comp = CreateCompilationWithMscorlib(text); comp.VerifyDiagnostics( // (3,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'A' // object A; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "A").WithArguments("C<A, B, D, E, F, G>", "A"), // (4,10): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'B' // void B() { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "B").WithArguments("C<A, B, D, E, F, G>", "B"), // (5,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'D' // object D { get; set; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "D").WithArguments("C<A, B, D, E, F, G>", "D"), // (6,11): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'E' // class E { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C<A, B, D, E, F, G>", "E"), // (7,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'F' // struct F { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "F").WithArguments("C<A, B, D, E, F, G>", "F"), // (8,10): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'G' // enum G { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C<A, B, D, E, F, G>", "G"), // (3,12): warning CS0169: The field 'C<A, B, D, E, F, G>.A' is never used // object A; Diagnostic(ErrorCode.WRN_UnreferencedField, "A").WithArguments("C<A, B, D, E, F, G>.A")); } [Fact] public void CS0101ERR_DuplicateNameInNS05() { CreateCompilationWithMscorlib( @"namespace N { enum E { A, B } enum E { A } // CS0101 }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "E").WithArguments("E", "N").WithLocation(4, 10)); } [WorkItem(528149, "DevDiv")] [Fact] public void CS0101ERR_DuplicateNameInNS06() { CreateCompilationWithMscorlib( @"namespace N { interface I { int P { get; } object Q { get; } } interface I // CS0101 { object Q { get; set; } } struct S { class T { } interface I { } } struct S // CS0101 { struct T { } // Dev10 reports CS0102 for T! int I; } class S // CS0101 { object T; } delegate void D(); delegate int D(int i); }") .VerifyDiagnostics( // (8,15): error CS0101: The namespace 'N' already contains a definition for 'I' // interface I // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "I").WithArguments("I", "N"), // (17,12): error CS0101: The namespace 'N' already contains a definition for 'S' // struct S // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "S").WithArguments("S", "N"), // (22,11): error CS0101: The namespace 'N' already contains a definition for 'S' // class S // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "S").WithArguments("S", "N"), // (27,18): error CS0101: The namespace 'N' already contains a definition for 'D' // delegate int D(int i); Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "D").WithArguments("D", "N"), // (24,16): warning CS0169: The field 'N.S.T' is never used // object T; Diagnostic(ErrorCode.WRN_UnreferencedField, "T").WithArguments("N.S.T"), // (20,13): warning CS0169: The field 'N.S.I' is never used // int I; Diagnostic(ErrorCode.WRN_UnreferencedField, "I").WithArguments("N.S.I") ); } [WorkItem(539742, "DevDiv")] [Fact] public void CS0102ERR_DuplicateNameInClass11() { CreateCompilationWithMscorlib( @"class C { enum E { A, B } enum E { A } // CS0102 }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "E").WithLocation(4, 10)); } [WorkItem(528149, "DevDiv")] [Fact] public void CS0102ERR_DuplicateNameInClass12() { CreateCompilationWithMscorlib( @"class C { interface I { int P { get; } object Q { get; } } interface I // CS0102 { object Q { get; set; } } struct S { class T { } interface I { } } struct S // CS0102 { struct T { } // Dev10 reports CS0102 for T! int I; } class S // CS0102 { object T; } delegate void D(); delegate int D(int i); }") .VerifyDiagnostics( // (8,15): error CS0102: The type 'C' already contains a definition for 'I' // interface I // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("C", "I"), // (17,12): error CS0102: The type 'C' already contains a definition for 'S' // struct S // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("C", "S"), // (22,11): error CS0102: The type 'C' already contains a definition for 'S' // class S // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("C", "S"), // (27,18): error CS0102: The type 'C' already contains a definition for 'D' // delegate int D(int i); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "D").WithArguments("C", "D"), // (24,16): warning CS0169: The field 'C.S.T' is never used // object T; Diagnostic(ErrorCode.WRN_UnreferencedField, "T").WithArguments("C.S.T"), // (20,13): warning CS0169: The field 'C.S.I' is never used // int I; Diagnostic(ErrorCode.WRN_UnreferencedField, "I").WithArguments("C.S.I") ); } [Fact] public void CS0102ERR_DuplicateNameInClass13() { CreateCompilationWithMscorlib( @"class C { private double add_E; // CS0102 private event System.Action remove_E; // CS0102 void add_F(object o) { } // no error class remove_F { } // CS0102 public event System.Action E; event System.Action F; event System.Action G; enum add_G { } // CS0102 struct remove_G { } // CS0102 }") .VerifyDiagnostics( // (7,32): error CS0102: The type 'C' already contains a definition for 'add_E' // public event System.Action E; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "add_E"), // (7,32): error CS0102: The type 'C' already contains a definition for 'remove_E' // public event System.Action E; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "remove_E"), // (8,25): error CS0102: The type 'C' already contains a definition for 'remove_F' // event System.Action F; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "F").WithArguments("C", "remove_F"), // (9,25): error CS0102: The type 'C' already contains a definition for 'add_G' // event System.Action G; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C", "add_G"), // (9,25): error CS0102: The type 'C' already contains a definition for 'remove_G' // event System.Action G; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C", "remove_G"), // (8,25): warning CS0067: The event 'C.F' is never used // event System.Action F; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F").WithArguments("C.F"), // (3,20): warning CS0169: The field 'C.add_E' is never used // private double add_E; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedField, "add_E").WithArguments("C.add_E"), // (4,33): warning CS0067: The event 'C.remove_E' is never used // private event System.Action remove_E; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "remove_E").WithArguments("C.remove_E"), // (7,32): warning CS0067: The event 'C.E' is never used // public event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E"), // (9,25): warning CS0067: The event 'C.G' is never used // event System.Action G; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "G").WithArguments("C.G")); } [Fact] public void CS0102ERR_DuplicateNameInClass14() { var text = @"using System.Runtime.CompilerServices; interface I { object this[object index] { get; set; } void Item(); } struct S { [IndexerName(""P"")] object this[object index] { get { return null; } } object Item; // no error object P; } class A { object get_Item; object set_Item; object this[int x, int y] { set { } } } class B { [IndexerName(""P"")] object this[object index] { get { return null; } } object get_Item; // no error object get_P; } class A1 { internal object this[object index] { get { return null; } } } class A2 { internal object Item; // no error } class B1 : A1 { internal object Item; } class B2 : A2 { internal object this[object index] { get { return null; } } // no error }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,12): error CS0102: The type 'I' already contains a definition for 'Item' // object this[object index] { get; set; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("I", "Item"), // (10,12): error CS0102: The type 'S' already contains a definition for 'P' // object this[object index] { get { return null; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("S", "P"), // (18,12): error CS0102: The type 'A' already contains a definition for 'get_Item' // object this[int x, int y] { set { } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_Item"), // (18,33): error CS0102: The type 'A' already contains a definition for 'set_Item' // object this[int x, int y] { set { } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_Item"), // (23,33): error CS0102: The type 'B' already contains a definition for 'get_P' // object this[object index] { get { return null; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("B", "get_P"), // (11,12): warning CS0169: The field 'S.Item' is never used // object Item; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("S.Item"), // (12,12): warning CS0169: The field 'S.P' is never used // object P; Diagnostic(ErrorCode.WRN_UnreferencedField, "P").WithArguments("S.P"), // (16,12): warning CS0169: The field 'A.get_Item' is never used // object get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item"), // (17,12): warning CS0169: The field 'A.set_Item' is never used // object set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item"), // (24,12): warning CS0169: The field 'B.get_Item' is never used // object get_Item; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("B.get_Item"), // (25,12): warning CS0169: The field 'B.get_P' is never used // object get_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("B.get_P"), // (33,21): warning CS0649: Field 'A2.Item' is never assigned to, and will always have its default value null // internal object Item; // no error Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item").WithArguments("A2.Item", "null"), // (37,21): warning CS0649: Field 'B1.Item' is never assigned to, and will always have its default value null // internal object Item; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item").WithArguments("B1.Item", "null") ); } // Indexers without IndexerNameAttribute [Fact] public void CS0102ERR_DuplicateNameInClass15() { var template = @" class A {{ public int this[int x] {{ set {{ }} }} {0} }}"; CreateCompilationWithMscorlib(string.Format(template, "int Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "Item"), // (5,9): warning CS0169: The field 'A.Item' is never used // int Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("A.Item")); // Error even though the indexer doesn't have a getter CreateCompilationWithMscorlib(string.Format(template, "int get_Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'get_Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_Item"), // (5,9): warning CS0169: The field 'A.get_Item' is never used // int get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item")); CreateCompilationWithMscorlib(string.Format(template, "int set_Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'set_Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_Item"), // (5,9): warning CS0169: The field 'A.set_Item' is never used // int set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item")); // Error even though the signatures don't match CreateCompilationWithMscorlib(string.Format(template, "int Item() { return 0; }")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "Item")); // Since the signatures don't match CreateCompilationWithMscorlib(string.Format(template, "int set_Item() { return 0; }")).VerifyDiagnostics(); } // Indexers with IndexerNameAttribute [Fact] public void CS0102ERR_DuplicateNameInClass16() { var template = @" using System.Runtime.CompilerServices; class A {{ [IndexerName(""P"")] public int this[int x] {{ set {{ }} }} {0} }}"; CreateCompilationWithMscorlib(string.Format(template, "int P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "P"), // (7,9): warning CS0169: The field 'A.P' is never used // int P; Diagnostic(ErrorCode.WRN_UnreferencedField, "P").WithArguments("A.P")); // Error even though the indexer doesn't have a getter CreateCompilationWithMscorlib(string.Format(template, "int get_P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'get_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_P"), // (7,9): warning CS0169: The field 'A.get_P' is never used // int get_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("A.get_P")); CreateCompilationWithMscorlib(string.Format(template, "int set_P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'set_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_P"), // (7,9): warning CS0169: The field 'A.set_P' is never used // int set_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_P").WithArguments("A.set_P")); // Error even though the signatures don't match CreateCompilationWithMscorlib(string.Format(template, "int P() { return 0; }")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "P")); // Since the signatures don't match CreateCompilationWithMscorlib(string.Format(template, "int set_P() { return 0; }")).VerifyDiagnostics(); // No longer have issues with "Item" names CreateCompilationWithMscorlib(string.Format(template, "int Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.Item' is never used // int Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("A.Item")); CreateCompilationWithMscorlib(string.Format(template, "int get_Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.get_Item' is never used // int get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item")); CreateCompilationWithMscorlib(string.Format(template, "int set_Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.set_Item' is never used // int set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item")); CreateCompilationWithMscorlib(string.Format(template, "int Item() { return 0; }")).VerifyDiagnostics(); CreateCompilationWithMscorlib(string.Format(template, "int set_Item() { return 0; }")).VerifyDiagnostics(); } [WorkItem(539625, "DevDiv")] [Fact] public void CS0104ERR_AmbigContext02() { var text = @" namespace Conformance.Expressions { using LevelOne.LevelTwo; using LevelOne.LevelTwo.LevelThree; public class Test { public static int Main() { return I<string>.Method(); // CS0104 } } namespace LevelOne { namespace LevelTwo { public class I<A1> { public static int Method() { return 1; } } namespace LevelThree { public class I<A1> { public static int Method() { return 2; } } } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigContext, Line = 12, Column = 20 }); } [Fact] public void CS0104ERR_AmbigContext03() { var text = @" namespace Conformance.Expressions { using LevelOne.LevelTwo; using LevelOne.LevelTwo.LevelThree; public class Test { public static int Main() { return I.Method(); // CS0104 } } namespace LevelOne { namespace LevelTwo { public class I { public static int Method() { return 1; } } namespace LevelThree { public class I { public static int Method() { return 2; } } } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigContext, Line = 12, Column = 20 }); } [WorkItem(540255, "DevDiv")] [Fact] public void CS0122ERR_BadAccess01() { var text = @" interface I<T> { } class A { private class B { } public class C : I<B> { } } class Program { static void Main() { Foo(new A.C()); } static void Foo<T>(I<T> x) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 15, Column = 9 }); } [Fact] public void CS0122ERR_BadAccess02() { var text = @" interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { static void Main() { Foo(new A.C()); } static void Foo<T>(I<T> x) { } static void Foo<T>(J<T> x) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); // no errors } [Fact] public void CS0122ERR_BadAccess03() { var text = @" interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { System.Console.WriteLine(""I""); } // static void M<T>(J<T> c) // { // System.Console.WriteLine(""J""); // } static void Main() { D d = M; d(null); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 29, Column = 15 }); } [Fact] public void CS0122ERR_BadAccess04() { var text = @"using System; interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { Console.WriteLine(""I""); } static void M<T>(J<T> c) { Console.WriteLine(""J""); } static void Main() { D d = M; d(null); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(3202, "DevDiv_Projects/Roslyn")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_InaccessibleImport() { var text = @"using A = A; namespace X { using B; } static class A { private static class B { } }"; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (4,11): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // using B; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(4, 11), // (1,1): info CS8019: Unnecessary using directive. // using A = A; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = A;").WithLocation(1, 1), // (4,5): info CS8019: Unnecessary using directive. // using B; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using B;").WithLocation(4, 5)); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_1() { var text = @"class ClassA { object F = new { f1<int> = 1 }; public static int f1 { get { return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidExprTerm, Line = 3, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidExprTerm, Line = 3, Column = 30 } ); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_2() { var text = @"class ClassA { object F = new { f1<T> }; public static int f1 { get { return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_TypeArgsNotAllowed, Line = 3, Column = 22 } ); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_3() { var text = @"class ClassA { object F = new { f1+ }; public static int f1 { get { return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidExprTerm, Line = 3, Column = 26 } ); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_4() { var text = @"class ClassA { object F = new { f1<int> }; public static int f1<T>() { return 1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, Line = 3, Column = 22 } ); } [Fact] public void CS7025ERR_BadVisEventType() { var text = @"internal interface InternalInterface { } internal delegate void InternalDelegate(); public class PublicClass { protected class Protected { } public event System.Action<InternalInterface> A; public event System.Action<InternalClass> B; internal event System.Action<Protected> C; public event InternalDelegate D; public event InternalDelegate E { add { } remove { } } } internal class InternalClass : PublicClass { public event System.Action<Protected> F; } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics( // (9,51): error CS7025: Inconsistent accessibility: event type 'System.Action<InternalInterface>' is less accessible than event 'PublicClass.A' // public event System.Action<InternalInterface> A; Diagnostic(ErrorCode.ERR_BadVisEventType, "A").WithArguments("PublicClass.A", "System.Action<InternalInterface>"), // (10,47): error CS7025: Inconsistent accessibility: event type 'System.Action<InternalClass>' is less accessible than event 'PublicClass.B' // public event System.Action<InternalClass> B; Diagnostic(ErrorCode.ERR_BadVisEventType, "B").WithArguments("PublicClass.B", "System.Action<InternalClass>"), // (11,45): error CS7025: Inconsistent accessibility: event type 'System.Action<PublicClass.Protected>' is less accessible than event 'PublicClass.C' // internal event System.Action<Protected> C; Diagnostic(ErrorCode.ERR_BadVisEventType, "C").WithArguments("PublicClass.C", "System.Action<PublicClass.Protected>"), // (13,35): error CS7025: Inconsistent accessibility: event type 'InternalDelegate' is less accessible than event 'PublicClass.D' // public event InternalDelegate D; Diagnostic(ErrorCode.ERR_BadVisEventType, "D").WithArguments("PublicClass.D", "InternalDelegate"), // (14,35): error CS7025: Inconsistent accessibility: event type 'InternalDelegate' is less accessible than event 'PublicClass.E' // public event InternalDelegate E { add { } remove { } } Diagnostic(ErrorCode.ERR_BadVisEventType, "E").WithArguments("PublicClass.E", "InternalDelegate"), // (18,43): error CS7025: Inconsistent accessibility: event type 'System.Action<PublicClass.Protected>' is less accessible than event 'InternalClass.F' // public event System.Action<Protected> F; Diagnostic(ErrorCode.ERR_BadVisEventType, "F").WithArguments("InternalClass.F", "System.Action<PublicClass.Protected>"), // (9,51): warning CS0067: The event 'PublicClass.A' is never used // public event System.Action<InternalInterface> A; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "A").WithArguments("PublicClass.A"), // (10,47): warning CS0067: The event 'PublicClass.B' is never used // public event System.Action<InternalClass> B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("PublicClass.B"), // (11,45): warning CS0067: The event 'PublicClass.C' is never used // internal event System.Action<Protected> C; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "C").WithArguments("PublicClass.C"), // (13,35): warning CS0067: The event 'PublicClass.D' is never used // public event InternalDelegate D; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "D").WithArguments("PublicClass.D"), // (18,43): warning CS0067: The event 'InternalClass.F' is never used // public event System.Action<Protected> F; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F").WithArguments("InternalClass.F")); } [Fact, WorkItem(543386, "DevDiv")] public void VolatileFieldWithGenericTypeConstrainedToClass() { var text = @" public class C {} class G<T> where T : C { public volatile T Fld = default(T); } "; CreateCompilationWithMscorlib(text).VerifyDiagnostics(); } #endregion [WorkItem(783920, "DevDiv")] [Fact()] public void Bug783920() { var comp1 = CreateCompilationWithMscorlib(@" public class MyAttribute1 : System.Attribute {} ", options: TestOptions.ReleaseDll, assemblyName: "Bug783920_CS"); var comp2 = CreateCompilationWithMscorlib(@" public class MyAttribute2 : MyAttribute1 {} ", new[] { new CSharpCompilationReference(comp1) }, options: TestOptions.ReleaseDll); var expected = new[] { // (2,2): error CS0012: The type 'MyAttribute1' is defined in an assembly that is not referenced. You must add a reference to assembly 'Bug783920_CS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // [MyAttribute2] Diagnostic(ErrorCode.ERR_NoTypeDef, "MyAttribute2").WithArguments("MyAttribute1", "Bug783920_CS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") }; var source3 = @" [MyAttribute2] public class Test {} "; var comp3 = CreateCompilationWithMscorlib(source3, new[] { new CSharpCompilationReference(comp2) }, options: TestOptions.ReleaseDll); comp3.GetDiagnostics().Verify(expected); var comp4 = CreateCompilationWithMscorlib(source3, new[] { comp2.EmitToImageReference() }, options: TestOptions.ReleaseDll); comp4.GetDiagnostics().Verify(expected); } } }
40.896229
338
0.599916
[ "Apache-2.0" ]
DavidKarlas/roslyn
src/Compilers/CSharp/Test/Symbol/Symbols/SymbolErrorTests.cs
781,897
C#
using System; namespace CSharpCodeAnalysis.Test.TestCodes { public partial class Test_NewMethodAddedToClass { public void Test1() { System.Diagnostics.Debug.WriteLine("hello"); } } }
19.333333
56
0.62931
[ "MIT" ]
andreinitescu/HotReloading
IDE/CSharpCodeAnalysis.Test/TestCodes/Test_NewMethodAddedToClass.cs
234
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.quickbi_public.Model.V20200731; namespace Aliyun.Acs.quickbi_public.Transform.V20200731 { public class GetUserGroupInfoResponseUnmarshaller { public static GetUserGroupInfoResponse Unmarshall(UnmarshallerContext _ctx) { GetUserGroupInfoResponse getUserGroupInfoResponse = new GetUserGroupInfoResponse(); getUserGroupInfoResponse.HttpResponse = _ctx.HttpResponse; getUserGroupInfoResponse.RequestId = _ctx.StringValue("GetUserGroupInfo.RequestId"); getUserGroupInfoResponse.Success = _ctx.BooleanValue("GetUserGroupInfo.Success"); List<GetUserGroupInfoResponse.GetUserGroupInfo_Data> getUserGroupInfoResponse_result = new List<GetUserGroupInfoResponse.GetUserGroupInfo_Data>(); for (int i = 0; i < _ctx.Length("GetUserGroupInfo.Result.Length"); i++) { GetUserGroupInfoResponse.GetUserGroupInfo_Data data = new GetUserGroupInfoResponse.GetUserGroupInfo_Data(); data.UsergroupId = _ctx.StringValue("GetUserGroupInfo.Result["+ i +"].UsergroupId"); data.UsergroupName = _ctx.StringValue("GetUserGroupInfo.Result["+ i +"].UsergroupName"); data.UsergroupDesc = _ctx.StringValue("GetUserGroupInfo.Result["+ i +"].UsergroupDesc"); data.ParentUsergroupId = _ctx.StringValue("GetUserGroupInfo.Result["+ i +"].ParentUsergroupId"); data.IdentifiedPath = _ctx.StringValue("GetUserGroupInfo.Result["+ i +"].IdentifiedPath"); data.CreateUser = _ctx.StringValue("GetUserGroupInfo.Result["+ i +"].CreateUser"); data.ModifyUser = _ctx.StringValue("GetUserGroupInfo.Result["+ i +"].ModifyUser"); data.CreateTime = _ctx.StringValue("GetUserGroupInfo.Result["+ i +"].CreateTime"); data.ModifiedTime = _ctx.StringValue("GetUserGroupInfo.Result["+ i +"].ModifiedTime"); getUserGroupInfoResponse_result.Add(data); } getUserGroupInfoResponse.Result = getUserGroupInfoResponse_result; return getUserGroupInfoResponse; } } }
49.103448
150
0.757022
[ "Apache-2.0" ]
aliyun/aliyun-openapi-net-sdk
aliyun-net-sdk-quickbi-public/Quickbi_public/Transform/V20200731/GetUserGroupInfoResponseUnmarshaller.cs
2,848
C#
namespace Intro.Web { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; public static class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.904762
70
0.555147
[ "MIT" ]
tonchevaAleksandra/C-Sharp-Web-Development-SoftUni-Problems
ASP.NET Core/ASP.Net Core App Intro/Web/Intro.Web/Program.cs
546
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200801.Outputs { [OutputType] public sealed class Ipv6CircuitConnectionConfigResponse { /// <summary> /// /125 IP address space to carve out customer addresses for global reach. /// </summary> public readonly string? AddressPrefix; /// <summary> /// Express Route Circuit connection state. /// </summary> public readonly string CircuitConnectionStatus; [OutputConstructor] private Ipv6CircuitConnectionConfigResponse( string? addressPrefix, string circuitConnectionStatus) { AddressPrefix = addressPrefix; CircuitConnectionStatus = circuitConnectionStatus; } } }
29.583333
83
0.667606
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Network/V20200801/Outputs/Ipv6CircuitConnectionConfigResponse.cs
1,065
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; public partial class DonateComplete : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if ((string)Session["username"] == null) { Response.Redirect("Home.aspx"); } else { HtmlMeta meta = new HtmlMeta(); meta.HttpEquiv = "Refresh"; meta.Content = "5;url=Donate.aspx"; this.Page.Controls.Add(meta); } // CREDIT TO http://www.aspsnippets.com/Articles/Redirect-to-another-page-after-5-seconds-in-ASPNet.aspx } void Page_PreInit(object sender, EventArgs e) { if ((Convert.ToInt32(Session["theme"])) == 0) { MasterPageFile = "~/MasterPage.master"; } else if ((Convert.ToInt32(Session["theme"])) == 1) { MasterPageFile = "~/SecondMasterPage.master"; } } }
28.25641
113
0.568058
[ "Unlicense" ]
Darren-Lim-School-Project/ESE3006
DonateComplete.aspx.cs
1,104
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.AI.QnA; using Newtonsoft.Json; namespace $safeprojectname$.Middleware.Telemetry { /// <summary> /// TelemetryQnaRecognizer invokes the Qna Maker and logs some results into Application Insights. /// Logs the score, and (optionally) question /// Along with Conversation and ActivityID. /// The Custom Event name this logs is "QnaMessage" /// See <seealso cref="QnaMaker"/> for additional information. /// </summary> public class TelemetryQnAMaker : QnAMaker { public const string QnaMsgEvent = "QnaMessage"; private QnAMakerEndpoint _endpoint; /// <summary> /// Initializes a new instance of the <see cref="TelemetryQnAMaker"/> class. /// </summary> /// <param name="endpoint">The endpoint of the knowledge base to query.</param> /// <param name="options">The options for the QnA Maker knowledge base.</param> /// <param name="logUserName">The flag to include username in logs.</param> /// <param name="logOriginalMessage">The flag to include original message in logs.</param> /// <param name="httpClient">An alternate client with which to talk to QnAMaker. /// If null, a default client is used for this instance.</param> public TelemetryQnAMaker(QnAMakerEndpoint endpoint, QnAMakerOptions options = null, bool logUserName = false, bool logOriginalMessage = false, HttpClient httpClient = null) : base(endpoint, options, httpClient) { LogUserName = logUserName; LogOriginalMessage = logOriginalMessage; _endpoint = endpoint; } public bool LogUserName { get; } public bool LogOriginalMessage { get; } public async Task<QueryResult[]> GetAnswersAsync(ITurnContext context) { // Call Qna Maker var queryResults = await base.GetAnswersAsync(context); // Find the Application Insights Telemetry Client if (queryResults != null && context.TurnState.TryGetValue(TelemetryLoggerMiddleware.AppInsightsServiceKey, out var telemetryClient)) { var telemetryProperties = new Dictionary<string, string>(); var telemetryMetrics = new Dictionary<string, double>(); telemetryProperties.Add(QnATelemetryConstants.KnowledgeBaseIdProperty, _endpoint.KnowledgeBaseId); // Make it so we can correlate our reports with Activity or Conversation telemetryProperties.Add(QnATelemetryConstants.ActivityIdProperty, context.Activity.Id); var conversationId = context.Activity.Conversation.Id; if (!string.IsNullOrEmpty(conversationId)) { telemetryProperties.Add(QnATelemetryConstants.ConversationIdProperty, conversationId); } // For some customers, logging original text name within Application Insights might be an issue var text = context.Activity.Text; if (LogOriginalMessage && !string.IsNullOrWhiteSpace(text)) { telemetryProperties.Add(QnATelemetryConstants.OriginalQuestionProperty, text); } // For some customers, logging user name within Application Insights might be an issue var userName = context.Activity.From.Name; if (LogUserName && !string.IsNullOrWhiteSpace(userName)) { telemetryProperties.Add(QnATelemetryConstants.UsernameProperty, userName); } // Fill in Qna Results (found or not) if (queryResults.Length > 0) { var queryResult = queryResults[0]; telemetryProperties.Add(QnATelemetryConstants.QuestionProperty, JsonConvert.SerializeObject(queryResult.Questions)); telemetryProperties.Add(QnATelemetryConstants.AnswerProperty, queryResult.Answer); telemetryMetrics.Add(QnATelemetryConstants.ScoreProperty, queryResult.Score); telemetryProperties.Add(QnATelemetryConstants.ArticleFoundProperty, "true"); } else { telemetryProperties.Add(QnATelemetryConstants.QuestionProperty, "No Qna Question matched"); telemetryProperties.Add(QnATelemetryConstants.AnswerProperty, "No Qna Answer matched"); telemetryProperties.Add(QnATelemetryConstants.ArticleFoundProperty, "true"); } // Track the event ((IBotTelemetryClient)telemetryClient).TrackEvent(QnaMsgEvent, telemetryProperties, telemetryMetrics); } return queryResults; } } }
48.2
180
0.643154
[ "MIT" ]
SVemulapalli/AI
templates/Enterprise-Template/src/csharp/EnterpriseBotTemplate/Bot Framework/Middleware/Telemetry/TelemetryQnAMaker.cs
5,063
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace ET { public struct ProcessActorId { public int Process; public long ActorId; public ProcessActorId(long actorId) { InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId); this.Process = instanceIdStruct.Process; instanceIdStruct.Process = Game.Options.Process; this.ActorId = instanceIdStruct.ToLong(); } } public class NetInnerComponent : Entity { public AService Service; public static NetInnerComponent Instance; public IMessageDispatcher MessageDispatcher { get; set; } } }
25
78
0.65931
[ "MIT" ]
dayfox5317/ET_Lua
Server/Model/Module/Message/NetInnerComponent.cs
727
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using VueExample.Models; namespace VueExample.Entities.Configurations { public class CodeProductConfiguration : IEntityTypeConfiguration<CodeProduct> { public void Configure(EntityTypeBuilder<CodeProduct> builder) { builder.HasMany(k => k.Wafers).WithOne(e => e.CodeProduct).HasForeignKey(fk => fk.CodeProductId); } } }
32.857143
109
0.73913
[ "MIT" ]
7is7/SVR2.0
Entities/Configurations/CodeProductConfiguration.cs
460
C#
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using Newtonsoft.Json; /* * TODO: * - Need Sessions (Cookie-based for HTTP): cannot currently distinguish between different requests */ namespace Nekara.Networking { delegate void Middleware(Request request, Response response, Action next); class Router { private protected List<Middleware> middlewares; private protected Dictionary<string, List<Middleware>> methodMiddlewares; private protected Dictionary<string, Router> routeMap; public Router() { this.middlewares = new List<Middleware>(); this.methodMiddlewares = new Dictionary<string, List<Middleware>>(); this.methodMiddlewares.Add("OPTIONS", new List<Middleware>()); this.methodMiddlewares.Add("GET", new List<Middleware>()); this.methodMiddlewares.Add("POST", new List<Middleware>()); this.methodMiddlewares.Add("PUT", new List<Middleware>()); this.methodMiddlewares.Add("DELETE", new List<Middleware>()); this.routeMap = new Dictionary<string, Router>(); } public Router Route(string path) { Router router; if (this.routeMap.TryGetValue(path, out router)) { return router; } else { router = new Router(); this.routeMap.Add(path, router); Console.WriteLine(" Added new Router at: {0}", path); return router; } } public void Use(Middleware middleware) { this.middlewares.Add(middleware); } public void Use(string path, Middleware middleware) { Router router = this.Route(path); router.Use(middleware); // this.middlewares.Add(middleware); Console.WriteLine(" Added new middleware at: {0}", path); } protected void UseOnMethod(string method, Middleware middleware) { this.methodMiddlewares[method].Add(middleware); } public void Options(string path, Middleware middleware) { Router router = this.Route(path); router.UseOnMethod("OPTIONS", middleware); } public void Get(string path, Middleware middleware) { Router router = this.Route(path); router.UseOnMethod("GET", middleware); } public void Post(string path, Middleware middleware) { Router router = this.Route(path); router.UseOnMethod("POST", middleware); } public void Put(string path, Middleware middleware) { Router router = this.Route(path); router.UseOnMethod("PUT", middleware); } public void Delete(string path, Middleware middleware) { Router router = this.Route(path); router.UseOnMethod("DELETE", middleware); } protected void HandleRequest(string[] pathSegments, Request request, Response response) { if (pathSegments.Length == 0) { Action next = null; int index = 0; // these variables are captured by "next" closure int methodIndex = 0; // these variables are captured by "next" closure next = () => { if (index < this.middlewares.Count) { Middleware handler = this.middlewares[index]; index++; handler(request, response, next); } else if (methodIndex < this.methodMiddlewares[request.method].Count) { Middleware handler = this.methodMiddlewares[request.method][methodIndex]; methodIndex++; handler(request, response, next); } }; next(); } else { Router router = this.routeMap[pathSegments[0]]; router.HandleRequest(pathSegments.Skip(1).ToArray(), request, response); } } } // light wrapper around the native HttpListenerRequest class to hide away the low-level details // this may not be necessary as the native class is pretty high-level, but keeping it for now in case we need that extra level of indirection. class Request { private HttpListenerRequest request; private readonly string _body; public Request(HttpListenerRequest request) { this.request = request; //Console.WriteLine("HTTP: {0} {1}", request.HttpMethod, request.Url.PathAndQuery); if (request.HasEntityBody) { Stream stream = request.InputStream; Encoding encoding = request.ContentEncoding; StreamReader reader = new StreamReader(stream, encoding); /*if (request.ContentType != null) { Console.WriteLine("Client data content type {0}", request.ContentType); } Console.WriteLine("Client data content length {0}", request.ContentLength64);*/ // Print some meta info /*if (request.ContentType != null) { Console.WriteLine(" Content-Type: {0}", request.ContentType); Console.WriteLine(" Payload Size: {0}", request.ContentLength64); }*/ // Console.WriteLine("Start of client data:"); // Convert the data to a string and display it on the console. this._body = reader.ReadToEnd(); //Console.WriteLine(this._body); // Console.WriteLine("End of client data:"); stream.Close(); reader.Close(); } else this._body = ""; } public string method { get { return this.request.HttpMethod; } } public string path { get { return this.request.Url.PathAndQuery; } } public string[] pathSegments { get { return this.request.Url.Segments; } } public string body { get { return this._body; } } public CookieCollection cookies { get { return this.request.Cookies; } } } // light wrapper around the native HttpListenerResponse class to hide away the low-level details class Response { private HttpListenerResponse response; public Response(HttpListenerResponse response) { this.response = response; } public void Send(int statusCode, string payload) { // Construct a response. // string responseString = "<HTML><BODY> Hello world!</BODY></HTML>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(payload); // Get a response stream and write the response to it. this.response.ContentLength64 = buffer.Length; this.response.StatusCode = statusCode; System.IO.Stream output = this.response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); // listener.Stop(); } public void Send(int statusCode, Object payload) { // try serializing object into JSON // this will throw an exception if the payload is not a serializable object - i.e., has DataContractAttribute string serialized = JsonConvert.SerializeObject(payload); // Construct a response. // string responseString = "<HTML><BODY> Hello world!</BODY></HTML>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(serialized); // Get a response stream and write the response to it. this.response.ContentLength64 = buffer.Length; this.response.StatusCode = statusCode; this.response.ContentEncoding = Encoding.UTF8; this.response.ContentType = "application/json; charset=utf-8"; System.IO.Stream output = this.response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); // listener.Stop(); } } // This is an HTTP Server providing an asynchronous API like Express.js // It should run strictly on a single thread, otherwise things like // session data will be under race condition. class HttpServer : Router { private string host; private int port; private HttpListener listener; public HttpServer(string host, int port) : base() { this.host = host; this.port = port; this.listener = new HttpListener(); this.listener.Prefixes.Add("http://" + host + ":" + port.ToString() + "/"); } // Listen returns immediately, and the "listening" is done asynchronously via Task loop. public void Listen() { listener.Start(); Console.WriteLine("Listening..."); Helpers.AsyncLoop(HandleRequest); } // top-level request handler, should wrap low-level API // and call subsequent handlers private void HandleRequest() { HttpListenerContext context = listener.GetContext(); // First check if this is a websocket handshake if (!context.Request.IsWebSocketRequest) { /* Console.WriteLine("WebSocket Request Received!!!"); context.AcceptWebSocketAsync(null) .ContinueWith(prev => this.wss.AddClient(prev.Result)); } else { */ Request request = new Request(context.Request); Response response = new Response(context.Response); // Before passing the request on to user-defined middleware functions, // route the request depending on the request method and path base.HandleRequest(request.pathSegments.Skip(1).ToArray(), request, response); } } } }
37.052817
146
0.561722
[ "MIT" ]
p-org/nekara-csharp
Source/NekaraRpcServer/Networking/HttpServer.cs
10,525
C#
#region License /* * WebSocketServer.cs * * The MIT License * * Copyright (c) 2012-2015 sta.blockhead * * 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 #region Contributors /* * Contributors: * - Juan Manuel Lallana <[email protected]> * - Jonas Hovgaard <[email protected]> * - Liryna <[email protected]> * - Rohan Singh <[email protected]> */ #endregion using System; using System.Collections.Generic; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; using System.Threading; using WebSocketSharp.Net; using WebSocketSharp.Net.WebSockets; namespace WebSocketSharp.Server { /// <summary> /// Provides a WebSocket protocol server. /// </summary> /// <remarks> /// This class can provide multiple WebSocket services. /// </remarks> public class WebSocketServer { #region Private Fields private System.Net.IPAddress _address; private bool _allowForwardedRequest; private AuthenticationSchemes _authSchemes; private static readonly string _defaultRealm; private bool _dnsStyle; private string _hostname; private TcpListener _listener; private Logger _log; private int _port; private string _realm; private string _realmInUse; private Thread _receiveThread; private bool _reuseAddress; private bool _secure; private WebSocketServiceManager _services; private ServerSslConfiguration _sslConfig; private ServerSslConfiguration _sslConfigInUse; private volatile ServerState _state; private object _sync; private Func<IIdentity, NetworkCredential> _userCredFinder; #endregion #region Static Constructor static WebSocketServer () { _defaultRealm = "SECRET AREA"; } #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class. /// </summary> /// <remarks> /// The new instance listens for incoming handshake requests on /// <see cref="System.Net.IPAddress.Any"/> and port 80. /// </remarks> public WebSocketServer () { var addr = System.Net.IPAddress.Any; init (addr.ToString (), addr, 80, false); } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class /// with the specified <paramref name="port"/>. /// </summary> /// <remarks> /// <para> /// The new instance listens for incoming handshake requests on /// <see cref="System.Net.IPAddress.Any"/> and <paramref name="port"/>. /// </para> /// <para> /// It provides secure connections if <paramref name="port"/> is 443. /// </para> /// </remarks> /// <param name="port"> /// An <see cref="int"/> that represents the number of the port /// on which to listen. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> is less than 1 or greater than 65535. /// </exception> public WebSocketServer (int port) : this (port, port == 443) { } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class /// with the specified <paramref name="url"/>. /// </summary> /// <remarks> /// <para> /// The new instance listens for incoming handshake requests on /// the IP address of the host of <paramref name="url"/> and /// the port of <paramref name="url"/>. /// </para> /// <para> /// Either port 80 or 443 is used if <paramref name="url"/> includes /// no port. Port 443 is used if the scheme of <paramref name="url"/> /// is wss; otherwise, port 80 is used. /// </para> /// <para> /// The new instance provides secure connections if the scheme of /// <paramref name="url"/> is wss. /// </para> /// </remarks> /// <param name="url"> /// A <see cref="string"/> that represents the WebSocket URL of the server. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="url"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="url"/> is an empty string. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="url"/> is invalid. /// </para> /// </exception> public WebSocketServer (string url) { if (url == null) throw new ArgumentNullException ("url"); if (url.Length == 0) throw new ArgumentException ("An empty string.", "url"); Uri uri; string msg; if (!tryCreateUri (url, out uri, out msg)) throw new ArgumentException (msg, "url"); var host = uri.DnsSafeHost; var addr = host.ToIPAddress (); if (addr == null) { msg = "The host part could not be converted to an IP address."; throw new ArgumentException (msg, "url"); } if (!addr.IsLocal ()) { msg = "The IP address of the host is not a local IP address."; throw new ArgumentException (msg, "url"); } init (host, addr, uri.Port, uri.Scheme == "wss"); } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class /// with the specified <paramref name="port"/> and <paramref name="secure"/>. /// </summary> /// <remarks> /// The new instance listens for incoming handshake requests on /// <see cref="System.Net.IPAddress.Any"/> and <paramref name="port"/>. /// </remarks> /// <param name="port"> /// An <see cref="int"/> that represents the number of the port /// on which to listen. /// </param> /// <param name="secure"> /// A <see cref="bool"/>: <c>true</c> if the new instance provides /// secure connections; otherwise, <c>false</c>. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> is less than 1 or greater than 65535. /// </exception> public WebSocketServer (int port, bool secure) { if (!port.IsPortNumber ()) { var msg = "Less than 1 or greater than 65535."; throw new ArgumentOutOfRangeException ("port", msg); } var addr = System.Net.IPAddress.Any; init (addr.ToString (), addr, port, secure); } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class /// with the specified <paramref name="address"/> and <paramref name="port"/>. /// </summary> /// <remarks> /// <para> /// The new instance listens for incoming handshake requests on /// <paramref name="address"/> and <paramref name="port"/>. /// </para> /// <para> /// It provides secure connections if <paramref name="port"/> is 443. /// </para> /// </remarks> /// <param name="address"> /// A <see cref="System.Net.IPAddress"/> that represents the local /// IP address on which to listen. /// </param> /// <param name="port"> /// An <see cref="int"/> that represents the number of the port /// on which to listen. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="address"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="address"/> is not a local IP address. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> is less than 1 or greater than 65535. /// </exception> public WebSocketServer (System.Net.IPAddress address, int port) : this (address, port, port == 443) { } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class /// with the specified <paramref name="address"/>, <paramref name="port"/>, /// and <paramref name="secure"/>. /// </summary> /// <remarks> /// The new instance listens for incoming handshake requests on /// <paramref name="address"/> and <paramref name="port"/>. /// </remarks> /// <param name="address"> /// A <see cref="System.Net.IPAddress"/> that represents the local /// IP address on which to listen. /// </param> /// <param name="port"> /// An <see cref="int"/> that represents the number of the port /// on which to listen. /// </param> /// <param name="secure"> /// A <see cref="bool"/>: <c>true</c> if the new instance provides /// secure connections; otherwise, <c>false</c>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="address"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="address"/> is not a local IP address. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> is less than 1 or greater than 65535. /// </exception> public WebSocketServer (System.Net.IPAddress address, int port, bool secure) { if (address == null) throw new ArgumentNullException ("address"); if (!address.IsLocal ()) throw new ArgumentException ("Not a local IP address.", "address"); if (!port.IsPortNumber ()) { var msg = "Less than 1 or greater than 65535."; throw new ArgumentOutOfRangeException ("port", msg); } init (address.ToString (), address, port, secure); } #endregion #region Public Properties /// <summary> /// Gets the IP address of the server. /// </summary> /// <value> /// A <see cref="System.Net.IPAddress"/> that represents the local /// IP address on which to listen for incoming handshake requests. /// </value> public System.Net.IPAddress Address { get { return _address; } } /// <summary> /// Gets or sets a value indicating whether the server accepts every /// handshake request without checking the request URI. /// </summary> /// <remarks> /// The set operation does nothing if the server has already started or /// it is shutting down. /// </remarks> /// <value> /// <para> /// <c>true</c> if the server accepts every handshake request without /// checking the request URI; otherwise, <c>false</c>. /// </para> /// <para> /// The default value is <c>false</c>. /// </para> /// </value> public bool AllowForwardedRequest { get { return _allowForwardedRequest; } set { string msg; if (!canSet (out msg)) { _log.Warn (msg); return; } lock (_sync) { if (!canSet (out msg)) { _log.Warn (msg); return; } _allowForwardedRequest = value; } } } /// <summary> /// Gets or sets the scheme used to authenticate the clients. /// </summary> /// <remarks> /// The set operation does nothing if the server has already started or /// it is shutting down. /// </remarks> /// <value> /// <para> /// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> /// enum values. /// </para> /// <para> /// It represents the scheme used to authenticate the clients. /// </para> /// <para> /// The default value is /// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>. /// </para> /// </value> public AuthenticationSchemes AuthenticationSchemes { get { return _authSchemes; } set { string msg; if (!canSet (out msg)) { _log.Warn (msg); return; } lock (_sync) { if (!canSet (out msg)) { _log.Warn (msg); return; } _authSchemes = value; } } } /// <summary> /// Gets a value indicating whether the server has started. /// </summary> /// <value> /// <c>true</c> if the server has started; otherwise, <c>false</c>. /// </value> public bool IsListening { get { return _state == ServerState.Start; } } /// <summary> /// Gets a value indicating whether secure connections are provided. /// </summary> /// <value> /// <c>true</c> if this instance provides secure connections; otherwise, /// <c>false</c>. /// </value> public bool IsSecure { get { return _secure; } } /// <summary> /// Gets or sets a value indicating whether the server cleans up /// the inactive sessions periodically. /// </summary> /// <remarks> /// The set operation does nothing if the server has already started or /// it is shutting down. /// </remarks> /// <value> /// <para> /// <c>true</c> if the server cleans up the inactive sessions every /// 60 seconds; otherwise, <c>false</c>. /// </para> /// <para> /// The default value is <c>true</c>. /// </para> /// </value> public bool KeepClean { get { return _services.KeepClean; } set { _services.KeepClean = value; } } /// <summary> /// Gets the logging function for the server. /// </summary> /// <remarks> /// The default logging level is <see cref="LogLevel.Error"/>. /// </remarks> /// <value> /// A <see cref="Logger"/> that provides the logging function. /// </value> public Logger Log { get { return _log; } } /// <summary> /// Gets the port of the server. /// </summary> /// <value> /// An <see cref="int"/> that represents the number of the port /// on which to listen for incoming handshake requests. /// </value> public int Port { get { return _port; } } /// <summary> /// Gets or sets the realm used for authentication. /// </summary> /// <remarks> /// <para> /// "SECRET AREA" is used as the realm if the value is /// <see langword="null"/> or an empty string. /// </para> /// <para> /// The set operation does nothing if the server has /// already started or it is shutting down. /// </para> /// </remarks> /// <value> /// <para> /// A <see cref="string"/> or <see langword="null"/> by default. /// </para> /// <para> /// That string represents the name of the realm. /// </para> /// </value> public string Realm { get { return _realm; } set { string msg; if (!canSet (out msg)) { _log.Warn (msg); return; } lock (_sync) { if (!canSet (out msg)) { _log.Warn (msg); return; } _realm = value; } } } /// <summary> /// Gets or sets a value indicating whether the server is allowed to /// be bound to an address that is already in use. /// </summary> /// <remarks> /// <para> /// You should set this property to <c>true</c> if you would /// like to resolve to wait for socket in TIME_WAIT state. /// </para> /// <para> /// The set operation does nothing if the server has already /// started or it is shutting down. /// </para> /// </remarks> /// <value> /// <para> /// <c>true</c> if the server is allowed to be bound to an address /// that is already in use; otherwise, <c>false</c>. /// </para> /// <para> /// The default value is <c>false</c>. /// </para> /// </value> public bool ReuseAddress { get { return _reuseAddress; } set { string msg; if (!canSet (out msg)) { _log.Warn (msg); return; } lock (_sync) { if (!canSet (out msg)) { _log.Warn (msg); return; } _reuseAddress = value; } } } /// <summary> /// Gets the configuration for secure connections. /// </summary> /// <remarks> /// This configuration will be referenced when attempts to start, /// so it must be configured before the start method is called. /// </remarks> /// <value> /// A <see cref="ServerSslConfiguration"/> that represents /// the configuration used to provide secure connections. /// </value> /// <exception cref="InvalidOperationException"> /// This instance does not provide secure connections. /// </exception> public ServerSslConfiguration SslConfiguration { get { if (!_secure) { var msg = "This instance does not provide secure connections."; throw new InvalidOperationException (msg); } return getSslConfiguration (); } } /// <summary> /// Gets or sets the delegate used to find the credentials /// for an identity. /// </summary> /// <remarks> /// <para> /// No credentials are found if the method invoked by /// the delegate returns <see langword="null"/> or /// the value is <see langword="null"/>. /// </para> /// <para> /// The set operation does nothing if the server has /// already started or it is shutting down. /// </para> /// </remarks> /// <value> /// <para> /// A <c>Func&lt;<see cref="IIdentity"/>, /// <see cref="NetworkCredential"/>&gt;</c> delegate or /// <see langword="null"/> if not needed. /// </para> /// <para> /// That delegate invokes the method called for finding /// the credentials used to authenticate a client. /// </para> /// <para> /// The default value is <see langword="null"/>. /// </para> /// </value> public Func<IIdentity, NetworkCredential> UserCredentialsFinder { get { return _userCredFinder; } set { string msg; if (!canSet (out msg)) { _log.Warn (msg); return; } lock (_sync) { if (!canSet (out msg)) { _log.Warn (msg); return; } _userCredFinder = value; } } } /// <summary> /// Gets or sets the time to wait for the response to the WebSocket Ping or /// Close. /// </summary> /// <remarks> /// The set operation does nothing if the server has already started or /// it is shutting down. /// </remarks> /// <value> /// <para> /// A <see cref="TimeSpan"/> to wait for the response. /// </para> /// <para> /// The default value is the same as 1 second. /// </para> /// </value> /// <exception cref="ArgumentOutOfRangeException"> /// The value specified for a set operation is zero or less. /// </exception> public TimeSpan WaitTime { get { return _services.WaitTime; } set { _services.WaitTime = value; } } /// <summary> /// Gets the management function for the WebSocket services /// provided by the server. /// </summary> /// <value> /// A <see cref="WebSocketServiceManager"/> that manages /// the WebSocket services provided by the server. /// </value> public WebSocketServiceManager WebSocketServices { get { return _services; } } #endregion #region Private Methods private void abort () { lock (_sync) { if (_state != ServerState.Start) return; _state = ServerState.ShuttingDown; } try { try { _listener.Stop (); } finally { _services.Stop (1006, String.Empty); } } catch { } _state = ServerState.Stop; } private bool canSet (out string message) { message = null; if (_state == ServerState.Start) { message = "The server has already started."; return false; } if (_state == ServerState.ShuttingDown) { message = "The server is shutting down."; return false; } return true; } private bool checkHostNameForRequest (string name) { return !_dnsStyle || Uri.CheckHostName (name) != UriHostNameType.Dns || name == _hostname; } private static bool checkSslConfiguration ( ServerSslConfiguration configuration, out string message ) { message = null; if (configuration.ServerCertificate == null) { message = "There is no server certificate for secure connections."; return false; } return true; } private string getRealm () { var realm = _realm; return realm != null && realm.Length > 0 ? realm : _defaultRealm; } private ServerSslConfiguration getSslConfiguration () { if (_sslConfig == null) _sslConfig = new ServerSslConfiguration (); return _sslConfig; } private void init ( string hostname, System.Net.IPAddress address, int port, bool secure ) { _hostname = hostname; _address = address; _port = port; _secure = secure; _authSchemes = AuthenticationSchemes.Anonymous; _dnsStyle = Uri.CheckHostName (hostname) == UriHostNameType.Dns; _listener = new TcpListener (address, port); _log = new Logger (); _services = new WebSocketServiceManager (_log); _sync = new object (); } private void processRequest (TcpListenerWebSocketContext context) { var uri = context.RequestUri; if (uri == null) { context.Close (HttpStatusCode.BadRequest); return; } if (!_allowForwardedRequest) { if (uri.Port != _port) { context.Close (HttpStatusCode.BadRequest); return; } if (!checkHostNameForRequest (uri.DnsSafeHost)) { context.Close (HttpStatusCode.NotFound); return; } } WebSocketServiceHost host; if (!_services.InternalTryGetServiceHost (uri.AbsolutePath, out host)) { context.Close (HttpStatusCode.NotImplemented); return; } host.StartSession (context); } private void receiveRequest () { while (true) { TcpClient cl = null; try { cl = _listener.AcceptTcpClient (); ThreadPool.QueueUserWorkItem ( state => { try { var ctx = new TcpListenerWebSocketContext ( cl, null, _secure, _sslConfigInUse, _log ); if (!ctx.Authenticate (_authSchemes, _realmInUse, _userCredFinder)) return; processRequest (ctx); } catch (Exception ex) { _log.Error (ex.Message); _log.Debug (ex.ToString ()); cl.Close (); } } ); } catch (SocketException ex) { if (_state == ServerState.ShuttingDown) { _log.Info ("The underlying listener is stopped."); break; } _log.Fatal (ex.Message); _log.Debug (ex.ToString ()); break; } catch (Exception ex) { _log.Fatal (ex.Message); _log.Debug (ex.ToString ()); if (cl != null) cl.Close (); break; } } if (_state != ServerState.ShuttingDown) abort (); } private void start (ServerSslConfiguration sslConfig) { if (_state == ServerState.Start) { _log.Info ("The server has already started."); return; } if (_state == ServerState.ShuttingDown) { _log.Warn ("The server is shutting down."); return; } lock (_sync) { if (_state == ServerState.Start) { _log.Info ("The server has already started."); return; } if (_state == ServerState.ShuttingDown) { _log.Warn ("The server is shutting down."); return; } _sslConfigInUse = sslConfig; _realmInUse = getRealm (); _services.Start (); try { startReceiving (); } catch { _services.Stop (1011, String.Empty); throw; } _state = ServerState.Start; } } private void startReceiving () { if (_reuseAddress) { _listener.Server.SetSocketOption ( SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true ); } try { _listener.Start (); } catch (Exception ex) { var msg = "The underlying listener has failed to start."; throw new InvalidOperationException (msg, ex); } _receiveThread = new Thread (new ThreadStart (receiveRequest)); _receiveThread.IsBackground = true; _receiveThread.Start (); } private void stop (ushort code, string reason) { if (_state == ServerState.Ready) { _log.Info ("The server is not started."); return; } if (_state == ServerState.ShuttingDown) { _log.Info ("The server is shutting down."); return; } if (_state == ServerState.Stop) { _log.Info ("The server has already stopped."); return; } lock (_sync) { if (_state == ServerState.ShuttingDown) { _log.Info ("The server is shutting down."); return; } if (_state == ServerState.Stop) { _log.Info ("The server has already stopped."); return; } _state = ServerState.ShuttingDown; } try { var threw = false; try { stopReceiving (5000); } catch { threw = true; throw; } finally { try { _services.Stop (code, reason); } catch { if (!threw) throw; } } } finally { _state = ServerState.Stop; } } private void stopReceiving (int millisecondsTimeout) { try { _listener.Stop (); } catch (Exception ex) { var msg = "The underlying listener has failed to stop."; throw new InvalidOperationException (msg, ex); } _receiveThread.Join (millisecondsTimeout); } private static bool tryCreateUri ( string uriString, out Uri result, out string message ) { if (!uriString.TryCreateWebSocketUri (out result, out message)) return false; if (result.PathAndQuery != "/") { result = null; message = "It includes either or both path and query components."; return false; } return true; } #endregion #region Public Methods /// <summary> /// Adds a WebSocket service with the specified behavior, /// <paramref name="path"/>, and <paramref name="creator"/>. /// </summary> /// <remarks> /// <paramref name="path"/> is converted to a URL-decoded string and /// '/' is trimmed from the end of the converted string if any. /// </remarks> /// <param name="path"> /// A <see cref="string"/> that represents an absolute path to /// the service to add. /// </param> /// <param name="creator"> /// <para> /// A <c>Func&lt;TBehavior&gt;</c> delegate. /// </para> /// <para> /// It invokes the method called for creating a new session /// instance for the service. /// </para> /// <para> /// The method must create a new instance of the specified /// behavior class and return it. /// </para> /// </param> /// <typeparam name="TBehavior"> /// <para> /// The type of the behavior for the service. /// </para> /// <para> /// It must inherit the <see cref="WebSocketBehavior"/> class. /// </para> /// </typeparam> /// <exception cref="ArgumentNullException"> /// <para> /// <paramref name="path"/> is <see langword="null"/>. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="creator"/> is <see langword="null"/>. /// </para> /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is an empty string. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is already in use. /// </para> /// </exception> [Obsolete ("This method will be removed. Use added one instead.")] public void AddWebSocketService<TBehavior> ( string path, Func<TBehavior> creator ) where TBehavior : WebSocketBehavior { if (path == null) throw new ArgumentNullException ("path"); if (creator == null) throw new ArgumentNullException ("creator"); if (path.Length == 0) throw new ArgumentException ("An empty string.", "path"); if (path[0] != '/') throw new ArgumentException ("Not an absolute path.", "path"); if (path.IndexOfAny (new[] { '?', '#' }) > -1) { var msg = "It includes either or both query and fragment components."; throw new ArgumentException (msg, "path"); } _services.Add<TBehavior> (path, creator); } /// <summary> /// Adds a WebSocket service with the specified behavior and /// <paramref name="path"/>. /// </summary> /// <remarks> /// <paramref name="path"/> is converted to a URL-decoded string and /// '/' is trimmed from the end of the converted string if any. /// </remarks> /// <param name="path"> /// A <see cref="string"/> that represents an absolute path to /// the service to add. /// </param> /// <typeparam name="TBehaviorWithNew"> /// <para> /// The type of the behavior for the service. /// </para> /// <para> /// It must inherit the <see cref="WebSocketBehavior"/> class and /// have a public parameterless constructor. /// </para> /// </typeparam> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is an empty string. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is already in use. /// </para> /// </exception> public void AddWebSocketService<TBehaviorWithNew> (string path) where TBehaviorWithNew : WebSocketBehavior, new () { _services.AddService<TBehaviorWithNew> (path, null); } /// <summary> /// Adds a WebSocket service with the specified behavior, /// <paramref name="path"/>, and <paramref name="initializer"/>. /// </summary> /// <remarks> /// <paramref name="path"/> is converted to a URL-decoded string and /// '/' is trimmed from the end of the converted string if any. /// </remarks> /// <param name="path"> /// A <see cref="string"/> that represents an absolute path to /// the service to add. /// </param> /// <param name="initializer"> /// <para> /// An <c>Action&lt;TBehaviorWithNew&gt;</c> delegate or /// <see langword="null"/> if not needed. /// </para> /// <para> /// That delegate invokes the method called for initializing /// a new session instance for the service. /// </para> /// </param> /// <typeparam name="TBehaviorWithNew"> /// <para> /// The type of the behavior for the service. /// </para> /// <para> /// It must inherit the <see cref="WebSocketBehavior"/> class and /// have a public parameterless constructor. /// </para> /// </typeparam> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is an empty string. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is already in use. /// </para> /// </exception> public void AddWebSocketService<TBehaviorWithNew> ( string path, Action<TBehaviorWithNew> initializer ) where TBehaviorWithNew : WebSocketBehavior, new () { _services.AddService<TBehaviorWithNew> (path, initializer); } /// <summary> /// Removes a WebSocket service with the specified <paramref name="path"/>. /// </summary> /// <remarks> /// <para> /// <paramref name="path"/> is converted to a URL-decoded string and /// '/' is trimmed from the end of the converted string if any. /// </para> /// <para> /// The service is stopped with close status 1001 (going away) /// if it has already started. /// </para> /// </remarks> /// <returns> /// <c>true</c> if the service is successfully found and removed; /// otherwise, <c>false</c>. /// </returns> /// <param name="path"> /// A <see cref="string"/> that represents an absolute path to /// the service to remove. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is an empty string. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// </exception> public bool RemoveWebSocketService (string path) { return _services.RemoveService (path); } /// <summary> /// Starts receiving incoming handshake requests. /// </summary> /// <remarks> /// This method does nothing if the server has already started or /// it is shutting down. /// </remarks> /// <exception cref="InvalidOperationException"> /// <para> /// There is no server certificate for secure connections. /// </para> /// <para> /// -or- /// </para> /// <para> /// The underlying <see cref="TcpListener"/> has failed to start. /// </para> /// </exception> public void Start () { ServerSslConfiguration sslConfig = null; if (_secure) { sslConfig = new ServerSslConfiguration (getSslConfiguration ()); string msg; if (!checkSslConfiguration (sslConfig, out msg)) throw new InvalidOperationException (msg); } start (sslConfig); } /// <summary> /// Stops receiving incoming handshake requests and closes /// each connection. /// </summary> /// <remarks> /// This method does nothing if the server is not started, /// it is shutting down, or it has already stopped. /// </remarks> /// <exception cref="InvalidOperationException"> /// The underlying <see cref="TcpListener"/> has failed to stop. /// </exception> public void Stop () { stop (1005, String.Empty); } /// <summary> /// Stops receiving incoming handshake requests and closes each /// connection with the specified <paramref name="code"/> and /// <paramref name="reason"/>. /// </summary> /// <remarks> /// This method does nothing if the server is not started, /// it is shutting down, or it has already stopped. /// </remarks> /// <param name="code"> /// <para> /// A <see cref="ushort"/> that represents the status code /// indicating the reason for the close. /// </para> /// <para> /// The status codes are defined in /// <see href="http://tools.ietf.org/html/rfc6455#section-7.4"> /// Section 7.4</see> of RFC 6455. /// </para> /// </param> /// <param name="reason"> /// <para> /// A <see cref="string"/> that represents the reason for the close. /// </para> /// <para> /// The size must be 123 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <para> /// <paramref name="code"/> is less than 1000 or greater than 4999. /// </para> /// <para> /// -or- /// </para> /// <para> /// The size of <paramref name="reason"/> is greater than 123 bytes. /// </para> /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="code"/> is 1010 (mandatory extension). /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="code"/> is 1005 (no status) and /// there is <paramref name="reason"/>. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="reason"/> could not be UTF-8-encoded. /// </para> /// </exception> /// <exception cref="InvalidOperationException"> /// The underlying <see cref="TcpListener"/> has failed to stop. /// </exception> public void Stop (ushort code, string reason) { if (!code.IsCloseStatusCode ()) { var msg = "Less than 1000 or greater than 4999."; throw new ArgumentOutOfRangeException ("code", msg); } if (code == 1010) { var msg = "1010 cannot be used."; throw new ArgumentException (msg, "code"); } if (!reason.IsNullOrEmpty ()) { if (code == 1005) { var msg = "1005 cannot be used."; throw new ArgumentException (msg, "code"); } byte[] bytes; if (!reason.TryGetUTF8EncodedBytes (out bytes)) { var msg = "It could not be UTF-8-encoded."; throw new ArgumentException (msg, "reason"); } if (bytes.Length > 123) { var msg = "Its size is greater than 123 bytes."; throw new ArgumentOutOfRangeException ("reason", msg); } } stop (code, reason); } /// <summary> /// Stops receiving incoming handshake requests and closes each /// connection with the specified <paramref name="code"/> and /// <paramref name="reason"/>. /// </summary> /// <remarks> /// This method does nothing if the server is not started, /// it is shutting down, or it has already stopped. /// </remarks> /// <param name="code"> /// <para> /// One of the <see cref="CloseStatusCode"/> enum values. /// </para> /// <para> /// It represents the status code indicating the reason for the close. /// </para> /// </param> /// <param name="reason"> /// <para> /// A <see cref="string"/> that represents the reason for the close. /// </para> /// <para> /// The size must be 123 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="code"/> is /// <see cref="CloseStatusCode.MandatoryExtension"/>. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="code"/> is /// <see cref="CloseStatusCode.NoStatus"/> and /// there is <paramref name="reason"/>. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="reason"/> could not be UTF-8-encoded. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The size of <paramref name="reason"/> is greater than 123 bytes. /// </exception> /// <exception cref="InvalidOperationException"> /// The underlying <see cref="TcpListener"/> has failed to stop. /// </exception> public void Stop (CloseStatusCode code, string reason) { if (code == CloseStatusCode.MandatoryExtension) { var msg = "MandatoryExtension cannot be used."; throw new ArgumentException (msg, "code"); } if (!reason.IsNullOrEmpty ()) { if (code == CloseStatusCode.NoStatus) { var msg = "NoStatus cannot be used."; throw new ArgumentException (msg, "code"); } byte[] bytes; if (!reason.TryGetUTF8EncodedBytes (out bytes)) { var msg = "It could not be UTF-8-encoded."; throw new ArgumentException (msg, "reason"); } if (bytes.Length > 123) { var msg = "Its size is greater than 123 bytes."; throw new ArgumentOutOfRangeException ("reason", msg); } } stop ((ushort) code, reason); } #endregion } }
28.967593
83
0.546314
[ "MIT" ]
ARAisling/NiceHashMiner
src/3rdparty/websocket-sharp/Server/WebSocketServer.cs
43,799
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class SFactToChange : CVariable { [Ordinal(0)] [RED("factName")] public CName FactName { get; set; } [Ordinal(1)] [RED("factValue")] public CInt32 FactValue { get; set; } [Ordinal(2)] [RED("operationType")] public CEnum<EMathOperationType> OperationType { get; set; } public SFactToChange(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
30.444444
100
0.691606
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/SFactToChange.cs
531
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Task02_WebFormsApp.Account { public partial class Confirm { /// <summary> /// successPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder successPanel; /// <summary> /// login control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HyperLink login; /// <summary> /// errorPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder errorPanel; } }
32.340909
84
0.508784
[ "MIT" ]
atanas-georgiev/TelerikAcademy
16.ASP.NET-Web-Forms/Homeworks/02. ASP.NET-Web-Forms-Intro/Task02_WebFormsApp/Account/Confirm.aspx.designer.cs
1,425
C#