content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.ComponentModel; namespace Sce.Atf.Controls.PropertyEditing { /// <summary> /// TypeConverter for use with enum editors where enum is stored as int. /// It converts int to string and string to int.</summary> public class IntEnumTypeConverter : TypeConverter, IAnnotatedParams { /// <summary> /// Default construct, required for IAnnotatedParams</summary> public IntEnumTypeConverter() { } /// <summary> /// Construct using an enum type</summary> /// <param name="enumType">Enum type</param> public IntEnumTypeConverter(Type enumType) { if (!enumType.IsEnum) throw new ArgumentException("enumType must Enum"); m_names = Enum.GetNames(enumType); //Note: don't use Enum.GetValues(...) to populate m_values m_values = new int[m_names.Length]; for (int i = 0; i < m_values.Length; i++) { m_values[i] = (int)Enum.Parse(enumType, m_names[i]); } } /// <summary> /// Construct using names and values /// </summary> /// <param name="names">Enum names</param> /// <param name="values">Enum values</param> public IntEnumTypeConverter(string[] names, int[] values) { DefineEnums(names, values); } #region IAnnotatedParams Members void IAnnotatedParams.Initialize(string[] parameters) { string[] displayNames; string[] names; int[] values; EnumUtil.ParseEnumDefinitions(parameters, out names, out displayNames, out values); DefineEnums(names, values); } #endregion #region base override /// <summary> /// Test if can convert value from a type in a context</summary> /// <param name="context">Context in which conversion occurs</param> /// <param name="sourceType">Type to convert from</param> /// <returns>True iff can convert type</returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } /// <summary> /// Convert value in a context and culture</summary> /// <param name="context">Context in which conversion occurs</param> /// <param name="culture">Culture that indicates conversion format</param> /// <param name="value">Value to convert</param> /// <returns>Converted value</returns> public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { string strVal = value as string; if (strVal != null) { for (int i = 0; i < m_names.Length; i++) { if (strVal == m_names[i]) return m_values[i]; } // no match. return -1; } throw new ArgumentException("value must be string"); } /// <summary> /// Test if can convert value to a type in a context</summary> /// <param name="context">Context in which conversion occurs</param> /// <param name="destinationType">Type to convert to</param> /// <returns>True iff can convert type</returns> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string); } /// <summary> /// Convert value to a type in a context and culture</summary> /// <param name="context">Context in which conversion occurs</param> /// <param name="culture">Culture that indicates conversion format</param> /// <param name="value">Value to convert</param> /// <param name="destinationType">Type to convert to</param> /// <returns>Converted value</returns> public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (value is int && destinationType == typeof(string)) { int intVal = (int)value; for (int i = 0; i < m_values.Length; i++) { if (intVal == m_values[i]) return m_names[i]; } return string.Empty; } throw new ArgumentException("value must be an int and destinationType must be a string"); } #endregion private void DefineEnums(string[] names, int[] values) { if (names == null || names.Length == 0 || values == null || names.Length != values.Length) throw new ArgumentException(); m_names = names; m_values = values; } private string[] m_names; private int[] m_values; } }
37.711268
151
0.548459
[ "Apache-2.0" ]
HaKDMoDz/ATF
Framework/Atf.Gui/Controls/PropertyEditing/IntEnumTypeConverter.cs
5,217
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace TestApp { /// <summary> /// Interaktionslogik für "App.xaml" /// </summary> public partial class App : Application { } }
17.944444
42
0.69969
[ "MIT" ]
C9Glax/Graf
Graf/TestApp/App.xaml.cs
326
C#
/* Win3mu - Windows 3 Emulator Copyright (C) 2017 Topten Software. Win3mu is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Win3mu is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Win3mu. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Win3muCore { class WindowCreationFilter : IWndProcFilter { public WindowCreationFilter(ushort hInstance) { _hInstance = hInstance; } ushort _hInstance; IntPtr _hWnd; bool _createMessageReceived; public IntPtr? PreWndProc(uint pfnProc, ref Win32.MSG msg, bool dlgProc) { // Wait for WM_NCCREATE message if (msg.message == Win32.WM_NCCREATE && _hWnd == IntPtr.Zero) { _hWnd = msg.hWnd; // Give window class early notification WindowClass.OnNcCreate(msg.hWnd); } // Correct window? if (msg.hWnd != _hWnd) return null; // Setup window instance handle if (_hInstance!=0 && HWND.HInstanaceOfHWnd(msg.hWnd) == 0) { HWND.RegisterHWndToHInstance(msg.hWnd, _hInstance); _hInstance = 0; } // Suppress WM_SIZE messages until WM_CREATE has been received (fixes for crash in Solitaire) if (msg.message == Win32.WM_SIZE && !_createMessageReceived) { return IntPtr.Zero; } // Flag receipt of WM_CREATE if (msg.message == Win32.WM_CREATE) { _createMessageReceived = true; } return null; } } }
29.578947
105
0.607206
[ "MIT" ]
mediaexplorer74/Win3Mu
Win3muCore/Windowing/WindowCreationFilter.cs
2,250
C#
using System.Runtime.Serialization; using Gherkin.Events.Args; using Gherkin.Events.Args.Ast; namespace Gherkin.Events { public class GherkinDocumentEvent : IEvent { public GherkinDocumentEvent(GherkinDocumentEventArgs eventArgs) { EventArgs = eventArgs; } public GherkinDocumentEvent() { } [DataMember(Name = "gherkinDocument")] public GherkinDocumentEventArgs EventArgs { get; set; } } }
21.190476
68
0.705618
[ "MIT" ]
Corristo/cucumber
gherkin/dotnet/Gherkin/Events/GherkinDocumentEvent.cs
447
C#
using System.IO; namespace Framework.Installer.Behaviour { /// <summary> /// Defines filters to exclude files from msi /// </summary> public static class FileFilters { /// <summary></summary> public static bool ExcludePackagesConfig(string filename) { filename = new FileInfo(filename).Name.ToLower(); return filename != "packages.config"; } /// <summary></summary> public static bool ExcludeRedundantConfigFromBinFolder(string filename) { filename = new FileInfo(filename).Name.ToLower(); return filename != "appsettings.config" && filename != "connectionstrings.config" && !filename.EndsWith(".dll.config"); } /// <summary></summary> public static bool ExcludeAllConfigs(string filename) { return !filename.EndsWith(".config"); } } }
31.225806
97
0.568182
[ "MIT" ]
Luxoft/BSSFramework
src.other/Framework.Installer/Behaviour/FileFilters.cs
940
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ActiveLogin.Authentication.BankId.Api.Models; namespace ActiveLogin.Authentication.BankId.Api { /// <summary> /// Dummy implementation that can be used for development and testing purposes. /// </summary> public class BankIdDevelopmentApiClient : IBankIdApiClient { private static readonly List<KeyValuePair<CollectStatus, CollectHintCode>> DefaultStatusesToReturn = new List<KeyValuePair<CollectStatus, CollectHintCode>> { new KeyValuePair<CollectStatus, CollectHintCode>(CollectStatus.Pending, CollectHintCode.OutstandingTransaction), new KeyValuePair<CollectStatus, CollectHintCode>(CollectStatus.Pending, CollectHintCode.OutstandingTransaction), new KeyValuePair<CollectStatus, CollectHintCode>(CollectStatus.Pending, CollectHintCode.Started), new KeyValuePair<CollectStatus, CollectHintCode>(CollectStatus.Pending, CollectHintCode.Started), new KeyValuePair<CollectStatus, CollectHintCode>(CollectStatus.Pending, CollectHintCode.UserSign), new KeyValuePair<CollectStatus, CollectHintCode>(CollectStatus.Complete, CollectHintCode.UserSign) }; private readonly string _givenName; private readonly string _surname; private readonly string _name; private readonly string _personalIdentityNumber; private readonly List<KeyValuePair<CollectStatus, CollectHintCode>> _statusesToReturn; private readonly Dictionary<string, Auth> _auths = new Dictionary<string, Auth>(); private TimeSpan _delay = TimeSpan.FromMilliseconds(250); public BankIdDevelopmentApiClient() : this(DefaultStatusesToReturn) { } public BankIdDevelopmentApiClient(List<KeyValuePair<CollectStatus, CollectHintCode>> statusesToReturn) : this("GivenName", "Surname", "199908072391", statusesToReturn) { } public BankIdDevelopmentApiClient(string givenName, string surname) : this(givenName, surname, "199908072391") { } public BankIdDevelopmentApiClient(string givenName, string surname, string personalIdentityNumber) : this(givenName, surname, personalIdentityNumber, DefaultStatusesToReturn) { } public BankIdDevelopmentApiClient(string givenName, string surname, string personalIdentityNumber, List<KeyValuePair<CollectStatus, CollectHintCode>> statusesToReturn) : this(givenName, surname, $"{givenName} {surname}", personalIdentityNumber, statusesToReturn) { } public BankIdDevelopmentApiClient(string givenName, string surname, string name, string personalIdentityNumber, List<KeyValuePair<CollectStatus, CollectHintCode>> statusesToReturn) { _givenName = givenName; _surname = surname; _name = name; _personalIdentityNumber = personalIdentityNumber; _statusesToReturn = statusesToReturn; } public TimeSpan Delay { get => _delay; set => _delay = value < TimeSpan.Zero ? TimeSpan.Zero : value; } public async Task<AuthResponse> AuthAsync(AuthRequest request) { await SimulateResponseDelay().ConfigureAwait(false); var personalIdentityNumber = GetPersonalIdentityNumber(request); await EnsureNoExistingAuth(personalIdentityNumber).ConfigureAwait(false); var orderRef = Guid.NewGuid().ToString(); var auth = new Auth(orderRef, personalIdentityNumber); _auths.Add(orderRef, auth); return new AuthResponse { OrderRef = orderRef, AutoStartToken = Guid.NewGuid().ToString() }; } private string GetPersonalIdentityNumber(AuthRequest request) { if (!string.IsNullOrEmpty(request.PersonalIdentityNumber)) { return request.PersonalIdentityNumber; } return _personalIdentityNumber; } private async Task EnsureNoExistingAuth(string personalIdentityNumber) { if (_auths.Any(x => x.Value.PersonalIdentityNumber == personalIdentityNumber)) { var existingAuthOrderRef = _auths.First(x => x.Value.PersonalIdentityNumber == personalIdentityNumber).Key; await CancelAsync(new CancelRequest(existingAuthOrderRef)).ConfigureAwait(false); throw new BankIdApiException(ErrorCode.AlreadyInProgress, "A login for this user is already in progress."); } } public async Task<CollectResponse> CollectAsync(CollectRequest request) { await SimulateResponseDelay().ConfigureAwait(false); if (!_auths.ContainsKey(request.OrderRef)) { throw new BankIdApiException(ErrorCode.NotFound, "OrderRef not found"); } var auth = _auths[request.OrderRef]; var status = GetStatus(auth.CollectCalls); var hintCode = GetHintCode(auth.CollectCalls); var completionData = GetCompletionData(status, auth.PersonalIdentityNumber); var response = new CollectResponse(status, hintCode) { OrderRef = auth.OrderRef, CompletionData = completionData }; if (status == CollectStatus.Complete) { if (_auths.ContainsKey(request.OrderRef)) { _auths.Remove(request.OrderRef); } } else { auth.CollectCalls += 1; } return response; } private CompletionData GetCompletionData(CollectStatus status, string personalIdentityNumber) { if (status != CollectStatus.Complete) { return null; } return new CompletionData { User = new User { PersonalIdentityNumber = personalIdentityNumber, Name = _name, GivenName = _givenName, Surname = _surname } }; } private CollectStatus GetStatus(int collectCalls) { var index = GetStatusesToReturnIndex(collectCalls); return _statusesToReturn[index].Key; } private CollectHintCode GetHintCode(int collectCalls) { var index = GetStatusesToReturnIndex(collectCalls); return _statusesToReturn[index].Value; } private int GetStatusesToReturnIndex(int collectCalls) { return Math.Min(collectCalls, (_statusesToReturn.Count - 1)); } public async Task<CancelResponse> CancelAsync(CancelRequest request) { await SimulateResponseDelay().ConfigureAwait(false); if (_auths.ContainsKey(request.OrderRef)) { _auths.Remove(request.OrderRef); } return new CancelResponse(); } private async Task SimulateResponseDelay() { await Task.Delay(Delay).ConfigureAwait(false); } private class Auth { public Auth(string orderRef, string personalIdentityNumber) { OrderRef = orderRef; PersonalIdentityNumber = personalIdentityNumber; } public string OrderRef { get; } public string PersonalIdentityNumber { get; } public int CollectCalls { get; set; } } } }
37.066038
188
0.622168
[ "MIT" ]
hematmedhelp/ActiveLogin.Authentication
src/ActiveLogin.Authentication.BankId.Api/BankIdDevelopmentApiClient.cs
7,860
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // 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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SilverlightApplication.Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft IT")] [assembly: AssemblyProduct("SilverlightApplication.Web")] [assembly: AssemblyCopyright("Copyright © Microsoft IT 2010")] [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("c0701f30-d545-4aec-b06a-9de70be57c90")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
51.18
463
0.765924
[ "MIT" ]
Acidburn0zzz/CodeContracts
Demo/SilverlightApplication.Web/Properties/AssemblyInfo.cs
2,560
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.DataFactory.Outputs { [OutputType] public sealed class JsonSourceResponse { /// <summary> /// Specifies the additional columns to be added to source data. Type: array of objects (or Expression with resultType array of objects). /// </summary> public readonly ImmutableArray<Outputs.AdditionalColumnsResponse> AdditionalColumns; /// <summary> /// Json format settings. /// </summary> public readonly Outputs.JsonReadSettingsResponse? FormatSettings; /// <summary> /// The maximum concurrent connection count for the source data store. Type: integer (or Expression with resultType integer). /// </summary> public readonly object? MaxConcurrentConnections; /// <summary> /// Source retry count. Type: integer (or Expression with resultType integer). /// </summary> public readonly object? SourceRetryCount; /// <summary> /// Source retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). /// </summary> public readonly object? SourceRetryWait; /// <summary> /// Json store settings. /// </summary> public readonly object? StoreSettings; /// <summary> /// Copy source type. /// Expected value is 'JsonSource'. /// </summary> public readonly string Type; [OutputConstructor] private JsonSourceResponse( ImmutableArray<Outputs.AdditionalColumnsResponse> additionalColumns, Outputs.JsonReadSettingsResponse? formatSettings, object? maxConcurrentConnections, object? sourceRetryCount, object? sourceRetryWait, object? storeSettings, string type) { AdditionalColumns = additionalColumns; FormatSettings = formatSettings; MaxConcurrentConnections = maxConcurrentConnections; SourceRetryCount = sourceRetryCount; SourceRetryWait = sourceRetryWait; StoreSettings = storeSettings; Type = type; } } }
35.319444
146
0.628785
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/DataFactory/Outputs/JsonSourceResponse.cs
2,543
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Backoffice.Models.ManageViewModels { public class TwoFactorAuthenticationViewModel { public bool HasAuthenticator { get; set; } public int RecoveryCodesLeft { get; set; } public bool Is2faEnabled { get; set; } } }
22.555556
50
0.729064
[ "MIT" ]
jorgemht/HospitalCore
Backoffice/Models/ManageViewModels/TwoFactorAuthenticationViewModel.cs
408
C#
// The MIT License (MIT) // Copyright (c) <year> <copyright holders> // 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. // <CreationDate>13-11-2016</CreationDate> namespace Angular2Playground.Controllers { using Microsoft.AspNetCore.Mvc; /// <summary> /// The <c>HomeController</c> /// </summary> /// <seealso cref="Microsoft.AspNetCore.Mvc.Controller" /> public class HomeController : Controller { private const string MAIN_INDEX_VIEW_NAME = "Views/Home/Index.cshtml"; private const string WELCOME_VIEW_NAME = "Views/Home/Welcome.cshtml"; /// <summary> /// Function will return 'Index' View /// </summary> /// <returns>Main page that will bring all the Angular2 staff</returns> public ViewResult Index() => new ViewResult(); /// <summary> /// Function will return 'welcome' partial page /// </summary> /// <returns>'Welcome' partial page</returns> public PartialViewResult WelcomePage() => new PartialViewResult { ViewName = WELCOME_VIEW_NAME }; } }
52.05
189
0.713256
[ "MIT" ]
jasper22/Angular2Playground
Controllers/HomeController.cs
2,084
C#
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace MobileConsole.UI { public class GenericTreeView : BaseView, IRecycleScrollViewDelegate { [SerializeField] protected AssetConfig _config; [SerializeField] protected UIBridge _title; [SerializeField] protected GameObject _filterGroup; [SerializeField] protected UIBridge _inputFilter; [SerializeField] protected GameObject _backButton; [SerializeField] protected GameObject _actionButton; [SerializeField] protected RecycleScrollView _scrollView; [SerializeField] protected Transform _scrollViewContent; Dictionary<string, ScrollViewCell> _resizableCells = new Dictionary<string, ScrollViewCell>(); List<Node> _filterNodes = new List<Node>(); ViewBuilder _viewBuilder; protected string _filterString; bool _isInitialized = false; bool _isPreparingView = false; public void Show(ViewBuilder builder) { if (builder == null) { throw new System.Exception("View Builder is null"); } base.Show(); if (!_isInitialized) { _isInitialized = true; _scrollView.AddCellTemplates(_config.cellTemplates); _scrollView.SetDelegate(this); } ClearOldBuilder(); SetupNewBuilder(builder); } public override void Hide() { base.Hide(); ClearOldBuilder(); } void ClearOldBuilder() { if (_viewBuilder != null) { _viewBuilder.OnRequireUpdateUI = null; _viewBuilder.scrollViewPosition = _scrollView.ScrollPosition; _viewBuilder.filterString = _filterString; _viewBuilder.OnPrepareToHide(); } _viewBuilder = null; } void SetupNewBuilder(ViewBuilder builder) { // Prevent input filter callback while we set its value _isPreparingView = true; _viewBuilder = builder; _viewBuilder.OnRequireUpdateUI = OnUpdateView; _viewBuilder.OnPrepareToShow(); // Update title bool hasTitle = !string.IsNullOrEmpty(_viewBuilder.title); _title.gameObject.SetActive(hasTitle); if (hasTitle) { _title.text = _viewBuilder.title; } // Update filter string _filterString = _viewBuilder.filterString; _inputFilter.input = _filterString; _filterGroup.SetActive(!hasTitle); // Update buttons _backButton.SetActive(_viewBuilder.level > 0); _actionButton.SetActive(_viewBuilder.actionButtonCallback != null); AssetConfig.SpriteInfo spriteInfo = _config.GetSpriteInfo(_viewBuilder.actionButtonIcon); if (spriteInfo != null) { UnityEngine.UI.Image buttonImage = _actionButton.GetComponentInChildren<UnityEngine.UI.Image>(); buttonImage.sprite = spriteInfo.sprite; buttonImage.color = spriteInfo.color; } // Rebuild the whole tree _viewBuilder.Rebuild(); // Update scroll view if (!_viewBuilder.saveScrollViewPosition) _scrollView.MoveViewToTop(); else _scrollView.ScrollPosition = _viewBuilder.scrollViewPosition; _isPreparingView = false; } void OnUpdateView(ViewBuilder.UpdateUIType updateType) { switch (updateType) { case ViewBuilder.UpdateUIType.DataChanged: { _scrollView.ReloadData(); break; } case ViewBuilder.UpdateUIType.CellVisibleChanged: case ViewBuilder.UpdateUIType.TreeChanged: { UpdateTree(); break; } default: break; } } void UpdateTree() { RootNode rootNode = _viewBuilder.GetRootNode(); _filterNodes.Clear(); if (string.IsNullOrEmpty(_filterString)) { _filterNodes.AddRange(rootNode.FlattenedVisibleChilds()); } else { HashSet<Node> passFilterNodes = new HashSet<Node>(); foreach (var node in rootNode.FlattenChilds()) { if (node.name.IndexOf(_filterString, StringComparison.OrdinalIgnoreCase) >= 0) { if (passFilterNodes.Contains(node)) continue; foreach (var n in node.GetBranch()) { if (n.isVisible) passFilterNodes.Add(n); } foreach (var n in node.GetAllChildren()) { if (n.isVisible) passFilterNodes.Add(n); } } } foreach (var node in passFilterNodes) { if (node.level == -1) { continue; } _filterNodes.Add(node); } } _scrollView.ReloadData(); } public void OnFilterValueChanged(string filterString) { // Don't process if view is being prepared if (_isPreparingView) return; _filterString = filterString; UpdateTree(); } public void OnClosed() { LogConsole.CloseAllSubView(); } public void OnBack() { LogConsole.PopSubView(); } public void OnAction() { if (_viewBuilder.actionButtonCallback != null) { try { _viewBuilder.actionButtonCallback(); if (_viewBuilder.closeAllSubViewOnAction) { LogConsole.CloseAllSubView(); } } catch (Exception e) { Debug.LogException(e); } } } public void OnExpandAll() { RootNode rootNode = _viewBuilder.GetRootNode(); rootNode.ExpandAllChild(true); rootNode.RebuildFlattenVisibleChilds(); OnUpdateView(ViewBuilder.UpdateUIType.CellVisibleChanged); } public void OnCollapseAll() { RootNode rootNode = _viewBuilder.GetRootNode(); rootNode.ExpandAllChild(false); rootNode.RebuildFlattenVisibleChilds(); OnUpdateView(ViewBuilder.UpdateUIType.CellVisibleChanged); } public ScrollViewCell ScrollCellCreated(int cellIndex) { NodeView nodeView = (NodeView)_filterNodes[cellIndex]; return nodeView.CreateCell(_scrollView, _config, cellIndex); } public void ScrollCellSelected(int cellIndex) { NodeView nodeView = (NodeView)_filterNodes[cellIndex]; nodeView.CellSelected(); } public void ScrollCellWillDisplay(ScrollViewCell cell) { } public float ScrollCellSize(int cellIndex) { NodeView nodeView = (NodeView)_filterNodes[cellIndex]; if (nodeView.resizable) { string cellIdentifier = nodeView.CellIdentifier(); if (!_resizableCells.ContainsKey(cellIdentifier)) { ScrollViewCell cellTemplate = _config.cellTemplates.Find(c => c.identifier == cellIdentifier); ScrollViewCell cell = Instantiate(cellTemplate, _scrollViewContent); _resizableCells[cellIdentifier] = cell; LayoutRebuilder.ForceRebuildLayoutImmediate(cell.rectTransform); cell.gameObject.SetActive(false); } return Mathf.Max(nodeView.CellSize(_resizableCells[cellIdentifier]), 120); } else { return nodeView.CellSize(); } } public int ScrollCellCount() { return _filterNodes.Count; } } }
22.877133
100
0.686111
[ "MIT" ]
brunomikoski/MobileConsoleKit
Internal/Scripts/Views/GenericTreeView.cs
6,705
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Engine { public class VirtualFileInfo { internal VirtualFileInfo(String name, String directoryName, String fullName, String realLocation, Int64 compressedSize, Int64 uncompressedSize) { Name = name; DirectoryName = directoryName; FullName = fullName; RealLocation = realLocation; CompressedSize = compressedSize; UncompressedSize = uncompressedSize; } public Int64 CompressedSize { get; private set; } public Int64 UncompressedSize { get; private set; } public String Name { get; private set; } public String DirectoryName { get; private set; } public String FullName { get; private set; } public String RealLocation { get; private set; } } }
28.333333
152
0.624599
[ "MIT" ]
AnomalousMedical/Adventure
Engine/Resources/Filesystem/VirtualFileInfo.cs
937
C#
using Core.Entities; using System; using System.Collections.Generic; using System.Text; namespace Entities.Concrete { public class Rental : IEntity { public int Id { get; set; } public int CarId { get; set; } public int CustomerId { get; set; } public DateTime RentDate { get; set; } public DateTime ReturnDate { get; set; } } }
21.333333
48
0.627604
[ "MIT" ]
hamdidamar/Step-by-Step-Bootcamp
day-10/Homework/ReCap/Entities/Concrete/Rental.cs
386
C#
using System; using System.Reactive.Disposables; using Avalonia; using Avalonia.Data; namespace TemplatedDataGrid.Internal { internal static class AvaloniaObjectExtensions { public static void OneWayBind( this IAvaloniaObject target, AvaloniaProperty targetProperty, IAvaloniaObject source, AvaloniaProperty sourceProperty, CompositeDisposable compositeDisposable) { var targetDisposable = target.Bind(targetProperty, source.GetObservable(sourceProperty)); compositeDisposable.Add(targetDisposable); } public static void TwoWayBind( this IAvaloniaObject target, AvaloniaProperty targetProperty, IAvaloniaObject source, AvaloniaProperty sourceProperty, CompositeDisposable compositeDisposable) { var targetDisposable = target.Bind(targetProperty, source.GetObservable(sourceProperty)); var sourceDisposable = source.Bind(sourceProperty, target.GetObservable(targetProperty)); compositeDisposable.Add(targetDisposable); compositeDisposable.Add(sourceDisposable); } public static void OneWayBind<T>( this IAvaloniaObject target, AvaloniaProperty<T> targetProperty, IObservable<BindingValue<T>> source, CompositeDisposable compositeDisposable) { var targetDisposable = target.Bind(targetProperty, source); compositeDisposable.Add(targetDisposable); } } }
36.022222
101
0.658853
[ "MIT" ]
wieslawsoltes/DataGrid
src/TemplatedDataGrid/Internal/AvaloniaObjectExtensions.cs
1,623
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class PlayerMovement : MonoBehaviour { public static Vector2 pos; private Rigidbody2D player; private Vector2 dir; private Vector2 mousePos; private Stats stats; private void Awake() { player = GetComponent<Rigidbody2D>(); if (!player) Debug.LogError("No player rigid body found in player movement"); stats = GetComponent<PlayerShip>().stats; if (stats==null) Debug.LogError("No stats found in player movement"); } private void Update() { dir.x = Input.GetAxisRaw("Horizontal"); dir.y = Input.GetAxisRaw("Vertical"); mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); pos = player.position; } void FixedUpdate() { // Movement player.AddForce(dir.normalized * stats.MovementSpeed); // Rotation Vector2 rDir = mousePos - player.position; player.transform.up = rDir; } }
25.116279
76
0.636111
[ "MIT" ]
iLigonis/Space-Shooter
UnitySource/Space Shooter/Assets/Scripts/PlayerMovement.cs
1,082
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using log4net.Unity.Config; using UnityEditor; using UnityEngine; namespace log4net.Unity { [InitializeOnLoad] public class EditorLogInitializer: AssetPostprocessor { private class Holder { private bool lastExist; private DateTime lastEdit; private readonly FileInfo fileInfo; private readonly PathConfigurator configurator; public void CheckChange() { if (fileInfo == null) return; fileInfo.Refresh(); if (fileInfo.Exists == lastExist && fileInfo.LastWriteTime == lastEdit) return; lastExist = fileInfo.Exists; lastEdit = fileInfo.LastWriteTime; configurator?.CallChange(); } public Holder(PathConfigurator configurator, string path) { if(string.IsNullOrEmpty(path)) return; path = Path.GetFullPath(path); fileInfo = new FileInfo(path); lastExist = fileInfo.Exists; lastEdit = fileInfo.LastWriteTime; this.configurator = configurator; } } private static List<Holder> _holders; static EditorLogInitializer() { Init(); } private static void Init() { RuntimeLogInitializer.Init(); var configurators = new PathConfigurator[] { AppDataPathConfigurator.Instance, AppPersistentDataPathConfigurator.Instance }; _holders = new List<Holder>(); for (var i = 0; i <= configurators.Length - 1; i++) { var configurator = configurators[i]; var paths = configurator.FilePaths; for (var j = 0; j <= paths.Length - 1; j++) { var path = paths[j]; _holders.Add(new Holder(configurator, path)); } } EditorApplication.update += Update; } private static void Update() { for (var i = 0; i <= _holders?.Count - 1; i++) { var holder = _holders[i]; holder?.CheckChange(); } } private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { var exists = (importedAssets ?? ArrayEmpty<string>.Instance) .Concat(deletedAssets ?? ArrayEmpty<string>.Instance) .Concat(movedAssets ?? ArrayEmpty<string>.Instance) .Concat(movedFromAssetPaths ?? ArrayEmpty<string>.Instance) .Distinct() .Where(s => { if (string.IsNullOrEmpty(s)) return false; var directories = Path.GetDirectoryName(s)? .Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) .ToList() ?? new List<string>(); var name = Path.GetFileNameWithoutExtension(s); return directories.Any(dir => dir?.ToLower() == "resources") && name.ToLower() == "log4net"; }).Any(); if (exists) { ResourceConfigurator.Instance.CallChange(); } } } }
33.504673
121
0.517434
[ "Apache-2.0" ]
Toxic2k/log4uni
log4uni.editor/log4net/Unity/EditorLogInitializer.cs
3,585
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Communication.PhoneNumbers.Models { public partial class LocationOptions : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(LabelId)) { writer.WritePropertyName("labelId"); writer.WriteStringValue(LabelId); } if (Optional.IsDefined(LabelName)) { writer.WritePropertyName("labelName"); writer.WriteStringValue(LabelName); } if (Optional.IsCollectionDefined(Options)) { writer.WritePropertyName("options"); writer.WriteStartArray(); foreach (var item in Options) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } writer.WriteEndObject(); } internal static LocationOptions DeserializeLocationOptions(JsonElement element) { Optional<string> labelId = default; Optional<string> labelName = default; Optional<IList<LocationOptionsDetails>> options = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("labelId")) { labelId = property.Value.GetString(); continue; } if (property.NameEquals("labelName")) { labelName = property.Value.GetString(); continue; } if (property.NameEquals("options")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<LocationOptionsDetails> array = new List<LocationOptionsDetails>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(LocationOptionsDetails.DeserializeLocationOptionsDetails(item)); } options = array; continue; } } return new LocationOptions(labelId.Value, labelName.Value, Optional.ToList(options)); } } }
34.443038
98
0.519662
[ "MIT" ]
MahmoudYounes/azure-sdk-for-net
sdk/communication/Azure.Communication.PhoneNumbers/src/Generated/Models/LocationOptions.Serialization.cs
2,721
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace dotnet_new_template_react_ts { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
24.92
76
0.70305
[ "MIT" ]
ltwlf/dotnet-new-template-react-ts
templates/content/Program.cs
623
C#
namespace CSharpier.SyntaxPrinter.SyntaxNodePrinters; internal static class AttributeList { public static Doc Print(AttributeListSyntax node, FormattingContext context) { var docs = new List<Doc>(); if ( node.Parent is CompilationUnitSyntax compilationUnitSyntax && compilationUnitSyntax.AttributeLists.First() != node ) { docs.Add(ExtraNewLines.Print(node)); } docs.Add(Token.Print(node.OpenBracketToken, context)); if (node.Target != null) { docs.Add( Token.Print(node.Target.Identifier, context), Token.PrintWithSuffix(node.Target.ColonToken, " ", context) ); } var printSeparatedSyntaxList = SeparatedSyntaxList.Print( node.Attributes, (attributeNode, _) => { var name = Node.Print(attributeNode.Name, context); if (attributeNode.ArgumentList == null) { return name; } return Doc.Group( name, Token.Print(attributeNode.ArgumentList.OpenParenToken, context), Doc.Indent( Doc.SoftLine, SeparatedSyntaxList.Print( attributeNode.ArgumentList.Arguments, (attributeArgumentNode, _) => Doc.Concat( attributeArgumentNode.NameEquals != null ? NameEquals.Print( attributeArgumentNode.NameEquals, context ) : Doc.Null, attributeArgumentNode.NameColon != null ? BaseExpressionColon.Print( attributeArgumentNode.NameColon, context ) : Doc.Null, Node.Print(attributeArgumentNode.Expression, context) ), Doc.Line, context ) ), Doc.SoftLine, Token.Print(attributeNode.ArgumentList.CloseParenToken, context) ); }, Doc.Line, context ); docs.Add( node.Attributes.Count > 1 ? Doc.Indent(Doc.SoftLine, printSeparatedSyntaxList) : printSeparatedSyntaxList ); docs.Add( node.Attributes.Count > 1 ? Doc.SoftLine : Doc.Null, Token.Print(node.CloseBracketToken, context) ); return Doc.Group(docs); } }
36.511905
89
0.431692
[ "MIT" ]
belav/prettier-plugin-csharpier
Src/CSharpier/SyntaxPrinter/SyntaxNodePrinters/AttributeList.cs
3,067
C#
namespace LiveSplit.Mgs3LoadRemover { public class ImageFeatures { public int MaxColorIntensity { get; } public int MinColorIntensity { get; } public ImageFeatures(int maxColorIntensity, int minColorIntensity) { MaxColorIntensity = maxColorIntensity; MinColorIntensity = minColorIntensity; } } }
26.642857
74
0.648794
[ "MIT" ]
makotocchi/LiveSplit.BlackScreenDetector
ImageFeatures.cs
375
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DotNetNinja.TypeFiltering.Tests { public class BaseClass { } }
15.333333
41
0.75
[ "MIT" ]
ninjah187/DotNetNinja
DotNetNinja.TypeFiltering/DotNetNinja.TypeFiltering.Tests/Data/BaseClass.cs
186
C#
using Com.Danliris.Service.Packing.Inventory.Application.ToBeRefactored.GarmentShipping.GarmentPackingList; using Com.Danliris.Service.Packing.Inventory.Application.ToBeRefactored.Utilities; using Com.Danliris.Service.Packing.Inventory.Data.Models.Garmentshipping.GarmentPackingList; using Com.Danliris.Service.Packing.Inventory.Infrastructure.IdentityProvider; using Moq; using System; using System.Net; using System.Threading.Tasks; using Xunit; namespace Com.Danliris.Service.Packing.Inventory.Test.Controllers.GarmentShipping.GarmentPackingList { public class GarmentPackingListControllerSetRevisedMdTest : GarmentPackingListControllerTest { [Fact] public async Task Set_RevisedMd_Success() { var serviceMock = new Mock<IGarmentPackingListService>(); serviceMock .Setup(s => s.SetStatus(It.IsAny<int>(), It.IsAny<GarmentPackingListStatusEnum>(), It.IsAny<string>())) .Verifiable(); var service = serviceMock.Object; var validateServiceMock = new Mock<IValidateService>(); var validateService = validateServiceMock.Object; var identityProviderMock = new Mock<IIdentityProvider>(); var identityProvider = identityProviderMock.Object; var controller = GetController(service, identityProvider, validateService); var response = await controller.SetRevisedMd(It.IsAny<int>(), It.IsAny<string>()); Assert.Equal((int)HttpStatusCode.OK, GetStatusCode(response)); } [Fact] public async Task Set_RevisedMd_Exception_InternalServerError() { var serviceMock = new Mock<IGarmentPackingListService>(); serviceMock .Setup(s => s.SetStatus(It.IsAny<int>(), It.IsAny<GarmentPackingListStatusEnum>(), It.IsAny<string>())) .ThrowsAsync(new Exception()); var service = serviceMock.Object; var validateServiceMock = new Mock<IValidateService>(); var validateService = validateServiceMock.Object; var identityProviderMock = new Mock<IIdentityProvider>(); var identityProvider = identityProviderMock.Object; var controller = GetController(service, identityProvider, validateService); var response = await controller.SetRevisedMd(It.IsAny<int>(), It.IsAny<string>()); Assert.Equal((int)HttpStatusCode.InternalServerError, GetStatusCode(response)); } } }
42.1
119
0.692399
[ "MIT" ]
kuswandanu-moonlay/com-danliris-service-packing-inventory
src/Com.Danliris.Service.Packing.Inventory.Test/Controllers/GarmentShipping/GarmentPackingList/GarmentPackingListControllerSetRevisedMdTest.cs
2,528
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Accord.Statistics; namespace PLImg_V2 { public class AFCalc { public double CalcAFV(byte[] input) { try { double output = 0; double[] contrastArr = new double[input.Length-2]; for (int i = 2; i < input.Length-2; i++) { contrastArr[i] = (double)(Math.Abs(input[i] - input[i - 1]) + Math.Abs(input[i] - input[i + 1])/ input.Length); } output = Measures.Variance(contrastArr); return output; } catch (Exception ex ) { Console.WriteLine(ex.ToString()); return -999; } } } }
22.052632
127
0.5
[ "MIT" ]
pimier15/AcsController
PLImg_V3/PLImg_V2/Function/AFCalc.cs
840
C#
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Linx.Tasks; namespace Linx.Timing { /// <summary> /// Access to current time. /// </summary> public static class Time { /// <summary> /// Gets the real <see cref="ITime"/>. /// </summary> public static ITime RealTime { get; } = new RealTimeImpl(); /// <summary> /// Schedule an action. /// </summary> public static async void Schedule(this ITime time, Action action, DateTimeOffset due, CancellationToken token) { if (time == null) throw new ArgumentNullException(nameof(time)); if (action == null) throw new ArgumentNullException(nameof(action)); if (token.IsCancellationRequested) return; try { await time.Delay(due, token).ConfigureAwait(false); action(); } catch {/**/} } /// <summary> /// Schedule an action. /// </summary> public static async void Schedule(this ITime time, Action action, TimeSpan due, CancellationToken token) { if (time == null) throw new ArgumentNullException(nameof(time)); if (action == null) throw new ArgumentNullException(nameof(action)); if (token.IsCancellationRequested) return; try { await time.Delay(due, token).ConfigureAwait(false); action(); } catch {/**/} } [DebuggerStepThrough] private sealed class RealTimeImpl : ITime { /// <inheritdoc /> public DateTimeOffset Now => DateTimeOffset.Now; /// <inheritdoc /> public ValueTask Delay(TimeSpan due, CancellationToken token) { token.ThrowIfCancellationRequested(); return new(due > TimeSpan.Zero ? Task.Delay(due, token) : Task.CompletedTask); } /// <inheritdoc /> public ValueTask Delay(DateTimeOffset due, CancellationToken token) => Delay(due - DateTimeOffset.Now, token); /// <inheritdoc /> public ITimer GetTimer(CancellationToken token) => new Timer(token); private sealed class Timer : ITimer { private const int _sInitial = 0; private const int _sWaiting = 1; private const int _sFinal = 2; private static readonly ObjectDisposedException _timerDisposedException = new(nameof(ITimer)); private readonly ManualResetValueTaskSource _tsDelay = new(); private readonly System.Threading.Timer _timer; private CancellationTokenRegistration _ctr; private int _state; public Timer(CancellationToken token) { _timer = new System.Threading.Timer(TimerCallback); if (token.CanBeCanceled) _ctr = token.Register(() => SetFinal(new OperationCanceledException(token))); } public ValueTask Delay(TimeSpan due) { var state = Atomic.Lock(ref _state); switch (state) { case _sInitial: _tsDelay.Reset(); if (due > TimeSpan.Zero) { _state = _sWaiting; try { _timer.Change(due, Timeout.InfiniteTimeSpan); } catch (Exception ex) { if (Atomic.CompareExchange(ref _state, _sInitial, _sWaiting) == _sWaiting) _tsDelay.SetException(ex); } } else { _state = _sInitial; _tsDelay.SetResult(); } return _tsDelay.Task; case _sFinal: _state = _sFinal; return _tsDelay.Task; case _sWaiting: _state = _sWaiting; throw new InvalidOperationException(Strings.MethodIsNotReentrant); default: _state = state; throw new Exception(state + "???"); } } public ValueTask Delay(DateTimeOffset due) => Delay(due - DateTimeOffset.Now); public void Dispose() => SetFinal(_timerDisposedException); private void SetFinal(Exception error) { Debug.Assert(error is not null); var state = Atomic.Lock(ref _state); switch (state) { case _sInitial: _tsDelay.Reset(); _state = _sFinal; _ctr.Dispose(); _tsDelay.SetException(error); break; case _sWaiting: _state = _sFinal; _ctr.Dispose(); _tsDelay.SetException(error); break; case _sFinal: _state = _sFinal; break; default: _state = state; throw new Exception(_state + "???"); } } private void TimerCallback(object _) { if (Atomic.CompareExchange(ref _state, _sInitial, _sWaiting) == _sWaiting) _tsDelay.SetResult(); } } } } }
35.827586
122
0.448989
[ "MIT" ]
tinudu/Linx
src/Linx/Timing/Time.cs
6,236
C#
namespace SiCo.Utilities.Helper.Test { using System.ComponentModel.DataAnnotations; using SiCo.Utilities.Helper.Attributes; using Xunit; public class ValidateCountryIsoAttributeTest { private static readonly ValidationContext s_testValidationContext = new ValidationContext(new object()); [Fact] public static void Can_get_and_set_AllowEmptyStrings() { var attribute = new ValidateCountryIsoAttribute(); Assert.False(attribute.AllowEmptyStrings); attribute.AllowEmptyStrings = true; Assert.True(attribute.AllowEmptyStrings); attribute.AllowEmptyStrings = false; Assert.False(attribute.AllowEmptyStrings); } [Theory] [InlineData("DE", true)] [InlineData("DEU", true)] [InlineData(" FRA ", true)] [InlineData("F1", false)] [InlineData("AAAAFRA", false)] public static void IsValid(string iso, bool result) { //Countries.Initialize(); var attribute = new ValidateCountryIsoAttribute { AllowEmptyStrings = true }; Assert.Equal(result, attribute.IsValid(iso)); } [Fact] public static void Validation_ErrorMessage() { //Countries.Initialize(); var attribute = new ValidateCountryIsoAttribute(); Assert.False(attribute.IsValid("INVALID")); var t = attribute.FormatErrorMessage("ISO"); Assert.NotEmpty(t); } [Fact] public static void Validation_throws_ValidationException_for_empty_string_if_AllowEmptyStrings_is_false() { //Countries.Initialize(); var attribute = new ValidateCountryIsoAttribute { AllowEmptyStrings = false }; Assert.Throws<ValidationException>(() => attribute.Validate(string.Empty, s_testValidationContext)); } [Theory] [InlineData("F")] [InlineData("1DE")] [InlineData("DE U")] public static void Validation_throws_ValidationException_for_inavlid_country_iso(string iso) { //Countries.Initialize(); var attribute = new ValidateCountryIsoAttribute { AllowEmptyStrings = true }; Assert.Throws<ValidationException>(() => attribute.Validate(iso, s_testValidationContext)); } [Fact] public static void Validation_throws_ValidationException_for_null_value() { var attribute = new ValidateCountryIsoAttribute(); Assert.Throws<ValidationException>(() => attribute.Validate(null, s_testValidationContext)); } [Theory] [InlineData("DE")] [InlineData("DEU")] [InlineData(" FRA ")] public static void Validation_valid_country_iso(string iso) { //Countries.Initialize(); var attribute = new ValidateCountryIsoAttribute { AllowEmptyStrings = true }; attribute.Validate(iso, s_testValidationContext); } [Fact] public static void Validation_valid_for_empty_string_if_AllowEmptyStrings_is_true() { //Countries.Initialize(); var attribute = new ValidateCountryIsoAttribute { AllowEmptyStrings = true }; attribute.Validate(string.Empty, s_testValidationContext); } } }
34.133333
113
0.595982
[ "MIT" ]
Silver-Connection/sico-net-utilities
test/SiCo.Utilities.Helper.Test/ValidateCountryIsoAttributeTest.cs
3,586
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if !NET472 #pragma warning disable IDE0055 // Fix formatting #endif #if NET472 using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using Xunit; using MemoryStream = System.IO.MemoryStream; using System; using Microsoft.CodeAnalysis.Emit; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { public class NoPiaEmbedTypes : EmitMetadataTestBase { [Fact] public void EmbedClass1() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public class Test { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { Test x = null; System.Action<Test> y = null; System.Console.WriteLine(x); System.Console.WriteLine(y); } }"; DiagnosticDescription[] expected = { // (6,14): error CS1752: Interop type 'Test' cannot be embedded. Use the applicable interface instead. // Test x = null; Diagnostic(ErrorCode.ERR_NewCoClassOnLink, "Test").WithArguments("Test"), // (7,29): error CS1752: Interop type 'Test' cannot be embedded. Use the applicable interface instead. // System.Action<Test> y = null; Diagnostic(ErrorCode.ERR_NewCoClassOnLink, "Test").WithArguments("Test") }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void EmbedClass2() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public class Test { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { System.Action<Test> y = null; System.Console.WriteLine(y); } }"; DiagnosticDescription[] expected = { // (6,29): error CS1752: Interop type 'Test' cannot be embedded. Use the applicable interface instead. // System.Action<Test> y = null; Diagnostic(ErrorCode.ERR_NewCoClassOnLink, "Test").WithArguments("Test") }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } // In VB use AssertTheseErrors format for expected diagnostics! private static void VerifyEmitDiagnostics( CSharpCompilation compilation, bool metadataOnlyShouldSucceed, DiagnosticDescription[] expectedFullBuildDiagnostics, DiagnosticDescription[] expectedMetadataOnlyDiagnostics = null ) { using (var executableStream = new MemoryStream()) { var result = compilation.Emit(executableStream); Assert.False(result.Success); result.Diagnostics.Verify(expectedFullBuildDiagnostics); } using (var executableStream = new MemoryStream()) { var result = compilation.Emit( executableStream, options: new EmitOptions(metadataOnly: true) ); if (metadataOnlyShouldSucceed) { Assert.True(result.Success); result.Diagnostics.Verify(); } else { Assert.False(result.Success); result.Diagnostics.Verify( expectedMetadataOnlyDiagnostics ?? expectedFullBuildDiagnostics ); } } } [Fact] public void EmbedClass3() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public class Test { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.DebugDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } class test2 : Test {} }"; DiagnosticDescription[] expected = { // (8,19): error CS1752: Interop type 'Test' cannot be embedded. Use the applicable interface instead. // class test2 : Test Diagnostic(ErrorCode.ERR_NewCoClassOnLink, "Test").WithArguments("Test") }; var compilation = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, false, expected); compilation = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, false, expected); } [Fact] public void EmbedNestedType1() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58271"")] public interface ITest20 { Test21.Test22 M22(); } public struct Test21 { public struct Test22 { } } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.DebugDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public object M13(ITest20 x) { Test21.Test22 y = x.M22(); return y; } public object M14(ITest20 x) { var y = x.M22(); return y; } }"; DiagnosticDescription[] expected = { // (10,16): error CS1754: Type 'Test21.Test22' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // Test21.Test22 y = x.M22(); Diagnostic(ErrorCode.ERR_NoPIANestedType, "Test22") .WithArguments("Test21.Test22"), // (16,13): error CS1754: Type 'Test21.Test22' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // var y = x.M22(); Diagnostic(ErrorCode.ERR_NoPIANestedType, "y = x.M22()") .WithArguments("Test21.Test22") }; var compilation = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void EmbedNestedType2() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58271"")] public interface ITest20 { Test21.Test22 M22(); } public struct Test21 { public struct Test22 { } } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.DebugDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public object M14(ITest20 x) { var y = x.M22(); return y; } }"; DiagnosticDescription[] expected = { // (10,13): error CS1754: Type 'Test21.Test22' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // var y = x.M22(); Diagnostic(ErrorCode.ERR_NoPIANestedType, "y = x.M22()") .WithArguments("Test21.Test22") }; var compilation = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void EmbedNestedType3() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct Test21 { public struct Test22 { } } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.DebugDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void M14(Test21.Test22 x) { } }"; DiagnosticDescription[] expected = { // (8,28): error CS1754: Type 'Test21.Test22' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // public void M14(Test21.Test22 x) Diagnostic(ErrorCode.ERR_NoPIANestedType, "Test22").WithArguments("Test21.Test22") }; var compilation = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, false, expected); compilation = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, false, expected); } [Fact] public void EmbedGenericType1() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58271"")] public interface ITest20<T> { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void M13(ITest20<int> x) { } }"; DiagnosticDescription[] expected = { // (8,21): error CS1768: Type 'ITest20<T>' cannot be embedded because it has a generic argument. Consider setting the 'Embed Interop Types' property to false. // public void M13(ITest20<int> x) Diagnostic(ErrorCode.ERR_GenericsUsedInNoPIAType, "ITest20<int>") .WithArguments("ITest20<T>"), }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, false, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, false, expected); } [Fact] public void EmbedGenericType2() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct Test21<T> { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public object M14() { return default(Test21<int>); } }"; DiagnosticDescription[] expected = { // (14,24): error CS1768: Type 'Test21<T>' cannot be embedded because it has a generic argument. Consider setting the 'Embed Interop Types' property to false. // return default(Test21<int>); Diagnostic(ErrorCode.ERR_GenericsUsedInNoPIAType, "Test21<int>") .WithArguments("Test21<T>") }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void EmbedStructWithPrivateField() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct Test21 { private int x; } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); //CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public object M14() { return default(Test21); } }"; DiagnosticDescription[] expected = { // (10,16): error CS1757: Embedded interop struct 'Test21' can contain only public instance fields. // return default(Test21); Diagnostic(ErrorCode.ERR_InteropStructContainsMethods, "default(Test21)") .WithArguments("Test21") }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void EmbedStructWithStaticField() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct Test21 { static int x; } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); //CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public object M14() { return default(Test21); } }"; DiagnosticDescription[] expected = { // (10,16): error CS1757: Embedded interop struct 'Test21' can contain only public instance fields. // return default(Test21); Diagnostic(ErrorCode.ERR_InteropStructContainsMethods, "default(Test21)") .WithArguments("Test21") }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void EmbedStructWithMethod() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct Test21 { public void M(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); //CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public object M14() { return default(Test21); } }"; DiagnosticDescription[] expected = { // (10,16): error CS1757: Embedded interop struct 'Test21' can contain only public instance fields. // return default(Test21); Diagnostic(ErrorCode.ERR_InteropStructContainsMethods, "default(Test21)") .WithArguments("Test21") }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void EmbedStructWithProperty() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct Test21 { int P4 { get {return 0;} } } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); //CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public object M14() { return default(Test21); } }"; DiagnosticDescription[] expected = { // (10,16): error CS1757: Embedded interop struct 'Test21' can contain only public instance fields. // return default(Test21); Diagnostic(ErrorCode.ERR_InteropStructContainsMethods, "default(Test21)") .WithArguments("Test21") }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void EmbedStructWithEvent() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct Test21 { event System.Action E5; } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); //CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public object M14() { return default(Test21); } }"; DiagnosticDescription[] expected = { // (10,16): error CS1757: Embedded interop struct 'Test21' can contain only public instance fields. // return default(Test21); Diagnostic(ErrorCode.ERR_InteropStructContainsMethods, "default(Test21)") .WithArguments("Test21") }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void CS1774ERR_InteropMethodWithBody() { string sources1 = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly A { .custom instance void [mscorlib]System.Runtime.InteropServices.ImportedFromTypeLibAttribute::.ctor(string) = {string('_.dll')} .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = {string('f9c2d51d-4f44-45f0-9eda-c9d599b58257')} } .class public sealed D extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor(object o, native int m) runtime { } .method public hidebysig instance void Invoke() runtime { } .method public hidebysig instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback c, object o) runtime { } .method public hidebysig instance void EndInvoke(class [mscorlib]System.IAsyncResult r) runtime { } .method public static void M1() { ldnull throw } .method public static pinvokeimpl(""A.dll"" winapi) void M2() { } .method public instance void M3() { ldnull throw } }"; string sources2 = @"class C { static void M(D d) { D.M1(); D.M2(); d.M3(); } }"; DiagnosticDescription[] expected = { // (5,9): error CS1774: Embedded interop method 'void D.M1()' contains a body. // D.M1(); Diagnostic(ErrorCode.ERR_InteropMethodWithBody, "D.M1()") .WithArguments("void D.M1()"), // (5,9): error CS1774: Embedded interop method 'void D.M3()' contains a body. // D.M1(); Diagnostic(ErrorCode.ERR_InteropMethodWithBody, "D.M1()") .WithArguments("void D.M3()") }; DiagnosticDescription[] expectedMetadataOnly = { // (5,9): error CS1774: Embedded interop method 'void D.M1()' contains a body. Diagnostic(ErrorCode.ERR_InteropMethodWithBody).WithArguments("void D.M1()"), // (5,9): error CS1774: Embedded interop method 'void D.M3()' contains a body. Diagnostic(ErrorCode.ERR_InteropMethodWithBody).WithArguments("void D.M3()") }; var reference1 = CompileIL( sources1, prependDefaultHeader: false, embedInteropTypes: true ); var compilation2 = CreateCompilation( sources2, references: new MetadataReference[] { reference1 } ); VerifyEmitDiagnostics(compilation2, false, expected, expectedMetadataOnly); } [Fact] public void TypeIdentifierIsMissing1() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public struct Test21 { } "; var piaCompilation = CreateEmptyCompilation( pia, new MetadataReference[] { MscorlibRef_v20 }, options: TestOptions.ReleaseDll ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public object M14() { return default(Test21); } }"; DiagnosticDescription[] expected = { // (15,16): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.TypeIdentifierAttribute..ctor' // return default(Test21); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "default(Test21)") .WithArguments( "System.Runtime.InteropServices.TypeIdentifierAttribute", ".ctor" ) }; var compilation = CreateEmptyCompilation( consumer, new MetadataReference[] { MscorlibRef_v20, new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) }, options: TestOptions.ReleaseExe ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateEmptyCompilation( consumer, references: new MetadataReference[] { MscorlibRef_v20, piaCompilation.EmitToImageReference(embedInteropTypes: true) }, options: TestOptions.ReleaseExe ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void TypeIdentifierIsMissing2() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58271"")] public interface ITest20 { } "; var piaCompilation = CreateEmptyCompilation( pia, new MetadataReference[] { MscorlibRef_v20 }, options: TestOptions.DebugDll ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public object M13() { var x = (ITest20)null; return x; } }"; DiagnosticDescription[] expected = { // (10,13): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.TypeIdentifierAttribute..ctor' // var x = (ITest20)null; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x = (ITest20)null") .WithArguments( "System.Runtime.InteropServices.TypeIdentifierAttribute", ".ctor" ) }; var compilation = CreateEmptyCompilation( consumer, new MetadataReference[] { MscorlibRef_v20, new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) }, options: TestOptions.DebugExe ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateEmptyCompilation( consumer, references: new MetadataReference[] { MscorlibRef_v20, piaCompilation.EmitToImageReference(embedInteropTypes: true) }, options: TestOptions.DebugExe ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void LocalTypeMetadata_Simple() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58258"")] public interface ITest1 { } public struct Test2 : ITest1 { } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58259"")] public interface ITest3 : ITest1 { void M2(); } public interface ITest4 { } [System.Serializable()] [StructLayout( LayoutKind.Explicit, CharSet =CharSet.Unicode, Pack = 16, Size = 64)] public struct Test5 { [FieldOffset(2)] public int F5; } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58260"")] public interface ITest6 { } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58261"")] public interface ITest7 { } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58262"")] public interface ITest8 { } public enum Test9 { F1 = 1, F2 = 2 } [StructLayout(LayoutKind.Sequential)] public struct Test10 { [NonSerialized()] public int F3; [MarshalAs(UnmanagedType.U4)] public int F4; } public delegate void Test11(); [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58264"")] public interface ITest13 { void M13(int x, __arglist); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58265"")] public interface ITest14 { void M14(); int P6 { set; } event System.Action E4; } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58266"")] public interface ITest15 : ITest14 { } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58267"")] public interface ITest16 { void M16(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58268"")] public interface ITest17 { void M17(); void _VtblGap(); void M18(); void _VtblGap3_2(); void M19(); void _VtblGap4_2(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58269"")] public interface ITest18 { void _VtblGap3_2(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58270"")] public interface ITest19 { string M20(ref int x, out int y, [In()] ref int z, [In(), Out()] ref int u, [Optional()] int v, int w = 34); [return: MarshalAs(UnmanagedType.LPWStr)] string M21([MarshalAs(UnmanagedType.U4)] int x); } public struct Test20 { } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58271"")] public interface ITest21 { [SpecialName()] int P1 { get; set; } } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58272"")] public interface ITest22 { int P2 { get; set; } } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58273"")] public interface ITest23 { int P3 { get; } } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58274"")] public interface ITest24 { int P4 { set; } event System.Action E3; void M27(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58275"")] public interface ITest25 { [SpecialName()] event System.Action E1; } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58276"")] public interface ITest26 { event System.Action E2; int P5 { set; } void M26(); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { Test2 x = new Test2(); ITest3 y = null; System.Console.WriteLine(x); System.Console.WriteLine(y); Test5 x5 = new Test5(); System.Console.WriteLine(x5); } [MyAttribute(typeof(ITest7))] void M2(ITest6 x) {} } class UsePia1 : ITest8 {} class MyAttribute : System.Attribute { public MyAttribute(System.Type type) { } } class UsePia2 { void Test(Test10 x, Test11 x11) { System.Console.WriteLine(Test9.F1); System.Console.WriteLine(x.F4); ITest17 y = null; y.M17(); y.M19(); } } class UsePia3 : ITest13 { public void M13(int x, __arglist) { } public void M14(ITest13 x) { x.M13(1, __arglist(2,3,4)); x.M13(1, __arglist((Test20[])null)); } } interface IUsePia4 : ITest15, ITest16, ITest18, ITest19 { } class UsePia4 { public int M1(ITest21 x) { return x.P1; } public void M2(ITest22 x) { x.P2 = 1; } public int M3(ITest23 x) { return x.P3; } public void M4(ITest24 x) { x.P4 = 1; } public void M5(ITest25 x) { x.E1 += null; } public void M6(ITest26 x) { x.E2 -= null; } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest1 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest1") .Single(); Assert.Equal(TypeKind.Interface, itest1.TypeKind); Assert.Null(itest1.BaseType()); Assert.Equal(0, itest1.Interfaces().Length); Assert.True(itest1.IsComImport); Assert.False(itest1.IsSerializable); Assert.False(itest1.IsSealed); Assert.Equal( System.Runtime.InteropServices.CharSet.Ansi, itest1.MarshallingCharSet ); Assert.Equal(System.Runtime.InteropServices.LayoutKind.Auto, itest1.Layout.Kind); Assert.Equal(0, itest1.Layout.Alignment); Assert.Equal(0, itest1.Layout.Size); var attributes = itest1.GetAttributes(); Assert.Equal(3, attributes.Length); Assert.Equal( "System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes[0].ToString() ); Assert.Equal( @"System.Runtime.InteropServices.GuidAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58258"")", attributes[1].ToString() ); Assert.Equal( "System.Runtime.InteropServices.TypeIdentifierAttribute", attributes[2].ToString() ); // TypDefName: ITest1 (02000018) // Flags : [Public] [AutoLayout] [Interface] [Abstract] [Import] [AnsiClass] (000010a1) Assert.Equal( TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.Import | TypeAttributes.AnsiClass, itest1.Flags ); var test2 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("Test2") .Single(); Assert.Equal(TypeKind.Struct, test2.TypeKind); Assert.Equal(SpecialType.System_ValueType, test2.BaseType().SpecialType); Assert.Same(itest1, test2.Interfaces().Single()); Assert.False(test2.IsComImport); Assert.False(test2.IsSerializable); Assert.True(test2.IsSealed); Assert.Equal(System.Runtime.InteropServices.CharSet.Ansi, test2.MarshallingCharSet); Assert.Equal( System.Runtime.InteropServices.LayoutKind.Sequential, test2.Layout.Kind ); Assert.Equal(0, test2.Layout.Alignment); Assert.Equal(1, test2.Layout.Size); // TypDefName: Test2 (02000013) // Flags : [Public] [SequentialLayout] [Class] [Sealed] [AnsiClass] [BeforeFieldInit] (00100109) Assert.Equal( TypeAttributes.Public | TypeAttributes.SequentialLayout | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit, test2.Flags ); attributes = test2.GetAttributes(); Assert.Equal(2, attributes.Length); Assert.Equal( "System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes[0].ToString() ); Assert.Equal( @"System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""Test2"")", attributes[1].ToString() ); var itest3 = module.GlobalNamespace.GetTypeMembers("ITest3").Single(); Assert.Equal(TypeKind.Interface, itest3.TypeKind); Assert.Same(itest1, itest3.Interfaces().Single()); Assert.True(itest3.IsComImport); Assert.False(itest3.IsSerializable); Assert.False(itest3.IsSealed); Assert.Equal( System.Runtime.InteropServices.CharSet.Ansi, itest3.MarshallingCharSet ); Assert.Equal(System.Runtime.InteropServices.LayoutKind.Auto, itest3.Layout.Kind); Assert.Equal(0, itest3.Layout.Alignment); Assert.Equal(0, itest3.Layout.Size); Assert.Equal(0, module.GlobalNamespace.GetTypeMembers("ITest4").Length); var test5 = module.GlobalNamespace.GetTypeMembers("Test5").Single(); Assert.Equal(TypeKind.Struct, test5.TypeKind); Assert.False(test5.IsComImport); Assert.True(test5.IsSerializable); Assert.True(test5.IsSealed); Assert.Equal( System.Runtime.InteropServices.CharSet.Unicode, test5.MarshallingCharSet ); Assert.Equal(System.Runtime.InteropServices.LayoutKind.Explicit, test5.Layout.Kind); Assert.Equal(16, test5.Layout.Alignment); Assert.Equal(64, test5.Layout.Size); var f5 = (PEFieldSymbol)test5.GetMembers()[0]; Assert.Equal("System.Int32 Test5.F5", f5.ToTestDisplayString()); Assert.Equal(2, f5.TypeLayoutOffset.Value); // Field Name: F5 (04000003) // Flags : [Public] (00000006) Assert.Equal(FieldAttributes.Public, f5.Flags); var itest6 = module.GlobalNamespace.GetTypeMembers("ITest6").Single(); Assert.Equal(TypeKind.Interface, itest6.TypeKind); var itest7 = module.GlobalNamespace.GetTypeMembers("ITest7").Single(); Assert.Equal(TypeKind.Interface, itest7.TypeKind); var itest8 = module.GlobalNamespace.GetTypeMembers("ITest8").Single(); Assert.Equal(TypeKind.Interface, itest8.TypeKind); Assert.Same( itest8, module.GlobalNamespace.GetTypeMembers("UsePia1").Single().Interfaces().Single() ); var test9 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("Test9") .Single(); Assert.Equal(TypeKind.Enum, test9.TypeKind); Assert.False(test9.IsComImport); Assert.False(test9.IsSerializable); Assert.True(test9.IsSealed); Assert.Equal(System.Runtime.InteropServices.CharSet.Ansi, test9.MarshallingCharSet); Assert.Equal(System.Runtime.InteropServices.LayoutKind.Auto, test9.Layout.Kind); Assert.Equal(SpecialType.System_Int32, test9.EnumUnderlyingType.SpecialType); // TypDefName: Test9 (02000016) // Flags : [Public] [AutoLayout] [Class] [Sealed] [AnsiClass] (00000101) Assert.Equal( TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.AnsiClass, test9.Flags ); attributes = test9.GetAttributes(); Assert.Equal(2, attributes.Length); Assert.Equal( "System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes[0].ToString() ); Assert.Equal( @"System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""Test9"")", attributes[1].ToString() ); var fieldToEmit = test9.GetFieldsToEmit().ToArray().AsImmutableOrNull(); Assert.Equal(3, fieldToEmit.Length); var value__ = (PEFieldSymbol)fieldToEmit[0]; Assert.Equal(Accessibility.Public, value__.DeclaredAccessibility); Assert.Equal("System.Int32 Test9.value__", value__.ToTestDisplayString()); Assert.False(value__.IsStatic); Assert.True(value__.HasSpecialName); Assert.True(value__.HasRuntimeSpecialName); Assert.Null(value__.ConstantValue); // Field Name: value__ (04000004) // Flags : [Public] [SpecialName] [RTSpecialName] (00000606) Assert.Equal( FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName, value__.Flags ); var f1 = (PEFieldSymbol)fieldToEmit[1]; Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility); Assert.Equal("Test9.F1", f1.ToTestDisplayString()); Assert.True(f1.IsStatic); Assert.False(f1.HasSpecialName); Assert.False(f1.HasRuntimeSpecialName); Assert.Equal(1, f1.ConstantValue); // Field Name: F1 (04000005) // Flags : [Public] [Static] [Literal] [HasDefault] (00008056) Assert.Equal( FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal | FieldAttributes.HasDefault, f1.Flags ); var f2 = (FieldSymbol)fieldToEmit[2]; Assert.Equal("Test9.F2", f2.ToTestDisplayString()); Assert.Equal(2, f2.ConstantValue); Assert.Equal(3, test9.GetMembers().Length); Assert.Same(f1, test9.GetMembers()[0]); Assert.Same(f2, test9.GetMembers()[1]); Assert.True(((MethodSymbol)test9.GetMembers()[2]).IsDefaultValueTypeConstructor()); var test10 = module.GlobalNamespace.GetTypeMembers("Test10").Single(); Assert.Equal(TypeKind.Struct, test10.TypeKind); Assert.Equal( System.Runtime.InteropServices.LayoutKind.Sequential, test10.Layout.Kind ); Assert.Equal(3, test10.GetMembers().Length); var f3 = (FieldSymbol)test10.GetMembers()[0]; Assert.Equal(Accessibility.Public, f3.DeclaredAccessibility); Assert.Equal("System.Int32 Test10.F3", f3.ToTestDisplayString()); Assert.False(f3.IsStatic); Assert.False(f3.HasSpecialName); Assert.False(f3.HasRuntimeSpecialName); Assert.Null(f3.ConstantValue); Assert.Equal((System.Runtime.InteropServices.UnmanagedType)0, f3.MarshallingType); Assert.False(f3.TypeLayoutOffset.HasValue); Assert.True(f3.IsNotSerialized); var f4 = (FieldSymbol)test10.GetMembers()[1]; Assert.Equal("System.Int32 Test10.F4", f4.ToTestDisplayString()); Assert.Equal(System.Runtime.InteropServices.UnmanagedType.U4, f4.MarshallingType); Assert.False(f4.IsNotSerialized); Assert.True(((MethodSymbol)test10.GetMembers()[2]).IsDefaultValueTypeConstructor()); var test11 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("Test11") .Single(); Assert.Equal(TypeKind.Delegate, test11.TypeKind); Assert.Equal(SpecialType.System_MulticastDelegate, test11.BaseType().SpecialType); // TypDefName: Test11 (02000012) // Flags : [Public] [AutoLayout] [Class] [Sealed] [AnsiClass] (00000101) Assert.Equal( TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.AnsiClass, test11.Flags ); attributes = test11.GetAttributes(); Assert.Equal(2, attributes.Length); Assert.Equal( "System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes[0].ToString() ); Assert.Equal( @"System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""Test11"")", attributes[1].ToString() ); Assert.Equal(4, test11.GetMembers().Length); var ctor = (PEMethodSymbol)test11.GetMembers(".ctor").Single(); // MethodName: .ctor (0600000F) // Flags : [Public] [HideBySig] [ReuseSlot] [SpecialName] [RTSpecialName] [.ctor] (00001886) // ImplFlags : [Runtime] [Managed] (00000003) // CallCnvntn: [DEFAULT] // hasThis // ReturnType: Void // 2 Arguments // Argument #1: Object // Argument #2: I Assert.Equal( MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, ctor.Flags ); Assert.Equal( MethodImplAttributes.Runtime, (MethodImplAttributes)ctor.ImplementationAttributes ); Assert.Equal( CallingConvention.Default | CallingConvention.HasThis, ctor.CallingConvention ); Assert.Equal( "Test11..ctor(System.Object @object, System.IntPtr method)", ctor.ToTestDisplayString() ); var begin = (PEMethodSymbol)test11.GetMembers("BeginInvoke").Single(); // MethodName: BeginInvoke (06000011) // Flags : [Public] [Virtual] [HideBySig] [NewSlot] (000001c6) // ImplFlags : [Runtime] [Managed] (00000003) // CallCnvntn: [DEFAULT] // hasThis // ReturnType: Class System.IAsyncResult // 2 Arguments // Argument #1: Class System.AsyncCallback // Argument #2: Object Assert.Equal( MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot, begin.Flags ); Assert.Equal( MethodImplAttributes.Runtime, (MethodImplAttributes)begin.ImplementationAttributes ); Assert.Equal( CallingConvention.Default | CallingConvention.HasThis, begin.CallingConvention ); Assert.Equal( "System.IAsyncResult Test11.BeginInvoke(System.AsyncCallback callback, System.Object @object)", begin.ToTestDisplayString() ); var end = (PEMethodSymbol)test11.GetMembers("EndInvoke").Single(); // MethodName: EndInvoke (06000012) // Flags : [Public] [Virtual] [HideBySig] [NewSlot] (000001c6) // ImplFlags : [Runtime] [Managed] (00000003) // CallCnvntn: [DEFAULT] // hasThis // ReturnType: Void // 1 Arguments // Argument #1: Class System.IAsyncResult Assert.Equal( MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot, end.Flags ); Assert.Equal( MethodImplAttributes.Runtime, (MethodImplAttributes)end.ImplementationAttributes ); Assert.Equal( CallingConvention.Default | CallingConvention.HasThis, end.CallingConvention ); Assert.Equal( "void Test11.EndInvoke(System.IAsyncResult result)", end.ToTestDisplayString() ); var invoke = (PEMethodSymbol)test11.GetMembers("Invoke").Single(); // MethodName: Invoke (06000010) // Flags : [Public] [Virtual] [HideBySig] [NewSlot] (000001c6) // ImplFlags : [Runtime] [Managed] (00000003) // CallCnvntn: [DEFAULT] // hasThis // ReturnType: Void // No arguments. Assert.Equal( MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot, invoke.Flags ); Assert.Equal( MethodImplAttributes.Runtime, (MethodImplAttributes)invoke.ImplementationAttributes ); Assert.Equal( CallingConvention.Default | CallingConvention.HasThis, invoke.CallingConvention ); Assert.Equal("void Test11.Invoke()", invoke.ToTestDisplayString()); var itest13 = module.GlobalNamespace.GetTypeMembers("ITest13").Single(); Assert.Equal(TypeKind.Interface, itest13.TypeKind); var m13 = (PEMethodSymbol)itest13.GetMembers()[0]; // MethodName: M13 (06000001) // Flags : [Public] [Virtual] [HideBySig] [NewSlot] [Abstract] (000005c6) // ImplFlags : [IL] [Managed] (00000000) // CallCnvntn: [VARARG] // hasThis // ReturnType: Void // 1 Arguments // Argument #1: I4 // 1 Parameters // (1) ParamToken : (08000001) Name : x flags: [none] (00000000) Assert.Equal( MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Abstract, m13.Flags ); Assert.Equal( MethodImplAttributes.IL, (MethodImplAttributes)m13.ImplementationAttributes ); Assert.Equal( CallingConvention.ExtraArguments | CallingConvention.HasThis, m13.CallingConvention ); Assert.Equal( "void ITest13.M13(System.Int32 x, __arglist)", m13.ToTestDisplayString() ); var itest14 = module.GlobalNamespace.GetTypeMembers("ITest14").Single(); Assert.Equal(TypeKind.Interface, itest14.TypeKind); Assert.Equal(6, itest14.GetMembers().Length); Assert.Equal("void ITest14.M14()", itest14.GetMembers()[0].ToTestDisplayString()); Assert.Equal("void ITest14.P6.set", itest14.GetMembers()[1].ToTestDisplayString()); Assert.Equal("void ITest14.E4.add", itest14.GetMembers()[2].ToTestDisplayString()); Assert.Equal( "void ITest14.E4.remove", itest14.GetMembers()[3].ToTestDisplayString() ); Assert.Equal( "System.Int32 ITest14.P6 { set; }", itest14.GetMembers()[4].ToTestDisplayString() ); Assert.Equal( "event System.Action ITest14.E4", itest14.GetMembers()[5].ToTestDisplayString() ); var itest16 = module.GlobalNamespace.GetTypeMembers("ITest16").Single(); Assert.Equal(TypeKind.Interface, itest16.TypeKind); Assert.Equal("void ITest16.M16()", itest16.GetMembers()[0].ToTestDisplayString()); var itest17 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest17") .Single(); Assert.Equal(TypeKind.Interface, itest17.TypeKind); var metadata = ((PEModuleSymbol)module).Module; var methodNames = metadata .GetMethodsOfTypeOrThrow(itest17.Handle) .AsEnumerable() .Select(rid => metadata.GetMethodDefNameOrThrow(rid)) .ToArray(); Assert.Equal(3, methodNames.Length); Assert.Equal("M17", methodNames[0]); Assert.Equal("_VtblGap1_4", methodNames[1]); Assert.Equal("M19", methodNames[2]); MethodDefinitionHandle gapMethodDef = metadata .GetMethodsOfTypeOrThrow(itest17.Handle) .AsEnumerable() .ElementAt(1); string name; MethodImplAttributes implFlags; MethodAttributes flags; int rva; metadata.GetMethodDefPropsOrThrow( gapMethodDef, out name, out implFlags, out flags, out rva ); Assert.Equal( MethodAttributes.Public | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName, flags ); Assert.Equal(MethodImplAttributes.IL | MethodImplAttributes.Runtime, implFlags); SignatureHeader signatureHeader; BadImageFormatException mrEx; ParamInfo<TypeSymbol>[] paramInfo = new MetadataDecoder( (PEModuleSymbol)module, itest17 ).GetSignatureForMethod(gapMethodDef, out signatureHeader, out mrEx); Assert.Null(mrEx); Assert.Equal( (byte)SignatureCallingConvention.Default | (byte)SignatureAttributes.Instance, signatureHeader.RawValue ); Assert.Equal(1, paramInfo.Length); Assert.Equal(SpecialType.System_Void, paramInfo[0].Type.SpecialType); Assert.False(paramInfo[0].IsByRef); Assert.True(paramInfo[0].CustomModifiers.IsDefault); Assert.Equal(2, itest17.GetMembers().Length); var m17 = (PEMethodSymbol)itest17.GetMembers("M17").Single(); // MethodName: M17 (06000013) // Flags : [Public] [Virtual] [HideBySig] [NewSlot] [Abstract] (000005c6) // ImplFlags : [IL] [Managed] (00000000) // CallCnvntn: [DEFAULT] // hasThis // ReturnType: Void // No arguments. Assert.Equal( MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Abstract, m17.Flags ); Assert.Equal( MethodImplAttributes.IL, (MethodImplAttributes)m17.ImplementationAttributes ); Assert.Equal( CallingConvention.Default | CallingConvention.HasThis, m17.CallingConvention ); Assert.Equal("void ITest17.M17()", m17.ToTestDisplayString()); var itest18 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest18") .Single(); Assert.Equal(TypeKind.Interface, itest18.TypeKind); Assert.False(metadata.GetMethodsOfTypeOrThrow(itest18.Handle).AsEnumerable().Any()); var itest19 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest19") .Single(); var m20 = (PEMethodSymbol)itest19.GetMembers("M20").Single(); // 6 Arguments // Argument #1: ByRef I4 // Argument #2: ByRef I4 // Argument #3: ByRef I4 // Argument #4: ByRef I4 // Argument #5: I4 // Argument #6: I4 // 6 Parameters // (1) ParamToken : (08000008) Name : x flags: [none] (00000000) // (2) ParamToken : (08000009) Name : y flags: [Out] (00000002) // (3) ParamToken : (0800000a) Name : z flags: [In] (00000001) // (4) ParamToken : (0800000b) Name : u flags: [In] [Out] (00000003) // (5) ParamToken : (0800000c) Name : v flags: [Optional] (00000010) // (6) ParamToken : (0800000d) Name : w flags: [Optional] [HasDefault] (00001010) Default: (I4) 34 var param = (PEParameterSymbol)m20.Parameters[0]; Assert.Equal(RefKind.Ref, param.RefKind); Assert.Equal((ParameterAttributes)0, param.Flags); Assert.Equal(0, param.Ordinal); param = (PEParameterSymbol)m20.Parameters[1]; Assert.Equal(RefKind.Out, param.RefKind); Assert.Equal(ParameterAttributes.Out, param.Flags); Assert.Equal(1, param.Ordinal); param = (PEParameterSymbol)m20.Parameters[2]; Assert.Equal(RefKind.Ref, param.RefKind); Assert.Equal(ParameterAttributes.In, param.Flags); Assert.Equal(2, param.Ordinal); param = (PEParameterSymbol)m20.Parameters[3]; Assert.Equal(RefKind.Ref, param.RefKind); Assert.Equal(ParameterAttributes.In | ParameterAttributes.Out, param.Flags); Assert.Equal(3, param.Ordinal); param = (PEParameterSymbol)m20.Parameters[4]; Assert.Equal(RefKind.None, param.RefKind); Assert.Equal(ParameterAttributes.Optional, param.Flags); Assert.Null(param.ExplicitDefaultConstantValue); Assert.Equal(4, param.Ordinal); param = (PEParameterSymbol)m20.Parameters[5]; Assert.Equal(RefKind.None, param.RefKind); Assert.Equal( ParameterAttributes.Optional | ParameterAttributes.HasDefault, param.Flags ); Assert.Equal(34, param.ExplicitDefaultValue); Assert.Equal(5, param.Ordinal); param = m20.ReturnTypeParameter; Assert.Equal((ParameterAttributes)0, param.Flags); var m21 = (PEMethodSymbol)itest19.GetMembers("M21").Single(); // 1 Arguments // Argument #1: I4 // 2 Parameters // (0) ParamToken : (0800000e) Name : flags: [HasFieldMarshal] (00002000) // NATIVE_TYPE_LPWSTR // (1) ParamToken : (0800000f) Name : x flags: [HasFieldMarshal] (00002000) // NATIVE_TYPE_U4 param = (PEParameterSymbol)m21.Parameters[0]; Assert.Equal(ParameterAttributes.HasFieldMarshal, param.Flags); Assert.Equal( System.Runtime.InteropServices.UnmanagedType.U4, (System.Runtime.InteropServices.UnmanagedType)param.MarshallingDescriptor[0] ); param = m21.ReturnTypeParameter; Assert.Equal(ParameterAttributes.HasFieldMarshal, param.Flags); Assert.Equal( System.Runtime.InteropServices.UnmanagedType.LPWStr, (System.Runtime.InteropServices.UnmanagedType)param.MarshallingDescriptor[0] ); var itest21 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest21") .Single(); var p1 = (PEPropertySymbol)itest21.GetMembers("P1").Single(); Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility); Assert.True(p1.HasSpecialName); Assert.False(p1.HasRuntimeSpecialName); var get_P1 = (PEMethodSymbol)itest21.GetMembers("get_P1").Single(); var set_P1 = (PEMethodSymbol)itest21.GetMembers("set_P1").Single(); Assert.Same(p1.GetMethod, get_P1); Assert.Same(p1.SetMethod, set_P1); var itest22 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest22") .Single(); var p2 = (PEPropertySymbol)itest22.GetMembers("P2").Single(); var get_P2 = (PEMethodSymbol)itest22.GetMembers("get_P2").Single(); var set_P2 = (PEMethodSymbol)itest22.GetMembers("set_P2").Single(); Assert.Same(p2.GetMethod, get_P2); Assert.Same(p2.SetMethod, set_P2); var itest23 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest23") .Single(); var p3 = (PEPropertySymbol)itest23.GetMembers("P3").Single(); var get_P3 = (PEMethodSymbol)itest23.GetMembers("get_P3").Single(); Assert.Same(p3.GetMethod, get_P3); Assert.Null(p3.SetMethod); var itest24 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest24") .Single(); var p4 = (PEPropertySymbol)itest24.GetMembers("P4").Single(); Assert.Equal(2, itest24.GetMembers().Length); Assert.False(p4.HasSpecialName); Assert.False(p4.HasRuntimeSpecialName); Assert.Equal( (byte)SignatureKind.Property | (byte)SignatureAttributes.Instance, (byte)p4.CallingConvention ); var set_P4 = (PEMethodSymbol)itest24.GetMembers("set_P4").Single(); Assert.Null(p4.GetMethod); Assert.Same(p4.SetMethod, set_P4); var itest25 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest25") .Single(); var e1 = (PEEventSymbol)itest25.GetMembers("E1").Single(); Assert.True(e1.HasSpecialName); Assert.False(e1.HasRuntimeSpecialName); var add_E1 = (PEMethodSymbol)itest25.GetMembers("add_E1").Single(); var remove_E1 = (PEMethodSymbol)itest25.GetMembers("remove_E1").Single(); Assert.Same(e1.AddMethod, add_E1); Assert.Same(e1.RemoveMethod, remove_E1); var itest26 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest26") .Single(); var e2 = (PEEventSymbol)itest26.GetMembers("E2").Single(); Assert.Equal(3, itest26.GetMembers().Length); Assert.False(e2.HasSpecialName); Assert.False(e2.HasRuntimeSpecialName); var add_E2 = (PEMethodSymbol)itest26.GetMembers("add_E2").Single(); var remove_E2 = (PEMethodSymbol)itest26.GetMembers("remove_E2").Single(); Assert.Same(e2.AddMethod, add_E2); Assert.Same(e2.RemoveMethod, remove_E2); }; var expected_M5 = @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldnull IL_0002: callvirt ""void ITest25.E1.add"" IL_0007: ret } "; var expected_M6 = @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldnull IL_0002: callvirt ""void ITest26.E2.remove"" IL_0007: ret } "; var verifier = CompileAndVerify(compilation1, symbolValidator: metadataValidator); verifier.VerifyIL("UsePia4.M5", expected_M5); verifier.VerifyIL("UsePia4.M6", expected_M6); verifier = CompileAndVerify(compilation2, symbolValidator: metadataValidator); verifier.VerifyIL("UsePia4.M5", expected_M5); verifier.VerifyIL("UsePia4.M6", expected_M6); } [Fact] public void LocalTypeMetadata_GenericParameters() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] public interface ITest28 { } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public interface ITest29 { void M21<T1, T2, T5, T6, T7>() where T2 : ITest28 where T5 : new() where T6 : struct where T7 : class; } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); //CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } interface UsePia5 : ITest29 { } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest28 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest28") .Single(); Assert.Equal(TypeKind.Interface, itest28.TypeKind); var itest29 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest29") .Single(); Assert.Equal(TypeKind.Interface, itest29.TypeKind); var m21 = (PEMethodSymbol)itest29.GetMembers("M21").Single(); Assert.Equal(5, m21.TypeParameters.Length); var t1 = m21.TypeParameters[0]; Assert.Equal("T1", t1.Name); Assert.False(t1.HasConstructorConstraint); Assert.False(t1.HasValueTypeConstraint); Assert.False(t1.HasReferenceTypeConstraint); Assert.Equal(0, t1.ConstraintTypes().Length); Assert.Equal(VarianceKind.None, t1.Variance); var t2 = m21.TypeParameters[1]; Assert.False(t2.HasConstructorConstraint); Assert.False(t2.HasValueTypeConstraint); Assert.False(t2.HasReferenceTypeConstraint); Assert.Equal(1, t2.ConstraintTypes().Length); Assert.Same(itest28, t2.ConstraintTypes()[0]); Assert.Equal(VarianceKind.None, t2.Variance); var t5 = m21.TypeParameters[2]; Assert.True(t5.HasConstructorConstraint); Assert.False(t5.HasValueTypeConstraint); Assert.False(t5.HasReferenceTypeConstraint); Assert.Equal(0, t5.ConstraintTypes().Length); Assert.Equal(VarianceKind.None, t5.Variance); var t6 = m21.TypeParameters[3]; Assert.False(t6.HasConstructorConstraint); Assert.True(t6.HasValueTypeConstraint); Assert.False(t6.HasReferenceTypeConstraint); Assert.Equal(0, t6.ConstraintTypes().Length); Assert.Equal(VarianceKind.None, t6.Variance); var t7 = m21.TypeParameters[4]; Assert.False(t7.HasConstructorConstraint); Assert.False(t7.HasValueTypeConstraint); Assert.True(t7.HasReferenceTypeConstraint); Assert.Equal(0, t7.ConstraintTypes().Length); Assert.Equal(VarianceKind.None, t7.Variance); }; CompileAndVerify( compilation1, symbolValidator: metadataValidator, verify: Verification.Fails ); CompileAndVerify( compilation2, symbolValidator: metadataValidator, verify: Verification.Fails ); } [Fact] public void NewWithoutCoClass() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58271"")] public interface ITest28 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public ITest28 Test() { return new ITest28(); } }"; DiagnosticDescription[] expected = { // (10,16): error CS0144: Cannot create an instance of the abstract type or interface 'ITest28' // return new ITest28(); Diagnostic(ErrorCode.ERR_NoNewAbstract, "new ITest28()").WithArguments("ITest28") }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void NewCoClassWithoutGiud() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(ClassITest28))] public interface ITest28 { int P1 { get; set; } } public class ClassITest28 //: ITest28 { private ClassITest28(){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.DebugDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public ITest28 Test() { return new ITest28 {P1 = 2}; } }"; var expected = @" { // Code size 39 (0x27) .maxstack 3 .locals init (ITest28 V_0) IL_0000: nop IL_0001: ldstr ""00000000-0000-0000-0000-000000000000"" IL_0006: newobj ""System.Guid..ctor(string)"" IL_000b: call ""System.Type System.Type.GetTypeFromCLSID(System.Guid)"" IL_0010: call ""object System.Activator.CreateInstance(System.Type)"" IL_0015: castclass ""ITest28"" IL_001a: dup IL_001b: ldc.i4.2 IL_001c: callvirt ""void ITest28.P1.set"" IL_0021: nop IL_0022: stloc.0 IL_0023: br.s IL_0025 IL_0025: ldloc.0 IL_0026: ret } "; Action<ModuleSymbol> metadataValidator = (ModuleSymbol module) => { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest28 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest28") .Single(); var interfaceType = itest28 .GetAttributes("System.Runtime.InteropServices", "CoClassAttribute") .Single(); Assert.Equal( "System.Runtime.InteropServices.CoClassAttribute(typeof(object))", interfaceType.ToString() ); }; var compilation = CreateCompilationWithMscorlib40( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var verifier = CompileAndVerify(compilation, symbolValidator: metadataValidator); verifier.VerifyIL("UsePia.Test", expected); compilation = CreateCompilationWithMscorlib40( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); verifier = CompileAndVerify(compilation, symbolValidator: metadataValidator); verifier.VerifyIL("UsePia.Test", expected); } [Fact] public void NewCoClassWithGiud() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(ClassITest28))] public interface ITest28 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest28 //: ITest28 { public ClassITest28(int x){} } "; var piaCompilation = CreateEmptyCompilation( pia, new MetadataReference[] { MscorlibRef_v4_0_30316_17626 }, options: TestOptions.DebugDll ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public ITest28 Test() { return new ITest28(); } }"; var expected = @" { // Code size 31 (0x1f) .maxstack 1 .locals init (ITest28 V_0) IL_0000: nop IL_0001: ldstr ""f9c2d51d-4f44-45f0-9eda-c9d599b58278"" IL_0006: newobj ""System.Guid..ctor(string)"" IL_000b: call ""System.Type System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(System.Guid)"" IL_0010: call ""object System.Activator.CreateInstance(System.Type)"" IL_0015: castclass ""ITest28"" IL_001a: stloc.0 IL_001b: br.s IL_001d IL_001d: ldloc.0 IL_001e: ret } "; Action<ModuleSymbol> metadataValidator = (ModuleSymbol module) => { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest28 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest28") .Single(); var interfaceType = itest28 .GetAttributes("System.Runtime.InteropServices", "CoClassAttribute") .Single(); Assert.Equal( "System.Runtime.InteropServices.CoClassAttribute(typeof(object))", interfaceType.ToString() ); }; var compilation = CreateEmptyCompilation( consumer, new MetadataReference[] { MscorlibRef_v4_0_30316_17626, new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) }, options: TestOptions.DebugExe ); var verifier = CompileAndVerify(compilation, symbolValidator: metadataValidator); verifier.VerifyIL("UsePia.Test", expected); compilation = CreateEmptyCompilation( consumer, new MetadataReference[] { MscorlibRef_v4_0_30316_17626, piaCompilation.EmitToImageReference(embedInteropTypes: true) }, options: TestOptions.DebugExe ); verifier = CompileAndVerify(compilation, symbolValidator: metadataValidator); verifier.VerifyIL("UsePia.Test", expected); } [Fact] public void NewCoClassWithArguments() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(ClassITest28))] public interface ITest28 { int P1 { get; set; } } public class ClassITest28 //: ITest28 { private ClassITest28(int x){} } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public ITest28 Test() { return new ITest28(1); } }"; DiagnosticDescription[] expected = { // (10,20): error CS1729: 'ITest28' does not contain a constructor that takes 1 arguments // return new ITest28(1); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ITest28") .WithArguments("ITest28", "1") .WithLocation(10, 20) }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void NewCoClassMissingWellKnownMembers() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(ClassITest28))] public interface ITest28 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public class ClassITest28 : ITest28 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" namespace System { public class Guid { private Guid() { } } public class Activator { } } class UsePia { public static void Main() { } public ITest28 Test() { return new ITest28(); } }"; DiagnosticDescription[] expected = { // (20,16): error CS0656: Missing compiler required member 'System.Guid..ctor' // return new ITest28(); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "new ITest28()") .WithArguments("System.Guid", ".ctor") .WithLocation(20, 16) }; var compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); compilation = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation, true, expected); } [Fact] public void AddHandler_Simple() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public delegate void MyDelegate(); [ComEventInterface(typeof(InterfaceEvents), typeof(int))] public interface Interface1_Event { event MyDelegate Goo; } [ComImport(), Guid(""84374891-a3b1-4f8f-8310-99ea58059b10"")] public interface InterfaceEvents { void Goo(); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void Test(Interface1_Event x) { x.Goo += Handler; } void Handler() {} } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(2, module.GetReferencedAssemblySymbols().Length); Assert.Equal("mscorlib", module.GetReferencedAssemblySymbols()[0].Name); Assert.Equal("System.Core", module.GetReferencedAssemblySymbols()[1].Name); var interface1_Event = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("Interface1_Event") .Single(); var attributes = interface1_Event.GetAttributes(); Assert.Equal(3, attributes.Length); Assert.Equal( "System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes[0].ToString() ); Assert.Equal( "System.Runtime.InteropServices.ComEventInterfaceAttribute(typeof(InterfaceEvents), typeof(InterfaceEvents))", attributes[1].ToString() ); Assert.Equal( @"System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""Interface1_Event"")", attributes[2].ToString() ); var goo = (PEEventSymbol)interface1_Event.GetMembers("Goo").Single(); var interfaceEvents = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("InterfaceEvents") .Single(); attributes = interfaceEvents.GetAttributes(); Assert.Equal(3, attributes.Length); Assert.Equal( "System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes[0].ToString() ); Assert.Equal( @"System.Runtime.InteropServices.GuidAttribute(""84374891-a3b1-4f8f-8310-99ea58059b10"")", attributes[1].ToString() ); Assert.Equal( "System.Runtime.InteropServices.TypeIdentifierAttribute", attributes[2].ToString() ); var goo1 = (PEMethodSymbol)interfaceEvents.GetMembers("Goo").Single(); }; var expected = @" { // Code size 39 (0x27) .maxstack 4 IL_0000: ldtoken ""Interface1_Event"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""Goo"" IL_000f: newobj ""System.Runtime.InteropServices.ComAwareEventInfo..ctor(System.Type, string)"" IL_0014: ldarg.1 IL_0015: ldarg.0 IL_0016: ldftn ""void UsePia.Handler()"" IL_001c: newobj ""MyDelegate..ctor(object, System.IntPtr)"" IL_0021: callvirt ""void System.Reflection.EventInfo.AddEventHandler(object, System.Delegate)"" IL_0026: ret } "; var verifier = CompileAndVerify(compilation1, symbolValidator: metadataValidator); verifier.VerifyIL("UsePia.Test", expected); verifier = CompileAndVerify(compilation2, symbolValidator: metadataValidator); verifier.VerifyIL("UsePia.Test", expected); } [Fact] public void RemoveHandler_Simple() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public delegate void MyDelegate(); [ComEventInterface(typeof(InterfaceEvents), typeof(int))] public interface Interface1_Event { event MyDelegate Goo; } [ComImport(), Guid(""84374891-a3b1-4f8f-8310-99ea58059b10"")] public interface InterfaceEvents { void Goo(int x); } [ComImport(), Guid(""84374c91-a3b1-4f8f-8310-99ea58059b10"")] public interface Interface1 : Interface1_Event { void Raise(); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void Test(Interface1 x) { x.Goo -= Handler; } void Handler() {} } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); var expected = @" { // Code size 39 (0x27) .maxstack 4 IL_0000: ldtoken ""Interface1_Event"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""Goo"" IL_000f: newobj ""System.Runtime.InteropServices.ComAwareEventInfo..ctor(System.Type, string)"" IL_0014: ldarg.1 IL_0015: ldarg.0 IL_0016: ldftn ""void UsePia.Handler()"" IL_001c: newobj ""MyDelegate..ctor(object, System.IntPtr)"" IL_0021: callvirt ""void System.Reflection.EventInfo.RemoveEventHandler(object, System.Delegate)"" IL_0026: ret } "; var verifier = CompileAndVerify(compilation1); verifier.VerifyIL("UsePia.Test", expected); verifier = CompileAndVerify(compilation2); verifier.VerifyIL("UsePia.Test", expected); } [Fact] public void CS1766ERR_MissingMethodOnSourceInterface() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public delegate void MyDelegate(); [ComEventInterface(typeof(InterfaceEvents), typeof(int))] public interface Interface1_Event { event MyDelegate Goo; } [ComImport(), Guid(""84374891-a3b1-4f8f-8310-99ea58059b10"")] public interface InterfaceEvents { } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void Test(Interface1_Event x) { x.Goo -= Handler; } void Handler() {} } "; DiagnosticDescription[] expected = { // (10,6): error CS1766: Source interface 'InterfaceEvents' is missing method 'Goo' which is required to embed event 'Interface1_Event.Goo'. // x.Goo -= Handler; Diagnostic(ErrorCode.ERR_MissingMethodOnSourceInterface, "x.Goo -= Handler") .WithArguments("InterfaceEvents", "Goo", "Interface1_Event.Goo") }; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation1, true, expected); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation2, true, expected); } [Fact] public void CS1767ERR_MissingSourceInterface() { string pia = @" using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public delegate void MyDelegate(); [ComEventInterface(typeof(object[]), typeof(object))] public interface Interface1_Event { event MyDelegate E; } [ComEventInterface(typeof(object[]), typeof(object))] public interface Interface2_Event { event MyDelegate E; } [ComEventInterface(null, null)] public interface Interface3_Event { event MyDelegate E; } [ComEventInterface(null, null)] public interface Interface4_Event { event MyDelegate E; }"; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { void M1(Interface1_Event x1) { x1.E += Handler; } void M2(Interface2_Event x2) { } void M3(Interface3_Event x3) { } void M4(Interface4_Event x4) { x4.E += Handler; } void Handler() { } }"; DiagnosticDescription[] expected = { // (6,6): error CS1767: Interface 'Interface1_Event' has an invalid source interface which is required to embed event 'Interface1_Event.E'. // x1.E += Handler; Diagnostic(ErrorCode.ERR_MissingSourceInterface, "x1.E += Handler") .WithArguments("Interface1_Event", "Interface1_Event.E") .WithLocation(6, 6), // (16,6): error CS1767: Interface 'Interface4_Event' has an invalid source interface which is required to embed event 'Interface4_Event.E'. // x4.E += Handler; Diagnostic(ErrorCode.ERR_MissingSourceInterface, "x4.E += Handler") .WithArguments("Interface4_Event", "Interface4_Event.E") .WithLocation(16, 6) }; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseDll, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation1, true, expected); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseDll, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation2, true, expected); } [Fact] public void MissingComImport() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public delegate void MyDelegate(); [Guid(""84374891-a3b1-4f8f-8310-99ea58059b10"")] public interface Interface1_Event { event MyDelegate Goo; } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void Test(Interface1_Event x) { x.Goo -= Handler; } void Handler() {} } "; DiagnosticDescription[] expected = { // (10,6): error CS1756: Interop type 'Interface1_Event' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.ComImportAttribute' attribute. // x.Goo -= Handler; Diagnostic(ErrorCode.ERR_InteropTypeMissingAttribute, "x.Goo -= Handler") .WithArguments( "Interface1_Event", "System.Runtime.InteropServices.ComImportAttribute" ) }; DiagnosticDescription[] expectedMetadataOnly = { // error CS1756: Interop type 'Interface1_Event' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.ComImportAttribute' attribute. Diagnostic(ErrorCode.ERR_InteropTypeMissingAttribute) .WithArguments( "Interface1_Event", "System.Runtime.InteropServices.ComImportAttribute" ) }; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation1, false, expected, expectedMetadataOnly); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation2, false, expected, expectedMetadataOnly); } [Fact] public void MissingGuid() { var iLSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly pia { .custom instance void [mscorlib]System.Runtime.InteropServices.ImportedFromTypeLibAttribute::.ctor(string) = ( 01 00 0E 47 65 6E 65 72 61 6C 50 49 41 2E 64 6C // ...GeneralPIA.dl 6C 00 00 ) // l.. .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 66 39 63 32 64 35 31 64 2D 34 66 34 34 // ..$f9c2d51d-4f44 2D 34 35 66 30 2D 39 65 64 61 2D 63 39 64 35 39 // -45f0-9eda-c9d59 39 62 35 38 32 35 37 00 00 ) // 9b58257.. } .module pia.dll // MVID: {FDF1B1F7-A867-40B9-83CD-3F75B2D2B3C2} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY .class public auto ansi sealed MyDelegate extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } // end of method MyDelegate::.ctor .method public hidebysig newslot virtual instance void Invoke() runtime managed { } // end of method MyDelegate::Invoke .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { } // end of method MyDelegate::BeginInvoke .method public hidebysig newslot virtual instance void EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed { } // end of method MyDelegate::EndInvoke } // end of class MyDelegate .class interface public abstract auto ansi import Interface1_Event { .method public hidebysig newslot specialname abstract virtual instance void add_Goo(class MyDelegate 'value') cil managed { } // end of method Interface1_Event::add_Goo .method public hidebysig newslot specialname abstract virtual instance void remove_Goo(class MyDelegate 'value') cil managed { } // end of method Interface1_Event::remove_Goo .event MyDelegate Goo { .removeon instance void Interface1_Event::remove_Goo(class MyDelegate) .addon instance void Interface1_Event::add_Goo(class MyDelegate) } // end of event Interface1_Event::Goo } // end of class Interface1_Event "; MetadataReference piaReference = CompileIL( iLSource, prependDefaultHeader: false, embedInteropTypes: true ); string consumer = @" class UsePia { public static void Main() { } public void Test(Interface1_Event x) { x.Goo -= Handler; } void Handler() {} } "; DiagnosticDescription[] expected = { // (10,6): error CS1756: Interop type 'Interface1_Event' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.GuidAttribute' attribute. // x.Goo -= Handler; Diagnostic(ErrorCode.ERR_InteropTypeMissingAttribute, "x.Goo -= Handler") .WithArguments( "Interface1_Event", "System.Runtime.InteropServices.GuidAttribute" ) }; DiagnosticDescription[] expectedMetadataOnly = { // error CS1756: Interop type 'Interface1_Event' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.GuidAttribute' attribute. Diagnostic(ErrorCode.ERR_InteropTypeMissingAttribute) .WithArguments( "Interface1_Event", "System.Runtime.InteropServices.GuidAttribute" ) }; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaReference } ); VerifyEmitDiagnostics(compilation1, false, expected, expectedMetadataOnly); } [Fact] public void InterfaceTypeAttribute() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ITest29 { } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [InterfaceType((short)ComInterfaceType.InterfaceIsIUnknown)] public interface ITest30 { } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } class UsePia5 : ITest29, ITest30 { } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest29 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest29") .Single(); var interfaceType = itest29 .GetAttributes("System.Runtime.InteropServices", "InterfaceTypeAttribute") .Single(); Assert.Equal( "System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)", interfaceType.ToString() ); var itest30 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest30") .Single(); interfaceType = itest30 .GetAttributes("System.Runtime.InteropServices", "InterfaceTypeAttribute") .Single(); Assert.Equal( "System.Runtime.InteropServices.InterfaceTypeAttribute(1)", interfaceType.ToString() ); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void BestFitMappingAttribute() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] [BestFitMapping(true)] public interface ITest29 { } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [BestFitMapping(false, ThrowOnUnmappableChar=true)] public interface ITest30 { } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } class UsePia5 : ITest29, ITest30 { } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest29 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest29") .Single(); var interfaceType = itest29 .GetAttributes("System.Runtime.InteropServices", "BestFitMappingAttribute") .Single(); Assert.Equal( "System.Runtime.InteropServices.BestFitMappingAttribute(true)", interfaceType.ToString() ); var itest30 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest30") .Single(); interfaceType = itest30 .GetAttributes("System.Runtime.InteropServices", "BestFitMappingAttribute") .Single(); Assert.Equal( "System.Runtime.InteropServices.BestFitMappingAttribute(false, ThrowOnUnmappableChar = true)", interfaceType.ToString() ); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void FlagsAttribute() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [Flags()] public enum Test31 { a = 0 } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void M6(Test31 x) { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var test31 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("Test31") .Single(); var interfaceType = test31.GetAttributes("System", "FlagsAttribute").Single(); Assert.Equal("System.FlagsAttribute", interfaceType.ToString()); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void DefaultMemberAttribute() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [System.Reflection.DefaultMember(""M1"")] public interface ITest30 { int[] M1(); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void M6(ITest30 x) { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest30 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest30") .Single(); var interfaceType = itest30 .GetAttributes("System.Reflection", "DefaultMemberAttribute") .Single(); Assert.Equal( @"System.Reflection.DefaultMemberAttribute(""M1"")", interfaceType.ToString() ); Assert.Equal( "System.Int32[] ITest30.M1()", itest30.GetMembers("M1").Single().ToTestDisplayString() ); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void LCIDConversionAttribute() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest30 { [LCIDConversionAttribute(123)] void M1(); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } class UsePia5 : ITest30 { public void M1() { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest30 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest30") .Single(); var m1 = (PEMethodSymbol)itest30.GetMembers("M1").Single(); var attr = m1.GetAttributes( "System.Runtime.InteropServices", "LCIDConversionAttribute" ) .Single(); Assert.Equal( "System.Runtime.InteropServices.LCIDConversionAttribute(123)", attr.ToString() ); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void DispIdAttribute() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest30 { [DispIdAttribute(124)] void M1(); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } class UsePia5 : ITest30 { public void M1() { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest30 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest30") .Single(); var m1 = (PEMethodSymbol)itest30.GetMembers("M1").Single(); var attr = m1.GetAttributes("System.Runtime.InteropServices", "DispIdAttribute") .Single(); Assert.Equal( "System.Runtime.InteropServices.DispIdAttribute(124)", attr.ToString() ); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void ParamArrayAttribute() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest30 { void M1(params int[] x); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } class UsePia5 : ITest30 { public void M1(params int[] x) { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest30 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest30") .Single(); var m1 = (PEMethodSymbol)itest30.GetMembers("M1").Single(); Assert.True(m1.Parameters[0].IsParams); Assert.Equal(0, m1.Parameters[0].GetAttributes().Length); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void DateTimeConstantAttribute() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest30 { void M1([Optional()][DateTimeConstantAttribute(987654321)] DateTime x); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } class UsePia5 : ITest30 { public void M1(System.DateTime x) { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest30 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest30") .Single(); var m1 = (PEMethodSymbol)itest30.GetMembers("M1").Single(); Assert.Equal(new System.DateTime(987654321), m1.Parameters[0].ExplicitDefaultValue); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void DecimalConstantAttribute() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest30 { void M1([Optional()][DecimalConstantAttribute(0,0,int.MinValue,-2, -3)] decimal x); void M2([Optional()][DecimalConstantAttribute(0,0,uint.MaxValue,2, 3)] decimal x); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } class UsePia5 : ITest30 { public void M1(decimal x) { } public void M2(decimal x) { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest30 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest30") .Single(); var m1 = (PEMethodSymbol)itest30.GetMembers("M1").Single(); Assert.Equal(39614081275578912866186559485m, m1.Parameters[0].ExplicitDefaultValue); var m2 = (PEMethodSymbol)itest30.GetMembers("M2").Single(); Assert.Equal(79228162495817593528424333315m, m2.Parameters[0].ExplicitDefaultValue); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void DefaultParameterValueAttribute() { var iLSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly pia { .custom instance void [mscorlib]System.Runtime.InteropServices.ImportedFromTypeLibAttribute::.ctor(string) = ( 01 00 0E 47 65 6E 65 72 61 6C 50 49 41 2E 64 6C // ...GeneralPIA.dl 6C 00 00 ) // l.. .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 66 39 63 32 64 35 31 64 2D 34 66 34 34 // ..$f9c2d51d-4f44 2D 34 35 66 30 2D 39 65 64 61 2D 63 39 64 35 39 // -45f0-9eda-c9d59 39 62 35 38 32 35 37 00 00 ) // 9b58257.. } .module pia.dll // MVID: {FDF1B1F7-A867-40B9-83CD-3F75B2D2B3C2} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY .class interface public abstract auto ansi import ITest30 { .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 66 39 63 32 64 35 31 64 2D 34 66 34 34 // ..$f9c2d51d-4f44 2D 34 35 66 30 2D 39 65 64 61 2D 63 39 64 35 39 // -45f0-9eda-c9d59 39 62 35 38 32 37 39 00 00 ) // 9b58279.. .method public newslot abstract strict virtual instance void M1([opt] valuetype [mscorlib]System.Decimal x) cil managed { .param [1] .custom instance void [System]System.Runtime.InteropServices.DefaultParameterValueAttribute::.ctor(object) = ( 01 00 0D 10 58 39 B4 C8 D6 5E 40 00 00 ) // ....X9...^@.. } // end of method ITest30::M1 } // end of class ITest30 "; MetadataReference piaReference = CompileIL( iLSource, prependDefaultHeader: false, embedInteropTypes: true ); string consumer = @" class UsePia { public static void Main() { } } class UsePia5 : ITest30 { public void M1(decimal x) { } } "; var compilation1 = CreateCompilationWithMscorlib40( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaReference, SystemRef } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(2, module.GetReferencedAssemblySymbols().Length); var itest30 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest30") .Single(); var m1 = (PEMethodSymbol)itest30.GetMembers("M1").Single(); var attr = m1.Parameters[0] .GetAttributes( "System.Runtime.InteropServices", "DefaultParameterValueAttribute" ) .Single(); Assert.Equal( "System.Runtime.InteropServices.DefaultParameterValueAttribute(123.356)", attr.ToString() ); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); } [Fact] public void UnmanagedFunctionPointerAttribute() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [UnmanagedFunctionPointerAttribute(CallingConvention.StdCall, SetLastError=true)] public delegate void MyDelegate(); "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } class UsePia5 { public void M1(MyDelegate x) { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var myDelegate = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("MyDelegate") .Single(); var attr = myDelegate .GetAttributes( "System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute" ) .Single(); Assert.Equal( "System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute(System.Runtime.InteropServices.CallingConvention.StdCall, SetLastError = true)", attr.ToString() ); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void PreserveSigAttribute() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest30 { [PreserveSigAttribute()] void M1(); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } class UsePia5 { public void M1(ITest30 x) { x.M1(); } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest30 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest30") .Single(); var m1 = (PEMethodSymbol)itest30.GetMembers("M1").Single(); Assert.Equal( MethodImplAttributes.IL | MethodImplAttributes.PreserveSig, (MethodImplAttributes)m1.ImplementationAttributes ); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void PiaWithoutGuid() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] //[assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest30 { void M1(); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); DiagnosticDescription[] expected = { // error CS1747: Cannot embed interop types from assembly 'Pia, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttribute) .WithArguments( "Pia, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Runtime.InteropServices.GuidAttribute" ) }; VerifyEmitDiagnostics(compilation1, false, expected); VerifyEmitDiagnostics(compilation2, false, expected); } [Fact] public void NotAPia() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; //[assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest30 { void M1(); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); DiagnosticDescription[] expected = { // error CS1759: Cannot embed interop types from assembly 'Pia, Version=0.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( "Pia, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Runtime.InteropServices.ImportedFromTypeLibAttribute", "System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute" ) }; VerifyEmitDiagnostics(compilation1, false, expected); VerifyEmitDiagnostics(compilation2, false, expected); } [Fact] public void TypeNameConflict1() { string pia1 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest32 { } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest321 : ITest32 { } "; var piaCompilation1 = CreateCompilation( pia1, options: TestOptions.ReleaseDll, assemblyName: "Pia1" ); CompileAndVerify(piaCompilation1); string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA2.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58256"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58281"")] public interface ITest32 { } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58282"")] public interface ITest322 : ITest32 { } "; var piaCompilation2 = CreateCompilation( pia2, options: TestOptions.ReleaseDll, assemblyName: "Pia2" ); CompileAndVerify(piaCompilation2); string consumer = @" class UsePia { public static void Main() { } public void M1(ITest321 x, ITest322 y) { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation1, embedInteropTypes: true), new CSharpCompilationReference(piaCompilation2, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation1.EmitToImageReference(embedInteropTypes: true), piaCompilation2.EmitToImageReference(embedInteropTypes: true) } ); DiagnosticDescription[] expected = { // error CS1758: Cannot embed interop type 'ITest32' found in both assembly 'Pia1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider setting the 'Embed Interop Types' property to false. Diagnostic(ErrorCode.ERR_InteropTypesWithSameNameAndGuid) .WithArguments( "ITest32", "Pia1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" ) }; VerifyEmitDiagnostics(compilation1, false, expected); VerifyEmitDiagnostics(compilation2, false, expected); } [Fact] public void TypeNameConflict2() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(ITest34 x); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest34 { void M2(); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia1" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia5 { public static void Main() { } public void M1(ITest33 y) { y.M1(null); } } class ITest34 { } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); DiagnosticDescription[] expected = { // error CS1761: Embedding the interop type 'ITest34' from assembly 'Pia1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' causes a name clash in the current assembly. Consider setting the 'Embed Interop Types' property to false. Diagnostic(ErrorCode.ERR_LocalTypeNameClash) .WithArguments( "ITest34", "Pia1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" ) }; VerifyEmitDiagnostics(compilation1, true, expected); VerifyEmitDiagnostics(compilation2, true, expected); } [Fact] public void NoIndirectReference() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest30 { [System.Security.SecurityCriticalAttribute()] void M1(); } "; string consumer1 = @" public class UsePia6 { public static void Main() { } public void M1(ITest30 x) { } } "; string consumer2 = @" class UsePia { public static void Main() { } public void M1(ITest30 x) { } } "; DiagnosticDescription[] expected = { }; System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); }; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); var piaMetadata = AssemblyMetadata.CreateFromImage(piaCompilation.EmitToArray()); var compilation1 = CreateCompilation( consumer1, options: TestOptions.ReleaseDll, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: false) }, assemblyName: "Consumer1" ); CompileAndVerify(compilation1); var metadata1 = AssemblyMetadata.CreateFromImage(compilation1.EmitToArray()); var compilation2 = CreateCompilation( consumer2, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true), new CSharpCompilationReference(compilation1, embedInteropTypes: false) } ); CompileAndVerify(compilation2, symbolValidator: metadataValidator) .VerifyDiagnostics(expected); var compilation3 = CreateCompilation( consumer2, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true), metadata1.GetReference(embedInteropTypes: false) } ); CompileAndVerify(compilation3, symbolValidator: metadataValidator) .VerifyDiagnostics(expected); var compilation4 = CreateCompilation( consumer2, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaMetadata.GetReference(embedInteropTypes: true), new CSharpCompilationReference(compilation1, embedInteropTypes: false) } ); CompileAndVerify(compilation4, symbolValidator: metadataValidator) .VerifyDiagnostics(expected); var compilation5 = CreateCompilation( consumer2, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaMetadata.GetReference(embedInteropTypes: true), metadata1.GetReference(embedInteropTypes: false) } ); CompileAndVerify(compilation5, symbolValidator: metadataValidator) .VerifyDiagnostics(expected); } [Fact] public void IndirectReference() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest30 { [System.Security.SecurityCriticalAttribute()] void M1(); } "; string consumer1 = @" public class UsePia6 { public static void Main() { } public void M1(ITest30 x) { } } "; string consumer2 = @" class UsePia { public static void Main() { UsePia6.Main(); } public void M1(ITest30 x) { } } "; DiagnosticDescription[] expected = { // warning CS1762: A reference was created to embedded interop assembly 'Pia, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because of an indirect reference to that assembly created by assembly 'Consumer1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider changing the 'Embed Interop Types' property on either assembly. Diagnostic(ErrorCode.WRN_ReferencedAssemblyReferencesLinkedPIA) .WithArguments( "Pia, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Consumer1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" ) }; System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(2, module.GetReferencedAssemblySymbols().Length); Assert.Equal("Consumer1", module.GetReferencedAssemblySymbols()[1].Name); }; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); var piaMetadata = AssemblyMetadata.CreateFromImage(piaCompilation.EmitToArray()); var compilation1 = CreateCompilation( consumer1, options: TestOptions.ReleaseDll, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: false) }, assemblyName: "Consumer1" ); CompileAndVerify(compilation1); var metadata1 = AssemblyMetadata.CreateFromImage(compilation1.EmitToArray()); var compilation2 = CreateCompilation( consumer2, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true), new CSharpCompilationReference(compilation1, embedInteropTypes: false) } ); CompileAndVerify(compilation2, symbolValidator: metadataValidator) .VerifyDiagnostics(expected); var compilation3 = CreateCompilation( consumer2, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true), metadata1.GetReference(embedInteropTypes: false) } ); CompileAndVerify(compilation3, symbolValidator: metadataValidator) .VerifyDiagnostics(expected); var compilation4 = CreateCompilation( consumer2, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaMetadata.GetReference(embedInteropTypes: true), new CSharpCompilationReference(compilation1, embedInteropTypes: false) } ); CompileAndVerify(compilation4, symbolValidator: metadataValidator) .VerifyDiagnostics(expected); var compilation5 = CreateCompilation( consumer2, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaMetadata.GetReference(embedInteropTypes: true), metadata1.GetReference(embedInteropTypes: false) } ); CompileAndVerify(compilation5, symbolValidator: metadataValidator) .VerifyDiagnostics(expected); } [Fact] public void ImplementedInterfacesAndTheirMembers_1() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest34 : ITest33 { void M2(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58281"")] public interface ITest35 : ITest34 { void M3(); }"; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } interface IUsePia6 : ITest35 { } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest33 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest33") .Single(); var m1 = (PEMethodSymbol)itest33.GetMembers("M1").Single(); var itest34 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest34") .Single(); var m2 = (PEMethodSymbol)itest34.GetMembers("M2").Single(); var itest35 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest35") .Single(); var m3 = (PEMethodSymbol)itest35.GetMembers("M3").Single(); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void ImplementedInterfacesAndTheirMembers_2() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest34 : ITest33 { void M2(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58281"")] public interface ITest35 : ITest34 { void M3(); }"; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } class UsePia6 { public virtual void M1(){} public virtual void M2(){} public virtual void M3(){} } class UsePia7 : UsePia6, ITest35 { } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest33 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest33") .Single(); var m1 = (PEMethodSymbol)itest33.GetMembers("M1").Single(); var itest34 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest34") .Single(); var m2 = (PEMethodSymbol)itest34.GetMembers("M2").Single(); var itest35 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest35") .Single(); var m3 = (PEMethodSymbol)itest35.GetMembers("M3").Single(); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void ImplementedInterfacesAndTheirMembers_3() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest34 : ITest33 { void M2(); } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58281"")] public interface ITest35 : ITest34 { void M3(); }"; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void M1(ITest35 x) { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest33 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest33") .Single(); Assert.Equal(0, itest33.GetMembers().Length); var itest34 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest34") .Single(); Assert.Equal(0, itest34.GetMembers().Length); var itest35 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest35") .Single(); Assert.Equal(0, itest35.GetMembers().Length); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void ExplicitInterfaceImplementation() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } } class UsePia7 : ITest33 { void ITest33.M1(){} } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(1, module.GetReferencedAssemblySymbols().Length); var itest33 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest33") .Single(); var m1 = (PEMethodSymbol)itest33.GetMembers("M1").Single(); var usePia7 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("UsePia7") .Single(); var m1Impl = (PEMethodSymbol)usePia7.GetMembers("ITest33.M1").Single(); Assert.Same(m1, m1Impl.ExplicitInterfaceImplementations[0]); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void DynamicIndexing_1() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { int this[int x] { get; set; } int this[long x] { get; set; } } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void M1(ITest33 x, dynamic y) { var z = x[y]; } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true), CSharpRef } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true), CSharpRef } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(3, module.GetReferencedAssemblySymbols().Length); var itest33 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest33") .Single(); Assert.Equal(2, itest33.GetMembers("this[]").Length); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void DynamicIndexing_2() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { int this[int x] { get; set; } int this[long x] { get; set; } } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void M1(ITest33 x, dynamic y) { x[y] = 1; } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true), CSharpRef } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true), CSharpRef } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(3, module.GetReferencedAssemblySymbols().Length); var itest33 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest33") .Single(); Assert.Equal(2, itest33.GetMembers("this[]").Length); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void DynamicInvocation() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { void M1(int x); void M1(long x); } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void M1(ITest33 x, dynamic y) { x.M1(y); } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true), CSharpRef } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true), CSharpRef } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(3, module.GetReferencedAssemblySymbols().Length); var itest33 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest33") .Single(); Assert.Equal(2, itest33.GetMembers("M1").Length); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void DynamicCollectionInitializer() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(int x); void Add(long x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void M1(dynamic y) { var z = new ITest33 { y }; } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true), CSharpRef } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true), CSharpRef } ); System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); Assert.Equal(3, module.GetReferencedAssemblySymbols().Length); var itest33 = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("ITest33") .Single(); Assert.Equal(2, itest33.GetMembers("Add").Length); }; CompileAndVerify(compilation1, symbolValidator: metadataValidator); CompileAndVerify(compilation2, symbolValidator: metadataValidator); } [Fact] public void ErrorType1() { string pia1 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { } "; var piaCompilation1 = CreateCompilation( pia1, options: TestOptions.ReleaseDll, assemblyName: "Pia1" ); CompileAndVerify(piaCompilation1); string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA2.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58290"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest34 : ITest33 { } "; var piaCompilation2 = CreateCompilation( pia2, options: TestOptions.ReleaseDll, assemblyName: "Pia2", references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation1, embedInteropTypes: true) } ); CompileAndVerify(piaCompilation2); string consumer = @" class UsePia5 { public static void Main() { } public void M1(ITest34 y) { } } "; DiagnosticDescription[] expected = { // error CS1748: Cannot find the interop type that matches the embedded interop type 'ITest33'. Are you missing an assembly reference? Diagnostic(ErrorCode.ERR_NoCanonicalView).WithArguments("ITest33") }; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation1, false, expected); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation2.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation2, false, expected); } [Fact] public void ErrorType2() { string pia1 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { } "; var piaCompilation1 = CreateCompilation( pia1, options: TestOptions.ReleaseDll, assemblyName: "Pia1" ); CompileAndVerify(piaCompilation1); string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA2.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58290"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] [ComEventInterface(typeof(ITest33), typeof(int))] public interface ITest34 { } "; var piaCompilation2 = CreateCompilation( pia2, options: TestOptions.ReleaseDll, assemblyName: "Pia2", references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation1, embedInteropTypes: true) } ); CompileAndVerify(piaCompilation2); string consumer = @" class UsePia5 { public static void Main() { } public void M1(ITest34 y) { } } "; DiagnosticDescription[] expected = { // error CS1748: Cannot find the interop type that matches the embedded interop type 'ITest33'. Are you missing an assembly reference? Diagnostic(ErrorCode.ERR_NoCanonicalView).WithArguments("ITest33") }; var fullName = MetadataTypeName.FromFullName("ITest33"); bool isNoPiaLocalType; var compilation1 = CreateCompilationWithMscorlib40( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2, embedInteropTypes: true) } ); Assert.IsType<MissingMetadataTypeSymbol.TopLevel>( compilation1.SourceModule.GetReferencedAssemblySymbols()[1].Modules[ 0 ].LookupTopLevelMetadataType(ref fullName) ); Assert.Null( compilation1.SourceModule.GetReferencedAssemblySymbols()[1].GetTypeByMetadataName( fullName.FullName ) ); VerifyEmitDiagnostics(compilation1, false, expected); var compilation2 = CreateCompilationWithMscorlib40( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation2.EmitToImageReference(embedInteropTypes: true) } ); Assert.IsType<NoPiaMissingCanonicalTypeSymbol>( ( (PEModuleSymbol)compilation2.SourceModule.GetReferencedAssemblySymbols()[ 1 ].Modules[0] ).LookupTopLevelMetadataType(ref fullName, out isNoPiaLocalType) ); Assert.True(isNoPiaLocalType); Assert.IsType<MissingMetadataTypeSymbol.TopLevel>( compilation2.SourceModule.GetReferencedAssemblySymbols()[1].Modules[ 0 ].LookupTopLevelMetadataType(ref fullName) ); Assert.Null( compilation2.SourceModule.GetReferencedAssemblySymbols()[1].GetTypeByMetadataName( fullName.FullName ) ); VerifyEmitDiagnostics(compilation2, false, expected); var compilation3 = CreateCompilationWithMscorlib40( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2) } ); Assert.IsType<MissingMetadataTypeSymbol.TopLevel>( compilation3.SourceModule.GetReferencedAssemblySymbols()[1].Modules[ 0 ].LookupTopLevelMetadataType(ref fullName) ); Assert.Null( compilation3.SourceModule.GetReferencedAssemblySymbols()[1].GetTypeByMetadataName( fullName.FullName ) ); CompileAndVerify(compilation3); var compilation4 = CreateCompilationWithMscorlib40( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { MetadataReference.CreateFromStream(piaCompilation2.EmitToStream()) } ); Assert.IsType<NoPiaMissingCanonicalTypeSymbol>( ( (PEModuleSymbol)compilation4.SourceModule.GetReferencedAssemblySymbols()[ 1 ].Modules[0] ).LookupTopLevelMetadataType(ref fullName, out isNoPiaLocalType) ); Assert.True(isNoPiaLocalType); Assert.IsType<MissingMetadataTypeSymbol.TopLevel>( compilation4.SourceModule.GetReferencedAssemblySymbols()[1].Modules[ 0 ].LookupTopLevelMetadataType(ref fullName) ); Assert.Null( compilation4.SourceModule.GetReferencedAssemblySymbols()[1].GetTypeByMetadataName( fullName.FullName ) ); CompileAndVerify(compilation4); } [Fact] public void ErrorType3() { string pia1 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { } "; var piaCompilation1 = CreateCompilation( pia1, options: TestOptions.DebugDll, assemblyName: "Pia1" ); CompileAndVerify(piaCompilation1); string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA2.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58290"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] [ComEventInterface(typeof(ITest33), typeof(int))] public interface ITest34 { void M2(); } "; var piaCompilation2 = CreateCompilation( pia2, options: TestOptions.DebugDll, assemblyName: "Pia2", references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation1, embedInteropTypes: true) } ); //CompileAndVerify(piaCompilation2, emitOptions: EmitOptions.RefEmitBug); string consumer = @" class UsePia5 { public static void Main() { } public void M1() { ITest34 y = null; y.M2(); } } "; DiagnosticDescription[] expected = { // (10,17): error CS1748: Cannot find the interop type that matches the embedded interop type 'ITest33'. Are you missing an assembly reference? // ITest34 y = null; Diagnostic(ErrorCode.ERR_NoCanonicalView, "y = null").WithArguments("ITest33") }; var compilation1 = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation1, true, expected); var compilation2 = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { piaCompilation2.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation2, true, expected); var compilation3 = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2) } ); CompileAndVerify(compilation3, verify: Verification.Fails); var compilation4 = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { MetadataReference.CreateFromStream(piaCompilation2.EmitToStream()) } ); CompileAndVerify(compilation4, verify: Verification.Fails); } [Fact] public void ErrorType4() { string pia1 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { } "; var piaCompilation1 = CreateCompilation( pia1, options: TestOptions.ReleaseDll, assemblyName: "Pia1" ); CompileAndVerify(piaCompilation1); string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Collections.Generic; [assembly: ImportedFromTypeLib(""GeneralPIA2.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58290"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] [ComEventInterface(typeof(IList<List<ITest33>>), typeof(int))] public interface ITest34 { } "; var piaCompilation2 = CreateCompilation( pia2, options: TestOptions.ReleaseDll, assemblyName: "Pia2", references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation1, embedInteropTypes: true) } ); CompileAndVerify(piaCompilation2); string consumer = @" class UsePia5 { public static void Main() { } public void M1(ITest34 y) { } } "; DiagnosticDescription[] expected = { // error CS1769: Type 'System.Collections.Generic.List<ITest33>' from assembly 'Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies) .WithArguments( "System.Collections.Generic.List<ITest33>", "Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" ) }; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation1, false, expected); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation2.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation2, false, expected); } [Fact] public void ErrorType5() { string pia1 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { } "; var piaCompilation1 = CreateCompilation( pia1, options: TestOptions.DebugDll, assemblyName: "Pia1" ); CompileAndVerify(piaCompilation1); string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Collections.Generic; [assembly: ImportedFromTypeLib(""GeneralPIA2.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58290"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] [ComEventInterface(typeof(IList<List<ITest33>>), typeof(int))] public interface ITest34 { void M2(); } "; var piaCompilation2 = CreateCompilation( pia2, options: TestOptions.DebugDll, assemblyName: "Pia2", references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation1, embedInteropTypes: true) } ); string consumer = @" class UsePia5 { public static void Main() { } public void M1() { ITest34 y = null; y.M2(); } } "; DiagnosticDescription[] expected = { // (10,17): error CS1769: Type 'System.Collections.Generic.List<ITest33>' from assembly 'Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // ITest34 y = null; Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "y = null") .WithArguments( "System.Collections.Generic.List<ITest33>", "Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" ) }; var compilation1 = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation1, true, expected); var compilation2 = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { piaCompilation2.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation2, true, expected); } [Fact] public void ErrorType6() { string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA2.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58290"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest34 : ITest33 { } "; var piaCompilation2 = CreateCompilation( pia2, options: TestOptions.ReleaseDll, assemblyName: "Pia2" ); //CompileAndVerify(piaCompilation2, emitOptions: EmitOptions.RefEmitBug); string consumer = @" class UsePia5 { public static void Main() { } public void M1(ITest34 y) { } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2, embedInteropTypes: true) } ); compilation1.VerifyEmitDiagnostics( // error CS0246: The type or namespace name 'ITest33' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound) .WithArguments("ITest33") .WithLocation(1, 1), // error CS0246: The type or namespace name 'ITest33' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound) .WithArguments("ITest33") .WithLocation(1, 1), // error CS0246: The type or namespace name 'ITest33' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound) .WithArguments("ITest33") .WithLocation(1, 1) ); } [Fact] public void ErrorType7() { string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA2.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58290"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest34 { void M2(ITest33 x); } "; var piaCompilation2 = CreateCompilation( pia2, options: TestOptions.ReleaseDll, assemblyName: "Pia2" ); //CompileAndVerify(piaCompilation2, emitOptions: EmitOptions.RefEmitBug); string consumer = @" class UsePia5 { public static void Main() { } public void M1(ITest34 y) { y.M2(null); } } "; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2, embedInteropTypes: true) } ); DiagnosticDescription[] expected = { // (10,9): error CS0246: The type or namespace name 'ITest33' could not be found (are you missing a using directive or an assembly reference?) // y.M2(null); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y.M2") .WithArguments("ITest33") .WithLocation(10, 9) }; VerifyEmitDiagnostics(compilation1, true, expected); } [Fact] public void ErrorType8() { string pia1 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { } "; var piaCompilation1 = CreateCompilation( pia1, options: TestOptions.ReleaseDll, assemblyName: "Pia1" ); CompileAndVerify(piaCompilation1); string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Collections.Generic; [assembly: ImportedFromTypeLib(""GeneralPIA2.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58290"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] [ComEventInterface(typeof(List<ITest33>), typeof(int))] public interface ITest34 { } "; var piaCompilation2 = CreateCompilation( pia2, options: TestOptions.ReleaseDll, assemblyName: "Pia2", references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation1, embedInteropTypes: true) } ); CompileAndVerify(piaCompilation2); string consumer = @" class UsePia5 { public static void Main() { } public void M1(ITest34 y) { } } "; DiagnosticDescription[] expected = { // error CS1769: Type 'System.Collections.Generic.List<ITest33>' from assembly 'Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies) .WithArguments( "System.Collections.Generic.List<ITest33>", "Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" ) }; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation1, false, expected); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation2.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation2, false, expected); var compilation3 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2) } ); CompileAndVerify(compilation3); var compilation4 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { MetadataReference.CreateFromStream(piaCompilation2.EmitToStream()) } ); CompileAndVerify(compilation4); } [Fact] public void ErrorType_Tuple() { string pia1 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { } "; var piaCompilation1 = CreateCompilationWithMscorlib40( pia1, options: TestOptions.ReleaseDll, assemblyName: "Pia1" ); CompileAndVerify(piaCompilation1); string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Collections.Generic; [assembly: ImportedFromTypeLib(""GeneralPIA2.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58290"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest34 { List<(ITest33, ITest33)> M(); } "; var piaCompilation2 = CreateCompilationWithMscorlib40( pia2, options: TestOptions.ReleaseDll, assemblyName: "Pia2", references: new MetadataReference[] { piaCompilation1.EmitToImageReference(embedInteropTypes: true), SystemRuntimeFacadeRef, ValueTupleRef } ); CompileAndVerify(piaCompilation2); string consumer = @" using System; using System.Collections.Generic; public class UsePia5 : ITest34 { public List<(ITest33, ITest33)> M() { throw new System.Exception(); } } "; DiagnosticDescription[] expected = { // (5,24): error CS1769: Type 'List<ValueTuple<ITest33, ITest33>>' from assembly 'Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // public class UsePia5 : ITest34 Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "ITest34") .WithArguments( "System.Collections.Generic.List<ValueTuple<ITest33, ITest33>>", "Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" ) .WithLocation(5, 24) }; var compilation1 = CreateCompilationWithMscorlib40( consumer, options: TestOptions.ReleaseDll, references: new MetadataReference[] { piaCompilation2.ToMetadataReference(embedInteropTypes: true), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef } ); VerifyEmitDiagnostics( compilation1, metadataOnlyShouldSucceed: false, expectedFullBuildDiagnostics: expected ); var compilation2 = CreateCompilationWithMscorlib40( consumer, options: TestOptions.ReleaseDll, references: new MetadataReference[] { piaCompilation2.EmitToImageReference(embedInteropTypes: true), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef } ); VerifyEmitDiagnostics( compilation2, metadataOnlyShouldSucceed: false, expectedFullBuildDiagnostics: expected ); var compilation3 = CreateCompilationWithMscorlib40( consumer, options: TestOptions.ReleaseDll, references: new MetadataReference[] { piaCompilation2.ToMetadataReference(), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef } ); VerifyEmitDiagnostics( compilation3, metadataOnlyShouldSucceed: false, expectedFullBuildDiagnostics: expected ); var compilation4 = CreateCompilationWithMscorlib40( consumer, options: TestOptions.ReleaseDll, references: new MetadataReference[] { piaCompilation2.EmitToImageReference(), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef } ); VerifyEmitDiagnostics( compilation4, metadataOnlyShouldSucceed: false, expectedFullBuildDiagnostics: expected ); } [Fact] public void ErrorType9() { string pia1 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA1.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] public interface ITest33 { } "; var piaCompilation1 = CreateCompilation( pia1, options: TestOptions.DebugDll, assemblyName: "Pia1" ); CompileAndVerify(piaCompilation1); string pia2 = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Collections.Generic; [assembly: ImportedFromTypeLib(""GeneralPIA2.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58290"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] [ComEventInterface(typeof(List<ITest33>), typeof(int))] public interface ITest34 { void M2(); } "; var piaCompilation2 = CreateCompilation( pia2, options: TestOptions.DebugDll, assemblyName: "Pia2", references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation1, embedInteropTypes: true) } ); //CompileAndVerify(piaCompilation2, emitOptions: EmitOptions.RefEmitBug); string consumer = @" class UsePia5 { public static void Main() { } public void M1() { ITest34 y = null; y.M2(); } } "; DiagnosticDescription[] expected = { // (10,17): error CS1769: Type 'System.Collections.Generic.List<ITest33>' from assembly 'Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type. // ITest34 y = null; Diagnostic(ErrorCode.ERR_GenericsUsedAcrossAssemblies, "y = null") .WithArguments( "System.Collections.Generic.List<ITest33>", "Pia2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" ) }; var compilation1 = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2, embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation1, true, expected); var compilation2 = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { piaCompilation2.EmitToImageReference(embedInteropTypes: true) } ); VerifyEmitDiagnostics(compilation2, true, expected); var compilation3 = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation2) } ); CompileAndVerify(compilation3, verify: Verification.Fails); var compilation4 = CreateCompilation( consumer, options: TestOptions.DebugExe, references: new MetadataReference[] { MetadataReference.CreateFromStream(piaCompilation2.EmitToStream()) } ); CompileAndVerify(compilation4, verify: Verification.Fails); } [ConditionalFact(typeof(ClrOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] [WorkItem(611578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611578")] public void Bug611578() { string IEvent_cs = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTest"")] [assembly: Guid(""ECED788D-2448-447A-B786-1646D2DBEEEE"")] public delegate void EventDelegate01(ref bool p); public delegate string EventDelegate02(string p); /// <summary> /// Source Interface /// </summary> [ComImport, Guid(""904458F3-005B-4DFD-8581-E9832DDFA433"")] public interface IEventsBase { [DispId(101), PreserveSig] void MyEvent01(ref bool p); } [ComImport, Guid(""904458F3-005B-4DFD-8581-E9832D7DA433"")] public interface IEventsDerived : IEventsBase { [DispId(102), PreserveSig] string MyEvent02(string p); } /// <summary> /// Event Interface /// </summary> [ComEventInterface(typeof(IEventsDerived), typeof(int))] [ComVisible(false)] public interface IEventsDerived_Event { event EventDelegate01 MyEvent01; event EventDelegate02 MyEvent02; } "; var IEvent_Compilation = CreateCompilation( IEvent_cs, options: TestOptions.ReleaseDll, assemblyName: "IEvent" ); CompileAndVerify(IEvent_Compilation); var IEvent_Metadata = AssemblyMetadata.CreateFromImage( IEvent_Compilation.EmitToArray() ); string NetImpl_cs = @" using System; using System.Collections; using System.Collections.Generic; public class NetImpl : IEventsDerived_Event { // Unique keys for events static readonly object[] myEventKeyList = new object[] { new object(), new object() }; Hashtable eventTable = new Hashtable(); #region Shared Func // return event handle associated with the key protected Delegate GetEventHandlerDelegate(int index) { object key = myEventKeyList[index]; return eventTable[key] as Delegate; } // add event handle associated with the key protected void AddEventHandlerDelegate(int index, Delegate handler) { lock (eventTable) { object key = myEventKeyList[index]; switch (index) { case 0: eventTable[key] = (EventDelegate01)eventTable[key] + (EventDelegate01)handler; break; case 1: eventTable[key] = (EventDelegate02)eventTable[key] + (EventDelegate02)handler; break; } } } // remove event handle associated with the key protected void RemoveEventHandlerDelegate(int index, Delegate handler) { lock (eventTable) { object key = myEventKeyList[index]; switch (index) { case 0: eventTable[key] = (EventDelegate01)eventTable[key] - (EventDelegate01)handler; break; case 1: eventTable[key] = (EventDelegate02)eventTable[key] - (EventDelegate02)handler; break; } } } #endregion #region Impl Event event EventDelegate01 IEventsDerived_Event.MyEvent01 { add { AddEventHandlerDelegate(0, value); } remove { RemoveEventHandlerDelegate(0, value); } } event EventDelegate02 IEventsDerived_Event.MyEvent02 { add { AddEventHandlerDelegate(1, value); } remove { RemoveEventHandlerDelegate(1, value); } } #endregion #region Fire Event public void Fire01(ref bool arg, int idx = 0) { EventDelegate01 e = GetEventHandlerDelegate(idx) as EventDelegate01; if (null != e) e(ref arg); } public string Fire02(string arg, int idx = 1) { EventDelegate02 e = GetEventHandlerDelegate(idx) as EventDelegate02; if (null != e) return e(arg); return String.Empty; } #endregion } "; System.Action<ModuleSymbol> metadataValidator = delegate(ModuleSymbol module) { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); var IEventsBase = (PENamedTypeSymbol)module.GlobalNamespace .GetTypeMembers("IEventsBase") .Single(); Assert.Equal(1, IEventsBase.GetMembers("MyEvent01").Length); }; var NetImpl_1_Compilation = CreateCompilation( NetImpl_cs, new[] { new CSharpCompilationReference(IEvent_Compilation, embedInteropTypes: true) }, options: TestOptions.ReleaseDll, assemblyName: "NetImpl" ); CompileAndVerify(NetImpl_1_Compilation, symbolValidator: metadataValidator); var NetImpl_1_Image = NetImpl_1_Compilation.EmitToStream(); var NetImpl_2_Compilation = CreateCompilation( NetImpl_cs, new[] { IEvent_Metadata.GetReference(embedInteropTypes: true) }, options: TestOptions.ReleaseDll, assemblyName: "NetImpl" ); CompileAndVerify(NetImpl_2_Compilation, symbolValidator: metadataValidator); var NetImpl_2_Image = NetImpl_2_Compilation.EmitToStream(); string App_cs = @" using System; class Test { public static void Main() { var obj = new NetImpl(); var d1 = false; dynamic d2 = ""123""; // cast to interface IEventsDerived_Event iobj = obj; // Event 1 iobj.MyEvent01 += new EventDelegate01(MyEvent01Handler); obj.Fire01(ref d1); // Event 2 iobj.MyEvent02 += new EventDelegate02(MyEvent02Handler); obj.Fire02(d2); } #region Event Handlers static void MyEvent01Handler(ref bool arg) { Console.WriteLine(""E01""); arg = true; } static string MyEvent02Handler(string arg) { Console.WriteLine(""E02""); return arg; } #endregion } "; MetadataReference[] NetImpl_refs = new MetadataReference[] { new CSharpCompilationReference(NetImpl_1_Compilation), new CSharpCompilationReference(NetImpl_2_Compilation), MetadataReference.CreateFromStream(NetImpl_1_Image), MetadataReference.CreateFromStream(NetImpl_2_Image) }; MetadataReference[] IEvent_refs = new MetadataReference[] { new CSharpCompilationReference(IEvent_Compilation), new CSharpCompilationReference(IEvent_Compilation, embedInteropTypes: true), IEvent_Metadata.GetReference(), IEvent_Metadata.GetReference(embedInteropTypes: true) }; foreach (var NetImpl_ref in NetImpl_refs) { foreach (var IEvent_ref in IEvent_refs) { var app_compilation = CreateCompilation( App_cs, new[] { NetImpl_ref, IEvent_ref, CSharpRef }, options: TestOptions.ReleaseExe, assemblyName: "App" ); CompileAndVerify( app_compilation, symbolValidator: IEvent_ref.Properties.EmbedInteropTypes ? metadataValidator : null, expectedOutput: @"E01 E02" ); } } } [Fact, WorkItem(651240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651240")] public void Bug651240() { string pia = @" using System;using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTest"")] [assembly: Guid(""A55E0B17-2558-447D-B786-84682CBEF136"")] [assembly: BestFitMapping(false)] public interface IMyInterface { void Method(int n); } public delegate void DelegateWithInterface(IMyInterface value); "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" namespace NoPiaTestApp { class Test { public event DelegateWithInterface e3; static void Main() { } } }"; var compilation1 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); var compilation2 = CreateCompilation( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) } ); DiagnosticDescription[] expected = { // (6,44): error CS1756: Interop type 'IMyInterface' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.ComImportAttribute' attribute. // public event DelegateWithInterface e3; Diagnostic(ErrorCode.ERR_InteropTypeMissingAttribute, "e3") .WithArguments( "IMyInterface", "System.Runtime.InteropServices.ComImportAttribute" ), // (6,44): warning CS0067: The event 'NoPiaTestApp.Test.e3' is never used // public event DelegateWithInterface e3; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "e3") .WithArguments("NoPiaTestApp.Test.e3") }; DiagnosticDescription[] expectedMEtadataOnly = { // error CS1756: Interop type 'IMyInterface' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.ComImportAttribute' attribute. Diagnostic(ErrorCode.ERR_InteropTypeMissingAttribute) .WithArguments( "IMyInterface", "System.Runtime.InteropServices.ComImportAttribute" ) }; VerifyEmitDiagnostics(compilation1, false, expected, expectedMEtadataOnly); VerifyEmitDiagnostics(compilation2, false, expected, expectedMEtadataOnly); } [Fact, WorkItem(651408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651408")] public void Bug651408() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTest"")] [assembly: Guid(""ECED788D-2448-447A-B786-64682CBECC40"")] namespace EventNS { /// <summary> /// Source Interface /// </summary> [ComImport, Guid(""904458F3-005B-4DFD-8581-E9832D7FA440"")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch), TypeLibType(TypeLibTypeFlags.FDual)] public interface IEvents { [DispId(101), PreserveSig] void OnEvent01(); } /// <summary> /// Event Interface /// </summary> [ComEventInterface(typeof(IEvents), typeof(int))] [ComVisible(false), TypeLibType(TypeLibTypeFlags.FHidden)] public interface IEvents_Event { event OnEvent01EventHandler OnEvent01; event OnEvent02EventHandler OnEvent02; } /// <summary> /// delegate /// </summary> public delegate void OnEvent01EventHandler(); public delegate void OnEvent02EventHandler(object i1); } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); var piaRef1 = new CSharpCompilationReference(piaCompilation, embedInteropTypes: true); var piaRef2 = piaCompilation.EmitToImageReference(embedInteropTypes: true); string consumer0 = @" namespace NetImplNS { public class NetImpl : EventNS.IEvents_Event { public event EventNS.OnEvent01EventHandler OnEvent01; public event EventNS.OnEvent02EventHandler OnEvent02; public void Fire1() { if (OnEvent01 != null) OnEvent01(); } public void Fire2(object obj) { if (OnEvent02 != null) OnEvent02(obj); } } } "; var compilation0 = CreateCompilation( consumer0, options: TestOptions.ReleaseDll, references: new MetadataReference[] { piaRef1 } ); System.Action<ModuleSymbol> symbolValidator = m => { Assert.Equal( "void EventNS.IEvents.OnEvent01()", m.GlobalNamespace .GetMember<NamespaceSymbol>("EventNS") .GetMember<NamedTypeSymbol>("IEvents") .GetMember<MethodSymbol>("OnEvent01") .ToTestDisplayString() ); }; CompileAndVerify(compilation0, symbolValidator: symbolValidator); compilation0 = CreateCompilation( consumer0, options: TestOptions.ReleaseDll, references: new MetadataReference[] { piaRef2 } ); CompileAndVerify(compilation0, symbolValidator: symbolValidator); string consumer2 = consumer0 + @" namespace NetImplNS2 { public class NetImpl { public void Fire1(EventNS.IEvents_Event x) { x.OnEvent02 += null; } public void Fire2(EventNS.IEvents_Event y) { y.OnEvent02 += null; } } }"; var compilation1 = CreateCompilation( consumer2, options: TestOptions.ReleaseDll, references: new MetadataReference[] { piaRef1 } ); var compilation2 = CreateCompilation( consumer2, options: TestOptions.ReleaseDll, references: new MetadataReference[] { piaRef2 } ); DiagnosticDescription[] expected = { // (10,13): error CS1766: Source interface 'EventNS.IEvents' is missing method 'OnEvent02' which is required to embed event 'EventNS.IEvents_Event.OnEvent02'. // x.OnEvent02 += null; Diagnostic(ErrorCode.ERR_MissingMethodOnSourceInterface, "x.OnEvent02 += null") .WithArguments( "EventNS.IEvents", "OnEvent02", "EventNS.IEvents_Event.OnEvent02" ), }; VerifyEmitDiagnostics(compilation1, true, expected); VerifyEmitDiagnostics(compilation2, true, expected); } [Fact, WorkItem(673546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673546")] public void MissingComAwareEventInfo() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public delegate void MyDelegate(); [ComEventInterface(typeof(InterfaceEvents), typeof(int))] public interface Interface1_Event { event MyDelegate Goo; } [ComImport(), Guid(""84374891-a3b1-4f8f-8310-99ea58059b10"")] public interface InterfaceEvents { void Goo(); } "; var piaCompilation = CreateCompilationWithMscorlib40( pia, options: TestOptions.ReleaseDll, assemblyName: "Pia" ); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public static void Main() { } public void Test(Interface1_Event x) { x.Goo += Handler; } void Handler() {} } "; var compilation1 = CreateCompilationWithMscorlib40( consumer, options: TestOptions.ReleaseExe, references: new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) } ); DiagnosticDescription[] expected = { // (10,6): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.ComAwareEventInfo..ctor' // x.Goo += Handler; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x.Goo += Handler") .WithArguments("System.Runtime.InteropServices.ComAwareEventInfo", ".ctor") .WithLocation(10, 6) }; VerifyEmitDiagnostics(compilation1, true, expected); } [Fact, WorkItem(2793, "https://github.com/dotnet/roslyn/issues/2793")] public void DefaultValueWithoutOptional_01() { var il = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly pia { .custom instance void [mscorlib]System.Runtime.InteropServices.ImportedFromTypeLibAttribute::.ctor(string) = ( 01 00 0E 47 65 6E 65 72 61 6C 50 49 41 2E 64 6C // ...GeneralPIA.dl 6C 00 00 ) // l.. .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 66 39 63 32 64 35 31 64 2D 34 66 34 34 // ..$f9c2d51d-4f44 2D 34 35 66 30 2D 39 65 64 61 2D 63 39 64 35 39 // -45f0-9eda-c9d59 39 62 35 38 32 35 37 00 00 ) // 9b58257.. } .module pia.dll // MVID: {FDF1B1F7-A867-40B9-83CD-3F75B2D2B3C2} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY .class interface public abstract auto ansi import IA { .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 44 45 41 44 42 45 45 46 2D 43 41 46 45 // ..$DEADBEEF-CAFE 2D 42 41 42 45 2D 42 41 41 44 2D 44 45 41 44 43 // -BABE-BAAD-DEADC 30 44 45 30 30 30 30 00 00 ) // 0DE0000.. .method public newslot abstract strict virtual instance void M(int32 x) cil managed { .param [1] = int32(0x0000000C) } // end of method IA::M } // end of class IA "; MetadataReference piaReference = CompileIL( il, prependDefaultHeader: false, embedInteropTypes: true ); var csharp = @" class B : IA { public void M(int x) { } } "; CompileAndVerify( csharp, references: new MetadataReference[] { piaReference }, symbolValidator: module => { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); var ia = module.GlobalNamespace.GetMember<NamedTypeSymbol>("IA"); var m = (MethodSymbol)ia.GetMember("M"); var p = (PEParameterSymbol)m.Parameters[0]; Assert.False(p.IsMetadataOptional); Assert.Equal(ParameterAttributes.HasDefault, p.Flags); Assert.Equal((object)0x0000000C, p.ExplicitDefaultConstantValue.Value); Assert.False(p.HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>( delegate { var tmp = p.ExplicitDefaultValue; } ); } ) .VerifyDiagnostics(); } [Fact, WorkItem(2793, "https://github.com/dotnet/roslyn/issues/2793")] public void DefaultValueWithoutOptional_02() { var il = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly pia { .custom instance void [mscorlib]System.Runtime.InteropServices.ImportedFromTypeLibAttribute::.ctor(string) = ( 01 00 0E 47 65 6E 65 72 61 6C 50 49 41 2E 64 6C // ...GeneralPIA.dl 6C 00 00 ) // l.. .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 66 39 63 32 64 35 31 64 2D 34 66 34 34 // ..$f9c2d51d-4f44 2D 34 35 66 30 2D 39 65 64 61 2D 63 39 64 35 39 // -45f0-9eda-c9d59 39 62 35 38 32 35 37 00 00 ) // 9b58257.. } .module pia.dll // MVID: {FDF1B1F7-A867-40B9-83CD-3F75B2D2B3C2} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY .class interface public abstract auto ansi import IA { .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 44 45 41 44 42 45 45 46 2D 43 41 46 45 // ..$DEADBEEF-CAFE 2D 42 41 42 45 2D 42 41 41 44 2D 44 45 41 44 43 // -BABE-BAAD-DEADC 30 44 45 30 30 30 30 00 00 ) // 0DE0000.. .method public newslot abstract strict virtual instance void M(valuetype [mscorlib]System.DateTime x) cil managed { .param [1] .custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 B1 68 DE 3A 00 00 00 00 00 00 ) // ...h.:...... } // end of method IA::M } // end of class IA "; MetadataReference piaReference = CompileIL( il, prependDefaultHeader: false, embedInteropTypes: true ); var csharp = @" class B : IA { public void M(System.DateTime x) { } } "; CompileAndVerify( csharp, references: new MetadataReference[] { piaReference }, symbolValidator: module => { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); var ia = module.GlobalNamespace.GetMember<NamedTypeSymbol>("IA"); var m = (MethodSymbol)ia.GetMember("M"); var p = (PEParameterSymbol)m.Parameters[0]; Assert.False(p.IsMetadataOptional); Assert.Equal(ParameterAttributes.None, p.Flags); Assert.Equal( "System.Runtime.CompilerServices.DateTimeConstantAttribute(987654321)", p.GetAttributes().Single().ToString() ); Assert.Null(p.ExplicitDefaultConstantValue); Assert.False(p.HasExplicitDefaultValue); Assert.Throws<InvalidOperationException>( delegate { var tmp = p.ExplicitDefaultValue; } ); } ) .VerifyDiagnostics(); } [Fact, WorkItem(8088, "https://github.com/dotnet/roslyn/issues/8088")] public void ParametersWithoutNames() { var source = @" class Program { public void M(I1 x) { x.M1(1, 2, 3); } public void M1(int value) { } public void M2(int Param) { } } "; var compilation = CreateCompilation( source, references: new MetadataReference[] { AssemblyMetadata .CreateFromImage(TestResources.SymbolsTests.NoPia.ParametersWithoutNames) .GetReference( display: "ParametersWithoutNames.dll", embedInteropTypes: true ) }, options: TestOptions.ReleaseDll ); AssertParametersWithoutNames( compilation.GlobalNamespace .GetMember<NamedTypeSymbol>("I1") .GetMember<MethodSymbol>("M1").Parameters, false ); CompileAndVerify( compilation, symbolValidator: module => { ((PEModuleSymbol)module).Module.PretendThereArentNoPiaLocalTypes(); AssertParametersWithoutNames( module.GlobalNamespace .GetMember<NamedTypeSymbol>("I1") .GetMember<MethodSymbol>("M1").Parameters, true ); PEParameterSymbol p; p = (PEParameterSymbol)module.GlobalNamespace .GetMember<NamedTypeSymbol>("Program") .GetMember<MethodSymbol>("M").Parameters[0]; Assert.Equal( "x", ((PEModuleSymbol)module).Module.GetParamNameOrThrow(p.Handle) ); Assert.Equal("x", p.Name); Assert.Equal("x", p.MetadataName); p = (PEParameterSymbol)module.GlobalNamespace .GetMember<NamedTypeSymbol>("Program") .GetMember<MethodSymbol>("M1").Parameters[0]; Assert.Equal( "value", ((PEModuleSymbol)module).Module.GetParamNameOrThrow(p.Handle) ); Assert.Equal("value", p.Name); Assert.Equal("value", p.MetadataName); p = (PEParameterSymbol)module.GlobalNamespace .GetMember<NamedTypeSymbol>("Program") .GetMember<MethodSymbol>("M2").Parameters[0]; Assert.Equal( "Param", ((PEModuleSymbol)module).Module.GetParamNameOrThrow(p.Handle) ); Assert.Equal("Param", p.Name); Assert.Equal("Param", p.MetadataName); } ) .VerifyDiagnostics(); } private static void AssertParametersWithoutNames( ImmutableArray<ParameterSymbol> parameters, bool isEmbedded ) { Assert.True(((PEParameterSymbol)parameters[0]).Handle.IsNil); var p1 = (PEParameterSymbol)parameters[1]; Assert.True(p1.IsMetadataOptional); Assert.False(p1.Handle.IsNil); Assert.True( ((PEModuleSymbol)p1.ContainingModule).Module.MetadataReader.GetParameter( p1.Handle ).Name.IsNil ); var p2 = (PEParameterSymbol)parameters[2]; if (isEmbedded) { Assert.True(p2.Handle.IsNil); } else { Assert.True( ((PEModuleSymbol)p2.ContainingModule).Module.MetadataReader.GetParameter( p2.Handle ).Name.IsNil ); } foreach (var p in parameters) { Assert.Equal("value", p.Name); Assert.Equal("", p.MetadataName); } } } } #endif
31.338082
359
0.553555
[ "MIT" ]
belav/roslyn
src/Compilers/CSharp/Test/Emit/Emit/NoPiaEmbedTypes.cs
246,382
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; using FantomLib; //Get External Storage folder information and Storage Access Framework demo public class ExternalStorageTest : MonoBehaviour { public Text displayText; public string saveSuccessMessage = "Successfully saving text to a file."; //Register 'ToastController.Show' in the inspector. [Serializable] public class ToastHandler : UnityEvent<string> { } //message public ToastHandler OnToast; //Register 'MediaScannerController.StartScan' in the inspector. [Serializable] public class MediaScanHandler : UnityEvent<string> { } //path public MediaScanHandler OnMediaScan; // Use this for initialization private void Start () { } // Update is called once per frame //private void Update () { //} //Get the storage information //ストレージの情報を取得する public void GetInfo() { XDebug.Clear(); //XDebug.Log("Application.dataPath = " + Application.dataPath); //ゲームデータのフォルダーパスを返します(読み取り専用) XDebug.Log("Application.persistentDataPath = " + Application.persistentDataPath); //永続的なデータディレクトリのパスを返します(読み取り専用) //XDebug.Log("Application.streamingAssetsPath = " + Application.streamingAssetsPath); //StreamingAssets フォルダーへのパスが含まれています(読み取り専用) //XDebug.Log("Application.temporaryCachePath = " + Application.temporaryCachePath); //一時的なデータ、キャッシュのディレクトリパスを返します(読み取り専用)値はデータを保存できる一時的なディレクトリパスです。 #if !UNITY_EDITOR && UNITY_ANDROID XDebug.Log("----------------------------"); XDebug.Log("IsExternalStorageEmulated = " + AndroidPlugin.IsExternalStorageEmulated()); XDebug.Log("IsExternalStorageRemovable = " + AndroidPlugin.IsExternalStorageRemovable()); XDebug.Log("IsExternalStorageMounted = " + AndroidPlugin.IsExternalStorageMounted()); XDebug.Log("IsExternalStorageMountedReadOnly = " + AndroidPlugin.IsExternalStorageMountedReadOnly()); XDebug.Log("IsExternalStorageMountedReadWrite = " + AndroidPlugin.IsExternalStorageMountedReadWrite()); XDebug.Log("GetExternalStorageState = " + AndroidPlugin.GetExternalStorageState()); XDebug.Log("GetExternalStorageDirectory = " + AndroidPlugin.GetExternalStorageDirectory()); XDebug.Log("GetExternalStorageDirectoryAlarms = " + AndroidPlugin.GetExternalStorageDirectoryAlarms()); XDebug.Log("GetExternalStorageDirectoryDCIM = " + AndroidPlugin.GetExternalStorageDirectoryDCIM()); XDebug.Log("GetExternalStorageDirectoryDocuments = " + AndroidPlugin.GetExternalStorageDirectoryDocuments()); XDebug.Log("GetExternalStorageDirectoryDownloads = " + AndroidPlugin.GetExternalStorageDirectoryDownloads()); XDebug.Log("GetExternalStorageDirectoryMovies = " + AndroidPlugin.GetExternalStorageDirectoryMovies()); XDebug.Log("GetExternalStorageDirectoryMusic = " + AndroidPlugin.GetExternalStorageDirectoryMusic()); XDebug.Log("GetExternalStorageDirectoryNotifications = " + AndroidPlugin.GetExternalStorageDirectoryNotifications()); XDebug.Log("GetExternalStorageDirectoryPictures = " + AndroidPlugin.GetExternalStorageDirectoryPictures()); XDebug.Log("GetExternalStorageDirectoryPodcasts = " + AndroidPlugin.GetExternalStorageDirectoryPodcasts()); XDebug.Log("GetExternalStorageDirectoryRingtones = " + AndroidPlugin.GetExternalStorageDirectoryRingtones()); #endif } //Callback handler when MediaScanner complete //MediaScanner 完了コールバック public void ReceiveMediaScanner(string path) { XDebug.Log("ReceiveMediaScanner complete : " + path); } //Save the text of the displayed information in a file. //(*)To write to External Storage on Android, you need permission in the 'AndroidManifest.xml' file. // //表示されている情報のテキストをファイルに保存する。 //※Android で External Storage に書き込みをするには、「AndroidManifest.xml」にパーミッションが必要。 //Required : <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> public void SaveInfoText() { #if UNITY_EDITOR Debug.Log("SaveInfoText called"); #elif UNITY_ANDROID if (AndroidPlugin.IsExternalStorageMountedReadWrite()) { if (displayText != null && !string.IsNullOrEmpty(displayText.text)) { string path = AndroidPlugin.GetExternalStorageDirectoryDocuments(); //API 19 or later if (string.IsNullOrEmpty(path)) path = AndroidPlugin.GetExternalStorageDirectory(); string file = path + "/info_" + DateTime.Now.ToString("yyMMdd_HHmmss") + ".txt"; if (SaveText(displayText.text, file)) { XDebug.Log("Save to : " + file); if (OnToast != null) OnToast.Invoke(saveSuccessMessage); if (OnMediaScan != null) OnMediaScan.Invoke(file); } } } #endif } //Required : '<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />' in 'AndroidManifest.xml'. //Save to a text file //(*) The file may not be visible until MediaScanner runs. // //テキストファイルに保存 //※MediaScanner が走るまではファイルが見えないことがある private static bool SaveText(string text, string path) { try { using (StreamWriter writer = new StreamWriter(path)) { writer.Write(text); writer.Flush(); writer.Close(); } } catch (Exception e) { XDebug.Log(e.Message); //Access to the path "filename" is denied. -> required : '<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />' in 'AndroidManifest.xml'. return false; } return true; } }
42.274648
197
0.675329
[ "MIT" ]
Devin0xFFFFFF/comp4020project
VolunteeringProject/Assets/FantomPlugin/Demo/Scripts/ExternalStorageTest.cs
6,499
C#
// ---------------------------------------------------------------------------- // The MIT License // Simple Entity Component System framework https://github.com/Leopotam/ecs // Copyright (c) 2017-2019 Leopotam <leopotam@gmail.com> // ---------------------------------------------------------------------------- using System; using System.Runtime.CompilerServices; namespace Leopotam.Ecs { /// <summary> /// Entity descriptor. /// </summary> public struct EcsEntity { internal int Id; internal ushort Gen; internal EcsWorld Owner; public static readonly EcsEntity Null = new EcsEntity (); /// <summary> /// Attaches or finds already attached component to entity. /// </summary> /// <typeparam name="T">Type of component.</typeparam> #if ENABLE_IL2CPP [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.NullChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)] #endif [MethodImpl (MethodImplOptions.AggressiveInlining)] public T Set<T> () where T : class { ref var entityData = ref Owner.GetEntityData (this); #if DEBUG if (entityData.Gen != Gen) { throw new Exception ("Cant add component to destroyed entity."); } #endif var typeIdx = EcsComponentPool<T>.Instance.TypeIndex; int idx; // check already attached components. for (int i = 0, iiMax = entityData.ComponentsCountX2; i < iiMax; i += 2) { if (entityData.Components[i] == typeIdx) { return EcsComponentPool<T>.Instance.Items[entityData.Components[i + 1]]; } } // attach new component. if (entityData.Components.Length == entityData.ComponentsCountX2) { Array.Resize (ref entityData.Components, entityData.ComponentsCountX2 << 1); } entityData.Components[entityData.ComponentsCountX2++] = typeIdx; idx = EcsComponentPool<T>.Instance.New (); entityData.Components[entityData.ComponentsCountX2++] = idx; #if DEBUG var component = EcsComponentPool<T>.Instance.Items[idx]; for (var ii = 0; ii < Owner._debugListeners.Count; ii++) { Owner._debugListeners[ii].OnComponentAdded (this, component); } #endif // create separate filter for one-frame components. if (EcsComponentPool<T>.Instance.IsOneFrame) { Owner.ValidateOneFrameFilter<T> (); } Owner.UpdateFilters (typeIdx, this, entityData); return EcsComponentPool<T>.Instance.Items[idx]; } /// <summary> /// Gets component attached to entity or null. /// </summary> /// <typeparam name="T">Type of component.</typeparam> #if ENABLE_IL2CPP [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.NullChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)] #endif [MethodImpl (MethodImplOptions.AggressiveInlining)] public T Get<T> () where T : class { ref var entityData = ref Owner.GetEntityData (this); #if DEBUG if (entityData.Gen != Gen) { throw new Exception ("Cant check component on destroyed entity."); } #endif var typeIdx = EcsComponentPool<T>.Instance.TypeIndex; for (int i = 0, iMax = entityData.ComponentsCountX2; i < iMax; i += 2) { if (entityData.Components[i] == typeIdx) { return EcsComponentPool<T>.Instance.Items[entityData.Components[i + 1]]; } } return null; } /// <summary> /// Removes component from entity. /// </summary> /// <typeparam name="T">Type of component.</typeparam> #if ENABLE_IL2CPP [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.NullChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)] #endif [MethodImpl (MethodImplOptions.AggressiveInlining)] public void Unset<T> () where T : class { Unset (EcsComponentPool<T>.Instance.TypeIndex); } /// <summary> /// Removes component from entity. /// </summary> #if ENABLE_IL2CPP [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.NullChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)] #endif [MethodImpl (MethodImplOptions.AggressiveInlining)] internal void Unset (int typeIndex) { ref var entityData = ref Owner.GetEntityData (this); #if DEBUG if (entityData.Gen != Gen) { throw new Exception ("Cant touch destroyed entity."); } #endif for (int i = 0, iMax = entityData.ComponentsCountX2; i < iMax; i += 2) { if (entityData.Components[i] == typeIndex) { Owner.UpdateFilters (-typeIndex, this, entityData); #if DEBUG var removedComponent = EcsComponentPools.Items[typeIndex].GetItem (entityData.Components[i + 1]); #endif EcsComponentPools.Items[typeIndex].Recycle (entityData.Components[i + 1]); // remove current item and move last component to this gap. entityData.ComponentsCountX2 -= 2; if (i < entityData.ComponentsCountX2) { entityData.Components[i] = entityData.Components[entityData.ComponentsCountX2]; entityData.Components[i + 1] = entityData.Components[entityData.ComponentsCountX2 + 1]; } #if DEBUG for (var ii = 0; ii < Owner._debugListeners.Count; ii++) { Owner._debugListeners[ii].OnComponentRemoved (this, removedComponent); } #endif break; } } // unrolled and inlined Destroy() call. if (entityData.ComponentsCountX2 == 0) { Owner.RecycleEntityData (Id, ref entityData); #if DEBUG for (var ii = 0; ii < Owner._debugListeners.Count; ii++) { Owner._debugListeners[ii].OnEntityDestroyed (this); } #endif } } /// <summary> /// Gets component index at component pool. /// If component doesnt exists "-1" will be returned. /// </summary> /// <typeparam name="T">Type of component.</typeparam> #if ENABLE_IL2CPP [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.NullChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)] #endif [MethodImpl (MethodImplOptions.AggressiveInlining)] public int GetComponentIndexInPool<T> () where T : class { ref var entityData = ref Owner.GetEntityData (this); #if DEBUG if (entityData.Gen != Gen) { throw new Exception ("Cant check component on destroyed entity."); } #endif var typeIdx = EcsComponentPool<T>.Instance.TypeIndex; for (int i = 0, iMax = entityData.ComponentsCountX2; i < iMax; i += 2) { if (entityData.Components[i] == typeIdx) { return entityData.Components[i + 1]; } } return -1; } /// <summary> /// Gets internal identifier. /// </summary> public int GetInternalId () { return Id; } /// <summary> /// Removes components from entity and destroys it. /// </summary> #if ENABLE_IL2CPP [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.NullChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)] #endif [MethodImpl (MethodImplOptions.AggressiveInlining)] public void Destroy () { ref var entityData = ref Owner.GetEntityData (this); #if DEBUG if (entityData.Gen != Gen) { throw new Exception ("Cant touch destroyed entity."); } #endif // remove components first. for (var i = entityData.ComponentsCountX2 - 2; i >= 0; i -= 2) { Owner.UpdateFilters (-entityData.Components[i], this, entityData); #if DEBUG var removedComponent = EcsComponentPools.Items[entityData.Components[i]].GetItem (entityData.Components[i + 1]); #endif EcsComponentPools.Items[entityData.Components[i]].Recycle (entityData.Components[i + 1]); entityData.ComponentsCountX2 -= 2; #if DEBUG for (var ii = 0; ii < Owner._debugListeners.Count; ii++) { Owner._debugListeners[ii].OnComponentRemoved (this, removedComponent); } #endif } entityData.ComponentsCountX2 = 0; Owner.RecycleEntityData (Id, ref entityData); #if DEBUG for (var ii = 0; ii < Owner._debugListeners.Count; ii++) { Owner._debugListeners[ii].OnEntityDestroyed (this); } #endif } /// <summary> /// Is entity nulled. /// </summary> [MethodImpl (MethodImplOptions.AggressiveInlining)] public bool IsNull () { return Id == 0 && Gen == 0; } /// <summary> /// Is entity alive. /// </summary> #if ENABLE_IL2CPP [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.NullChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)] #endif [MethodImpl (MethodImplOptions.AggressiveInlining)] public bool IsAlive () { ref var entityData = ref Owner.GetEntityData (this); return entityData.Gen == Gen && entityData.ComponentsCountX2 >= 0; } /// <summary> /// Gets components count on entity. /// </summary> #if ENABLE_IL2CPP [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.NullChecks, false)] [Unity.IL2CPP.CompilerServices.Il2CppSetOption (Unity.IL2CPP.CompilerServices.Option.ArrayBoundsChecks, false)] #endif [MethodImpl (MethodImplOptions.AggressiveInlining)] public int GetComponentsCount () { ref var entityData = ref Owner.GetEntityData (this); #if DEBUG if (entityData.Gen != Gen) { throw new Exception ("Cant touch destroyed entity."); } #endif return entityData.ComponentsCountX2 <= 0 ? 0 : (entityData.ComponentsCountX2 >> 1); } /// <summary> /// Gets all components on entity. /// </summary> /// <param name="list">List to put results in it. if null - will be created.</param> /// <returns>Amount of components in list.</returns> public int GetComponents (ref object[] list) { ref var entityData = ref Owner.GetEntityData (this); #if DEBUG if (entityData.Gen != Gen) { throw new Exception ("Cant touch destroyed entity."); } #endif var itemsCount = entityData.ComponentsCountX2 >> 1; if (list == null || list.Length < itemsCount) { list = new object[itemsCount]; } for (int i = 0, j = 0, iMax = entityData.ComponentsCountX2; i < iMax; i += 2, j++) { list[j] = EcsComponentPools.Items[entityData.Components[i]].GetItem (entityData.Components[i + 1]); } return itemsCount; } [MethodImpl (MethodImplOptions.AggressiveInlining)] public static bool operator == (in EcsEntity lhs, in EcsEntity rhs) { return lhs.Id == rhs.Id && lhs.Gen == rhs.Gen; } [MethodImpl (MethodImplOptions.AggressiveInlining)] public static bool operator != (in EcsEntity lhs, in EcsEntity rhs) { return lhs.Id != rhs.Id || lhs.Gen != rhs.Gen; } [MethodImpl (MethodImplOptions.AggressiveInlining)] public override int GetHashCode () { return Id.GetHashCode () ^ (Gen.GetHashCode () << 2); } [MethodImpl (MethodImplOptions.AggressiveInlining)] public override bool Equals (object other) { if (!(other is EcsEntity)) { return false; } var rhs = (EcsEntity) other; return Id == rhs.Id && Gen == rhs.Gen; } #if DEBUG public override string ToString () { return IsNull () ? "Entity-Null" : string.Format ("Entity-{0}:{1}", Id, Gen); } #endif } }
43.576667
128
0.599174
[ "MIT" ]
ralreegorganon/RoadTrip
ecs-20191022/src/EcsEntity.cs
13,073
C#
using System; using System.Collections.Generic; using System.Text; using NPOI.HSSF.Record.Formula.Eval; using NPOI.HSSF.Record.Formula.Functions; namespace NPOI.SS.Formula { public class UserDefinedFunction : FreeRefFunction { public static FreeRefFunction instance = new UserDefinedFunction(); private UserDefinedFunction() { // enforce Singleton } public ValueEval Evaluate(ValueEval[] args, OperationEvaluationContext ec) { int nIncomingArgs = args.Length; if (nIncomingArgs < 1) { throw new Exception("function name argument missing"); } ValueEval nameArg = args[0]; String functionName = string.Empty ; if (nameArg is NameEval) { functionName = ((NameEval)nameArg).FunctionName; } else if (nameArg is NameXEval) { functionName = ec.GetWorkbook().ResolveNameXText(((NameXEval)nameArg).Ptg); } else { throw new Exception("First argument should be a NameEval, but got (" + nameArg.GetType().Name + ")"); } FreeRefFunction targetFunc = ec.FindUserDefinedFunction(functionName); if (targetFunc == null) { throw new NotImplementedException(functionName); } int nOutGoingArgs = nIncomingArgs - 1; ValueEval[] outGoingArgs = new ValueEval[nOutGoingArgs]; Array.Copy(args, 1, outGoingArgs, 0, nOutGoingArgs); return targetFunc.Evaluate(outGoingArgs, ec); } } }
31.907407
91
0.567615
[ "MIT" ]
cschen1205/myob-accounting-plugin
NPOI/main/SS/Formula/UserDefinedFunction.cs
1,725
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Es.V20180416.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class CosBackup : AbstractModel { /// <summary> /// Whether to enable auto-backup to COS /// </summary> [JsonProperty("IsAutoBackup")] public bool? IsAutoBackup{ get; set; } /// <summary> /// Auto-backup time (accurate down to the hour), such as "22:00" /// </summary> [JsonProperty("BackupTime")] public string BackupTime{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "IsAutoBackup", this.IsAutoBackup); this.SetParamSimple(map, prefix + "BackupTime", this.BackupTime); } } }
31.411765
81
0.644195
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/Es/V20180416/Models/CosBackup.cs
1,602
C#
using GAPPSF.Commands; using GAPPSF.Core.Data; using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace GAPPSF.UIControls { /// <summary> /// Interaction logic for CacheList.xaml /// </summary> public partial class CacheList : UserControl, IDisposable, IUIControl { private ICollectionView _geocacheCollectionView = null; private static CacheListColumnInfoCollection _cacheListColumnInfoCollection = null; public CacheList() { if (_cacheListColumnInfoCollection == null) { _cacheListColumnInfoCollection = new CacheListColumnInfoCollection(); } InitializeComponent(); DataContext = this; if (Core.Settings.Default.CacheListEnableAutomaticSorting && Core.Settings.Default.CacheListSortOnColumnIndex >= 0 && Core.Settings.Default.CacheListSortOnColumnIndex < cacheList.Columns.Count) { this.cacheList.Columns[Core.Settings.Default.CacheListSortOnColumnIndex].SortDirection = Core.Settings.Default.CacheListSortDirection == 0 ? ListSortDirection.Ascending : ListSortDirection.Descending; } ColorPickerArchived.SelectedColor = (Color)ColorConverter.ConvertFromString(Core.Settings.Default.ArchivedRowColor); ColorPickerDisabled.SelectedColor = (Color)ColorConverter.ConvertFromString(Core.Settings.Default.DisabledRowColor); ColorPickerOwn.SelectedColor = (Color)ColorConverter.ConvertFromString(Core.Settings.Default.IsOwnRowColor); ColorPickerFound.SelectedColor = (Color)ColorConverter.ConvertFromString(Core.Settings.Default.FoundRowColor); setGeocacheCollectionView(); _cacheListColumnInfoCollection.AssignDataGrid(cacheList); _cacheListColumnInfoCollection.UpdateDataGrid(cacheList); Core.Settings.Default.PropertyChanged += Default_PropertyChanged; Core.ApplicationData.Instance.PropertyChanged += Instance_PropertyChanged; Localization.TranslationManager.Instance.LanguageChanged += Instance_LanguageChanged; if (Core.ApplicationData.Instance.ActiveGeocache != null) { cacheList.ScrollIntoView(Core.ApplicationData.Instance.ActiveGeocache); } } void Instance_LanguageChanged(object sender, EventArgs e) { foreach(var item in ColumnInfoCollection) { item.Name = cacheList.Columns[item.ColumnIndex].Header as string; } } AsyncDelegateCommand _centerLocationCommand; public ICommand CenterLocationCommand { get { if (_centerLocationCommand == null) { _centerLocationCommand = new AsyncDelegateCommand(param => this.CenterLocationGeocache(), param => cacheList.SelectedItems.Count == 1); } return _centerLocationCommand; } } async private Task CenterLocationGeocache() { if (cacheList.SelectedItems.Count == 1) { Core.Data.Geocache gc = (cacheList.SelectedItems[0] as Core.Data.Geocache); if (gc != null) { using (Utils.DataUpdater upd = new Utils.DataUpdater(gc.Database)) { await Task.Run(() => { Utils.DataAccess.SetCenterLocation(gc.Lat, gc.Lon); }); } } } } AsyncDelegateCommand _copyCommand; public ICommand CopyCommand { get { if (_copyCommand == null) { _copyCommand = new AsyncDelegateCommand(param => this.CopyGeocache(), param => cacheList.SelectedItems.Count > 0); } return _copyCommand; } } async private Task CopyGeocache() { if (cacheList.SelectedItems.Count>0) { List<string> gcList = new List<string>(); foreach (Core.Data.Geocache gc in cacheList.SelectedItems) { gcList.Add(gc.Code); } await Clipboard.ClipboardHandler.Instance.CopyGeocachesAsync(Core.ApplicationData.Instance.ActiveDatabase, gcList); } } AsyncDelegateCommand _deleteCommand; public ICommand DeleteCommand { get { if (_deleteCommand == null) { _deleteCommand = new AsyncDelegateCommand(param => this.DeleteGeocache(false), param => cacheList.SelectedItems.Count > 0); } return _deleteCommand; } } AsyncDelegateCommand _deleteIgnoreCommand; public ICommand DeleteIgnoreCommand { get { if (_deleteIgnoreCommand == null) { _deleteIgnoreCommand = new AsyncDelegateCommand(param => this.DeleteGeocache(true), param => cacheList.SelectedItems.Count > 0); } return _deleteIgnoreCommand; } } async private Task DeleteGeocache(bool ignore) { if (cacheList.SelectedItems.Count > 0) { List<Core.Data.Geocache> gcList = new List<Core.Data.Geocache>(); foreach (Core.Data.Geocache gc in cacheList.SelectedItems) { gcList.Add(gc); } Core.ApplicationData.Instance.ActiveGeocache = null; using (Utils.DataUpdater upd = new Utils.DataUpdater(Core.ApplicationData.Instance.ActiveDatabase)) { await Task.Run(() => { int index = 0; DateTime nextUpdate = DateTime.Now.AddSeconds(1); using (Utils.ProgressBlock prog = new Utils.ProgressBlock("DeletingGeocaches", "DeletingGeocaches", gcList.Count, 0, true)) { foreach (var gc in gcList) { Utils.DataAccess.DeleteGeocache(gc); if (ignore) { Core.Settings.Default.AddIgnoreGeocacheCodes((new string[] { gc.Code }).ToList()); } index++; if (DateTime.Now >= nextUpdate) { if (!prog.Update("DeletingGeocaches", gcList.Count, index)) { break; } nextUpdate = DateTime.Now.AddSeconds(1); } } } }); } } } public static CacheListColumnInfoCollection ColumnInfoCollection { get { return _cacheListColumnInfoCollection; } } private bool GeocacheViewFilter(object o) { Core.Data.Geocache gc = o as Core.Data.Geocache; bool result = !Core.Settings.Default.CacheListShowSelectedOnly || gc.Selected; result &= !Core.Settings.Default.CacheListShowFlaggedOnly || gc.Flagged; string ft = Core.Settings.Default.CacheListFilterText; if (!string.IsNullOrEmpty(ft)) { if (result) { string s = gc.Code; result = s.IndexOf(ft, StringComparison.CurrentCultureIgnoreCase) >= 0; s = gc.Name; result |= s != null && s.IndexOf(ft, StringComparison.CurrentCultureIgnoreCase) >= 0; } } return result; } private void setGeocacheCollectionView() { if (Core.ApplicationData.Instance.ActiveDatabase != null) { DataGridSortDescription sort = null; sort = DataGridUtil.SaveSorting(cacheList, this._geocacheCollectionView); this._geocacheCollectionView = CollectionViewSource.GetDefaultView(Core.ApplicationData.Instance.ActiveDatabase.GeocacheCollection); this._geocacheCollectionView.Filter = this.GeocacheViewFilter; cacheList.ItemsSource = this._geocacheCollectionView; if (sort != null && Core.Settings.Default.CacheListEnableAutomaticSorting) { DataGridUtil.RestoreSorting(sort, cacheList, this._geocacheCollectionView); } } else { cacheList.ItemsSource = null; } } void Instance_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "ActiveDatabase") { setGeocacheCollectionView(); } else if (e.PropertyName == "AccountInfos") { if ((cacheList.ItemsSource as ListCollectionView) != null) { (cacheList.ItemsSource as ListCollectionView).Refresh(); } } else if (e.PropertyName=="ActiveGeocache") { if (Core.ApplicationData.Instance.ActiveGeocache!=null) { cacheList.ScrollIntoView(Core.ApplicationData.Instance.ActiveGeocache); } } } void Default_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "CacheListShowSelectedOnly" || e.PropertyName == "CacheListShowFlaggedOnly" || e.PropertyName == "CacheListFilterText") { if ((cacheList.ItemsSource as ListCollectionView) != null) { (cacheList.ItemsSource as ListCollectionView).Refresh(); } } else if (e.PropertyName == "CacheListColumnInfo") { _cacheListColumnInfoCollection.UpdateDataGrid(cacheList); } } public void Dispose() { for (int i = 0; i < cacheList.Columns.Count; i++) { if (cacheList.Columns[i].SortDirection != null) { Core.Settings.Default.CacheListSortOnColumnIndex = i; Core.Settings.Default.CacheListSortDirection = cacheList.Columns[i].SortDirection == ListSortDirection.Ascending ? 0 : 1; } } Localization.TranslationManager.Instance.LanguageChanged -= Instance_LanguageChanged; Core.ApplicationData.Instance.PropertyChanged -= Instance_PropertyChanged; Core.Settings.Default.PropertyChanged -= Default_PropertyChanged; } RelayCommand _invertSelectionCommand; public ICommand InvertSelectionCommand { get { if (_invertSelectionCommand == null) { _invertSelectionCommand = new RelayCommand(param => this.invertSelection(), param => cacheList.SelectedItems.Count>0); } return _invertSelectionCommand; } } public void invertSelection() { using (Utils.DataUpdater upd = new Utils.DataUpdater(Core.ApplicationData.Instance.ActiveDatabase)) { foreach (Core.Data.Geocache gc in cacheList.SelectedItems) { gc.Selected = !gc.Selected; } } } void cacheList_LoadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e) { // Get the DataRow corresponding to the DataGridRow that is loading. GAPPSF.Core.Data.Geocache item = e.Row.Item as GAPPSF.Core.Data.Geocache; if (item != null) { e.Row.Header = (e.Row.GetIndex()+1).ToString(); } else { e.Row.Visibility = System.Windows.Visibility.Collapsed; } } public override string ToString() { return Localization.TranslationManager.Instance.Translate("CacheList") as string; } public int WindowWidth { get { return Core.Settings.Default.CacheListWindowWidth; } set { Core.Settings.Default.CacheListWindowWidth = value; } } public int WindowHeight { get { return Core.Settings.Default.CacheListWindowHeight; } set { Core.Settings.Default.CacheListWindowHeight = value; } } public int WindowLeft { get { return Core.Settings.Default.CacheListWindowLeft; } set { Core.Settings.Default.CacheListWindowLeft = value; } } public int WindowTop { get { return Core.Settings.Default.CacheListWindowTop; } set { Core.Settings.Default.CacheListWindowTop = value; } } private void cacheList_ColumnReordered(object sender, DataGridColumnEventArgs e) { _cacheListColumnInfoCollection.UpdateFromDataGrid(cacheList); } private void ColorPickerArchived_ColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e) { Core.Settings.Default.ArchivedRowColor = ColorPickerArchived.SelectedColor.ToString(); } private void ColorPickerDisabled_ColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e) { Core.Settings.Default.DisabledRowColor = ColorPickerDisabled.SelectedColor.ToString(); } private void ColorPickerOwn_ColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e) { Core.Settings.Default.IsOwnRowColor = ColorPickerOwn.SelectedColor.ToString(); } private void ColorPickerFound_ColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e) { Core.Settings.Default.FoundRowColor = ColorPickerFound.SelectedColor.ToString(); } } }
37.341346
216
0.544419
[ "MIT" ]
GlobalcachingEU/GAPP
GAPPSF/UIControls/CacheList/CacheList.xaml.cs
15,536
C#
// <auto-generated /> namespace DotNetAppSqlDb.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")] public sealed partial class InitialCreate : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(InitialCreate)); string IMigrationMetadata.Id { get { return "201707311501229_InitialCreate"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
27.5
96
0.624242
[ "MIT" ]
jojojen/TodoListDotnet
DotNetAppSqlDb/Migrations/201707311501229_InitialCreate.Designer.cs
825
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.IO.MemoryMappedFiles { internal partial class MemoryMappedView { // These control the retry behaviour when lock violation errors occur during Flush: private const int MaxFlushWaits = 15; // must be <=30 private const int MaxFlushRetriesPerWait = 20; [SecurityCritical] public unsafe static MemoryMappedView CreateView(SafeMemoryMappedFileHandle memMappedFileHandle, MemoryMappedFileAccess access, long offset, long size) { // MapViewOfFile can only create views that start at a multiple of the system memory allocation // granularity. We decided to hide this restriction from the user by creating larger views than the // user requested and hiding the parts that the user did not request. extraMemNeeded is the amount of // extra memory we allocate before the start of the requested view. MapViewOfFile will also round the // capacity of the view to the nearest multiple of the system page size. Once again, we hide this // from the user by preventing them from writing to any memory that they did not request. ulong nativeSize; long extraMemNeeded, newOffset; ValidateSizeAndOffset( size, offset, GetSystemPageAllocationGranularity(), out nativeSize, out extraMemNeeded, out newOffset); // if request is >= than total virtual, then MapViewOfFile will fail with meaningless error message // "the parameter is incorrect"; this provides better error message in advance Interop.mincore.MEMORYSTATUSEX memStatus; memStatus.dwLength = (uint)sizeof(Interop.mincore.MEMORYSTATUSEX); Interop.mincore.GlobalMemoryStatusEx(out memStatus); ulong totalVirtual = memStatus.ullTotalVirtual; if (nativeSize >= totalVirtual) { throw new IOException(SR.IO_NotEnoughMemory); } // split the long into two ints int offsetLow = unchecked((int)(newOffset & 0x00000000FFFFFFFFL)); int offsetHigh = unchecked((int)(newOffset >> 32)); // create the view SafeMemoryMappedViewHandle viewHandle = Interop.mincore.MapViewOfFile(memMappedFileHandle, (int)MemoryMappedFile.GetFileMapAccess(access), offsetHigh, offsetLow, new UIntPtr(nativeSize)); if (viewHandle.IsInvalid) { throw Win32Marshal.GetExceptionForLastWin32Error(); } // Query the view for its size and allocation type Interop.mincore.MEMORY_BASIC_INFORMATION viewInfo = new Interop.mincore.MEMORY_BASIC_INFORMATION(); Interop.mincore.VirtualQuery(viewHandle, ref viewInfo, (UIntPtr)Marshal.SizeOf(viewInfo)); ulong viewSize = (ulong)viewInfo.RegionSize; // Allocate the pages if we were using the MemoryMappedFileOptions.DelayAllocatePages option // OR check if the allocated view size is smaller than the expected native size // If multiple overlapping views are created over the file mapping object, the pages in a given region // could have different attributes(MEM_RESERVE OR MEM_COMMIT) as MapViewOfFile preserves coherence between // views created on a mapping object backed by same file. // In which case, the viewSize will be smaller than nativeSize required and viewState could be MEM_COMMIT // but more pages may need to be committed in the region. // This is because, VirtualQuery function(that internally invokes VirtualQueryEx function) returns the attributes // and size of the region of pages with matching attributes starting from base address. // VirtualQueryEx: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366907(v=vs.85).aspx if (((viewInfo.State & Interop.mincore.MemOptions.MEM_RESERVE) != 0) || ((ulong)viewSize < (ulong)nativeSize)) { IntPtr tempHandle = Interop.mincore.VirtualAlloc( viewHandle, (UIntPtr)(nativeSize != MemoryMappedFile.DefaultSize ? nativeSize : viewSize), Interop.mincore.MemOptions.MEM_COMMIT, MemoryMappedFile.GetPageAccess(access)); int lastError = Marshal.GetLastWin32Error(); if (viewHandle.IsInvalid) { throw Win32Marshal.GetExceptionForWin32Error(lastError); } // again query the view for its new size viewInfo = new Interop.mincore.MEMORY_BASIC_INFORMATION(); Interop.mincore.VirtualQuery(viewHandle, ref viewInfo, (UIntPtr)Marshal.SizeOf(viewInfo)); viewSize = (ulong)viewInfo.RegionSize; } // if the user specified DefaultSize as the size, we need to get the actual size if (size == MemoryMappedFile.DefaultSize) { size = (long)(viewSize - (ulong)extraMemNeeded); } else { Debug.Assert(viewSize >= (ulong)size, "viewSize < size"); } viewHandle.Initialize((ulong)size + (ulong)extraMemNeeded); return new MemoryMappedView(viewHandle, extraMemNeeded, size, access); } // Flushes the changes such that they are in sync with the FileStream bits (ones obtained // with the win32 ReadFile and WriteFile functions). Need to call FileStream's Flush to // flush to the disk. // NOTE: This will flush all bytes before and after the view up until an offset that is a multiple // of SystemPageSize. [SecurityCritical] public void Flush(UIntPtr capacity) { unsafe { byte* firstPagePtr = null; try { _viewHandle.AcquirePointer(ref firstPagePtr); bool success = Interop.mincore.FlushViewOfFile((IntPtr)firstPagePtr, capacity) != 0; if (success) return; // This will visit the finally block. // It is a known issue within the NTFS transaction log system that // causes FlushViewOfFile to intermittently fail with ERROR_LOCK_VIOLATION // As a workaround, we catch this particular error and retry the flush operation // a few milliseconds later. If it does not work, we give it a few more tries with // increasing intervals. Eventually, however, we need to give up. In ad-hoc tests // this strategy successfully flushed the view after no more than 3 retries. int error = Marshal.GetLastWin32Error(); bool canRetry = (!success && error == Interop.mincore.Errors.ERROR_LOCK_VIOLATION); SpinWait spinWait = new SpinWait(); for (int w = 0; canRetry && w < MaxFlushWaits; w++) { int pause = (1 << w); // MaxFlushRetries should never be over 30 MemoryMappedFile.ThreadSleep(pause); for (int r = 0; canRetry && r < MaxFlushRetriesPerWait; r++) { success = Interop.mincore.FlushViewOfFile((IntPtr)firstPagePtr, capacity) != 0; if (success) return; // This will visit the finally block. spinWait.SpinOnce(); error = Marshal.GetLastWin32Error(); canRetry = (error == Interop.mincore.Errors.ERROR_LOCK_VIOLATION); } } // We got to here, so there was no success: throw Win32Marshal.GetExceptionForWin32Error(error); } finally { if (firstPagePtr != null) { _viewHandle.ReleasePointer(); } } } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- [SecurityCritical] private static int GetSystemPageAllocationGranularity() { Interop.mincore.SYSTEM_INFO info; Interop.mincore.GetSystemInfo(out info); return (int)info.dwAllocationGranularity; } } }
50.893855
126
0.597475
[ "MIT" ]
benjamin-bader/corefx
src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs
9,110
C#
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Attributes { using System; using System.ComponentModel; using System.Globalization; /// <summary> /// Support <see cref="NLog.LogLevel"/> implementation of <see cref="IConvertible"/> /// </summary> public class LogLevelTypeConverter : TypeConverter { /// <inheritdoc/> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string) || IsNumericType(sourceType) || base.CanConvertFrom(context, sourceType); } /// <inheritdoc/> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value?.GetType() == typeof(string)) return LogLevel.FromString(value.ToString()); else if (IsNumericType(value?.GetType())) return LogLevel.FromOrdinal(Convert.ToInt32(value)); else return base.ConvertFrom(context, culture, value); } /// <inheritdoc/> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string) || IsNumericType(destinationType) || base.CanConvertTo(context, destinationType); } /// <inheritdoc/> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is LogLevel logLevel) { if (destinationType == typeof(string)) return logLevel.ToString(); else if (IsNumericType(destinationType)) return Convert.ChangeType(logLevel.Ordinal, destinationType, culture); } return base.ConvertTo(context, culture, value, destinationType); } private static bool IsNumericType(Type sourceType) { return sourceType == typeof(int) || sourceType == typeof(uint) || sourceType == typeof(long) || sourceType == typeof(ulong) || sourceType == typeof(short) || sourceType == typeof(ushort); } } }
43.153846
134
0.665648
[ "BSD-3-Clause" ]
aTiKhan/NLog
src/NLog/Attributes/LogLevelTypeConverter.cs
3,929
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using Orbit.Core.Client; using System.Windows.Media; using Orbit.Core.Helpers; using System.Windows.Media.Effects; namespace Orbit.Core.Scene.Entities.HeavyWeight { class HeavyweightLine : Line, IHeavyWeightSceneObject { private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public UIElement HeavyWeightGeometry { get; set; } public override bool Visible { get { return visible; } set { visible = value; if (HeavyWeightGeometry == null) return; SceneMgr.BeginInvoke(new Action(() => HeavyWeightGeometry.Visibility = visible ? Visibility.Visible : Visibility.Hidden)); } } public HeavyweightLine(SceneMgr mgr, long id, Vector start, Vector end, Color color, int width) : base(mgr, id) { SceneMgr = mgr; Start = start; End = end; SceneMgr.BeginInvoke(new Action(() => { HeavyWeightGeometry = HeavyweightGeometryFactory.CreateLineGeometry(Start, End, color, width); BlurEffect effect = new BlurEffect(); effect.Radius = 6; effect.KernelType = KernelType.Box; HeavyWeightGeometry.Effect = effect; })); } /// <summary> /// prepisujte jen pokud je to nezbytne, jinak pouzijte UpdateGeometricState()! /// </summary> public override void UpdateGeometric() { System.Windows.Shapes.Line line = HeavyWeightGeometry as System.Windows.Shapes.Line; line.X1 = Start.X; line.Y1 = Start.Y; line.X2 = End.X; line.Y2 = End.Y; } public override void SetGeometry(DrawingGroup geometryElement) { Logger.Warn("Trying to set DrawingGroup geometry to HeavyweightSphere -> ignoring!"); } } }
31.826087
146
0.58561
[ "MIT" ]
ecl1ps/orbital-devastation
Application/Core/Scene/Entities/HeavyWeight/HeavyweightLine.cs
2,198
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 lightsail-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Lightsail.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Lightsail.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for GetInstanceState operation /// </summary> public class GetInstanceStateResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { GetInstanceStateResponse response = new GetInstanceStateResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("state", targetDepth)) { var unmarshaller = InstanceStateUnmarshaller.Instance; response.State = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return new AccessDeniedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("AccountSetupInProgressException")) { return new AccountSetupInProgressException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidInputException")) { return new InvalidInputException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException")) { return new NotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("OperationFailureException")) { return new OperationFailureException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceException")) { return new ServiceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthenticatedException")) { return new UnauthenticatedException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonLightsailException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static GetInstanceStateResponseUnmarshaller _instance = new GetInstanceStateResponseUnmarshaller(); internal static GetInstanceStateResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetInstanceStateResponseUnmarshaller Instance { get { return _instance; } } } }
43.68
175
0.664103
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Lightsail/Generated/Model/Internal/MarshallTransformations/GetInstanceStateResponseUnmarshaller.cs
5,460
C#
#if UNITY_EDITOR || RUNTIME_CSG using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Sabresaurus.SabreCSG { [ExecuteInEditMode] public class TrimBrush : CompoundBrush { /// <summary> /// The size of the trim. /// </summary> [SerializeField] float trimSize = 0.25f; /// <summary> /// Gets or sets the size of the trim. /// </summary> /// <value>The size of the trim.</value> public float TrimSize { get { return trimSize; } set { trimSize = value; } } /// <summary> /// Gets the beautiful name of the brush used in auto-generation of the hierarchy name. /// </summary> /// <value>The beautiful name of the brush.</value> public override string BeautifulBrushName { get { return "Trim Brush"; } } public override int BrushCount { get { // If the brush is too small for trims, just default to a single brush to not break things ok! return (localBounds.size.x > trimSize * 2.0f && localBounds.size.z > trimSize * 2.0f)?5:1; } } public override void UpdateVisibility () { } Polygon[] GeneratePolys(int index) { Polygon[] output = generatedBrushes[index].GetPolygons(); float xNorm = Mathf.Cos(index * Mathf.PI * 0.5f); float zNorm = -Mathf.Sin(index * Mathf.PI * 0.5f); Vector3 frontOuterTop = new Vector3( localBounds.center.x + (localBounds.size.x * 0.5f * xNorm) + (localBounds.size.x * 0.5f * zNorm), localBounds.max.y, localBounds.center.z + (localBounds.size.z * 0.5f * xNorm) + (localBounds.size.z * 0.5f * zNorm) ); Vector3 frontOuterBottom = frontOuterTop; frontOuterBottom.y = localBounds.min.y; Vector3 backOuterTop = new Vector3( localBounds.center.x + (localBounds.size.x * 0.5f * xNorm) + (localBounds.size.x * 0.5f * -zNorm), localBounds.max.y, localBounds.center.z + (localBounds.size.z * 0.5f * -xNorm) + (localBounds.size.z * 0.5f * zNorm) ); Vector3 backOuterBottom = backOuterTop; backOuterBottom.y = localBounds.min.y; Vector3 frontInnerTop = new Vector3( localBounds.center.x + ((localBounds.size.x - trimSize * 2.0f) * 0.5f * xNorm) + ((localBounds.size.x - trimSize * 2.0f) * 0.5f * zNorm), localBounds.max.y, localBounds.center.z + ((localBounds.size.z - trimSize * 2.0f) * 0.5f * xNorm) + ((localBounds.size.z - trimSize * 2.0f) * 0.5f * zNorm) ); Vector3 frontInnerBottom = frontInnerTop; frontInnerBottom.y = localBounds.min.y; Vector3 backInnerTop = new Vector3( localBounds.center.x + ((localBounds.size.x - trimSize * 2.0f) * 0.5f * xNorm) + ((localBounds.size.x - trimSize * 2.0f) * 0.5f * -zNorm), localBounds.max.y, localBounds.center.z + ((localBounds.size.z - trimSize * 2.0f) * 0.5f * -xNorm) + ((localBounds.size.z - trimSize * 2.0f) * 0.5f * zNorm) ); Vector3 backInnerBottom = backInnerTop; backInnerBottom.y = localBounds.min.y; // Outer Plane output[0].Vertices[0].Position = frontOuterTop; output[0].Vertices[1].Position = frontOuterBottom; output[0].Vertices[2].Position = backOuterBottom; output[0].Vertices[3].Position = backOuterTop; // Inner Plane output[1].Vertices[0].Position = frontInnerTop; output[1].Vertices[1].Position = backInnerTop; output[1].Vertices[2].Position = backInnerBottom; output[1].Vertices[3].Position = frontInnerBottom; // Top Plane output[2].Vertices[0].Position = frontInnerTop; output[2].Vertices[1].Position = frontOuterTop; output[2].Vertices[2].Position = backOuterTop; output[2].Vertices[3].Position = backInnerTop; // Bottom Plane output[3].Vertices[0].Position = frontOuterBottom; output[3].Vertices[1].Position = frontInnerBottom; output[3].Vertices[2].Position = backInnerBottom; output[3].Vertices[3].Position = backOuterBottom; // Front Plane output[4].Vertices[0].Position = frontInnerTop; output[4].Vertices[1].Position = frontInnerBottom; output[4].Vertices[2].Position = frontOuterBottom; output[4].Vertices[3].Position = frontOuterTop; // Back Plane output[5].Vertices[0].Position = backInnerBottom; output[5].Vertices[1].Position = backInnerTop; output[5].Vertices[2].Position = backOuterTop; output[5].Vertices[3].Position = backOuterBottom; for (int i = 0; i < 6; i++) { if (index % 2 == 1) Array.Reverse(output[i].Vertices); GenerateNormals(output[i]); GenerateUvCoordinates(output[i]); } return output; } /// <summary> /// Generates the UV coordinates for a <see cref="Polygon"/> automatically. /// </summary> /// <param name="polygon">The polygon to be updated.</param> private void GenerateUvCoordinates(Polygon polygon) { // stolen code from the surface editor "AutoUV". Vector3 planeNormal = polygon.Plane.normal; Quaternion cancellingRotation = Quaternion.Inverse(Quaternion.LookRotation(-planeNormal)); // Sets the UV at each point to the position on the plane for (int i = 0; i < polygon.Vertices.Length; i++) { Vector3 position = polygon.Vertices[i].Position; Vector2 uv = (cancellingRotation * position) * 0.5f; polygon.Vertices[i].UV = uv; } } private void GenerateNormals(Polygon polygon) { Plane plane = new Plane(polygon.Vertices[1].Position, polygon.Vertices[2].Position, polygon.Vertices[3].Position); foreach (Vertex vertex in polygon.Vertices) vertex.Normal = plane.normal; } public override void Invalidate (bool polygonsChanged) { base.Invalidate(polygonsChanged); for (int i = 0; i < BrushCount; i++) { generatedBrushes[i].Mode = this.Mode; generatedBrushes[i].IsNoCSG = this.IsNoCSG; generatedBrushes[i].IsVisible = this.IsVisible; generatedBrushes[i].HasCollision = this.HasCollision; } Vector3 baseSize; if (localBounds.size.x > trimSize * 2.0f && localBounds.size.z > trimSize * 2.0f) { float sizeX = localBounds.size.x - trimSize * 2.0f; float sizeZ = localBounds.size.z - trimSize * 2.0f; baseSize = new Vector3(sizeX, localBounds.size.y, sizeZ); // Build the trims here for (int i = 1; i < BrushCount; i++) { // Vector3 brushPos = localBounds.center; // brushPos.x += Mathf.Sin(i * Mathf.PI * 0.5f) * ((localBounds.size.x - trimSize) * 0.5f); // brushPos.z += Mathf.Cos(i * Mathf.PI * 0.5f) * ((localBounds.size.z - trimSize) * 0.5f); // generatedBrushes[i].transform.localPosition = brushPos; Vector3 brushSize = new Vector3(); if (i % 2 == 0) { brushSize.x = sizeX; brushSize.z = trimSize; } else { brushSize.x = trimSize; brushSize.z = sizeZ; } brushSize.y = localBounds.size.y; BrushUtility.Resize(generatedBrushes[i], brushSize); generatedBrushes[i].SetPolygons(GeneratePolys(i)); generatedBrushes[i].Invalidate(true); } } else { baseSize = localBounds.size; } generatedBrushes[0].transform.localPosition = localBounds.center; BrushUtility.Resize(generatedBrushes[0], baseSize); } } } #endif
35.792271
143
0.635848
[ "MIT" ]
CloudDevStudios/SabreCSG
Scripts/Brushes/CompoundBrushes/TrimBrush.cs
7,411
C#
namespace CodeFirstExistingDatabase { using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; public partial class PlutoContext : DbContext { public PlutoContext() : base("name=PlutoContext") { } public virtual DbSet<Author> Authors { get; set; } public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Tag> Tags { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Author>() .HasMany(e => e.Courses) .WithOptional(e => e.Author) .HasForeignKey(e => e.Author_Id); modelBuilder.Entity<Course>() .HasMany(e => e.Tags) .WithMany(e => e.Courses) .Map(m => m.ToTable("TagCourses").MapLeftKey("Course_Id")); } } }
28.705882
76
0.563525
[ "MIT" ]
georgetour/Entity-Framework
Chapter 4 Code-first workflow/CodeFirstExistingDatabase/CodeFirstExistingDatabase/PlutoContext.cs
976
C#
namespace Examples.FirstAutomappedProject.Entities { public class Employee { public virtual int Id { get; protected set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual Store Store { get; set; } } }
31.1
54
0.62701
[ "BSD-3-Clause" ]
BrunoJuchli/fluent-nhibernate
src/Examples.FirstAutomappedProject/Entities/Employee.cs
311
C#
using Elizabeth; using System; namespace mogate { public class Attack : IBehavior { public Type Behavior { get { return typeof(Attack); } } public int Damage { get; set; } public int Distance { get; set; } public int ArchetypeID { get; set; } public Attack (int damage, int distance, int id = 0) { Damage = damage; Distance = distance; ArchetypeID = id; } } }
17.130435
57
0.64467
[ "MIT" ]
rustamserg/mogate
mogate.Shared/Behaviors/Attack.cs
394
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 Microsoft.AspNetCore.Blazor.Shared; using Microsoft.AspNetCore.Razor.Language; using System; namespace Microsoft.AspNetCore.Blazor.Razor { internal class RefTagHelperDescriptorProvider : ITagHelperDescriptorProvider { // Run after the component tag helper provider, because later we may want component-type-specific variants of this public int Order { get; set; } = 1000; public RazorEngine Engine { get; set; } public void Execute(TagHelperDescriptorProviderContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } context.Results.Add(CreateRefTagHelper()); } private TagHelperDescriptor CreateRefTagHelper() { var builder = TagHelperDescriptorBuilder.Create(BlazorMetadata.Ref.TagHelperKind, "Ref", BlazorApi.AssemblyName); builder.Documentation = Resources.RefTagHelper_Documentation; builder.Metadata.Add(BlazorMetadata.SpecialKindKey, BlazorMetadata.Ref.TagHelperKind); builder.Metadata[TagHelperMetadata.Runtime.Name] = BlazorMetadata.Ref.RuntimeName; // WTE has a bug in 15.7p1 where a Tag Helper without a display-name that looks like // a C# property will crash trying to create the toolips. builder.SetTypeName("Microsoft.AspNetCore.Blazor.Components.Ref"); builder.TagMatchingRule(rule => { rule.TagName = "*"; rule.Attribute(attribute => { attribute.Name = "ref"; }); }); builder.BindAttribute(attribute => { attribute.Documentation = Resources.RefTagHelper_Documentation; attribute.Name = "ref"; // WTE has a bug 15.7p1 where a Tag Helper without a display-name that looks like // a C# property will crash trying to create the toolips. attribute.SetPropertyName("Ref"); attribute.TypeName = typeof(object).FullName; }); return builder.Build(); } } }
37.809524
125
0.623426
[ "Apache-2.0" ]
BickelLukas/Blazor
src/Microsoft.AspNetCore.Blazor.Razor.Extensions/RefTagHelperDescriptorProvider.cs
2,384
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Baseline; using Marten.Internal.Operations; using Marten.Linq; using Marten.Linq.Fields; using Marten.Linq.Filters; using Marten.Linq.Parsing; using Marten.Linq.QueryHandlers; using Marten.Linq.Selectors; using Marten.Linq.SqlGeneration; using Marten.Schema; using Marten.Services; using Marten.Storage; using Marten.Util; using Remotion.Linq; namespace Marten.Internal.Storage { public class SubClassDocumentStorage<T, TRoot, TId>: IDocumentStorage<T, TId> where T : TRoot { private readonly IDocumentStorage<TRoot, TId> _parent; private readonly SubClassMapping _mapping; private readonly ISqlFragment _defaultWhere; private readonly string[] _fields; public SubClassDocumentStorage(IDocumentStorage<TRoot, TId> parent, SubClassMapping mapping) { _parent = parent; _mapping = mapping; FromObject = _mapping.TableName.QualifiedName; _defaultWhere = determineWhereFragment(); _fields = _parent.SelectFields(); } public TenancyStyle TenancyStyle => _parent.TenancyStyle; object IDocumentStorage<T>.IdentityFor(T document) { return _parent.Identity(document); } public string FromObject { get; } public Type SelectedType => typeof(T); public void WriteSelectClause(CommandBuilder sql) { _parent.WriteSelectClause(sql); } public string[] SelectFields() { return _fields; } public ISelector BuildSelector(IMartenSession session) { var inner = _parent.BuildSelector(session); return new CastingSelector<T, TRoot>((ISelector<TRoot>) inner); } public IQueryHandler<TResult> BuildHandler<TResult>(IMartenSession session, Statement statement, Statement currentStatement) { var selector = (ISelector<T>)BuildSelector(session); return LinqHandlerBuilder.BuildHandler<T, TResult>(selector, statement); } public ISelectClause UseStatistics(QueryStatistics statistics) { return new StatsSelectClause<T>(this, statistics); } public Type SourceType => typeof(TRoot); public IFieldMapping Fields => _mapping.Parent; public ISqlFragment FilterDocuments(QueryModel model, ISqlFragment query) { var extras = extraFilters(query).ToArray(); var extraCompound = new CompoundWhereFragment("and", extras); return new CompoundWhereFragment("and", query, extraCompound); } // TODO -- there's duplication here w/ DocumentStorage private IEnumerable<ISqlFragment> extraFilters(ISqlFragment query) { yield return toBasicWhere(); if (_mapping.DeleteStyle == DeleteStyle.SoftDelete && !query.Contains(SchemaConstants.DeletedColumn)) yield return ExcludeSoftDeletedFilter.Instance; if (_mapping.Parent.TenancyStyle == TenancyStyle.Conjoined && !query.SpecifiesTenant()) yield return new CurrentTenantFilter(); } // TODO -- there's duplication here w/ DocumentStorage private IEnumerable<ISqlFragment> defaultFilters() { yield return toBasicWhere(); if (_mapping.Parent.TenancyStyle == TenancyStyle.Conjoined) yield return new CurrentTenantFilter(); if (_mapping.DeleteStyle == DeleteStyle.SoftDelete) yield return ExcludeSoftDeletedFilter.Instance; } public ISqlFragment DefaultWhereFragment() { return _defaultWhere; } public ISqlFragment determineWhereFragment() { var defaults = defaultFilters().ToArray(); switch (defaults.Length) { case 0: return null; case 1: return defaults[0]; default: return new CompoundWhereFragment("and", defaults); } } private WhereFragment toBasicWhere() { var aliasValues = _mapping.Aliases.Select(a => $"d.{SchemaConstants.DocumentTypeColumn} = '{a}'").ToArray() .Join(" or "); var sql = _mapping.Alias.Length > 1 ? $"({aliasValues})" : aliasValues; return new WhereFragment(sql); } public bool UseOptimisticConcurrency => _parent.UseOptimisticConcurrency; public IOperationFragment DeleteFragment => _parent.DeleteFragment; public DuplicatedField[] DuplicatedFields => _parent.DuplicatedFields; public DbObjectName TableName => _parent.TableName; public Type DocumentType => typeof(T); public Type IdType => typeof(TId); public Guid? VersionFor(T document, IMartenSession session) { return _parent.VersionFor(document, session); } public void Store(IMartenSession session, T document) { _parent.Store(session, document); } public void Store(IMartenSession session, T document, Guid? version) { _parent.Store(session, document, version); } public void Eject(IMartenSession session, T document) { _parent.Eject(session, document); } public IStorageOperation Update(T document, IMartenSession session, ITenant tenant) { return _parent.Update(document, session, tenant); } public IStorageOperation Insert(T document, IMartenSession session, ITenant tenant) { return _parent.Insert(document, session, tenant); } public IStorageOperation Upsert(T document, IMartenSession session, ITenant tenant) { return _parent.Upsert(document, session, tenant); } public IStorageOperation Overwrite(T document, IMartenSession session, ITenant tenant) { return _parent.Overwrite(document, session, tenant); } public IDeletion DeleteForDocument(T document) { return _parent.DeleteForDocument(document); } public IDeletion DeleteForDocument(T document, ITenant tenant) { return _parent.DeleteForDocument(document, tenant); } public void SetIdentity(T document, TId identity) { throw new NotSupportedException(); } public IDeletion DeleteForId(TId id) { return _parent.DeleteForId(id); } public IDeletion DeleteForId(TId id, ITenant tenant) { return _parent.DeleteForId(id, tenant); } public T Load(TId id, IMartenSession session) { var doc = _parent.Load(id, session); if (doc is T x) return x; return default; } public async Task<T> LoadAsync(TId id, IMartenSession session, CancellationToken token) { var doc = await _parent.LoadAsync(id, session, token); if (doc is T x) return x; return default; } public IReadOnlyList<T> LoadMany(TId[] ids, IMartenSession session) { return _parent.LoadMany(ids, session).OfType<T>().ToList(); } public async Task<IReadOnlyList<T>> LoadManyAsync(TId[] ids, IMartenSession session, CancellationToken token) { return (await _parent.LoadManyAsync(ids, session, token)).OfType<T>().ToList(); } public TId AssignIdentity(T document, ITenant tenant) { return _parent.AssignIdentity(document, tenant); } public TId Identity(T document) { return _parent.Identity(document); } public ISqlFragment ByIdFilter(TId id) { return _parent.ByIdFilter(id); } public void EjectById(IMartenSession session, object id) { _parent.EjectById(session, id); } public void RemoveDirtyTracker(IMartenSession session, object id) { _parent.RemoveDirtyTracker(session, id); } } }
30.948339
119
0.617384
[ "MIT" ]
barclayadam/marten
src/Marten/Internal/Storage/SubClassDocumentStorage.cs
8,387
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: EntityRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The type WorkbookFormatProtectionRequestBuilder. /// </summary> public partial class WorkbookFormatProtectionRequestBuilder : EntityRequestBuilder, IWorkbookFormatProtectionRequestBuilder { /// <summary> /// Constructs a new WorkbookFormatProtectionRequestBuilder. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> public WorkbookFormatProtectionRequestBuilder( string requestUrl, IBaseClient client) : base(requestUrl, client) { } /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> public new IWorkbookFormatProtectionRequest Request() { return this.Request(null); } /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> public new IWorkbookFormatProtectionRequest Request(IEnumerable<Option> options) { return new WorkbookFormatProtectionRequest(this.RequestUrl, this.Client, options); } } }
35.454545
153
0.585128
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/WorkbookFormatProtectionRequestBuilder.cs
1,950
C#
using ItLank.CleanArchitecture.Core.Entities; using ItLank.CleanArchitecture.SharedKernel; namespace ItLank.CleanArchitecture.Core.Events { public class ToDoItemCompletedEvent : BaseDomainEvent { public ToDoItem CompletedItem { get; set; } public ToDoItemCompletedEvent(ToDoItem completedItem) { CompletedItem = completedItem; } } }
26.066667
61
0.710997
[ "MIT" ]
ShabanGomaa/CleanArchitecture
src/ItLank.CleanArchitecture.Core/Events/ToDoItemCompletedEvent.cs
393
C#
namespace Rcon { public enum PacketType { ServerdataAuth = 3, ServerdataAuthResponse = 2, ServerdataExeccommand = 2, ServerdataResponseValue = 0 } }
17.636364
35
0.603093
[ "MIT" ]
Psychoboy/AtlasChatRelay
Rcon/PacketType.cs
196
C#
using System; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; using NHapi.Model.V24.Datatype; using NHapi.Base.Log; namespace NHapi.Model.V24.Segment{ ///<summary> /// Represents an HL7 QRF message segment. /// This segment has the following fields:<ol> ///<li>QRF-1: Where Subject Filter (ST)</li> ///<li>QRF-2: When Data Start Date/Time (TS)</li> ///<li>QRF-3: When Data End Date/Time (TS)</li> ///<li>QRF-4: What User Qualifier (ST)</li> ///<li>QRF-5: Other QRY Subject Filter (ST)</li> ///<li>QRF-6: Which Date/Time Qualifier (ID)</li> ///<li>QRF-7: Which Date/Time Status Qualifier (ID)</li> ///<li>QRF-8: Date/Time Selection Qualifier (ID)</li> ///<li>QRF-9: When Quantity/Timing Qualifier (TQ)</li> ///<li>QRF-10: Search Confidence Threshold (NM)</li> ///</ol> /// The get...() methods return data from individual fields. These methods /// do not throw exceptions and may therefore have to handle exceptions internally. /// If an exception is handled internally, it is logged and null is returned. /// This is not expected to happen - if it does happen this indicates not so much /// an exceptional circumstance as a bug in the code for this class. ///</summary> [Serializable] public class QRF : AbstractSegment { /** * Creates a QRF (Original Style Query Filter) segment object that belongs to the given * message. */ public QRF(IGroup parent, IModelClassFactory factory) : base(parent,factory) { IMessage message = Message; try { this.add(typeof(ST), true, 0, 20, new System.Object[]{message}, "Where Subject Filter"); this.add(typeof(TS), false, 1, 26, new System.Object[]{message}, "When Data Start Date/Time"); this.add(typeof(TS), false, 1, 26, new System.Object[]{message}, "When Data End Date/Time"); this.add(typeof(ST), false, 0, 60, new System.Object[]{message}, "What User Qualifier"); this.add(typeof(ST), false, 0, 60, new System.Object[]{message}, "Other QRY Subject Filter"); this.add(typeof(ID), false, 0, 12, new System.Object[]{message, 156}, "Which Date/Time Qualifier"); this.add(typeof(ID), false, 0, 12, new System.Object[]{message, 157}, "Which Date/Time Status Qualifier"); this.add(typeof(ID), false, 0, 12, new System.Object[]{message, 158}, "Date/Time Selection Qualifier"); this.add(typeof(TQ), false, 1, 60, new System.Object[]{message}, "When Quantity/Timing Qualifier"); this.add(typeof(NM), false, 1, 10, new System.Object[]{message}, "Search Confidence Threshold"); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he); } } ///<summary> /// Returns a single repetition of Where Subject Filter(QRF-1). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public ST GetWhereSubjectFilter(int rep) { ST ret = null; try { IType t = this.GetField(1, rep); ret = (ST)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Where Subject Filter (QRF-1). ///</summary> public ST[] GetWhereSubjectFilter() { ST[] ret = null; try { IType[] t = this.GetField(1); ret = new ST[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (ST)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Where Subject Filter (QRF-1). ///</summary> public int WhereSubjectFilterRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(1); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns When Data Start Date/Time(QRF-2). ///</summary> public TS WhenDataStartDateTime { get{ TS ret = null; try { IType t = this.GetField(2, 0); ret = (TS)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns When Data End Date/Time(QRF-3). ///</summary> public TS WhenDataEndDateTime { get{ TS ret = null; try { IType t = this.GetField(3, 0); ret = (TS)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns a single repetition of What User Qualifier(QRF-4). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public ST GetWhatUserQualifier(int rep) { ST ret = null; try { IType t = this.GetField(4, rep); ret = (ST)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of What User Qualifier (QRF-4). ///</summary> public ST[] GetWhatUserQualifier() { ST[] ret = null; try { IType[] t = this.GetField(4); ret = new ST[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (ST)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of What User Qualifier (QRF-4). ///</summary> public int WhatUserQualifierRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(4); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns a single repetition of Other QRY Subject Filter(QRF-5). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public ST GetOtherQRYSubjectFilter(int rep) { ST ret = null; try { IType t = this.GetField(5, rep); ret = (ST)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Other QRY Subject Filter (QRF-5). ///</summary> public ST[] GetOtherQRYSubjectFilter() { ST[] ret = null; try { IType[] t = this.GetField(5); ret = new ST[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (ST)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Other QRY Subject Filter (QRF-5). ///</summary> public int OtherQRYSubjectFilterRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(5); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns a single repetition of Which Date/Time Qualifier(QRF-6). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public ID GetWhichDateTimeQualifier(int rep) { ID ret = null; try { IType t = this.GetField(6, rep); ret = (ID)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Which Date/Time Qualifier (QRF-6). ///</summary> public ID[] GetWhichDateTimeQualifier() { ID[] ret = null; try { IType[] t = this.GetField(6); ret = new ID[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (ID)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Which Date/Time Qualifier (QRF-6). ///</summary> public int WhichDateTimeQualifierRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(6); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns a single repetition of Which Date/Time Status Qualifier(QRF-7). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public ID GetWhichDateTimeStatusQualifier(int rep) { ID ret = null; try { IType t = this.GetField(7, rep); ret = (ID)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Which Date/Time Status Qualifier (QRF-7). ///</summary> public ID[] GetWhichDateTimeStatusQualifier() { ID[] ret = null; try { IType[] t = this.GetField(7); ret = new ID[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (ID)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Which Date/Time Status Qualifier (QRF-7). ///</summary> public int WhichDateTimeStatusQualifierRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(7); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns a single repetition of Date/Time Selection Qualifier(QRF-8). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public ID GetDateTimeSelectionQualifier(int rep) { ID ret = null; try { IType t = this.GetField(8, rep); ret = (ID)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Date/Time Selection Qualifier (QRF-8). ///</summary> public ID[] GetDateTimeSelectionQualifier() { ID[] ret = null; try { IType[] t = this.GetField(8); ret = new ID[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (ID)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Date/Time Selection Qualifier (QRF-8). ///</summary> public int DateTimeSelectionQualifierRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(8); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns When Quantity/Timing Qualifier(QRF-9). ///</summary> public TQ WhenQuantityTimingQualifier { get{ TQ ret = null; try { IType t = this.GetField(9, 0); ret = (TQ)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Search Confidence Threshold(QRF-10). ///</summary> public NM SearchConfidenceThreshold { get{ NM ret = null; try { IType t = this.GetField(10, 0); ret = (NM)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } }}
36.927419
122
0.644409
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
afaonline/nHapi
src/NHapi.Model.V24/Segment/QRF.cs
18,316
C#
using System.Collections.Generic; using tezcat.Framework.Database; using UnityEngine; namespace tezcat.Framework.UI { /// <summary> /// 浮动Tip /// </summary> public class TezFloatingTip : TezUIWidget , ITezSinglePrefab { [SerializeField] protected RectTransform m_Content = null; [SerializeField] Vector2 m_BottomLeft = new Vector2(-8, -24); [SerializeField] Vector2 m_TopRight = new Vector2(32, 8); RectTransform m_RectTransform = null; Vector2 m_Pivot = new Vector2(0, 1); List<ITezBaseWidget> m_Widgets = new List<ITezBaseWidget>(); bool m_NeedClear = false; protected override void initWidget() { m_RectTransform = this.GetComponent<RectTransform>(); this.gameObject.SetActive(false); } /// <summary> /// 添加一个控件 /// </summary> public virtual void addWidget(ITezBaseWidget widget) { m_Widgets.Add(widget); } protected override void onHide() { this.clearTip(); } protected override void onShow() { this.clearTip(); m_NeedClear = true; this.calculatePosition(); } protected void clearTip() { if (m_NeedClear) { foreach (var widget in m_Widgets) { widget.close(); } m_Widgets.Clear(); m_NeedClear = false; } } private void Update() { this.calculatePosition(); } private void calculatePosition() { /* * (0, 1080)-------------(1920, 1080) * * * * * (0, 0)-------------(1920, 0) */ var position = Input.mousePosition; var rect = m_RectTransform.rect; var width = rect.width; var height = rect.height; if (position.x + width >= Screen.width) { m_Pivot.x = 1; position.x += m_BottomLeft.x; } else { m_Pivot.x = 0; position.x += m_TopRight.x; } if (position.y - height <= 0) { m_Pivot.y = 0; position.y += m_TopRight.y; } else { m_Pivot.y = 1; position.y += m_BottomLeft.y; } m_RectTransform.pivot = m_Pivot; m_RectTransform.position = position; } } }
24.39823
68
0.451941
[ "MIT" ]
tzkt623/TezcatFramework-Unity
UI/TezFloatingTip.cs
2,775
C#
using System.Diagnostics.CodeAnalysis; using NUnit.Framework; using SharpGEDParser.Parser; // TODO valid symbol namespace SharpGEDParser.Tests { [ExcludeFromCodeCoverage] [TestFixture] public class DateToken { [Test] public void Test() { string val = "13 Apr 1964"; var tokenize = new DateTokens(); var toks = tokenize.Tokenize(val); Assert.AreEqual(3, toks.Count); Assert.AreEqual(0, toks[0].offset); Assert.AreEqual(2, toks[0].length); Assert.AreEqual(TokType.NUM, toks[0].type); Assert.AreEqual(3, toks[1].offset); Assert.AreEqual(3, toks[1].length); Assert.AreEqual(TokType.WORD, toks[1].type); Assert.AreEqual(7, toks[2].offset); Assert.AreEqual(4, toks[2].length); Assert.AreEqual(TokType.NUM, toks[2].type); } [Test] public void Reuse() { string val = "13 Apr 1964"; var tokenize = new DateTokens(); var toks = tokenize.Tokenize(val); Assert.AreEqual(3, toks.Count); toks = tokenize.Tokenize(val); Assert.AreEqual(3, toks.Count); } [Test] public void Test2() { string val = "@#DGREGORIAN@ 1964B.C."; var tokenize = new DateTokens(); var toks = tokenize.Tokenize(val); Assert.AreEqual(3, toks.Count); CheckToken(toks[0], TokType.CALEN, 1, 11); CheckToken(toks[1], TokType.NUM, 15, 4); CheckToken(toks[2], TokType.WORD, 19, 4); } [Test] public void Test3() { // improperly terminate calendar escape string val = "@#DGREGORIAN 1964B.C."; var tokenize = new DateTokens(); var toks = tokenize.Tokenize(val); Assert.AreEqual(3, toks.Count); CheckToken(toks[0], TokType.CALEN, 1, 11); CheckToken(toks[1], TokType.NUM, 14, 4); CheckToken(toks[2], TokType.WORD, 18, 4); } [Test] public void TestPhrase() { string val = "INT 1964 (tombstone calculated)"; var toks = new DateTokens().Tokenize(val); Assert.AreEqual(3, toks.Count); CheckToken(toks[0], TokType.WORD, 0, 3); CheckToken(toks[1], TokType.NUM, 4, 4); CheckToken(toks[2], TokType.PHRASE, 10, 20); } private void CheckToken(Token tok, TokType targetType, int off = -1, int len = -1) { Assert.AreEqual(targetType, tok.type); if (len != -1) Assert.AreEqual(len, tok.length, "length"); if (off != -1) Assert.AreEqual(off, tok.offset, "offset"); } [Test] public void TestMix() { string val = "BET Jun 1910 AND 1 Aug 1911"; var toks = new DateTokens().Tokenize(val); Assert.AreEqual(7, toks.Count); CheckToken(toks[0], TokType.WORD); CheckToken(toks[1], TokType.WORD); CheckToken(toks[3], TokType.WORD); CheckToken(toks[5], TokType.WORD); CheckToken(toks[2], TokType.NUM); CheckToken(toks[4], TokType.NUM); CheckToken(toks[6], TokType.NUM); } [Test] public void TestUnk() { string val = "gibber!"; var toks = new DateTokens().Tokenize(val); Assert.AreEqual(2, toks.Count); CheckToken(toks[0], TokType.WORD, 0, 6); CheckToken(toks[1], TokType.UNK, 6, 1); } [Test] public void TestSym() { string val = "1860/61"; var toks = new DateTokens().Tokenize(val); Assert.AreEqual(3, toks.Count); CheckToken(toks[0], TokType.NUM, 0, 4); CheckToken(toks[1], TokType.SYMB, 4, 1); CheckToken(toks[2], TokType.NUM, 5, 2); } } }
32.365079
90
0.518391
[ "Apache-2.0" ]
ennoborg/YAGP
SharpGEDParse/SharpGEDParser/Tests/DateToken.cs
4,080
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.480/blob/master/LICENSE * */ #endregion using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace ExtendedControls.ExtendedToolkit.Ribbon { [ToolboxBitmap(typeof(Button))] public class RibbonRoundButton : Button { #region About Constructor public RibbonRoundButton() { this.SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer, true); this.SetStyle(ControlStyles.Opaque, false); this.FlatAppearance.BorderSize = 0; this.FlatStyle = FlatStyle.Flat; this.BackColor = Color.Transparent; this.TextImageRelation = TextImageRelation.ImageAboveText; this.Text = ""; this.Size = new Size(40, 40); timer1.Interval = 1; timer1.Tick += new EventHandler(timer1_Tick); } #endregion #region About Image Properties private Point _imgoffset = new Point(0, 0); public Point ImgOffset { get { return _imgoffset; } set { _imgoffset = value; this.Refresh(); } } private int _imgscale = 100; public int ImgScale { get { return _imgscale; } set { _imgscale = value; this.Refresh(); } } #endregion #region Colors private Color _baseColor = Color.FromArgb(209, 209, 209); private Color _strokeColor = Color.FromArgb(80, 80, 80); private Color _hoverColor = Color.FromArgb(255, 255, 255); private Color _onColor = Color.FromArgb(255, 255, 255); private Color _onColorlight = Color.FromArgb(255, 255, 255); private Color _pressColor = Color.FromArgb(255, 255, 255); public Color ColourBase { get { return _baseColor; } set { _baseColor = value; R0 = _baseColor.R; B0 = _baseColor.B; G0 = _baseColor.G; } } public Color ColourStroke { get { return _strokeColor; } set { _strokeColor = value; } } public Color ColourOver { get { return _hoverColor; } set { _hoverColor = value; } } public Color ColourOn { get { return _onColor; } set { _onColor = value; } } public Color ColourPress { get { return _pressColor; } set { _pressColor = value; } } public Color GetLightColor() { int _r0 = R0 + 127, _g0 = G0 + 196, _b0 = B0 + 111; if (_r0 > 255) _r0 = 255; if (_g0 > 255) _g0 = 255; if (_b0 > 255) _b0 = 255; return Color.FromArgb(_r0, _g0, _b0); } #endregion private int regionoffset = 1; protected override void OnPaint(PaintEventArgs pevent) { #region Variables & Conf Graphics g = pevent.Graphics; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.High; Rectangle r = new Rectangle(0, 0, this.Width - regionoffset, this.Height - regionoffset); #endregion #region Transform to Circle Region GraphicsPath path = new GraphicsPath(); if (this.Size != null) { path.AddEllipse(0, 0, this.Width - 1, this.Height - 1); this.Region = new Region(path); } #endregion #region Paint FillShadow(g, r); FillStroke(g, r, 2, Color.FromArgb(R0, G0, B0)); FillGradient(g, r, GetLightColor(), Color.FromArgb(R0, G0, B0)); FillBeizer(g, r, 1, ColourOver, ColourBase); DrawImage(g, r, ImgOffset, ImgScale); DrawStroke(g, r, 1, ColourStroke, GetLightColor()); #endregion } #region Paint Methods public void FillStroke(Graphics gr, Rectangle re, int stroke, Color incolor) { Rectangle _re = new Rectangle(stroke, stroke, this.Width - 2 * stroke - regionoffset, this.Height - 2 * stroke - regionoffset); gr.FillEllipse(new SolidBrush(incolor), _re); } public void DrawStroke(Graphics gr, Rectangle re, int stroke, Color incolor, Color outcolor) { Rectangle _re = new Rectangle(stroke, stroke, this.Width - 3 * stroke - regionoffset, this.Height - 3 * stroke - regionoffset); gr.DrawEllipse(new Pen(incolor, stroke), _re); } public void FillGradient(Graphics gr, Rectangle re, Color incolor, Color outcolor) { try { Rectangle _re = new Rectangle((int)(re.Width * -0.15), (int)(re.Height * 0.12), (int)(re.Width * 1.26) - regionoffset, (int)(re.Height * 0.875) - regionoffset); GraphicsPath path = new GraphicsPath(); path.AddEllipse(_re); PathGradientBrush brush = new PathGradientBrush(path); brush.CenterPoint = new PointF(this.Width / 2, this.Height); float[] pos = new float[5]; pos[0] = 0.0F; pos[1] = 0.2F; pos[2] = 0.3F; pos[3] = 0.7F; pos[4] = 1.0F; Color[] colors = new Color[5]; colors[0] = Color.FromArgb(10, incolor); colors[1] = Color.FromArgb(10, incolor); colors[2] = Color.FromArgb(40, outcolor); colors[3] = incolor; colors[4] = incolor; ColorBlend mix = new ColorBlend(); mix.Colors = colors; mix.Positions = pos; brush.InterpolationColors = mix; gr.FillPath(brush, path); brush.Dispose(); } catch { } } public void DrawImage(Graphics gr, Rectangle re, Point off, int scale) { if (this.Image != null) { gr.DrawImage(this.Image, off.X, off.Y, re.Width * scale / 100, re.Height * scale / 100); } } public void FillBeizer(Graphics gr, Rectangle re, int stroke, Color incolor, Color basecolor) { Rectangle _re = new Rectangle(stroke, stroke, re.Width - 2 * stroke - regionoffset, re.Height - 2 * stroke - regionoffset); GraphicsPath path = new GraphicsPath(); Point[] points = new Point[4]; points[0] = new Point(re.Width / 2, 1); points[1] = new Point(2, re.Height / 2); points[2] = new Point(re.Width / 2, (int)(re.Height / 2 * 0.9)); points[3] = new Point(re.Width - 2, re.Height / 2); path.AddClosedCurve(points, 1.16F); PathGradientBrush brush = new PathGradientBrush(path); brush.CenterPoint = new PointF(this.Width / 2, this.Height); float[] pos = new float[4]; pos[0] = 0.0F; pos[1] = 0.018F; pos[2] = 0.15F; pos[3] = 1.0F; Color[] colors = new Color[4]; colors[0] = Color.FromArgb(10, incolor); colors[1] = Color.FromArgb(200, incolor); colors[2] = Color.FromArgb(30, incolor); colors[3] = Color.FromArgb(10, incolor); ColorBlend mix = new ColorBlend(); mix.Colors = colors; mix.Positions = pos; brush.InterpolationColors = mix; gr.CompositingQuality = CompositingQuality.HighQuality; gr.FillPath(brush, path); brush.Dispose(); } public void FillShadow(Graphics gr, Rectangle re) { int stroke = 1; Color incolor = Color.Black; Rectangle _re = new Rectangle(stroke, stroke, re.Width - 2 * stroke, re.Height - 2 * stroke); GraphicsPath path = new GraphicsPath(); path.AddArc(1, 1, this.Width - 2, this.Height - 2, 270, 210); PathGradientBrush brush = new PathGradientBrush(path); brush.CenterPoint = new PointF(this.Width / 2, this.Height / 2); float[] pos = new float[4]; pos[0] = 0.0F; pos[1] = 0.01F; pos[2] = 0.5F; pos[3] = 1.0F; Color[] colors = new Color[4]; colors[0] = Color.FromArgb(0, incolor); colors[1] = Color.FromArgb(100, incolor); colors[2] = Color.FromArgb(0, incolor); colors[3] = Color.FromArgb(0, incolor); ColorBlend mix = new ColorBlend(); mix.Colors = colors; mix.Positions = pos; brush.InterpolationColors = mix; gr.CompositingQuality = CompositingQuality.HighQuality; gr.FillPath(brush, path); brush.Dispose(); } #endregion #region About Fading private Timer timer1 = new Timer(); private int i_mode = 0; //0 Entering, 1 Leaving, 2 Pressing, 3 Up private int i_factor = 20; private int i_fR = 1; private int i_fG = 1; private int i_fB = 1; private int R0 = 0; private int G0 = 0; private int B0 = 0; private void timer1_Tick(object sender, EventArgs e) { #region Entering if (i_mode == 0 | i_mode == 3) { if (System.Math.Abs(ColourOn.R - R0) > i_factor) { i_fR = i_factor; } else { i_fR = 1; } if (System.Math.Abs(ColourOn.G - G0) > i_factor) { i_fG = i_factor; } else { i_fG = 1; } if (System.Math.Abs(ColourOn.B - B0) > i_factor) { i_fB = i_factor; } else { i_fB = 1; } if (ColourOn.R < R0) { R0 -= i_fR; } else if (ColourOn.R > R0) { R0 += i_fR; } if (ColourOn.G < G0) { G0 -= i_fG; } else if (ColourOn.G > G0) { G0 += i_fG; } if (ColourOn.B < B0) { B0 -= i_fB; } else if (ColourOn.B > B0) { B0 += i_fB; } if (ColourOn == Color.FromArgb(R0, G0, B0)) { timer1.Stop(); } else { this.Refresh(); } } #endregion #region Pressing if (i_mode == 2) { if (System.Math.Abs(ColourPress.R - R0) > i_factor) { i_fR = i_factor; } else { i_fR = 1; } if (System.Math.Abs(ColourPress.G - G0) > i_factor) { i_fG = i_factor; } else { i_fG = 1; } if (System.Math.Abs(ColourPress.B - B0) > i_factor) { i_fB = i_factor; } else { i_fB = 1; } if (ColourPress.R < R0) { R0 -= i_fR; } else if (ColourPress.R > R0) { R0 += i_fR; } if (ColourPress.G < G0) { G0 -= i_fG; } else if (ColourPress.G > G0) { G0 += i_fG; } if (ColourPress.B < B0) { B0 -= i_fB; } else if (ColourPress.B > B0) { B0 += i_fB; } if (ColourPress == Color.FromArgb(R0, G0, B0)) { timer1.Stop(); } else { this.Refresh(); } } #endregion #region Leaving if (i_mode == 1) { if (System.Math.Abs(ColourBase.R - R0) < i_factor) { i_fR = 1; } else { i_fR = i_factor; } if (System.Math.Abs(ColourBase.G - G0) < i_factor) { i_fG = 1; } else { i_fG = i_factor; } if (System.Math.Abs(ColourBase.B - B0) < i_factor) { i_fB = 1; } else { i_fB = i_factor; } if (ColourBase.R < R0) { R0 -= i_fR; } else if (ColourBase.R > R0) { R0 += i_fR; } if (ColourBase.G < G0) { G0 -= i_fG; } else if (ColourBase.G > G0) { G0 += i_fG; } if (ColourBase.B < B0) { B0 -= i_fB; } else if (ColourBase.B > B0) { B0 += i_fB; } if (ColourBase == Color.FromArgb(R0, G0, B0)) { timer1.Stop(); } else { this.Refresh(); } } #endregion } #endregion #region About Mouse Events protected override void OnMouseEnter(EventArgs e) { i_mode = 0; timer1.Start(); base.OnMouseEnter(e); } protected override void OnMouseDown(MouseEventArgs mevent) { timer1.Stop(); i_mode = 2; timer1.Start(); base.OnMouseDown(mevent); } protected override void OnMouseUp(MouseEventArgs mevent) { timer1.Stop(); i_mode = 3; timer1.Start(); base.OnMouseUp(mevent); } protected override void OnMouseLeave(EventArgs e) { i_mode = 1; timer1.Start(); base.OnMouseLeave(e); } #endregion } }
32.086957
176
0.461382
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.480
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/ExtendedToolkit/Ribbon/RibbonRoundButton.cs
14,762
C#
namespace MaSiRoProject { namespace Format { /// <summary> /// VMD フォーマットの構造 /// </summary> public partial class VMD_Format_Struct { /// <summary> /// X軸とY軸をまとめたクラス /// </summary> public class MotionInterpolation_Rectangle<T> { /// <summary> /// 開始座標 /// </summary> public MotionInterpolation_Coordinate<T> Start = new MotionInterpolation_Coordinate<T>(); /// <summary> /// 終了座標 /// </summary> public MotionInterpolation_Coordinate<T> Stop = new MotionInterpolation_Coordinate<T>(); /// <summary> /// 補間曲線の開始座標 /// </summary> public MotionInterpolation_Coordinate<byte> Biging = new MotionInterpolation_Coordinate<byte>(0, 0); /// <summary> /// 補間曲線の開始座標 /// </summary> public MotionInterpolation_Coordinate<byte> End = new MotionInterpolation_Coordinate<byte>(127, 127); /// <summary> /// コンストラクタ /// </summary> /// <param name="startTime">開始座標のX軸</param> /// <param name="startAmount">開始座標のY軸</param> /// <param name="endTime">終了座標のX軸</param> /// <param name="endAmount">終了座標のY軸</param> public MotionInterpolation_Rectangle(T startTime, T startAmount, T endTime, T endAmount) { this.Set(startTime, startAmount, endTime, endAmount); } /// <summary> /// コンストラクタ /// </summary> public MotionInterpolation_Rectangle() { } /// <summary> /// 設定関数 /// </summary> /// <param name="startTime">開始座標のX軸</param> /// <param name="startAmount">開始座標のY軸</param> /// <param name="stopTime">終了座標のX軸</param> /// <param name="stopAmount">終了座標のY軸</param> public void Set(T startTime, T startAmount, T stopTime, T stopAmount) { this.Start.Time = startTime; this.Start.Amount = startAmount; this.Stop.Time = stopTime; this.Stop.Amount = stopAmount; } } /// <summary> /// X軸とY軸をまとめたクラス /// </summary> public class MotionInterpolation_Coordinate<T> { /// <summary> /// X軸 /// </summary> public T Time; /// <summary> /// Y軸 /// </summary> public T Amount; /// <summary> /// コンストラクタ /// </summary> /// <param name="time">X軸</param> /// <param name="amount">Y軸</param> public MotionInterpolation_Coordinate(T time, T amount) { this.Set(time, amount); } /// <summary> /// コンストラクタ /// </summary> public MotionInterpolation_Coordinate() { } /// <summary> /// 設定関数 /// </summary> /// <param name="time">X軸</param> /// <param name="amount">Y軸</param> public void Set(T time, T amount) { this.Time = time; this.Amount = amount; } } /// <summary> /// 拡張 フォーマット /// </summary> /// <remarks> /// VMD ファイルフォーマット以外で、別途把握/操作するためのデータ /// </remarks> public class FORMAT_Expansion { /// <summary> /// 座標系 /// </summary> public CoordinateSystemList CoordinateSystem = CoordinateSystemList.LeftHand; /// <summary> /// モーション開始位置 /// </summary> public int StartFrame { get { return VMD_Format.StartFrame; } } /// <summary> /// ファイルタイプ /// </summary> public string FileType { get { return inner_filetype; } } /// <summary> /// ターゲットID /// </summary> /// <remarks> /// 複数のデータを呼び出した際にどのデータが分からなくなるので /// IDを指定できるようにするため。 /// </remarks> public int TargetID { get { return inner_targetID; } set { inner_targetID = value; } } /// <summary> /// VMD バージョンの値 /// </summary> /// <remarks> /// VMD ファイルシグニチャでも判断できるが、数字として取得するためのもの。 /// </remarks> public int Version { get { return (int)inner_version; } } //////////////////////////////////////////////////////////// // 定数 //////////////////////////////////////////////////////////// /// <summary> /// ターゲットと未指定の場合の数値 /// </summary> public const int TARGETID_NONE = -1; /// <summary> /// VMDを示すファイルタイプ /// </summary> public const string FILETYPE_VMD = "VMD"; /// <summary> /// ファイルタイプが不明 /// </summary> public const string FILETYPE_UNKNOWN = "UNKNOWN"; //////////////////////////////////////////////////////////// // 列挙子 //////////////////////////////////////////////////////////// public enum CoordinateSystemList { /// <summary> /// 左手系 /// </summary> LeftHand, /// <summary> /// 右手系 /// </summary> RightHand, /// <summary> /// MMDの座標系 /// </summary> MMDHand } public enum EXPANSION_VERSION { /// <summary> /// バージョン不明 /// </summary> VMD_VERSION_UNKOWN = -1, /// <summary> /// Version 0000 /// </summary> VMD_VERSION_000 = 0, /// <summary> /// Version 0100 /// </summary> VMD_VERSION_001 = 1, /// <summary> /// Version 0200 /// </summary> VMD_VERSION_002 = 2, } //////////////////////////////////////////////////////////// // 内部変数 //////////////////////////////////////////////////////////// /// <summary> /// [内部変数] バージョン /// </summary> private EXPANSION_VERSION inner_version = EXPANSION_VERSION.VMD_VERSION_UNKOWN; /// <summary> /// [内部変数] ターゲットID /// </summary> private int inner_targetID = TARGETID_NONE; /// <summary> /// [内部変数] ファイルタイプ /// </summary> private string inner_filetype = FILETYPE_UNKNOWN; //////////////////////////////////////////////////////////// // 関数 //////////////////////////////////////////////////////////// /// <summary> /// ファイルシグニチャからVersionを特定する関数 /// </summary> /// <param name="signature">ファイルシグニチャ</param> /// <remarks> /// 旧バージョンのシグニチャは未確認 /// </remarks> public void SetFileSignature(string signature) { if (0 <= signature.IndexOf("Vocaloid Motion Data 0002")) { this.inner_version = EXPANSION_VERSION.VMD_VERSION_002; inner_filetype = FILETYPE_VMD; } else if (0 <= signature.IndexOf("Vocaloid Motion Data 0001")) { this.inner_version = EXPANSION_VERSION.VMD_VERSION_001; inner_filetype = FILETYPE_VMD; } else if (0 <= signature.IndexOf("Vocaloid Motion Data 0000")) { this.inner_version = EXPANSION_VERSION.VMD_VERSION_000; inner_filetype = FILETYPE_VMD; } else { inner_filetype = FILETYPE_UNKNOWN; } } } } } }
33.305085
117
0.347176
[ "Apache-2.0" ]
MaSiRo-Project-OSS/VMDtoJSON
src/CS/Format/VMD_Format_Struct_Expansion.cs
10,677
C#
using IdentityModel; using IdentityServer4; using IdentityServer4.Models; using System.Collections.Generic; using System.Security.Claims; namespace IdentityServer { public static class Config { // User Role Mapping private static IdentityResource RoleResource = new IdentityResource { Name = "role", DisplayName = "Role", Description = "Allow the service access to your user roles.", UserClaims = new[] { JwtClaimTypes.Role, ClaimTypes.Role }, ShowInDiscoveryDocument = true, Required = true, Emphasize = true }; public static IEnumerable<IdentityResource> Ids => new IdentityResource[] { new IdentityResources.OpenId(), new IdentityResources.Profile(), new IdentityResources.Email(), RoleResource, }; public static IEnumerable<ApiResource> Apis => new List<ApiResource> { }; public static IEnumerable<Client> Clients => new List<Client> { new Client { ClientId = "ClientOne", RedirectUris = { "https://localhost:5003/signin-oidc" }, PostLogoutRedirectUris = { "https://localhost:5003/" }, FrontChannelLogoutUri = "https://localhost:5003/signout-oidc", AllowedGrantTypes = GrantTypes.Code, AllowAccessTokensViaBrowser = true, // secret for authentication ClientSecrets = { new Secret("client.secret".Sha256()) }, // scopes that client has access to AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, IdentityServerConstants.StandardScopes.Email, ClaimTypes.Role, // User Role Mapping JwtClaimTypes.Role, // User Role Mapping }, RequireConsent = false, } }; } }
34.5
86
0.507673
[ "MIT" ]
houseofcat/Authentication
AspNetCore3.x_IS4.1/IS01_IdentityServer4.1_AspNetIdentity/IdentityServer/Config.cs
2,348
C#
using System.Collections.Generic; using NBitcoin; namespace Stratis.Features.SQLiteWalletRepository.External { public interface IWalletTransactionReadOnlyLookup { /// <summary> /// Determines if the outpoint has been added to this collection. /// </summary> /// <param name="outPoint">The transaction id.</param> /// <param name="addresses">Identifies the addresses related to the outpoint (if any).</param> /// <returns><c>True</c> if the address exists or has been added tentatively.</returns> bool Contains(OutPoint outPoint, out HashSet<AddressIdentifier> addresses); } }
38
102
0.685759
[ "MIT" ]
AYCHPay/AYCHPayGenesisFullnode
src/Stratis.Features.SQLiteWalletRepository/External/IWalletTransactionReadOnlyLookup.cs
648
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AoC.Advent2016.Test { [TestCategory("2016")] [TestClass] public class Day12Test { string input = Util.GetInput<Day12>(); [TestCategory("Regression")] [DataTestMethod] public void Part1_Regression() { Assert.AreEqual(318020, Day12.Part1(input)); } [TestCategory("Regression")] [DataTestMethod] public void Part2_Regression() { Assert.AreEqual(9227674, Day12.Part2(input)); } } }
22.115385
57
0.591304
[ "MIT" ]
benjymous/AdventOfCode
test/Advent2016/Day12Test.cs
575
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Documents; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; // The Templated Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234235 namespace rMindBaseControls.Buttons { public sealed class HeaderButton : Button { public HeaderButton() { this.DefaultStyleKey = typeof(HeaderButton); } } }
25.208333
102
0.73719
[ "Apache-2.0" ]
Korhog/rMind.Home
rMind.Server/Libs/NodeEngine/rMind.BaseControls/Buttons/HeaderButton.cs
607
C#
/* * Marketplace * * API Cloud Loyalty LTM - Webpremios * * OpenAPI spec version: 1.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; namespace IO.Swagger.Models { /// <summary> /// /// </summary> [DataContract] public partial class Sections : IEquatable<Sections> { /// <summary> /// Initializes a new instance of the <see cref="Sections" /> class. /// </summary> /// <param name="Id">Identificador da categorização.</param> /// <param name="SectionType">Tipo da categorização.</param> /// <param name="Name">Nome da categorização.</param> /// <param name="Slug">URL amigável da categorização.</param> public Sections(string Id = default(string), string SectionType = default(string), string Name = default(string), string Slug = default(string)) { this.Id = Id; this.SectionType = SectionType; this.Name = Name; this.Slug = Slug; } /// <summary> /// Identificador da categorização /// </summary> /// <value>Identificador da categorização</value> [DataMember(Name="id")] public string Id { get; set; } /// <summary> /// Tipo da categorização /// </summary> /// <value>Tipo da categorização</value> [DataMember(Name="sectionType")] public string SectionType { get; set; } /// <summary> /// Nome da categorização /// </summary> /// <value>Nome da categorização</value> [DataMember(Name="name")] public string Name { get; set; } /// <summary> /// URL amigável da categorização /// </summary> /// <value>URL amigável da categorização</value> [DataMember(Name="slug")] public string Slug { 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 Sections {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" SectionType: ").Append(SectionType).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Slug: ").Append(Slug).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 string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((Sections)obj); } /// <summary> /// Returns true if Sections instances are equal /// </summary> /// <param name="other">Instance of Sections to be compared</param> /// <returns>Boolean</returns> public bool Equals(Sections other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.SectionType == other.SectionType || this.SectionType != null && this.SectionType.Equals(other.SectionType) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Slug == other.Slug || this.Slug != null && this.Slug.Equals(other.Slug) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.SectionType != null) hash = hash * 59 + this.SectionType.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.Slug != null) hash = hash * 59 + this.Slug.GetHashCode(); return hash; } } #region Operators public static bool operator ==(Sections left, Sections right) { return Equals(left, right); } public static bool operator !=(Sections left, Sections right) { return !Equals(left, right); } #endregion Operators } }
32.245902
152
0.509744
[ "MIT" ]
ltm-arquitetura/webpremios-csharp-sdks
src/IO.Swagger/Models/Sections.cs
5,928
C#
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.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 System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// LocalePolicy /// </summary> [DataContract] public partial class LocalePolicy : IEquatable<LocalePolicy>, IValidatableObject { public LocalePolicy() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="LocalePolicy" /> class. /// </summary> /// <param name="AddressFormat">AddressFormat.</param> /// <param name="AddressFormatMetadata">AddressFormatMetadata.</param> /// <param name="AllowRegion">AllowRegion.</param> /// <param name="CalendarType">CalendarType.</param> /// <param name="CalendarTypeMetadata">CalendarTypeMetadata.</param> /// <param name="CultureName">CultureName.</param> /// <param name="CultureNameMetadata">CultureNameMetadata.</param> /// <param name="CurrencyCode">CurrencyCode.</param> /// <param name="CurrencyCodeMetadata">CurrencyCodeMetadata.</param> /// <param name="CurrencyNegativeFormat">CurrencyNegativeFormat.</param> /// <param name="CurrencyNegativeFormatMetadata">CurrencyNegativeFormatMetadata.</param> /// <param name="CurrencyPositiveFormat">CurrencyPositiveFormat.</param> /// <param name="CurrencyPositiveFormatMetadata">CurrencyPositiveFormatMetadata.</param> /// <param name="CustomDateFormat">CustomDateFormat.</param> /// <param name="CustomSignDateFormat">CustomSignDateFormat.</param> /// <param name="CustomSignTimeFormat">CustomSignTimeFormat.</param> /// <param name="CustomTimeFormat">CustomTimeFormat.</param> /// <param name="DateFormat">DateFormat.</param> /// <param name="DateFormatMetadata">DateFormatMetadata.</param> /// <param name="EffectiveAddressFormat">EffectiveAddressFormat.</param> /// <param name="EffectiveCalendarType">EffectiveCalendarType.</param> /// <param name="EffectiveCurrencyCode">EffectiveCurrencyCode.</param> /// <param name="EffectiveCurrencyNegativeFormat">EffectiveCurrencyNegativeFormat.</param> /// <param name="EffectiveCurrencyPositiveFormat">EffectiveCurrencyPositiveFormat.</param> /// <param name="EffectiveCustomDateFormat">EffectiveCustomDateFormat.</param> /// <param name="EffectiveCustomTimeFormat">EffectiveCustomTimeFormat.</param> /// <param name="EffectiveDateFormat">EffectiveDateFormat.</param> /// <param name="EffectiveInitialFormat">EffectiveInitialFormat.</param> /// <param name="EffectiveNameFormat">EffectiveNameFormat.</param> /// <param name="EffectiveTimeFormat">EffectiveTimeFormat.</param> /// <param name="EffectiveTimeZone">EffectiveTimeZone.</param> /// <param name="InitialFormat">InitialFormat.</param> /// <param name="InitialFormatMetadata">InitialFormatMetadata.</param> /// <param name="NameFormat">NameFormat.</param> /// <param name="NameFormatMetadata">NameFormatMetadata.</param> /// <param name="SignDateFormat">SignDateFormat.</param> /// <param name="SignDateFormatMetadata">SignDateFormatMetadata.</param> /// <param name="SignTimeFormat">SignTimeFormat.</param> /// <param name="SignTimeFormatMetadata">SignTimeFormatMetadata.</param> /// <param name="TimeFormat">TimeFormat.</param> /// <param name="TimeFormatMetadata">TimeFormatMetadata.</param> /// <param name="TimeZone">TimeZone.</param> /// <param name="TimeZoneMetadata">TimeZoneMetadata.</param> public LocalePolicy(string AddressFormat = default(string), SettingsMetadata AddressFormatMetadata = default(SettingsMetadata), string AllowRegion = default(string), string CalendarType = default(string), SettingsMetadata CalendarTypeMetadata = default(SettingsMetadata), string CultureName = default(string), SettingsMetadata CultureNameMetadata = default(SettingsMetadata), string CurrencyCode = default(string), SettingsMetadata CurrencyCodeMetadata = default(SettingsMetadata), string CurrencyNegativeFormat = default(string), SettingsMetadata CurrencyNegativeFormatMetadata = default(SettingsMetadata), string CurrencyPositiveFormat = default(string), SettingsMetadata CurrencyPositiveFormatMetadata = default(SettingsMetadata), string CustomDateFormat = default(string), string CustomSignDateFormat = default(string), string CustomSignTimeFormat = default(string), string CustomTimeFormat = default(string), string DateFormat = default(string), SettingsMetadata DateFormatMetadata = default(SettingsMetadata), string EffectiveAddressFormat = default(string), string EffectiveCalendarType = default(string), string EffectiveCurrencyCode = default(string), string EffectiveCurrencyNegativeFormat = default(string), string EffectiveCurrencyPositiveFormat = default(string), string EffectiveCustomDateFormat = default(string), string EffectiveCustomTimeFormat = default(string), string EffectiveDateFormat = default(string), string EffectiveInitialFormat = default(string), string EffectiveNameFormat = default(string), string EffectiveTimeFormat = default(string), string EffectiveTimeZone = default(string), string InitialFormat = default(string), SettingsMetadata InitialFormatMetadata = default(SettingsMetadata), string NameFormat = default(string), SettingsMetadata NameFormatMetadata = default(SettingsMetadata), string SignDateFormat = default(string), SettingsMetadata SignDateFormatMetadata = default(SettingsMetadata), string SignTimeFormat = default(string), SettingsMetadata SignTimeFormatMetadata = default(SettingsMetadata), string TimeFormat = default(string), SettingsMetadata TimeFormatMetadata = default(SettingsMetadata), string TimeZone = default(string), SettingsMetadata TimeZoneMetadata = default(SettingsMetadata)) { this.AddressFormat = AddressFormat; this.AddressFormatMetadata = AddressFormatMetadata; this.AllowRegion = AllowRegion; this.CalendarType = CalendarType; this.CalendarTypeMetadata = CalendarTypeMetadata; this.CultureName = CultureName; this.CultureNameMetadata = CultureNameMetadata; this.CurrencyCode = CurrencyCode; this.CurrencyCodeMetadata = CurrencyCodeMetadata; this.CurrencyNegativeFormat = CurrencyNegativeFormat; this.CurrencyNegativeFormatMetadata = CurrencyNegativeFormatMetadata; this.CurrencyPositiveFormat = CurrencyPositiveFormat; this.CurrencyPositiveFormatMetadata = CurrencyPositiveFormatMetadata; this.CustomDateFormat = CustomDateFormat; this.CustomSignDateFormat = CustomSignDateFormat; this.CustomSignTimeFormat = CustomSignTimeFormat; this.CustomTimeFormat = CustomTimeFormat; this.DateFormat = DateFormat; this.DateFormatMetadata = DateFormatMetadata; this.EffectiveAddressFormat = EffectiveAddressFormat; this.EffectiveCalendarType = EffectiveCalendarType; this.EffectiveCurrencyCode = EffectiveCurrencyCode; this.EffectiveCurrencyNegativeFormat = EffectiveCurrencyNegativeFormat; this.EffectiveCurrencyPositiveFormat = EffectiveCurrencyPositiveFormat; this.EffectiveCustomDateFormat = EffectiveCustomDateFormat; this.EffectiveCustomTimeFormat = EffectiveCustomTimeFormat; this.EffectiveDateFormat = EffectiveDateFormat; this.EffectiveInitialFormat = EffectiveInitialFormat; this.EffectiveNameFormat = EffectiveNameFormat; this.EffectiveTimeFormat = EffectiveTimeFormat; this.EffectiveTimeZone = EffectiveTimeZone; this.InitialFormat = InitialFormat; this.InitialFormatMetadata = InitialFormatMetadata; this.NameFormat = NameFormat; this.NameFormatMetadata = NameFormatMetadata; this.SignDateFormat = SignDateFormat; this.SignDateFormatMetadata = SignDateFormatMetadata; this.SignTimeFormat = SignTimeFormat; this.SignTimeFormatMetadata = SignTimeFormatMetadata; this.TimeFormat = TimeFormat; this.TimeFormatMetadata = TimeFormatMetadata; this.TimeZone = TimeZone; this.TimeZoneMetadata = TimeZoneMetadata; } /// <summary> /// Gets or Sets AddressFormat /// </summary> [DataMember(Name="addressFormat", EmitDefaultValue=false)] public string AddressFormat { get; set; } /// <summary> /// Gets or Sets AddressFormatMetadata /// </summary> [DataMember(Name="addressFormatMetadata", EmitDefaultValue=false)] public SettingsMetadata AddressFormatMetadata { get; set; } /// <summary> /// Gets or Sets AllowRegion /// </summary> [DataMember(Name="allowRegion", EmitDefaultValue=false)] public string AllowRegion { get; set; } /// <summary> /// Gets or Sets CalendarType /// </summary> [DataMember(Name="calendarType", EmitDefaultValue=false)] public string CalendarType { get; set; } /// <summary> /// Gets or Sets CalendarTypeMetadata /// </summary> [DataMember(Name="calendarTypeMetadata", EmitDefaultValue=false)] public SettingsMetadata CalendarTypeMetadata { get; set; } /// <summary> /// Gets or Sets CultureName /// </summary> [DataMember(Name="cultureName", EmitDefaultValue=false)] public string CultureName { get; set; } /// <summary> /// Gets or Sets CultureNameMetadata /// </summary> [DataMember(Name="cultureNameMetadata", EmitDefaultValue=false)] public SettingsMetadata CultureNameMetadata { get; set; } /// <summary> /// Gets or Sets CurrencyCode /// </summary> [DataMember(Name="currencyCode", EmitDefaultValue=false)] public string CurrencyCode { get; set; } /// <summary> /// Gets or Sets CurrencyCodeMetadata /// </summary> [DataMember(Name="currencyCodeMetadata", EmitDefaultValue=false)] public SettingsMetadata CurrencyCodeMetadata { get; set; } /// <summary> /// Gets or Sets CurrencyNegativeFormat /// </summary> [DataMember(Name="currencyNegativeFormat", EmitDefaultValue=false)] public string CurrencyNegativeFormat { get; set; } /// <summary> /// Gets or Sets CurrencyNegativeFormatMetadata /// </summary> [DataMember(Name="currencyNegativeFormatMetadata", EmitDefaultValue=false)] public SettingsMetadata CurrencyNegativeFormatMetadata { get; set; } /// <summary> /// Gets or Sets CurrencyPositiveFormat /// </summary> [DataMember(Name="currencyPositiveFormat", EmitDefaultValue=false)] public string CurrencyPositiveFormat { get; set; } /// <summary> /// Gets or Sets CurrencyPositiveFormatMetadata /// </summary> [DataMember(Name="currencyPositiveFormatMetadata", EmitDefaultValue=false)] public SettingsMetadata CurrencyPositiveFormatMetadata { get; set; } /// <summary> /// Gets or Sets CustomDateFormat /// </summary> [DataMember(Name="customDateFormat", EmitDefaultValue=false)] public string CustomDateFormat { get; set; } /// <summary> /// Gets or Sets CustomSignDateFormat /// </summary> [DataMember(Name="customSignDateFormat", EmitDefaultValue=false)] public string CustomSignDateFormat { get; set; } /// <summary> /// Gets or Sets CustomSignTimeFormat /// </summary> [DataMember(Name="customSignTimeFormat", EmitDefaultValue=false)] public string CustomSignTimeFormat { get; set; } /// <summary> /// Gets or Sets CustomTimeFormat /// </summary> [DataMember(Name="customTimeFormat", EmitDefaultValue=false)] public string CustomTimeFormat { get; set; } /// <summary> /// Gets or Sets DateFormat /// </summary> [DataMember(Name="dateFormat", EmitDefaultValue=false)] public string DateFormat { get; set; } /// <summary> /// Gets or Sets DateFormatMetadata /// </summary> [DataMember(Name="dateFormatMetadata", EmitDefaultValue=false)] public SettingsMetadata DateFormatMetadata { get; set; } /// <summary> /// Gets or Sets EffectiveAddressFormat /// </summary> [DataMember(Name="effectiveAddressFormat", EmitDefaultValue=false)] public string EffectiveAddressFormat { get; set; } /// <summary> /// Gets or Sets EffectiveCalendarType /// </summary> [DataMember(Name="effectiveCalendarType", EmitDefaultValue=false)] public string EffectiveCalendarType { get; set; } /// <summary> /// Gets or Sets EffectiveCurrencyCode /// </summary> [DataMember(Name="effectiveCurrencyCode", EmitDefaultValue=false)] public string EffectiveCurrencyCode { get; set; } /// <summary> /// Gets or Sets EffectiveCurrencyNegativeFormat /// </summary> [DataMember(Name="effectiveCurrencyNegativeFormat", EmitDefaultValue=false)] public string EffectiveCurrencyNegativeFormat { get; set; } /// <summary> /// Gets or Sets EffectiveCurrencyPositiveFormat /// </summary> [DataMember(Name="effectiveCurrencyPositiveFormat", EmitDefaultValue=false)] public string EffectiveCurrencyPositiveFormat { get; set; } /// <summary> /// Gets or Sets EffectiveCustomDateFormat /// </summary> [DataMember(Name="effectiveCustomDateFormat", EmitDefaultValue=false)] public string EffectiveCustomDateFormat { get; set; } /// <summary> /// Gets or Sets EffectiveCustomTimeFormat /// </summary> [DataMember(Name="effectiveCustomTimeFormat", EmitDefaultValue=false)] public string EffectiveCustomTimeFormat { get; set; } /// <summary> /// Gets or Sets EffectiveDateFormat /// </summary> [DataMember(Name="effectiveDateFormat", EmitDefaultValue=false)] public string EffectiveDateFormat { get; set; } /// <summary> /// Gets or Sets EffectiveInitialFormat /// </summary> [DataMember(Name="effectiveInitialFormat", EmitDefaultValue=false)] public string EffectiveInitialFormat { get; set; } /// <summary> /// Gets or Sets EffectiveNameFormat /// </summary> [DataMember(Name="effectiveNameFormat", EmitDefaultValue=false)] public string EffectiveNameFormat { get; set; } /// <summary> /// Gets or Sets EffectiveTimeFormat /// </summary> [DataMember(Name="effectiveTimeFormat", EmitDefaultValue=false)] public string EffectiveTimeFormat { get; set; } /// <summary> /// Gets or Sets EffectiveTimeZone /// </summary> [DataMember(Name="effectiveTimeZone", EmitDefaultValue=false)] public string EffectiveTimeZone { get; set; } /// <summary> /// Gets or Sets InitialFormat /// </summary> [DataMember(Name="initialFormat", EmitDefaultValue=false)] public string InitialFormat { get; set; } /// <summary> /// Gets or Sets InitialFormatMetadata /// </summary> [DataMember(Name="initialFormatMetadata", EmitDefaultValue=false)] public SettingsMetadata InitialFormatMetadata { get; set; } /// <summary> /// Gets or Sets NameFormat /// </summary> [DataMember(Name="nameFormat", EmitDefaultValue=false)] public string NameFormat { get; set; } /// <summary> /// Gets or Sets NameFormatMetadata /// </summary> [DataMember(Name="nameFormatMetadata", EmitDefaultValue=false)] public SettingsMetadata NameFormatMetadata { get; set; } /// <summary> /// Gets or Sets SignDateFormat /// </summary> [DataMember(Name="signDateFormat", EmitDefaultValue=false)] public string SignDateFormat { get; set; } /// <summary> /// Gets or Sets SignDateFormatMetadata /// </summary> [DataMember(Name="signDateFormatMetadata", EmitDefaultValue=false)] public SettingsMetadata SignDateFormatMetadata { get; set; } /// <summary> /// Gets or Sets SignTimeFormat /// </summary> [DataMember(Name="signTimeFormat", EmitDefaultValue=false)] public string SignTimeFormat { get; set; } /// <summary> /// Gets or Sets SignTimeFormatMetadata /// </summary> [DataMember(Name="signTimeFormatMetadata", EmitDefaultValue=false)] public SettingsMetadata SignTimeFormatMetadata { get; set; } /// <summary> /// Gets or Sets TimeFormat /// </summary> [DataMember(Name="timeFormat", EmitDefaultValue=false)] public string TimeFormat { get; set; } /// <summary> /// Gets or Sets TimeFormatMetadata /// </summary> [DataMember(Name="timeFormatMetadata", EmitDefaultValue=false)] public SettingsMetadata TimeFormatMetadata { get; set; } /// <summary> /// Gets or Sets TimeZone /// </summary> [DataMember(Name="timeZone", EmitDefaultValue=false)] public string TimeZone { get; set; } /// <summary> /// Gets or Sets TimeZoneMetadata /// </summary> [DataMember(Name="timeZoneMetadata", EmitDefaultValue=false)] public SettingsMetadata TimeZoneMetadata { 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 LocalePolicy {\n"); sb.Append(" AddressFormat: ").Append(AddressFormat).Append("\n"); sb.Append(" AddressFormatMetadata: ").Append(AddressFormatMetadata).Append("\n"); sb.Append(" AllowRegion: ").Append(AllowRegion).Append("\n"); sb.Append(" CalendarType: ").Append(CalendarType).Append("\n"); sb.Append(" CalendarTypeMetadata: ").Append(CalendarTypeMetadata).Append("\n"); sb.Append(" CultureName: ").Append(CultureName).Append("\n"); sb.Append(" CultureNameMetadata: ").Append(CultureNameMetadata).Append("\n"); sb.Append(" CurrencyCode: ").Append(CurrencyCode).Append("\n"); sb.Append(" CurrencyCodeMetadata: ").Append(CurrencyCodeMetadata).Append("\n"); sb.Append(" CurrencyNegativeFormat: ").Append(CurrencyNegativeFormat).Append("\n"); sb.Append(" CurrencyNegativeFormatMetadata: ").Append(CurrencyNegativeFormatMetadata).Append("\n"); sb.Append(" CurrencyPositiveFormat: ").Append(CurrencyPositiveFormat).Append("\n"); sb.Append(" CurrencyPositiveFormatMetadata: ").Append(CurrencyPositiveFormatMetadata).Append("\n"); sb.Append(" CustomDateFormat: ").Append(CustomDateFormat).Append("\n"); sb.Append(" CustomSignDateFormat: ").Append(CustomSignDateFormat).Append("\n"); sb.Append(" CustomSignTimeFormat: ").Append(CustomSignTimeFormat).Append("\n"); sb.Append(" CustomTimeFormat: ").Append(CustomTimeFormat).Append("\n"); sb.Append(" DateFormat: ").Append(DateFormat).Append("\n"); sb.Append(" DateFormatMetadata: ").Append(DateFormatMetadata).Append("\n"); sb.Append(" EffectiveAddressFormat: ").Append(EffectiveAddressFormat).Append("\n"); sb.Append(" EffectiveCalendarType: ").Append(EffectiveCalendarType).Append("\n"); sb.Append(" EffectiveCurrencyCode: ").Append(EffectiveCurrencyCode).Append("\n"); sb.Append(" EffectiveCurrencyNegativeFormat: ").Append(EffectiveCurrencyNegativeFormat).Append("\n"); sb.Append(" EffectiveCurrencyPositiveFormat: ").Append(EffectiveCurrencyPositiveFormat).Append("\n"); sb.Append(" EffectiveCustomDateFormat: ").Append(EffectiveCustomDateFormat).Append("\n"); sb.Append(" EffectiveCustomTimeFormat: ").Append(EffectiveCustomTimeFormat).Append("\n"); sb.Append(" EffectiveDateFormat: ").Append(EffectiveDateFormat).Append("\n"); sb.Append(" EffectiveInitialFormat: ").Append(EffectiveInitialFormat).Append("\n"); sb.Append(" EffectiveNameFormat: ").Append(EffectiveNameFormat).Append("\n"); sb.Append(" EffectiveTimeFormat: ").Append(EffectiveTimeFormat).Append("\n"); sb.Append(" EffectiveTimeZone: ").Append(EffectiveTimeZone).Append("\n"); sb.Append(" InitialFormat: ").Append(InitialFormat).Append("\n"); sb.Append(" InitialFormatMetadata: ").Append(InitialFormatMetadata).Append("\n"); sb.Append(" NameFormat: ").Append(NameFormat).Append("\n"); sb.Append(" NameFormatMetadata: ").Append(NameFormatMetadata).Append("\n"); sb.Append(" SignDateFormat: ").Append(SignDateFormat).Append("\n"); sb.Append(" SignDateFormatMetadata: ").Append(SignDateFormatMetadata).Append("\n"); sb.Append(" SignTimeFormat: ").Append(SignTimeFormat).Append("\n"); sb.Append(" SignTimeFormatMetadata: ").Append(SignTimeFormatMetadata).Append("\n"); sb.Append(" TimeFormat: ").Append(TimeFormat).Append("\n"); sb.Append(" TimeFormatMetadata: ").Append(TimeFormatMetadata).Append("\n"); sb.Append(" TimeZone: ").Append(TimeZone).Append("\n"); sb.Append(" TimeZoneMetadata: ").Append(TimeZoneMetadata).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 string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as LocalePolicy); } /// <summary> /// Returns true if LocalePolicy instances are equal /// </summary> /// <param name="other">Instance of LocalePolicy to be compared</param> /// <returns>Boolean</returns> public bool Equals(LocalePolicy other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AddressFormat == other.AddressFormat || this.AddressFormat != null && this.AddressFormat.Equals(other.AddressFormat) ) && ( this.AddressFormatMetadata == other.AddressFormatMetadata || this.AddressFormatMetadata != null && this.AddressFormatMetadata.Equals(other.AddressFormatMetadata) ) && ( this.AllowRegion == other.AllowRegion || this.AllowRegion != null && this.AllowRegion.Equals(other.AllowRegion) ) && ( this.CalendarType == other.CalendarType || this.CalendarType != null && this.CalendarType.Equals(other.CalendarType) ) && ( this.CalendarTypeMetadata == other.CalendarTypeMetadata || this.CalendarTypeMetadata != null && this.CalendarTypeMetadata.Equals(other.CalendarTypeMetadata) ) && ( this.CultureName == other.CultureName || this.CultureName != null && this.CultureName.Equals(other.CultureName) ) && ( this.CultureNameMetadata == other.CultureNameMetadata || this.CultureNameMetadata != null && this.CultureNameMetadata.Equals(other.CultureNameMetadata) ) && ( this.CurrencyCode == other.CurrencyCode || this.CurrencyCode != null && this.CurrencyCode.Equals(other.CurrencyCode) ) && ( this.CurrencyCodeMetadata == other.CurrencyCodeMetadata || this.CurrencyCodeMetadata != null && this.CurrencyCodeMetadata.Equals(other.CurrencyCodeMetadata) ) && ( this.CurrencyNegativeFormat == other.CurrencyNegativeFormat || this.CurrencyNegativeFormat != null && this.CurrencyNegativeFormat.Equals(other.CurrencyNegativeFormat) ) && ( this.CurrencyNegativeFormatMetadata == other.CurrencyNegativeFormatMetadata || this.CurrencyNegativeFormatMetadata != null && this.CurrencyNegativeFormatMetadata.Equals(other.CurrencyNegativeFormatMetadata) ) && ( this.CurrencyPositiveFormat == other.CurrencyPositiveFormat || this.CurrencyPositiveFormat != null && this.CurrencyPositiveFormat.Equals(other.CurrencyPositiveFormat) ) && ( this.CurrencyPositiveFormatMetadata == other.CurrencyPositiveFormatMetadata || this.CurrencyPositiveFormatMetadata != null && this.CurrencyPositiveFormatMetadata.Equals(other.CurrencyPositiveFormatMetadata) ) && ( this.CustomDateFormat == other.CustomDateFormat || this.CustomDateFormat != null && this.CustomDateFormat.Equals(other.CustomDateFormat) ) && ( this.CustomSignDateFormat == other.CustomSignDateFormat || this.CustomSignDateFormat != null && this.CustomSignDateFormat.Equals(other.CustomSignDateFormat) ) && ( this.CustomSignTimeFormat == other.CustomSignTimeFormat || this.CustomSignTimeFormat != null && this.CustomSignTimeFormat.Equals(other.CustomSignTimeFormat) ) && ( this.CustomTimeFormat == other.CustomTimeFormat || this.CustomTimeFormat != null && this.CustomTimeFormat.Equals(other.CustomTimeFormat) ) && ( this.DateFormat == other.DateFormat || this.DateFormat != null && this.DateFormat.Equals(other.DateFormat) ) && ( this.DateFormatMetadata == other.DateFormatMetadata || this.DateFormatMetadata != null && this.DateFormatMetadata.Equals(other.DateFormatMetadata) ) && ( this.EffectiveAddressFormat == other.EffectiveAddressFormat || this.EffectiveAddressFormat != null && this.EffectiveAddressFormat.Equals(other.EffectiveAddressFormat) ) && ( this.EffectiveCalendarType == other.EffectiveCalendarType || this.EffectiveCalendarType != null && this.EffectiveCalendarType.Equals(other.EffectiveCalendarType) ) && ( this.EffectiveCurrencyCode == other.EffectiveCurrencyCode || this.EffectiveCurrencyCode != null && this.EffectiveCurrencyCode.Equals(other.EffectiveCurrencyCode) ) && ( this.EffectiveCurrencyNegativeFormat == other.EffectiveCurrencyNegativeFormat || this.EffectiveCurrencyNegativeFormat != null && this.EffectiveCurrencyNegativeFormat.Equals(other.EffectiveCurrencyNegativeFormat) ) && ( this.EffectiveCurrencyPositiveFormat == other.EffectiveCurrencyPositiveFormat || this.EffectiveCurrencyPositiveFormat != null && this.EffectiveCurrencyPositiveFormat.Equals(other.EffectiveCurrencyPositiveFormat) ) && ( this.EffectiveCustomDateFormat == other.EffectiveCustomDateFormat || this.EffectiveCustomDateFormat != null && this.EffectiveCustomDateFormat.Equals(other.EffectiveCustomDateFormat) ) && ( this.EffectiveCustomTimeFormat == other.EffectiveCustomTimeFormat || this.EffectiveCustomTimeFormat != null && this.EffectiveCustomTimeFormat.Equals(other.EffectiveCustomTimeFormat) ) && ( this.EffectiveDateFormat == other.EffectiveDateFormat || this.EffectiveDateFormat != null && this.EffectiveDateFormat.Equals(other.EffectiveDateFormat) ) && ( this.EffectiveInitialFormat == other.EffectiveInitialFormat || this.EffectiveInitialFormat != null && this.EffectiveInitialFormat.Equals(other.EffectiveInitialFormat) ) && ( this.EffectiveNameFormat == other.EffectiveNameFormat || this.EffectiveNameFormat != null && this.EffectiveNameFormat.Equals(other.EffectiveNameFormat) ) && ( this.EffectiveTimeFormat == other.EffectiveTimeFormat || this.EffectiveTimeFormat != null && this.EffectiveTimeFormat.Equals(other.EffectiveTimeFormat) ) && ( this.EffectiveTimeZone == other.EffectiveTimeZone || this.EffectiveTimeZone != null && this.EffectiveTimeZone.Equals(other.EffectiveTimeZone) ) && ( this.InitialFormat == other.InitialFormat || this.InitialFormat != null && this.InitialFormat.Equals(other.InitialFormat) ) && ( this.InitialFormatMetadata == other.InitialFormatMetadata || this.InitialFormatMetadata != null && this.InitialFormatMetadata.Equals(other.InitialFormatMetadata) ) && ( this.NameFormat == other.NameFormat || this.NameFormat != null && this.NameFormat.Equals(other.NameFormat) ) && ( this.NameFormatMetadata == other.NameFormatMetadata || this.NameFormatMetadata != null && this.NameFormatMetadata.Equals(other.NameFormatMetadata) ) && ( this.SignDateFormat == other.SignDateFormat || this.SignDateFormat != null && this.SignDateFormat.Equals(other.SignDateFormat) ) && ( this.SignDateFormatMetadata == other.SignDateFormatMetadata || this.SignDateFormatMetadata != null && this.SignDateFormatMetadata.Equals(other.SignDateFormatMetadata) ) && ( this.SignTimeFormat == other.SignTimeFormat || this.SignTimeFormat != null && this.SignTimeFormat.Equals(other.SignTimeFormat) ) && ( this.SignTimeFormatMetadata == other.SignTimeFormatMetadata || this.SignTimeFormatMetadata != null && this.SignTimeFormatMetadata.Equals(other.SignTimeFormatMetadata) ) && ( this.TimeFormat == other.TimeFormat || this.TimeFormat != null && this.TimeFormat.Equals(other.TimeFormat) ) && ( this.TimeFormatMetadata == other.TimeFormatMetadata || this.TimeFormatMetadata != null && this.TimeFormatMetadata.Equals(other.TimeFormatMetadata) ) && ( this.TimeZone == other.TimeZone || this.TimeZone != null && this.TimeZone.Equals(other.TimeZone) ) && ( this.TimeZoneMetadata == other.TimeZoneMetadata || this.TimeZoneMetadata != null && this.TimeZoneMetadata.Equals(other.TimeZoneMetadata) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.AddressFormat != null) hash = hash * 59 + this.AddressFormat.GetHashCode(); if (this.AddressFormatMetadata != null) hash = hash * 59 + this.AddressFormatMetadata.GetHashCode(); if (this.AllowRegion != null) hash = hash * 59 + this.AllowRegion.GetHashCode(); if (this.CalendarType != null) hash = hash * 59 + this.CalendarType.GetHashCode(); if (this.CalendarTypeMetadata != null) hash = hash * 59 + this.CalendarTypeMetadata.GetHashCode(); if (this.CultureName != null) hash = hash * 59 + this.CultureName.GetHashCode(); if (this.CultureNameMetadata != null) hash = hash * 59 + this.CultureNameMetadata.GetHashCode(); if (this.CurrencyCode != null) hash = hash * 59 + this.CurrencyCode.GetHashCode(); if (this.CurrencyCodeMetadata != null) hash = hash * 59 + this.CurrencyCodeMetadata.GetHashCode(); if (this.CurrencyNegativeFormat != null) hash = hash * 59 + this.CurrencyNegativeFormat.GetHashCode(); if (this.CurrencyNegativeFormatMetadata != null) hash = hash * 59 + this.CurrencyNegativeFormatMetadata.GetHashCode(); if (this.CurrencyPositiveFormat != null) hash = hash * 59 + this.CurrencyPositiveFormat.GetHashCode(); if (this.CurrencyPositiveFormatMetadata != null) hash = hash * 59 + this.CurrencyPositiveFormatMetadata.GetHashCode(); if (this.CustomDateFormat != null) hash = hash * 59 + this.CustomDateFormat.GetHashCode(); if (this.CustomSignDateFormat != null) hash = hash * 59 + this.CustomSignDateFormat.GetHashCode(); if (this.CustomSignTimeFormat != null) hash = hash * 59 + this.CustomSignTimeFormat.GetHashCode(); if (this.CustomTimeFormat != null) hash = hash * 59 + this.CustomTimeFormat.GetHashCode(); if (this.DateFormat != null) hash = hash * 59 + this.DateFormat.GetHashCode(); if (this.DateFormatMetadata != null) hash = hash * 59 + this.DateFormatMetadata.GetHashCode(); if (this.EffectiveAddressFormat != null) hash = hash * 59 + this.EffectiveAddressFormat.GetHashCode(); if (this.EffectiveCalendarType != null) hash = hash * 59 + this.EffectiveCalendarType.GetHashCode(); if (this.EffectiveCurrencyCode != null) hash = hash * 59 + this.EffectiveCurrencyCode.GetHashCode(); if (this.EffectiveCurrencyNegativeFormat != null) hash = hash * 59 + this.EffectiveCurrencyNegativeFormat.GetHashCode(); if (this.EffectiveCurrencyPositiveFormat != null) hash = hash * 59 + this.EffectiveCurrencyPositiveFormat.GetHashCode(); if (this.EffectiveCustomDateFormat != null) hash = hash * 59 + this.EffectiveCustomDateFormat.GetHashCode(); if (this.EffectiveCustomTimeFormat != null) hash = hash * 59 + this.EffectiveCustomTimeFormat.GetHashCode(); if (this.EffectiveDateFormat != null) hash = hash * 59 + this.EffectiveDateFormat.GetHashCode(); if (this.EffectiveInitialFormat != null) hash = hash * 59 + this.EffectiveInitialFormat.GetHashCode(); if (this.EffectiveNameFormat != null) hash = hash * 59 + this.EffectiveNameFormat.GetHashCode(); if (this.EffectiveTimeFormat != null) hash = hash * 59 + this.EffectiveTimeFormat.GetHashCode(); if (this.EffectiveTimeZone != null) hash = hash * 59 + this.EffectiveTimeZone.GetHashCode(); if (this.InitialFormat != null) hash = hash * 59 + this.InitialFormat.GetHashCode(); if (this.InitialFormatMetadata != null) hash = hash * 59 + this.InitialFormatMetadata.GetHashCode(); if (this.NameFormat != null) hash = hash * 59 + this.NameFormat.GetHashCode(); if (this.NameFormatMetadata != null) hash = hash * 59 + this.NameFormatMetadata.GetHashCode(); if (this.SignDateFormat != null) hash = hash * 59 + this.SignDateFormat.GetHashCode(); if (this.SignDateFormatMetadata != null) hash = hash * 59 + this.SignDateFormatMetadata.GetHashCode(); if (this.SignTimeFormat != null) hash = hash * 59 + this.SignTimeFormat.GetHashCode(); if (this.SignTimeFormatMetadata != null) hash = hash * 59 + this.SignTimeFormatMetadata.GetHashCode(); if (this.TimeFormat != null) hash = hash * 59 + this.TimeFormat.GetHashCode(); if (this.TimeFormatMetadata != null) hash = hash * 59 + this.TimeFormatMetadata.GetHashCode(); if (this.TimeZone != null) hash = hash * 59 + this.TimeZone.GetHashCode(); if (this.TimeZoneMetadata != null) hash = hash * 59 + this.TimeZoneMetadata.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
54.24967
2,249
0.599265
[ "MIT" ]
MaxMood96/docusign-esign-csharp-client
sdk/src/DocuSign.eSign/Model/LocalePolicy.cs
41,067
C#
namespace Xamarin.Forms.Controls.GalleryPages.AppThemeGalleries { public class AppThemeGallery : ContentPage { public AppThemeGallery() { var descriptionLabel = new Label { Text = "AppTheme Galleries", Margin = new Thickness(2, 2, 2, 2) }; Title = "AppTheme Galleries"; var button = new Button { Text = "Enable AppTheme", AutomationId = "EnableAppTheme" }; button.Clicked += ButtonClicked; Content = new ScrollView { Content = new StackLayout { Children = { descriptionLabel, button, GalleryBuilder.NavButton("AppTheme Code", () => new AppThemeCodeGallery(), Navigation), GalleryBuilder.NavButton("AppTheme XAML", () => new AppThemeXamlGallery(), Navigation), GalleryBuilder.NavButton("GetNamedColor", () => new NamedPlatformColorGallery(), Navigation) } } }; } void ButtonClicked(object sender, System.EventArgs e) { var button = sender as Button; button.Text = "AppTheme Enabled!"; button.TextColor = Color.Black; button.IsEnabled = false; } } }
23.404255
85
0.648182
[ "MIT" ]
AlleSchonWeg/Xamarin.Forms
Xamarin.Forms.Controls/GalleryPages/AppThemeGalleries/AppThemeGallery.cs
1,102
C#
namespace MoogleEngine { public class WordWeigther { public char Operator { get; set;} public string Word { get; set; } public float Weigth { get; set; } public WordWeigther(string word, float weigth, char operators) { Word = word; Weigth = weigth; Operator = operators; } } }
23.375
70
0.540107
[ "MIT" ]
davidalba2001/First_project_moogle-2021-main
MoogleEngine/WordWeigther.cs
374
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace jabbR.Services { public class IChatService { } }
14.166667
33
0.735294
[ "Apache-2.0" ]
BrennanConroy/jabbR
src/Services/IChatService.cs
172
C#
namespace Unity.MARS.Companion.Core { /// <summary> /// Delegate used by the IssueHandling framework when an issue is requested. /// Implementers of <see cref="IUsesIssueHandling"/> must subscribe and handle /// how the request is presented to the user. /// </summary> /// <param name="request">The request data struct.</param> public delegate void IssueHandlingRequested(in IssueHandlingRequest request); /// <summary> /// The callback that signals the issue has been handled by user action /// </summary> /// <param name="result">The results struct that contains the results of the user's decision (if applicable)</param> public delegate void IssueHandledCallback(IssueHandlingResult result); }
44.882353
121
0.695937
[ "Apache-2.0" ]
bsides44/MARSGeofencing
MARS geofencing/Library/PackageCache/com.unity.mars-companion-core@0.3.11-preview/Runtime/Scripts/IssueHandling/IssueHandlingCallbacks.cs
765
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Text; using System.Threading.Tasks; #if nope namespace CitizenFX.Core { public class RageFileStream : Stream { private IntPtr m_handle; [SecuritySafeCritical] internal RageFileStream(string fileName) { // attempt opening the file m_handle = GameInterface.OpenFile(fileName); if (m_handle == IntPtr.Zero) { throw new IOException("Could not open RAGE file " + fileName + " for reading."); } } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override bool CanSeek { get { return false; } } [SecuritySafeCritical] public override int Read(byte[] buffer, int offset, int count) { return GameInterface.ReadFile(m_handle, buffer, offset, count); } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void Flush() { throw new NotImplementedException(); } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [SecuritySafeCritical] public override void Close() { GameInterface.CloseFile(m_handle); base.Close(); } public override long Length { [SecuritySafeCritical] get { return GameInterface.GetFileLength(m_handle); } } } } #endif
23.707071
97
0.504474
[ "MIT" ]
0x965/fivem
code/client/clrcore/RageFileStream.cs
2,349
C#
// Generated on 03/23/2022 09:50:13 using System; using System.Collections.Generic; using System.Linq; using AmaknaProxy.API.Protocol.Types; using AmaknaProxy.API.IO; using AmaknaProxy.API.Network; namespace AmaknaProxy.API.Protocol.Messages { public class ReloginTokenRequestMessage : NetworkMessage { public const uint Id = 9853; public override uint MessageId { get { return Id; } } public ReloginTokenRequestMessage() { } public override void Serialize(IDataWriter writer) { } public override void Deserialize(IDataReader reader) { } } }
19.756757
60
0.588235
[ "MIT" ]
ImNotARobot742/DofusProtocol
DofusProtocol/D2Parser/Protocol/Messages/game/approach/ReloginTokenRequestMessage.cs
731
C#
namespace ElectronicElections.Data.Models { public enum ElectionTypeId { NationalAssembly = 0, PresidentalElections = 1, EuropeanParliament = 2 } }
18.5
42
0.643243
[ "MIT" ]
siderisltd/ElectronicElections
src/ElectronicElections.Data/Models/ElectionTypeId.cs
187
C#
using Lucene.Net.Index; using Lucene.Net.Util.Mutable; using System; namespace Lucene.Net.Queries.Function.DocValues { /* * 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. */ /// <summary> /// Abstract <see cref="FunctionValues"/> implementation which supports retrieving <see cref="long"/> values. /// Implementations can control how the <see cref="long"/> values are loaded through <see cref="Int64Val(int)"/> /// <para/> /// NOTE: This was LongDocValues in Lucene /// </summary> public abstract class Int64DocValues : FunctionValues { protected readonly ValueSource m_vs; public Int64DocValues(ValueSource vs) { this.m_vs = vs; } public override byte ByteVal(int doc) { return (byte)Int64Val(doc); } /// <summary> /// NOTE: This was shortVal() in Lucene /// </summary> public override short Int16Val(int doc) { return (short)Int64Val(doc); } /// <summary> /// NOTE: This was floatVal() in Lucene /// </summary> public override float SingleVal(int doc) { return (float)Int64Val(doc); } /// <summary> /// NOTE: This was intVal() in Lucene /// </summary> public override int Int32Val(int doc) { return (int)Int64Val(doc); } public override abstract long Int64Val(int doc); public override double DoubleVal(int doc) { return (double)Int64Val(doc); } public override bool BoolVal(int doc) { return Int64Val(doc) != 0; } public override string StrVal(int doc) // LUCENENET TODO: API - Add overload to include CultureInfo ? { return Convert.ToString(Int64Val(doc)); } public override object ObjectVal(int doc) { return Exists(doc) ? Int64Val(doc) : (long?)null; } public override string ToString(int doc) { return m_vs.GetDescription() + '=' + StrVal(doc); } /// <summary> /// NOTE: This was externalToLong() in Lucene /// </summary> protected virtual long ExternalToInt64(string extVal) // LUCENENET TODO: API - Add overload to include CultureInfo ? { return Convert.ToInt64(extVal); } public override ValueSourceScorer GetRangeScorer(IndexReader reader, string lowerVal, string upperVal, bool includeLower, bool includeUpper) { long lower, upper; // instead of using separate comparison functions, adjust the endpoints. if (lowerVal == null) { lower = long.MinValue; } else { lower = ExternalToInt64(lowerVal); if (!includeLower && lower < long.MaxValue) { lower++; } } if (upperVal == null) { upper = long.MaxValue; } else { upper = ExternalToInt64(upperVal); if (!includeUpper && upper > long.MinValue) { upper--; } } long ll = lower; long uu = upper; return new ValueSourceScorer.AnonymousValueSourceScorer(reader, this, matchesValue: (doc) => { long val = Int64Val(doc); // only check for deleted if it's the default value // if (val==0 && reader.isDeleted(doc)) return false; return val >= ll && val <= uu; }); } public override ValueFiller GetValueFiller() { return new ValueFiller.AnonymousValueFiller<MutableValueInt64>(new MutableValueInt64(), fillValue: (doc, mutableValue) => { mutableValue.Value = Int64Val(doc); mutableValue.Exists = Exists(doc); }); } } }
31.737179
148
0.551808
[ "Apache-2.0" ]
sreejukg/lucenenet
src/Lucene.Net.Queries/Function/DocValues/LongDocValues.cs
4,953
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the appmesh-2019-01-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.AppMesh.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AppMesh.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ListenerTlsCertificate Object /// </summary> public class ListenerTlsCertificateUnmarshaller : IUnmarshaller<ListenerTlsCertificate, XmlUnmarshallerContext>, IUnmarshaller<ListenerTlsCertificate, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ListenerTlsCertificate IUnmarshaller<ListenerTlsCertificate, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ListenerTlsCertificate Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ListenerTlsCertificate unmarshalledObject = new ListenerTlsCertificate(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("acm", targetDepth)) { var unmarshaller = ListenerTlsAcmCertificateUnmarshaller.Instance; unmarshalledObject.Acm = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("file", targetDepth)) { var unmarshaller = ListenerTlsFileCertificateUnmarshaller.Instance; unmarshalledObject.File = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ListenerTlsCertificateUnmarshaller _instance = new ListenerTlsCertificateUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ListenerTlsCertificateUnmarshaller Instance { get { return _instance; } } } }
35.438776
179
0.640656
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Services/AppMesh/Generated/Model/Internal/MarshallTransformations/ListenerTlsCertificateUnmarshaller.cs
3,473
C#
namespace ResourcesCalculator.Models { public class BuildingItem { public long Id { get; set; } public string Name { get; set; } public string Resource { get; set; } } }
22.777778
44
0.6
[ "MIT" ]
Tierbolg/ResourcesCalculator
ResourcesCalculator/Models/BuildingItem.cs
205
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace NBi.Testing.Acceptance.Resources { /// <summary> /// This class is only used for acceptance testing purpose /// </summary> class AssemblyClass { public AssemblyClass() { } /// <summary> /// Method returning a valid MDX query /// </summary> /// <param name="calendarYear">A year between 2005 and 2008 preceded by 'CY'</param> /// <returns>Valid MDX query</returns> public string GetSelectMdx(string calendarYear) { var mdx = $"SELECT [Measures].[Reseller Order Count] ON 0, [Date].[Calendar Year].[{calendarYear}] ON 1 FROM [Adventure Works]"; return mdx; } public enum Measure { FirstMeasure = 0, OrderCount = 1 } /// <summary> /// Method returning a valid MDX query if the param Measure is equal to OrderCount else an invalid MDX statement /// </summary> /// <param name="year">a calendar year without the 'CY'</param> /// <param name="measure"></param> /// <returns></returns> public string GetSelectMdxWithTwoParams(int year, Measure measure) { if (measure == Measure.OrderCount) return $"SELECT [Measures].[Reseller Order Count] ON 0, [Date].[Calendar Year].[CY {year}] ON 1 FROM [Adventure Works]"; else return "Incorrect Query"; } public string GetTextSelectSql(string prefix) { return $@"select '{prefix} 2005', 366 union all select '{prefix} 2006', 1015 union all select '{prefix} 2007', 1521 union all select '{prefix} 2008', 894"; } public IDbCommand GetCommandSelectSql(string prefix) { var cmd = new SqlCommand(); cmd.CommandText = $@"select '{prefix} 2005', 366 union all select '{prefix} 2006', 1015 union all select '{prefix} 2007', 1521 union all select '{prefix} 2008', 894"; return cmd; } public DataSet GetDataSetSelectSql(string prefix, string connectionString) { using (var da = new SqlDataAdapter($@"select '{prefix} 2005', 366 union all select '{prefix} 2006', 1015 union all select '{prefix} 2007', 1521 union all select '{prefix} 2008', 894", connectionString)) { var ds = new DataSet(); da.Fill(ds); return ds; } } public DataTable GetDataTableSelectSql(string prefix, string connectionString) { return GetDataSetSelectSql(prefix, connectionString).Tables[0]; } } }
32.677419
141
0.538335
[ "Apache-2.0" ]
CoolsJoris/NBi
NBi.Testing/Acceptance/Resources/AssemblyClass.cs
3,041
C#
using System; using System.IO; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using UnityEngine; using HarmonyLib; namespace DysonSphereProgram.Modding.Blackbox { public class BlackboxSelection { public readonly int factoryIndex; public readonly WeakReference<PlanetFactory> factoryRef; public readonly ImmutableSortedSet<int> entityIds; public readonly ImmutableSortedSet<int> pcIds; public readonly ImmutableSortedSet<int> assemblerIds; public readonly ImmutableSortedSet<int> labIds; public readonly ImmutableSortedSet<int> inserterIds; public readonly ImmutableSortedSet<int> stationIds; public readonly ImmutableSortedSet<int> cargoPathIds; public readonly ImmutableSortedSet<int> splitterIds; public readonly ImmutableSortedSet<int> pilerIds; public readonly ImmutableSortedSet<int> spraycoaterIds; public readonly ImmutableSortedSet<int> monitorIds; public readonly ImmutableSortedSet<int> fractionatorIds; public readonly ImmutableSortedSet<int> itemIds; private BlackboxSelection( PlanetFactory factory , ImmutableSortedSet<int> entityIds , ImmutableSortedSet<int> pcIds , ImmutableSortedSet<int> assemblerIds , ImmutableSortedSet<int> labIds , ImmutableSortedSet<int> inserterIds , ImmutableSortedSet<int> stationIds , ImmutableSortedSet<int> cargoPathIds , ImmutableSortedSet<int> splitterIds , ImmutableSortedSet<int> pilerIds , ImmutableSortedSet<int> spraycoaterIds , ImmutableSortedSet<int> monitorIds , ImmutableSortedSet<int> fractionatorIds , ImmutableSortedSet<int> itemIds ) { this.factoryIndex = factory.index; this.factoryRef = new WeakReference<PlanetFactory>(factory); this.entityIds = entityIds; this.pcIds = pcIds; this.assemblerIds = assemblerIds; this.labIds = labIds; this.inserterIds = inserterIds; this.stationIds = stationIds; this.cargoPathIds = cargoPathIds; this.splitterIds = splitterIds; this.pilerIds = pilerIds; this.spraycoaterIds = spraycoaterIds; this.monitorIds = monitorIds; this.fractionatorIds = fractionatorIds; this.itemIds = itemIds; } public static BlackboxSelection CreateFrom(PlanetFactory factory, ICollection<int> entityIds) { var tmp_stationIds = new List<int>(); var tmp_assemblerIds = new List<int>(); //var tmp_assemblerTimeSpends = new List<int>(); var tmp_inserterIds = new List<int>(); var tmp_labIds = new List<int>(); var tmp_pcIds = new List<int>(); var tmp_itemIds = new HashSet<int>(); var tmp_cargoPathIds = new HashSet<int>(); var tmp_splitterIds = new List<int>(); var tmp_pilerIds = new List<int>(); var tmp_spraycoaterIds = new List<int>(); var tmp_monitorIds = new List<int>(); var tmp_fractionatorIds = new List<int>(); foreach (var entityId in entityIds) { if (entityId < 0) continue; ref readonly var entity = ref factory.entityPool[entityId]; if (entity.stationId > 0) { tmp_stationIds.Add(entity.stationId); ref readonly var station = ref factory.transport.stationPool[entity.stationId]; for (int j = 0; j < station.storage.Length; j++) { var stationStorage = station.storage[j]; var effectiveLogic = stationStorage.remoteLogic == ELogisticStorage.None ? stationStorage.localLogic : stationStorage.remoteLogic; if (effectiveLogic != ELogisticStorage.None && stationStorage.itemId > 0) tmp_itemIds.Add(stationStorage.itemId); } } if (entity.assemblerId > 0) { tmp_assemblerIds.Add(entity.assemblerId); ref readonly var assembler = ref factory.factorySystem.assemblerPool[entity.assemblerId]; if (assembler.recipeId > 0) { //tmp_assemblerTimeSpends.Add(assembler.timeSpend / assembler.speed); for (int i = 0; i < assembler.requires.Length; i++) tmp_itemIds.Add(assembler.requires[i]); for (int i = 0; i < assembler.products.Length; i++) tmp_itemIds.Add(assembler.products[i]); tmp_pcIds.Add(entity.powerConId); } } if (entity.inserterId > 0) { tmp_inserterIds.Add(entity.inserterId); tmp_pcIds.Add(entity.powerConId); } if (entity.labId > 0) { ref readonly var lab = ref factory.factorySystem.labPool[entity.labId]; if (lab.matrixMode && lab.recipeId > 0) { tmp_labIds.Add(entity.labId); //tmp_assemblerTimeSpends.Add(lab.timeSpend / 10000); for (int i = 0; i < lab.requires.Length; i++) tmp_itemIds.Add(lab.requires[i]); for (int i = 0; i < lab.products.Length; i++) tmp_itemIds.Add(lab.products[i]); tmp_pcIds.Add(entity.powerConId); } } if (entity.beltId > 0) { ref readonly var belt = ref factory.cargoTraffic.beltPool[entity.beltId]; tmp_cargoPathIds.Add(belt.segPathId); } if (entity.splitterId > 0) { tmp_splitterIds.Add(entity.splitterId); } if (entity.pilerId > 0) { tmp_pilerIds.Add(entity.pilerId); tmp_pcIds.Add(entity.powerConId); } if (entity.spraycoaterId > 0) { tmp_spraycoaterIds.Add(entity.spraycoaterId); tmp_pcIds.Add(entity.powerConId); } if (entity.monitorId > 0) { tmp_monitorIds.Add(entity.monitorId); tmp_pcIds.Add(entity.powerConId); } if (entity.fractionatorId > 0) { tmp_fractionatorIds.Add(entity.fractionatorId); tmp_pcIds.Add(entity.powerConId); } } var pcIds = tmp_pcIds.ToImmutableSortedSet(); var assemblerIds = tmp_assemblerIds.ToImmutableSortedSet(); var stationIds = tmp_stationIds.ToImmutableSortedSet(); var inserterIds = tmp_inserterIds.ToImmutableSortedSet(); var labIds = tmp_labIds.ToImmutableSortedSet(); var itemIds = tmp_itemIds.ToImmutableSortedSet(); var cargoPathIds = tmp_cargoPathIds.ToImmutableSortedSet(); var splitterIds = tmp_splitterIds.ToImmutableSortedSet(); var pilerIds = tmp_pilerIds.ToImmutableSortedSet(); var spraycoaterIds = tmp_spraycoaterIds.ToImmutableSortedSet(); var monitorIds = tmp_monitorIds.ToImmutableSortedSet(); var fractionatorIds = tmp_fractionatorIds.ToImmutableSortedSet(); var entityIdsSet = entityIds.ToImmutableSortedSet(); return new BlackboxSelection( factory , entityIdsSet , pcIds , assemblerIds , labIds , inserterIds , stationIds , cargoPathIds , splitterIds , pilerIds , spraycoaterIds , monitorIds , fractionatorIds , itemIds ); } public static BlackboxSelection Expand(BlackboxSelection selection) { if (!selection.factoryRef.TryGetTarget(out var factory)) { Plugin.Log.LogError("PlanetFactory instance pulled out from under " + nameof(BlackboxSelection) + " in " + nameof(Expand)); return selection; } var entityPool = factory.entityPool; var stationPool = factory.transport.stationPool; var beltPool = factory.cargoTraffic.beltPool; var yetToExpandEntityIds = new Queue<int>(); var expandedEntityIds = ImmutableSortedSet.CreateBuilder<int>(); var stations = from x in selection.stationIds select factory.transport.stationPool[x] ; foreach (var station in stations) yetToExpandEntityIds.Enqueue(station.entityId); BFS(yetToExpandEntityIds, expandedEntityIds, factory); var invalidEntityIds = new HashSet<int>(); var stationEntityIds = new HashSet<int>(); var expandedStations = new HashSet<StationComponent>(); foreach (var entityId in expandedEntityIds) { if (IsInvalid(entityId, factory)) invalidEntityIds.Add(entityId); ref readonly var entity = ref entityPool[entityId]; if (entity.stationId > 0) { stationEntityIds.Add(entityId); expandedStations.Add(stationPool[entity.stationId]); } } // Remove invalid entities from the expanded selection var yetToExpandInvalidEntityIds = new Queue<int>(); var expandedInvalidEntityIds = new HashSet<int>(); while (invalidEntityIds.Count != 0) { var invalidEntityId = invalidEntityIds.First(); yetToExpandInvalidEntityIds.Clear(); yetToExpandInvalidEntityIds.Enqueue(invalidEntityId); expandedInvalidEntityIds.Clear(); expandedInvalidEntityIds.UnionWith(stationEntityIds); BFS(yetToExpandInvalidEntityIds, expandedInvalidEntityIds, factory); expandedInvalidEntityIds.ExceptWith(stationEntityIds); expandedEntityIds.ExceptWith(expandedInvalidEntityIds); invalidEntityIds.ExceptWith(expandedInvalidEntityIds); } const int warperItemId = 1210; // Remove warper belts foreach (var station in expandedStations) { foreach (var slot in station.slots) { if (slot.storageIdx <= 0 || slot.dir != IODir.Output || slot.beltId <= 0) continue; var storageIdx = slot.storageIdx - 1; var itemId = storageIdx < station.storage.Length ? station.storage[storageIdx].itemId : warperItemId; if (itemId != warperItemId) continue; var beltEntityId = beltPool[slot.beltId].entityId; yetToExpandInvalidEntityIds.Clear(); yetToExpandInvalidEntityIds.Enqueue(beltEntityId); expandedInvalidEntityIds.Clear(); expandedInvalidEntityIds.UnionWith(stationEntityIds); BFS(yetToExpandInvalidEntityIds, expandedInvalidEntityIds, factory); expandedInvalidEntityIds.ExceptWith(stationEntityIds); expandedEntityIds.ExceptWith(expandedInvalidEntityIds); } } return BlackboxSelection.CreateFrom(factory, expandedEntityIds); } private static void BFS(Queue<int> yetToExpandEntityIds, ISet<int> expandedEntityIds, PlanetFactory factory) { while (yetToExpandEntityIds.Count != 0) { var entityIdToExpand = yetToExpandEntityIds.Dequeue(); expandedEntityIds.Add(entityIdToExpand); for (int i = 0; i < 16; i++) { factory.ReadObjectConn(entityIdToExpand, i, out _, out var otherEntityId, out _); if (otherEntityId == 0) continue; if (!expandedEntityIds.Contains(otherEntityId) && !yetToExpandEntityIds.Contains(otherEntityId)) yetToExpandEntityIds.Enqueue(otherEntityId); } } } public static bool IsInvalid(BlackboxSelection selection) { if (!selection.factoryRef.TryGetTarget(out var factory)) { Plugin.Log.LogError("PlanetFactory instance pulled out from under " + nameof(BlackboxSelection) + " in " + nameof(IsInvalid)); return true; } foreach (var entityId in selection.entityIds) { if (IsInvalid(entityId, factory)) return true; } if (selection.stationIds.Count == 0) return true; if (selection.assemblerIds.Count == 0 && selection.labIds.Count == 0 && selection.fractionatorIds.Count == 0) return true; return false; } private static bool IsInvalid(int entityId, PlanetFactory factory) { if (entityId < 0) return true; ref readonly var entity = ref factory.entityPool[entityId]; if (entity.minerId > 0) return true; if (entity.beltId > 0) return false; if (entity.splitterId > 0) return false; if (entity.pilerId > 0) return false; if (entity.spraycoaterId > 0) return false; if (entity.monitorId > 0) return false; if (entity.fractionatorId > 0) return false; if (entity.inserterId > 0) return false; if (entity.assemblerId > 0) return false; if (entity.labId > 0) { ref readonly var lab = ref factory.factorySystem.labPool[entity.labId]; if (!lab.researchMode) return false; } if (entity.stationId > 0) return false; return true; } const int saveLogicVersion = 1; public void Export(BinaryWriter w) { w.Write(saveLogicVersion); w.Write(factoryIndex); w.Write(entityIds.Count); for (int i = 0; i < entityIds.Count; i++) w.Write(entityIds[i]); } public static BlackboxSelection Import(BinaryReader r) { var saveLogicVersion = r.ReadInt32(); var factoryIndex = r.ReadInt32(); var entityIdsCount = r.ReadInt32(); var entityIds = new int[entityIdsCount]; for (int i = 0; i < entityIdsCount; i++) { entityIds[i] = r.ReadInt32(); } var factory = GameMain.data.factories[factoryIndex]; return BlackboxSelection.CreateFrom(factory, entityIds); } } }
34.378173
142
0.640162
[ "MIT" ]
Velociraptor115/DSPMods_Blackbox
Blackbox/BlackboxSelection.cs
13,545
C#
namespace TestSchoolApp { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using SchoolApplication; using System.Linq; [TestClass] public class TestCourse { private const string ValidCourse = "Programing"; private const string StudentValid = "Petar"; [TestMethod] [ExpectedException(typeof(ArgumentException))] [TestCategory("Course")] public void ShouldThrowException_WhenCreatingACourseWithNoName() { var course = new Course(""); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [TestCategory("Course")] public void ShouldThrowException_WhenCreatingACourseWithNameContainigSpaces() { var course = new Course(" "); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [TestCategory("Course")] public void ShouldThrowException_WhenCreatingACourseWithNameNull() { var course = new Course(null); } [TestMethod] [TestCategory("Course")] public void IncreasingStudensInCourse_WhenAddingStudents() { var course = new Course(ValidCourse); var student = new Student(StudentValid, 15000); course.AddStudentToCourse(student); Assert.AreEqual(1, course.NumberOfStudents.Count); } [TestMethod] [TestCategory("Course")] public void DecreasingStudensInCourse_WhenRemovingStudents() { var course = new Course(ValidCourse); var student1 = new Student(StudentValid, 15000); var student2 = new Student("Ivancho", 13000); course.AddStudentToCourse(student1); course.AddStudentToCourse(student2); course.RemovestudentFromCourse(student1); var sorted = course.NumberOfStudents.OrderBy(x => x.StudentID > 10000); Assert.AreEqual(sorted.Count(), 1); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [TestCategory("Course")] public void CourseShouldThrowError_WhenTryingToRemoveNotExistingStudent() { var course = new Course(ValidCourse); var student = new Student("Petar", 15000); course.RemovestudentFromCourse(student); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [TestCategory("Course")] public void CourseShouldThrowError_WhenTryingToExceedLimitOf30People() { var course = new Course(ValidCourse); for (int i = 0; i < 32; i++) { course.AddStudentToCourse(new Student(StudentValid + i, 15000 + i)); } } } }
32.609195
85
0.607332
[ "MIT" ]
VVoev/Telerik-Academy
07.Unit Testing with C#/01. Unit Testing/Homework/TestSchoolUnitTesting/TestSchoolApp/TestCourse.cs
2,839
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 PatanHospital { public partial class DeletePatient { /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// ImageButton1 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.ImageButton ImageButton1; /// <summary> /// HyperLink1 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 HyperLink1; /// <summary> /// DropDownList1 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.DropDownList DropDownList1; /// <summary> /// SqlDataSource1 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.SqlDataSource SqlDataSource1; /// <summary> /// Button3 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.Button Button3; /// <summary> /// Label1 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.Label Label1; /// <summary> /// table2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlTable table2; /// <summary> /// TextBox1 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 TextBox1; /// <summary> /// TextBox2 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 TextBox2; /// <summary> /// TextBox3 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 TextBox3; /// <summary> /// TextBox4 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 TextBox4; /// <summary> /// Button4 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.Button Button4; /// <summary> /// Button5 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.Button Button5; } }
34.704225
84
0.534903
[ "Apache-2.0" ]
richa615/PatanHospital
PatanHospital/DeletePatient.aspx.designer.cs
4,930
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Target : MonoBehaviour { public float health = 50f; public void TakeDamage(float amount){ health -= amount; if(health <= 0f){ Die(); } } void Die(){ Destroy(gameObject); } }
14.409091
41
0.621451
[ "MIT" ]
DanielYang432/SDD-Task-2-Assessment
Assets/Scripts/Target.cs
317
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 TVAutoFakeServer2.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.7
151
0.5845
[ "Apache-2.0" ]
daoxuanhung/TVAutoFakeServer2
TVAutoFakeServer2/Properties/Settings.Designer.cs
1,073
C#
namespace Movies.Web.ViewModels.Account { using System.ComponentModel.DataAnnotations; public class LoginViewModel { [Required] [Display(Name = "Email")] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } }
24.15
48
0.585921
[ "MIT" ]
puhabg/Template
Movies/Web/Movies.Web/ViewModels/Account/LoginViewModel.cs
485
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { public class DelistedIndexOptionDivestedRegression : QCAlgorithm, IRegressionAlgorithmDefinition { private Symbol _spx; private Symbol _optionSymbol; private DateTime _optionExpiry = DateTime.MaxValue; private string _ticker; private bool _addOption = true; private bool _receivedWarning; public override void Initialize() { SetStartDate(2021, 1, 3); //Set Start Date SetEndDate(2021, 1, 20); //Set End Date _ticker = "SPX"; var spxSecurity = AddIndex(_ticker, Resolution.Minute); spxSecurity.SetDataNormalizationMode(DataNormalizationMode.Raw); _spx = spxSecurity.Symbol; } public override void OnData(Slice slice) { if (!slice.ContainsKey(_spx)) { return; } if (_addOption) { var contracts = OptionChainProvider.GetOptionContractList(_spx, Time); contracts = contracts.Where(x => x.ID.OptionRight == OptionRight.Put && x.ID.Date.Date == new DateTime(2021, 1, 15)); var option = AddIndexOptionContract(contracts.First(), Resolution.Minute); _optionExpiry = option.Expiry; _optionSymbol = option.Symbol; _addOption = false; } if (slice.ContainsKey(_optionSymbol)) { if (!Portfolio.Invested) { SetHoldings(_optionSymbol, 0.25); } // Verify the order of delisting; warning then delisting Delisting delisting; if (slice.Delistings.TryGetValue(_optionSymbol, out delisting)) { switch (delisting.Type) { case DelistingType.Warning: _receivedWarning = true; break; case DelistingType.Delisted: if (!_receivedWarning) { throw new Exception("Did not receive warning before delisting"); } break; } } // Verify we aren't receiving expired option data. if (_optionExpiry < Time.Date) { throw new Exception($"Received expired contract {_optionSymbol} expired: {_optionExpiry} current time: {Time}"); } } } public override void OnEndOfAlgorithm() { foreach (var holding in Portfolio.Values) { Log($"Holding {holding.Symbol.Value}; Invested: {holding.Invested}; Quantity: {holding.Quantity}"); if (holding.Symbol == _optionSymbol && holding.Invested) { throw new Exception($"Index option {_optionSymbol.Value} is still invested after delisting"); } } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp }; /// <summary> /// Data Points count of all timeslices of algorithm /// </summary> public long DataPoints => 17600; /// <summary> /// Data Points count of the algorithm history /// </summary> public int AlgorithmHistoryDataPoints => 0; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "2"}, {"Average Win", "0%"}, {"Average Loss", "-26.40%"}, {"Compounding Annual Return", "-99.821%"}, {"Drawdown", "45.600%"}, {"Expectancy", "-1"}, {"Net Profit", "-26.400%"}, {"Sharpe Ratio", "-0.602"}, {"Probabilistic Sharpe Ratio", "19.127%"}, {"Loss Rate", "100%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "-0.559"}, {"Beta", "-0.807"}, {"Annual Standard Deviation", "1.582"}, {"Annual Variance", "2.502"}, {"Information Ratio", "-0.905"}, {"Tracking Error", "1.593"}, {"Treynor Ratio", "1.181"}, {"Total Fees", "$0.00"}, {"Estimated Strategy Capacity", "$1000000.00"}, {"Lowest Capacity Asset", "SPX 31KC0UJFONTBI|SPX 31"}, {"Fitness Score", "0.005"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-0.249"}, {"Return Over Maximum Drawdown", "-2.699"}, {"Portfolio Turnover", "0.016"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "721fddfd1327f7adcc2883d1412708c9"} }; } }
38.786885
146
0.53973
[ "Apache-2.0" ]
AsquaredXIV/Lean
Algorithm.CSharp/DelistedIndexOptionDivestedRegression.cs
7,098
C#
// <auto-generated /> // Built from: hl7.fhir.r4b.core version: 4.1.0 // Option: "NAMESPACE" = "fhirCsR4" using fhirCsR4.Models; namespace fhirCsR4.ValueSets { /// <summary> /// The value set to instantiate this attribute should be drawn from a terminologically robust code system that consists of or contains concepts to support describing the reasons why a given recommendation status is assigned. This value set is provided as a suggestive example and includes SNOMED CT concepts. /// </summary> public static class ImmunizationRecommendationReasonCodes { /// <summary> /// /// </summary> public static readonly Coding VAL77176002 = new Coding { Code = "77176002", System = "http://snomed.info/sct" }; /// <summary> /// /// </summary> public static readonly Coding VAL77386006 = new Coding { Code = "77386006", System = "http://snomed.info/sct" }; /// <summary> /// Literal for code: VAL77176002 /// </summary> public const string LiteralVAL77176002 = "77176002"; /// <summary> /// Literal for code: VAL77386006 /// </summary> public const string LiteralVAL77386006 = "77386006"; }; }
28.857143
311
0.653465
[ "MIT" ]
GinoCanessa/Subscription-CS-Endpoint
src/Fhir/R4B/ValueSets/ImmunizationRecommendationReason.cs
1,212
C#
using System; namespace BarcodeLib.Symbologies { /// <summary> /// Pharmacode encoding /// Written by: Brad Barnhill /// </summary> class Pharmacode: BarcodeCommon, IBarcode { string _thinBar = "1"; string _gap = "00"; string _thickBar = "111"; /// <summary> /// Encodes with Pharmacode. /// </summary> /// <param name="input">Data to encode.</param> public Pharmacode(string input) { Raw_Data = input; if (!CheckNumericOnly(Raw_Data)) { Error("EPHARM-1: Data contains invalid characters (non-numeric)."); }//if else if (Raw_Data.Length > 6) { Error("EPHARM-2: Data too long (invalid data input length)."); }//if } /// <summary> /// Encode the raw data using the Pharmacode algorithm. /// </summary> private string Encode_Pharmacode() { int num; if (!Int32.TryParse(Raw_Data, out num)) { Error("EPHARM-3: Input is unparseable."); } else if (num < 3 || num > 131070) { Error("EPHARM-4: Data contains invalid characters (invalid numeric range)."); }//if string result = String.Empty; do { if ((num & 1) == 0) { result = _thickBar + result; num = (num - 2) / 2; } else { result = _thinBar + result; num = (num - 1) / 2; } if (num != 0) { result = _gap + result; } } while (num != 0); return result; } #region IBarcode Members public string Encoded_Value { get { return Encode_Pharmacode(); } } #endregion } }
25.195122
94
0.424976
[ "Apache-2.0" ]
9200237/barcodelib
BarcodeStandard/Symbologies/Pharmacode.cs
2,068
C#
/* * Elemental Annotations <https://github.com/takeshik/ElementalAnnotations> * Copyright © 2015 Takeshi KIRIYA (aka takeshik) <takeshik@tksk.io> * Licensed under the zlib License; for details, see the website. */ using System; using System.Diagnostics; // ReSharper disable CheckNamespace #if ELEMENTAL_ANNOTATIONS_DEFAULT_NAMESPACE namespace Elemental.Annotations #else namespace BattleInfoPlugin.Annotations #endif // ReSharper restore CheckNamespace { [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [Conditional("DEBUG")] public class LightAttribute : ElementalAttribute { public const string Name = "Light"; public LightAttribute(string description = null) : base(description) { } } partial class CodeElement { public const string Light = LightAttribute.Name; } }
22.611111
75
0.767813
[ "MIT" ]
CirnoV/BattleInfoPlugin
BattleInfoPlugin/Annotations/LightAttribute.cs
815
C#
// // PackedByteArrayTests.cs // // Author: Jeffrey Stedfast <jestedfa@microsoft.com> // // Copyright (c) 2013-2018 Xamarin Inc. (www.xamarin.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; using NUnit.Framework; using MimeKit.Utils; namespace UnitTests.Utils { [TestFixture] public class PackedByteArrayTests { [Test] public void TestArgumentExceptions () { var packed = new PackedByteArray (); Assert.Throws<ArgumentNullException> (() => packed.CopyTo (null, 0)); Assert.Throws<ArgumentOutOfRangeException> (() => packed.CopyTo (new byte[16], -1)); } [Test] public void TestBasicFunctionality () { var packed = new PackedByteArray (); var expected = new byte[1024]; var buffer = new byte[1024]; int index = 0; for (int i = 0; i < 257; i++) { expected[index++] = (byte) 'A'; packed.Add ((byte) 'A'); } for (int i = 1; i < 26; i++) { expected[index++] = (byte) ('A' + i); packed.Add ((byte) ('A' + i)); } for (int i = 0; i < 128; i++) { expected[index++] = (byte) 'B'; packed.Add ((byte) 'B'); } Assert.AreEqual (index, packed.Count, "Count"); packed.CopyTo (buffer, 0); for (int i = 0; i < index; i++) Assert.AreEqual (expected[i], buffer[i], "buffer[{0}]", i); } } }
29.833333
87
0.675978
[ "MIT" ]
humayun-ahmed/MimeKit
UnitTests/Utils/PackedByteArrayTests.cs
2,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 robomaker-2018-06-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RoboMaker.Model { /// <summary> /// Container for the parameters to the ListDeploymentJobs operation. /// Returns a list of deployment jobs for a fleet. You can optionally provide filters /// to retrieve specific deployment jobs. /// </summary> public partial class ListDeploymentJobsRequest : AmazonRoboMakerRequest { private List<Filter> _filters = new List<Filter>(); private int? _maxResults; private string _nextToken; /// <summary> /// Gets and sets the property Filters. /// <para> /// Optional filters to limit results. /// </para> /// /// <para> /// The filter names <code>status</code> and <code>fleetName</code> are supported. When /// filtering, you must use the complete value of the filtered item. You can use up to /// three filters, but they must be for the same named item. For example, if you are looking /// for items with the status <code>InProgress</code> or the status <code>Pending</code>. /// </para> /// </summary> [AWSProperty(Min=1, Max=1)] public List<Filter> Filters { get { return this._filters; } set { this._filters = value; } } // Check to see if Filters property is set internal bool IsSetFilters() { return this._filters != null && this._filters.Count > 0; } /// <summary> /// Gets and sets the property MaxResults. /// <para> /// When this parameter is used, <code>ListDeploymentJobs</code> only returns <code>maxResults</code> /// results in a single page along with a <code>nextToken</code> response element. The /// remaining results of the initial request can be seen by sending another <code>ListDeploymentJobs</code> /// request with the returned <code>nextToken</code> value. This value can be between /// 1 and 200. If this parameter is not used, then <code>ListDeploymentJobs</code> returns /// up to 200 results and a <code>nextToken</code> value if applicable. /// </para> /// </summary> public int MaxResults { get { return this._maxResults.GetValueOrDefault(); } set { this._maxResults = value; } } // Check to see if MaxResults property is set internal bool IsSetMaxResults() { return this._maxResults.HasValue; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// The <code>nextToken</code> value returned from a previous paginated <code>ListDeploymentJobs</code> /// request where <code>maxResults</code> was used and the results exceeded the value /// of that parameter. Pagination continues from the end of the previous results that /// returned the <code>nextToken</code> value. /// </para> /// </summary> [AWSProperty(Min=1, Max=2048)] public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
37.522124
115
0.623349
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/RoboMaker/Generated/Model/ListDeploymentJobsRequest.cs
4,240
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Security.Principal; using Xunit; namespace System.Security.AccessControl.Tests { public class CommonSecurityDescriptor_Owner { public static IEnumerable<object[]> CommonSecurityDescriptor_Owner_TestData() { yield return new object[] { null }; yield return new object[] { "S-1-0-0" }; yield return new object[] { "S-1-1-0" }; yield return new object[] { "S-1-2-0" }; yield return new object[] { "S-1-3-0" }; yield return new object[] { "S-1-4-0" }; yield return new object[] { "S-1-5-0" }; yield return new object[] { "S-1-6-0" }; yield return new object[] { "S-1-7-0" }; yield return new object[] { "S-1-8-0" }; yield return new object[] { "S-1-9-0" }; yield return new object[] { "S-1-10-0" }; yield return new object[] { "S-1-11-0" }; yield return new object[] { "S-1-5-0" }; yield return new object[] { "S-1-5-0-1-2-3-4-5-6-7" }; yield return new object[] { "S-1-5-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14" }; yield return new object[] { "S-1-0-0" }; yield return new object[] { "S-1-1-0" }; yield return new object[] { "S-1-2-0" }; yield return new object[] { "S-1-3-0" }; yield return new object[] { "S-1-3-1" }; yield return new object[] { "S-1-3-2" }; yield return new object[] { "S-1-3-3" }; yield return new object[] { "S-1-5-1" }; yield return new object[] { "S-1-5-2" }; yield return new object[] { "S-1-5-3" }; yield return new object[] { "S-1-5-4" }; yield return new object[] { "S-1-5-6" }; yield return new object[] { "S-1-5-7" }; yield return new object[] { "S-1-5-8" }; yield return new object[] { "S-1-5-9" }; yield return new object[] { "S-1-5-10" }; yield return new object[] { "S-1-5-11" }; yield return new object[] { "S-1-5-12" }; yield return new object[] { "S-1-5-13" }; yield return new object[] { "S-1-5-14" }; yield return new object[] { "S-1-5-18" }; yield return new object[] { "S-1-5-19" }; yield return new object[] { "S-1-5-20" }; yield return new object[] { "S-1-5-32" }; yield return new object[] { "S-1-5-32-544" }; yield return new object[] { "S-1-5-32-545" }; yield return new object[] { "S-1-5-32-546" }; yield return new object[] { "S-1-5-32-547" }; yield return new object[] { "S-1-5-32-548" }; yield return new object[] { "S-1-5-32-549" }; yield return new object[] { "S-1-5-32-550" }; yield return new object[] { "S-1-5-32-551" }; yield return new object[] { "S-1-5-32-552" }; yield return new object[] { "S-1-5-32-554" }; yield return new object[] { "S-1-5-32-555" }; yield return new object[] { "S-1-5-32-556-0" }; } [Theory] [MemberData(nameof(CommonSecurityDescriptor_Owner_TestData))] public static void TestOwner(string newOwnerStr) { bool isContainer = false; bool isDS = false; int controlFlags = 1; string ownerStr = "BA"; string groupStr = "BG"; CommonSecurityDescriptor commonSecurityDescriptor = null; SecurityIdentifier owner = new SecurityIdentifier( Utils.TranslateStringConstFormatSidToStandardFormatSid(ownerStr) ); SecurityIdentifier newOwner = ( newOwnerStr != null ? new SecurityIdentifier( Utils.TranslateStringConstFormatSidToStandardFormatSid(newOwnerStr) ) : null ); SecurityIdentifier group = new SecurityIdentifier( Utils.TranslateStringConstFormatSidToStandardFormatSid(groupStr) ); SystemAcl sacl = null; DiscretionaryAcl dacl = null; commonSecurityDescriptor = new CommonSecurityDescriptor( isContainer, isDS, (ControlFlags)controlFlags, owner, group, sacl, dacl ); commonSecurityDescriptor.Owner = newOwner; // verify the result, we can use == here as SecurityIdentifier overrides the comparsison Assert.True(newOwner == commonSecurityDescriptor.Owner); } } }
44.590909
100
0.519062
[ "MIT" ]
belav/runtime
src/libraries/System.Security.AccessControl/tests/CommonSecurityDescriptor/CommonSecurityDescriptor_Owner.cs
4,905
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Gcp.Compute.Outputs { [OutputType] public sealed class URLMapPathMatcherPathRuleRouteActionCorsPolicy { /// <summary> /// In response to a preflight request, setting this to true indicates that the actual request can include user credentials. /// This translates to the Access-Control-Allow-Credentials header. /// </summary> public readonly bool? AllowCredentials; /// <summary> /// Specifies the content for the Access-Control-Allow-Headers header. /// </summary> public readonly ImmutableArray<string> AllowHeaders; /// <summary> /// Specifies the content for the Access-Control-Allow-Methods header. /// </summary> public readonly ImmutableArray<string> AllowMethods; /// <summary> /// Specifies the regular expression patterns that match allowed origins. For regular expression grammar /// please see en.cppreference.com/w/cpp/regex/ecmascript /// An origin is allowed if it matches either an item in allowOrigins or an item in allowOriginRegexes. /// </summary> public readonly ImmutableArray<string> AllowOriginRegexes; /// <summary> /// Specifies the list of origins that will be allowed to do CORS requests. /// An origin is allowed if it matches either an item in allowOrigins or an item in allowOriginRegexes. /// </summary> public readonly ImmutableArray<string> AllowOrigins; /// <summary> /// If true, specifies the CORS policy is disabled. The default value is false, which indicates that the CORS policy is in effect. /// </summary> public readonly bool Disabled; /// <summary> /// Specifies the content for the Access-Control-Expose-Headers header. /// </summary> public readonly ImmutableArray<string> ExposeHeaders; /// <summary> /// Specifies how long results of a preflight request can be cached in seconds. /// This translates to the Access-Control-Max-Age header. /// </summary> public readonly int? MaxAge; [OutputConstructor] private URLMapPathMatcherPathRuleRouteActionCorsPolicy( bool? allowCredentials, ImmutableArray<string> allowHeaders, ImmutableArray<string> allowMethods, ImmutableArray<string> allowOriginRegexes, ImmutableArray<string> allowOrigins, bool disabled, ImmutableArray<string> exposeHeaders, int? maxAge) { AllowCredentials = allowCredentials; AllowHeaders = allowHeaders; AllowMethods = allowMethods; AllowOriginRegexes = allowOriginRegexes; AllowOrigins = allowOrigins; Disabled = disabled; ExposeHeaders = exposeHeaders; MaxAge = maxAge; } } }
39.39759
138
0.651376
[ "ECL-2.0", "Apache-2.0" ]
la3mmchen/pulumi-gcp
sdk/dotnet/Compute/Outputs/URLMapPathMatcherPathRuleRouteActionCorsPolicy.cs
3,270
C#
namespace ATF.Repository.ExpressionConverters { using System; using System.Linq.Expressions; public static class SimpleAggregationExpressionConverter { internal static ExpressionMetadata Convert(MethodCallExpression expression, ExpressionModelMetadata modelMetadata) { var body = ExpressionConverterUtilities.GetSecondArgumentExpression(expression); if (!ExpressionConverterUtilities.TryGetColumnMemberPath(body, modelMetadata, out var path)) { throw new NotSupportedException(); } var response = ExpressionConverterUtilities.GetColumnMetadata(body.Type, path); response.MethodName = expression.Method.Name; return response; } } }
34.947368
118
0.808735
[ "MIT" ]
Advance-Technologies-Foundation/repository
ATF.Repository/ExpressionConverters/SimpleAggregationExpressionConverter.cs
666
C#
namespace Hybrid.Zero.IdentityServer4.Services.Dtos { public class ApiResourcePropertyDto { public int Id { get; set; } public string Key { get; set; } public string Value { get; set; } } }
22.7
52
0.61674
[ "Apache-2.0" ]
ArcherTrister/ESoftor
src/Hybrid.Zero.IdentityServer4/Services/Dtos/ApiResourcePropertyDto.cs
229
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; /* Euler Problem 19 Keith Fletcher Jun 2017 This file is Unlicensed. See the foot of the file, or refer to <http://unlicense.org> */ namespace HisRoyalRedness.com { [Title("Counting Sundays")] [Solution("")] public class Problem19 : ProblemBase { protected override string InternalSolve() { return ""; } } } /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org> */
30.508772
71
0.751006
[ "Unlicense" ]
HisRoyalRedness/ProjectEuler
EulerProblems/1 to 100/1 to 25/Problem019.cs
1,741
C#
// <auto-generated /> using DataStructureOfTheDay.Server.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using System; namespace DataStructureOfTheDay.Server.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.0.0-rc1.19455.8") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("DataStructureOfTheDay.Server.Models.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.DeviceFlowCodes", b => { b.Property<string>("UserCode") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(50000); b.Property<string>("DeviceCode") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<DateTime?>("Expiration") .IsRequired() .HasColumnType("datetime2"); b.Property<string>("SubjectId") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.HasKey("UserCode"); b.HasIndex("DeviceCode") .IsUnique(); b.HasIndex("Expiration"); b.ToTable("DeviceCodes"); }); modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b => { b.Property<string>("Key") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(50000); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.Property<string>("SubjectId") .HasColumnType("nvarchar(200)") .HasMaxLength(200); b.Property<string>("Type") .IsRequired() .HasColumnType("nvarchar(50)") .HasMaxLength(50); b.HasKey("Key"); b.HasIndex("Expiration"); b.HasIndex("SubjectId", "ClientId", "Type"); b.ToTable("PersistedGrants"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("DataStructureOfTheDay.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("DataStructureOfTheDay.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("DataStructureOfTheDay.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("DataStructureOfTheDay.Server.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
37.410615
125
0.458224
[ "MIT" ]
dkintop/DataStructureOfTheDay
DataStructureOfTheDay/Server/Data/Migrations/ApplicationDbContextModelSnapshot.cs
13,393
C#
using System; namespace FireflySoft.RateLimit.Core { /// <summary> /// The type of statistics start time /// </summary> public enum StartTimeType { /// <summary> /// From the current time. /// </summary> FromCurrent = 1, /// <summary> /// From the beginning of the natural period. /// In this way, the statistical time window must be an integer and coincide with the natural time period. /// </summary> FromNaturalPeriodBeign = 2 } }
25.333333
114
0.577068
[ "Apache-2.0" ]
Neos-Metaverse/FireflySoft.RateLimit
FireflySoft.RateLimit.Core/Rule/StartTimeType.cs
534
C#
using System; using System.Collections.Generic; using System.Text; namespace Zeph.Core.Questing { public class QuestingSystem { //public static bool ObjectiveProgressed(Classes.PlayerQuestObjective pqo, int progress) { // //Progress the playerQuestObjective object // pqo.pqo_Progress += progress; // //Get the quest objective // var qo = new Classes.QuestObjective(pqo.pqo_QuestObjective); // if (qo.qo_Goal <= pqo.pqo_Progress) { // //Quest finished // pqo.pqo_Status = Enums.PlayerQuestObjectiveStatus.Complete; // var playerQuest = new Classes.PlayerQuest(pqo.pqo_PlayerQuest); // if (playerQuest.IsQuestComplete()) { // playerQuest.pq_Status = Enums.PlayerQuestStatus.Complete; // } // } //} public static void Initialise() { Inventory.InventorySystem.OnItemAdded += (s, e) => { GatherProgress(e.Player, e.Item); }; Inventory.InventorySystem.OnItemRemoved += (s, e) => { GatherProgress(e.Player, e.Item); }; Zones.ZoneSystem.OnZoneEntered += (s, e) => { if (e.Trigger != null) { TriggerProgress(e.Player, e.Trigger, 1); } }; var combatSystem = SystemLocator.GetService<Combat.ICombatSystem>(); combatSystem.OnNPCDeath += (s, e) => { if (e.Reason.source == Combat.DeathSource.Player) { DefeatProgress(e.Reason.player, e.NPC, 1); } }; } public static Classes.PlayerQuest Start(Zeph.Core.Classes.Player player, Classes.Quest quest) { var pq = new Classes.PlayerQuest(player, quest, quest.QuestObjectives); return Classes.PlayerQuest.Save(pq); } public static Classes.PlayerQuest HandIn(Zeph.Core.Classes.Player player, Classes.Quest quest) { foreach (var pq in Zeph.Core.Classes.PlayerQuest.Read()) { if (pq.pq_Player.p_ID == player.p_ID && pq.pq_Quest.q_ID == quest.q_ID) { if (pq.pq_Finished.Year != 1900 && !pq.pq_HandedIn) { //Can hand in return HandIn(pq); } } } return null; } public static Classes.PlayerQuest HandIn(Classes.PlayerQuest pq) { pq.pq_HandedIn = true; return Zeph.Core.Classes.PlayerQuest.Save(pq, false); } public static QuestProgressResult TriggerProgress(Zeph.Core.Classes.Player player, Classes.Trigger trigger, int progress) { return logProgressOnQuest(player, (qo, pqo) => { if (qo.qo_Type == Enums.QuestObjectiveType.Trigger && qo.qo_Trigger == trigger.t_ID) { //Progress! woo pqo.pqo_Progress += progress; return true; } else { return false; } }); } public static QuestProgressResult GatherProgress(Zeph.Core.Classes.Player player, Classes.Item item) { return logProgressOnQuest(player, (qo, pqo) => { if (qo.qo_Type == Enums.QuestObjectiveType.Gather && qo.qo_Item == item.i_ID) { //get the total quantity of this item the player has in inventory in total var quantityInInventory = SystemLocator.GetService<Inventory.IInventorySystem>().GetQuantity(player, item); bool wasProgressLogged = false; if (quantityInInventory > qo.qo_Goal) { pqo.pqo_Progress = qo.qo_Goal; wasProgressLogged = true; } else { if (pqo.pqo_Progress != quantityInInventory) { wasProgressLogged = true; pqo.pqo_Progress = quantityInInventory; } } return wasProgressLogged; } else { return false; } }); } public static QuestProgressResult DefeatProgress(Zeph.Core.Classes.Player player, Classes.NPC npc, int progress) { return logProgressOnQuest(player, (qo, pqo) => { if (qo.qo_Type == Enums.QuestObjectiveType.Defeat && qo.qo_NPC == npc.npc_ID) { //Progress! woo pqo.pqo_Progress += progress; return true; } else { return false; } }); } /// <summary> /// /// </summary> /// <param name="player"></param> /// <param name="fn">The function which gets called to perform the progress on the <see cref="Classes.PlayerQuestObjective"/> object. Return true if actual progress was logged towards the players quest.</param> /// <returns></returns> private static QuestProgressResult logProgressOnQuest(Zeph.Core.Classes.Player player, Func<Classes.QuestObjective, Classes.PlayerQuestObjective, bool> fn) { var res = new QuestProgressResult(); //Get all quests for player who have current objectives of type item. // If quest bojective item is this item, work out how many of this item the player has in inventory in total, log progress var playersCurrentPlayerQuests = Classes.PlayerQuest.Read(); foreach (var pq in playersCurrentPlayerQuests) { if (pq.pq_Finished.Year == 1900 && //not finished pq.pq_Player.p_ID == player.p_ID) { bool anObjectiveWasFinished = false; foreach (var pqo in pq.PlayerQuestObjectives) { var qo = Classes.QuestObjective.Read(pqo.pqo_QuestObjective); if (pqo.pqo_Progress != qo.qo_Goal) { //is not finished if (fn(qo, pqo)) { //Progress! woo var _pqo = Classes.PlayerQuestObjective.Save(pqo); bool finishedObjective = _pqo.pqo_Progress == qo.qo_Goal; if (finishedObjective) anObjectiveWasFinished = true; res.progressed = true; res.objectiveResults.Add(new QuestProgressObjectiveResult() { playerQuestObjective = _pqo, finished = finishedObjective }); } } } if (anObjectiveWasFinished) { bool theresAnObjectiveUnfinished = false; foreach (var pqo in pq.PlayerQuestObjectives) { var qo = Classes.QuestObjective.Read(pqo.pqo_QuestObjective); if (pqo.pqo_Progress != qo.qo_Goal) { //is not finished theresAnObjectiveUnfinished = true; break; } } if (!theresAnObjectiveUnfinished) { pq.pq_Finished = DateTime.Now; var _pq = Classes.PlayerQuest.Save(pq); res.questsFinished.Add(_pq); } } } } return res; } } public class QuestProgressObjectiveResult { public Classes.PlayerQuestObjective playerQuestObjective = null; public bool finished = false; } public class QuestProgressResult { public List<QuestProgressObjectiveResult> objectiveResults = new List<QuestProgressObjectiveResult>(); public List<Classes.PlayerQuest> questsFinished = new List<Classes.PlayerQuest>(); public bool progressed = false; } }
42.817708
218
0.521226
[ "Apache-2.0" ]
the-kings-man/Zeph
Zeph/ZephCore/Questing/QuestingSystem.cs
8,223
C#
namespace Views { partial class frmFuncionario { /// <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.lbNome_PF = new System.Windows.Forms.Label(); this.lbCpf_PF = new System.Windows.Forms.Label(); this.lbEmail_PF = new System.Windows.Forms.Label(); this.lbEndereco_PF = new System.Windows.Forms.Label(); this.textNome_PF = new System.Windows.Forms.TextBox(); this.textCpf_PF = new System.Windows.Forms.TextBox(); this.textEmail_PF = new System.Windows.Forms.TextBox(); this.textEndereco_PF = new System.Windows.Forms.TextBox(); this.btnSalvarPessoaFisica = new System.Windows.Forms.Button(); this.btnVoltarFrmPF = new System.Windows.Forms.Button(); this.SuspendLayout(); // // lbNome_PF // this.lbNome_PF.AutoSize = true; this.lbNome_PF.Location = new System.Drawing.Point(31, 58); this.lbNome_PF.Name = "lbNome_PF"; this.lbNome_PF.Size = new System.Drawing.Size(35, 13); this.lbNome_PF.TabIndex = 0; this.lbNome_PF.Text = "Nome"; // // lbCpf_PF // this.lbCpf_PF.AutoSize = true; this.lbCpf_PF.Location = new System.Drawing.Point(34, 164); this.lbCpf_PF.Name = "lbCpf_PF"; this.lbCpf_PF.Size = new System.Drawing.Size(27, 13); this.lbCpf_PF.TabIndex = 1; this.lbCpf_PF.Text = "CPF"; // // lbEmail_PF // this.lbEmail_PF.AutoSize = true; this.lbEmail_PF.Location = new System.Drawing.Point(34, 293); this.lbEmail_PF.Name = "lbEmail_PF"; this.lbEmail_PF.Size = new System.Drawing.Size(35, 13); this.lbEmail_PF.TabIndex = 2; this.lbEmail_PF.Text = "E-mail"; // // lbEndereco_PF // this.lbEndereco_PF.AutoSize = true; this.lbEndereco_PF.Location = new System.Drawing.Point(34, 423); this.lbEndereco_PF.Name = "lbEndereco_PF"; this.lbEndereco_PF.Size = new System.Drawing.Size(53, 13); this.lbEndereco_PF.TabIndex = 3; this.lbEndereco_PF.Text = "Endereço"; // // textNome_PF // this.textNome_PF.Location = new System.Drawing.Point(37, 89); this.textNome_PF.Name = "textNome_PF"; this.textNome_PF.Size = new System.Drawing.Size(376, 20); this.textNome_PF.TabIndex = 4; // // textCpf_PF // this.textCpf_PF.Location = new System.Drawing.Point(37, 198); this.textCpf_PF.Name = "textCpf_PF"; this.textCpf_PF.Size = new System.Drawing.Size(160, 20); this.textCpf_PF.TabIndex = 5; // // textEmail_PF // this.textEmail_PF.Location = new System.Drawing.Point(37, 336); this.textEmail_PF.Name = "textEmail_PF"; this.textEmail_PF.Size = new System.Drawing.Size(231, 20); this.textEmail_PF.TabIndex = 6; // // textEndereco_PF // this.textEndereco_PF.Location = new System.Drawing.Point(37, 456); this.textEndereco_PF.Name = "textEndereco_PF"; this.textEndereco_PF.Size = new System.Drawing.Size(407, 20); this.textEndereco_PF.TabIndex = 7; // // btnSalvarPessoaFisica // this.btnSalvarPessoaFisica.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnSalvarPessoaFisica.Location = new System.Drawing.Point(1135, 605); this.btnSalvarPessoaFisica.Name = "btnSalvarPessoaFisica"; this.btnSalvarPessoaFisica.Size = new System.Drawing.Size(75, 23); this.btnSalvarPessoaFisica.TabIndex = 8; this.btnSalvarPessoaFisica.Text = "Salvar"; this.btnSalvarPessoaFisica.UseVisualStyleBackColor = true; this.btnSalvarPessoaFisica.Click += new System.EventHandler(this.salvarFuncionario); // // btnVoltarFrmPF // this.btnVoltarFrmPF.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnVoltarFrmPF.Location = new System.Drawing.Point(1054, 605); this.btnVoltarFrmPF.Name = "btnVoltarFrmPF"; this.btnVoltarFrmPF.Size = new System.Drawing.Size(75, 23); this.btnVoltarFrmPF.TabIndex = 9; this.btnVoltarFrmPF.Text = "Voltar"; this.btnVoltarFrmPF.UseVisualStyleBackColor = true; this.btnVoltarFrmPF.Click += new System.EventHandler(this.voltar); // // frmFuncionario // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1222, 640); this.Controls.Add(this.btnVoltarFrmPF); this.Controls.Add(this.btnSalvarPessoaFisica); this.Controls.Add(this.textEndereco_PF); this.Controls.Add(this.textEmail_PF); this.Controls.Add(this.textCpf_PF); this.Controls.Add(this.textNome_PF); this.Controls.Add(this.lbEndereco_PF); this.Controls.Add(this.lbEmail_PF); this.Controls.Add(this.lbCpf_PF); this.Controls.Add(this.lbNome_PF); this.Name = "frmFuncionario"; this.Text = "Funcionario"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lbNome_PF; private System.Windows.Forms.Label lbCpf_PF; private System.Windows.Forms.Label lbEmail_PF; private System.Windows.Forms.Label lbEndereco_PF; private System.Windows.Forms.TextBox textNome_PF; private System.Windows.Forms.TextBox textCpf_PF; private System.Windows.Forms.TextBox textEmail_PF; private System.Windows.Forms.TextBox textEndereco_PF; private System.Windows.Forms.Button btnSalvarPessoaFisica; private System.Windows.Forms.Button btnVoltarFrmPF; } }
44.810976
172
0.591509
[ "MIT" ]
lidia-freitas/zurne
zurne/Views/frmFuncionario.Designer.cs
7,352
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Sep.Git.Tfs.Commands; using Sep.Git.Tfs.Core.TfsInterop; namespace Sep.Git.Tfs.Core { public class TfsWorkspace : ITfsWorkspace { private readonly IWorkspace _workspace; private readonly string _localDirectory; private readonly TextWriter _stdout; private readonly TfsChangesetInfo _contextVersion; private readonly IGitTfsRemote _remote; private readonly CheckinOptions _checkinOptions; private readonly ITfsHelper _tfsHelper; private readonly CheckinPolicyEvaluator _policyEvaluator; public TfsWorkspace(IWorkspace workspace, string localDirectory, TextWriter stdout, TfsChangesetInfo contextVersion, IGitTfsRemote remote, CheckinOptions checkinOptions, ITfsHelper tfsHelper, CheckinPolicyEvaluator policyEvaluator) { _workspace = workspace; _policyEvaluator = policyEvaluator; _contextVersion = contextVersion; _remote = remote; _checkinOptions = checkinOptions; _tfsHelper = tfsHelper; _localDirectory = localDirectory; _stdout = stdout; } public void Shelve(string shelvesetName, bool evaluateCheckinPolicies, Func<string> generateCheckinComment) { var pendingChanges = _workspace.GetPendingChanges(); if (pendingChanges.IsEmpty()) throw new GitTfsException("Nothing to shelve!"); var shelveset = _tfsHelper.CreateShelveset(_workspace, shelvesetName); shelveset.Comment = string.IsNullOrWhiteSpace(_checkinOptions.CheckinComment) && !_checkinOptions.NoGenerateCheckinComment ? generateCheckinComment() : _checkinOptions.CheckinComment; shelveset.WorkItemInfo = GetWorkItemInfos().ToArray(); if (evaluateCheckinPolicies) { foreach (var message in _policyEvaluator.EvaluateCheckin(_workspace, pendingChanges, shelveset.Comment, null, shelveset.WorkItemInfo).Messages) { _stdout.WriteLine("[Checkin Policy] " + message); } } _workspace.Shelve(shelveset, pendingChanges, _checkinOptions.Force ? TfsShelvingOptions.Replace : TfsShelvingOptions.None); } public long CheckinTool(Func<string> generateCheckinComment) { var pendingChanges = _workspace.GetPendingChanges(); if (pendingChanges.IsEmpty()) throw new GitTfsException("Nothing to checkin!"); var checkinComment = _checkinOptions.CheckinComment; if (string.IsNullOrWhiteSpace(checkinComment) && !_checkinOptions.NoGenerateCheckinComment) checkinComment = generateCheckinComment(); var newChangesetId = _tfsHelper.ShowCheckinDialog(_workspace, pendingChanges, GetWorkItemCheckedInfos(), checkinComment); if (newChangesetId <= 0) throw new GitTfsException("Checkin cancelled!"); return newChangesetId; } public long Checkin(CheckinOptions options) { if (options == null) options = _checkinOptions; var pendingChanges = _workspace.GetPendingChanges(); if (pendingChanges.IsEmpty()) throw new GitTfsException("Nothing to checkin!"); var workItemInfos = GetWorkItemInfos(options); var checkinNote = _tfsHelper.CreateCheckinNote(options.CheckinNotes); var checkinProblems = _policyEvaluator.EvaluateCheckin(_workspace, pendingChanges, options.CheckinComment, checkinNote, workItemInfos); if (checkinProblems.HasErrors) { foreach (var message in checkinProblems.Messages) { if (options.Force && string.IsNullOrWhiteSpace(options.OverrideReason) == false) { _stdout.WriteLine("[OVERRIDDEN] " + message); } else { _stdout.WriteLine("[ERROR] " + message); } } if (!options.Force) { throw new GitTfsException("No changes checked in."); } if (String.IsNullOrWhiteSpace(options.OverrideReason)) { throw new GitTfsException("A reason must be supplied (-f REASON) to override the policy violations."); } } var policyOverride = GetPolicyOverrides(options, checkinProblems.Result); var newChangeset = _workspace.Checkin(pendingChanges, options.CheckinComment, checkinNote, workItemInfos, policyOverride, options.OverrideGatedCheckIn); if (newChangeset == 0) { throw new GitTfsException("Checkin failed!"); } else { return newChangeset; } } private TfsPolicyOverrideInfo GetPolicyOverrides(CheckinOptions options, ICheckinEvaluationResult checkinProblems) { if (!options.Force || String.IsNullOrWhiteSpace(options.OverrideReason)) return null; return new TfsPolicyOverrideInfo { Comment = options.OverrideReason, Failures = checkinProblems.PolicyFailures }; } public string GetLocalPath(string path) { return Path.Combine(_localDirectory, path); } public void Add(string path) { _stdout.WriteLine(" add " + path); var added = _workspace.PendAdd(GetLocalPath(path)); if (added != 1) throw new Exception("One item should have been added, but actually added " + added + " items."); } public void Edit(string path) { _stdout.WriteLine(" edit " + path); GetFromTfs(path); var edited = _workspace.PendEdit(GetLocalPath(path)); if (edited != 1) throw new Exception("One item should have been edited, but actually edited " + edited + " items."); } public void Delete(string path) { _stdout.WriteLine(" delete " + path); GetFromTfs(path); var deleted = _workspace.PendDelete(GetLocalPath(path)); if (deleted != 1) throw new Exception("One item should have been deleted, but actually deleted " + deleted + " items."); } public void Rename(string pathFrom, string pathTo, string score) { _stdout.WriteLine(" rename " + pathFrom + " to " + pathTo + " (score: " + score + ")"); GetFromTfs(pathFrom); var result = _workspace.PendRename(GetLocalPath(pathFrom), GetLocalPath(pathTo)); if (result != 1) throw new ApplicationException("Unable to rename item from " + pathFrom + " to " + pathTo); } private void GetFromTfs(string path) { _workspace.ForceGetFile(_remote.TfsRepositoryPath + "/" + path, (int)_contextVersion.ChangesetId); } public void Get(int changesetId) { _workspace.GetSpecificVersion(changesetId); } public void Get(IChangeset changeset) { changeset.Get(_workspace); } private IEnumerable<IWorkItemCheckinInfo> GetWorkItemInfos(CheckinOptions options = null) { return GetWorkItemInfosHelper<IWorkItemCheckinInfo>(_tfsHelper.GetWorkItemInfos, options); } private IEnumerable<IWorkItemCheckedInfo> GetWorkItemCheckedInfos() { return GetWorkItemInfosHelper<IWorkItemCheckedInfo>(_tfsHelper.GetWorkItemCheckedInfos); } private IEnumerable<T> GetWorkItemInfosHelper<T>(Func<IEnumerable<string>, TfsWorkItemCheckinAction, IEnumerable<T>> func, CheckinOptions options = null) { var checkinOptions = options ?? _checkinOptions; var workItemInfos = func(checkinOptions.WorkItemsToAssociate, TfsWorkItemCheckinAction.Associate); workItemInfos = workItemInfos.Append( func(checkinOptions.WorkItemsToResolve, TfsWorkItemCheckinAction.Resolve)); return workItemInfos; } } }
42.426396
239
0.625508
[ "Apache-2.0" ]
spraints/git-tfs
GitTfs/Core/TfsWorkspace.cs
8,358
C#
using System; using System.Windows; using System.Windows.Data; using Squiggle.Client; using Squiggle.Core.Presence; using Squiggle.UI.Resources; namespace Squiggle.UI.Converters { public class StatusConverter: IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value != null && value is UserStatus) { var status = (UserStatus)value; switch (status) { case UserStatus.Online: return Translation.Instance.BuddyStatus_Online; case UserStatus.Busy: return Translation.Instance.BuddyStatus_Busy; case UserStatus.BeRightBack: return Translation.Instance.BuddyStatus_BeRightBack; case UserStatus.Away: return Translation.Instance.BuddyStatus_Away; case UserStatus.Idle: return Translation.Instance.BuddyStatus_Idle; case UserStatus.Offline: return Translation.Instance.BuddyStatus_Offline; default: return status.ToString(); } } else return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return DependencyProperty.UnsetValue; } #endregion } }
33.959184
124
0.564904
[ "MIT" ]
minhduystg1999/Squiggle-developed
Squiggle.UI/Converters/StatusConverter.cs
1,666
C#
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System.Diagnostics.CodeAnalysis; namespace Microsoft.VisualStudio.Project { /// <summary> /// Defines the constant strings for various msbuild targets /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ms")] public static class MsBuildTarget { public const string ResolveProjectReferences = "ResolveProjectReferences"; public const string ResolveAssemblyReferences = "ResolveAssemblyReferences"; public const string ResolveComReferences = "ResolveComReferences"; public const string Build = "Build"; public const string Rebuild = "ReBuild"; public const string Clean = "Clean"; } [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Ms")] public static class MsBuildGeneratedItemType { public const string ReferenceCopyLocalPaths = "ReferenceCopyLocalPaths"; public const string ComReferenceWrappers = "ComReferenceWrappers"; } /// <summary> /// Defines the constant strings used with project files. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "COM")] public static class ProjectFileConstants { public const string Include = "Include"; public const string Name = "Name"; public const string HintPath = "HintPath"; public const string AssemblyName = "AssemblyName"; public const string FinalOutputPath = "FinalOutputPath"; public const string Project = "Project"; public const string LinkedIntoProjectAt = "LinkedIntoProjectAt"; public const string TypeGuid = "TypeGuid"; public const string InstanceGuid = "InstanceGuid"; public const string Private = "Private"; public const string EmbedInteropTypes = "EmbedInteropTypes"; public const string ProjectReference = "ProjectReference"; public const string Reference = "Reference"; public const string WebReference = "WebReference"; public const string WebReferenceFolder = "WebReferenceFolder"; public const string Folder = "Folder"; public const string Content = "Content"; public const string EmbeddedResource = "EmbeddedResource"; public const string RootNamespace = "RootNamespace"; public const string OutputType = "OutputType"; [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SubType")] public const string SubType = "SubType"; public const string DependentUpon = "DependentUpon"; public const string Compile = "Compile"; public const string ReferencePath = "ReferencePath"; public const string ResolvedProjectReferencePaths = "ResolvedProjectReferencePaths"; public const string Configuration = "Configuration"; public const string Platform = "Platform"; public const string AvailablePlatforms = "AvailablePlatforms"; public const string BuildVerbosity = "BuildVerbosity"; public const string Template = "Template"; [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SubProject")] public const string SubProject = "SubProject"; public const string BuildAction = "BuildAction"; public const string CopyToOutputDirectory = "CopyToOutputDirectory"; [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "COM")] public const string COMReference = "COMReference"; public const string Guid = "Guid"; public const string VersionMajor = "VersionMajor"; public const string VersionMinor = "VersionMinor"; [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lcid")] public const string Lcid = "Lcid"; public const string Isolated = "Isolated"; public const string WrapperTool = "WrapperTool"; public const string BuildingInsideVisualStudio = "BuildingInsideVisualStudio"; [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")] public const string SccProjectName = "SccProjectName"; [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")] public const string SccLocalPath = "SccLocalPath"; [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")] public const string SccAuxPath = "SccAuxPath"; [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")] public const string SccProvider = "SccProvider"; public const string ProjectGuid = "ProjectGuid"; public const string ProjectTypeGuids = "ProjectTypeGuids"; public const string Generator = "Generator"; public const string CustomToolNamespace = "CustomToolNamespace"; public const string FlavorProperties = "FlavorProperties"; public const string VisualStudio = "VisualStudio"; public const string User = "User"; public const string ApplicationDefinition = "ApplicationDefinition"; public const string Link = "Link"; public const string Page = "Page"; public const string Resource = "Resource"; public const string None = "None"; } public static class ProjectFileAttributeValue { public const string Code = "Code"; public const string Form = "Form"; public const string Component = "Component"; public const string Designer = "Designer"; public const string UserControl = "UserControl"; } internal static class ProjectFileValues { internal const string AnyCPU = "AnyCPU"; } public enum WrapperToolAttributeValue { Primary, TlbImp } /// <summary> /// A set of constants that specify the default sort order for different types of hierarchy nodes. /// </summary> public static class DefaultSortOrderNode { public const int HierarchyNode = 1000; public const int FolderNode = 500; public const int NestedProjectNode = 200; public const int ReferenceContainerNode = 300; } }
45.267606
112
0.735843
[ "BSD-3-Clause" ]
aaron-hardin/M-Files-SDK
Libs/Microsoft.VisualStudio.Project/ProjectFileConstants.cs
6,428
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using System.Xml; using VideoOS.Platform; using VideoOS.Platform.Admin; using VideoOS.Platform.Background; using VideoOS.Platform.Data; using VideoOS.Platform.Messaging; using VideoOS.Platform.Util; namespace SensorMonitor.Admin { public class SensorMonitorSensorItemManager : ItemManager { private SensorMonitorUserControl _userControl; private readonly Guid _kind; private object msgRef; #region Constructors public SensorMonitorSensorItemManager(Guid kind) { _kind = kind; } public override void Init() { msgRef = EnvironmentManager.Instance.RegisterReceiver(TriggerReceiver, new MessageIdFilter(MessageId.Control.TriggerCommand)); } public override void Close() { EnvironmentManager.Instance.UnRegisterReceiver(msgRef); msgRef = null; } #endregion #region UserControl Methods /// <summary> /// Generate the UserControl for configuring a type of item that this ItemManager manages. /// </summary> /// <returns></returns> public override UserControl GenerateDetailUserControl() { _userControl = new SensorMonitorUserControl("Sensor"); _userControl.ConfigurationChangedByUser += new EventHandler(ConfigurationChangedByUserHandler); return _userControl; } /// <summary> /// A user control to display when the administrator clicks on the treeNode. /// This can be a help page or a status over of the configuration /// </summary> public override ItemNodeUserControl GenerateOverviewUserControl() { return new VideoOS.Platform.UI.HelpUserControl( SensorMonitorDefinition._treeNodeSensorImage, "Sensor Monitor - Sensor", "Here you can add a sample sensor assumed to be controlled by its parent controller.\r\nThe sample show how multi level Items can be created."); } /// <summary> /// Clear all user entries on the UserControl. /// </summary> public override void ClearUserControl() { CurrentItem = null; if (_userControl!=null) _userControl.ClearContent(); } /// <summary> /// Fill the UserControl with the content of the Item or the data it represent. /// </summary> /// <param name="item">The Item to work with</param> public override void FillUserControl(Item item) { CurrentItem = item; if (_userControl != null) { _userControl.FillContent(item); } } /// <summary> /// Use the Status XML format to describe the parent of the sensor /// </summary> /// <param name="parent">parent item</param> /// <returns></returns> private static string SensorDetails(Item parent) { MemoryStream xmlStream = new MemoryStream(256); XmlTextWriter xmlWriter = new XmlTextWriter(xmlStream, null) {Formatting = Formatting.None}; // utf-8 encoding // create root element xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("details"); xmlWriter.WriteAttributeString("language", "en-US"); xmlWriter.WriteStartElement("detail"); xmlWriter.WriteAttributeString("detailname", "parent"); { xmlWriter.WriteStartElement("detail_string"); if (parent != null) { xmlWriter.WriteString(parent.Name); } else { xmlWriter.WriteString("orphan!!"); } xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Close(); return Encoding.UTF8.GetString(xmlStream.GetBuffer()); } public override string GetItemStatusDetails(Item item, String language) { SensorItem sensor = item as SensorItem; if (sensor != null) { return SensorDetails(sensor.GetParent()); } return SensorDetails(item.GetParent()); } private object TriggerReceiver(VideoOS.Platform.Messaging.Message message, FQID dest, FQID sender) { try { if (dest != null && dest.Kind == _kind) { string userSID = ""; if (sender != null && sender.Kind == Kind.User) userSID = sender.ObjectIdString; // Get hold of the user executing the command String command = message.Data as String; Item item = GetItem(dest); if (command != null && item != null) { // We have selected to use the "Manage" tick-mark for these operations: ("Manage" is stored as "GENERIC_WRITE") if (userSID == null) SecurityAccess.CheckPermission(item, "GENERIC_WRITE"); else SecurityAccess.CheckPermission(item, "GENERIC_WRITE", userSID); if (command == "ACTIVATESENSOR") { EnvironmentManager.Instance.Log(false, "SensorMonitor", "Activate sensor" + command, null); SensorItem.SensorActiveState[item.FQID.ObjectId] = true; EventServerControl.Instance.ItemStatusChanged(item); FQID cameraFQID = null; if (item.Properties.ContainsKey("RelatedFQID")) { cameraFQID = new FQID(item.Properties["RelatedFQID"]); } EventHeader eventHeader = new EventHeader() { ID = Guid.NewGuid(), Class = "Operational", Type = "SensorState", Timestamp = DateTime.Now, Message = SensorMonitorControllerItemManager.SensorActiveMessage, Name = item.Name, Source = new EventSource { FQID = item.FQID, Name = item.Name }, CustomTag = "<My><MiniXml>Sensor info</MiniXml></My>" }; AnalyticsEvent eventData = new AnalyticsEvent { EventHeader = eventHeader, }; if (cameraFQID != null) { eventData.ReferenceList = new ReferenceList(); eventData.ReferenceList.Add(new Reference() { FQID = cameraFQID }); // Ensure that camera will be presented in the preview } EnvironmentManager.Instance.SendMessage(new VideoOS.Platform.Messaging.Message(MessageId.Server.NewEventCommand) { Data = eventData, RelatedFQID = cameraFQID }); } if (command == "DEACTIVATESENSOR") { EnvironmentManager.Instance.Log(false, "SensorMonitor", "Deactive sensor " + command, null); SensorItem.SensorActiveState[item.FQID.ObjectId] = false; EventServerControl.Instance.ItemStatusChanged(item); FQID cameraFQID = null; if (item.Properties.ContainsKey("RelatedFQID")) { cameraFQID = new FQID(item.Properties["RelatedFQID"]); } EventHeader eventHeader = new EventHeader() { ID = Guid.NewGuid(), Class = "Operational", Type = "SensorState", Timestamp = DateTime.Now, Message = SensorMonitorControllerItemManager.SensorPassiveMessage, Name = item.Name, Source = new EventSource { FQID = item.FQID, Name = item.Name }, CustomTag = "<My><MiniXml>Some other info</MiniXml></My>" }; AnalyticsEvent eventData = new AnalyticsEvent { EventHeader = eventHeader, }; if (cameraFQID != null) { eventData.ReferenceList = new ReferenceList(); eventData.ReferenceList.Add(new Reference() { FQID = cameraFQID }); // Ensure that camera will be presented in the preview } EnvironmentManager.Instance.SendMessage(new VideoOS.Platform.Messaging.Message(MessageId.Server.NewEventCommand) { Data = eventData, RelatedFQID = cameraFQID }); } } } } catch (NotAuthorizedMIPException) { throw; } catch (Exception ex) { EnvironmentManager.Instance.Log(false, "SensorMonitor", "SensorMonitor-9 " + ex.Message, new[] { ex }); //User not authorized to perform the action } return null; } #endregion #region Working with currentItem /// <summary> /// Get the name of the current Item. /// </summary> /// <returns></returns> public override string GetItemName() { if (_userControl != null) { return _userControl.DisplayName; } return ""; } /// <summary> /// Update the name for current Item. the user edited the Name via F2 in the TreeView /// </summary> /// <param name="name"></param> public override void SetItemName(string name) { if (_userControl != null) { _userControl.DisplayName = name; } } /// <summary> /// Validate the user entry, and return true for OK /// </summary> /// <returns></returns> public override bool ValidateAndSaveUserControl() { if (CurrentItem != null) { //Get user entered fields _userControl.UpdateItem(CurrentItem); //In this template we save configuration on the VMS system Configuration.Instance.SaveItemConfiguration(SensorMonitorDefinition.SensorMonitorPluginId, CurrentItem); } return true; } /// <summary> /// Create a new Item /// </summary> /// <param name="parentItem">The parent for the new Item</param> /// <param name="suggestedFQID">A suggested FQID for the new Item</param> public override Item CreateItem(Item parentItem, FQID suggestedFQID) { CurrentItem = new SensorItem(suggestedFQID, "Enter a name", parentItem); if (_userControl != null) { _userControl.FillContent(CurrentItem); } Configuration.Instance.SaveItemConfiguration(SensorMonitorDefinition.SensorMonitorPluginId, CurrentItem); SecurityAccess.RegisterItem(CurrentItem); return CurrentItem; } /// <summary> /// Delete an Item /// </summary> /// <param name="item">The Item to delete</param> public override void DeleteItem(Item item) { if (item != null) { Configuration.Instance.DeleteItemConfiguration(SensorMonitorDefinition.SensorMonitorPluginId, item); SecurityAccess.UnregisterItem(item); } } #endregion #region Configuration Access Methods /// <summary> /// Returns a list of all Items of this Kind /// </summary> /// <returns>A list of items. Allowed to return null if no Items found.</returns> public override List<Item> GetItems() { //All items in this sample are stored with the Video, therefor no ServerIs or parent ids is used. List<Item> items = Configuration.Instance.GetItemConfigurations(SensorMonitorDefinition.SensorMonitorPluginId, null, _kind).Select(i => (Item)(new SensorItem(i))).ToList(); return items; } /// <summary> /// Returns a list of all Items from a specific server. /// </summary> /// <param name="parentItem">The parent Items</param> /// <returns>A list of items. Allowed to return null if no Items found.</returns> public override List<Item> GetItems(Item parentItem) { List<Item> items = Configuration.Instance.GetItemConfigurations(SensorMonitorDefinition.SensorMonitorPluginId, parentItem, _kind).Select(i => (Item)(new SensorItem(i))).ToList(); return items; } /// <summary> /// Returns the Item defined by the FQID. Will return null if not found. /// </summary> /// <param name="fqid">Fully Qualified ID of an Item</param> /// <returns>An Item</returns> public override Item GetItem(FQID fqid) { Item item = Configuration.Instance.GetItemConfiguration(SensorMonitorDefinition.SensorMonitorPluginId, _kind, fqid.ObjectId); if (item != null) { return new SensorItem(item); } return item; } #endregion #region Translation /// <summary> /// Get dictionary to be used for translation for Smart Map /// </summary> /// <param name="culture"></param> /// <returns></returns> public override Dictionary<string, string> GetTranslationDictionary(CultureInfo culture) { return SensorMonitorDefinition.GetTranslationDictionary(culture); } #endregion } }
34.763021
189
0.594277
[ "MIT" ]
Silex/mipsdk-samples-plugin
SensorMonitor/Admin/SensorMonitorSensorItemManager.cs
13,349
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GDEngine3.Event { /// <summary> /// Class that defines an interface for objects that handle event dispatching /// </summary> public interface IEventHandler { /// <summary> /// Clears all the events on this IEventHandler /// </summary> void Clear(); /// <summary> /// Registers the given IEventReceiver object to receive events of the given type /// </summary> /// <param name="receiver">The event receiver to register</param> /// <param name="eventType">The event type to notify the receiver of</param> void RegisterEventReceiver(IEventReceiver receiver, string eventType); /// <summary> /// Unregisters the given IEventReceiver object from receiving events of the given type /// </summary> /// <param name="receiver">The event receiver to unregister</param> /// <param name="eventType">The event type to unregister</param> void UnregisterEventReceiver(IEventReceiver receiver, string eventType); /// <summary> /// Unregisters the given IEventReceiver object from receiving all events it is currently registered on /// </summary> /// <param name="receiver">The event receiver</param> void UnregisterEventReceiverFromAllEvents(IEventReceiver receiver); /// <summary> /// Broadcasts the given GDEvent to all currently registered receivers /// </summary> /// <param name="gameEvent">The event to broadcast</param> void BroadcastEvent(GDEvent gameEvent); } }
38.363636
111
0.651066
[ "MIT" ]
LuizZak/GDEngine
GDEngine3/Event/IEventHandler.cs
1,690
C#
using SFA.DAS.Activities.Configuration; namespace SFA.DAS.Activities.IntegrationTests { public class ActivitiesIntegrationTestsConfiguration : IMessageServiceBusConfiguration, ICosmosConfiguration, IAzureBlobStorageConfiguration { public string ElasticUrl { get; set; } public string ElasticUsername { get; set; } public string ElasticPassword { get; set; } public string CosmosDatabase { get; set; } public string CosmosEndpointUrl { get; set; } public string CosmosPrimaryKey { get; set; } public string CosmosCollectionName { get; set; } public string MessageServiceBusConnectionString { get; set; } public string LogStorageConnectionString { get; set; } } }
43.941176
144
0.714859
[ "MIT" ]
SkillsFundingAgency/das-activities
src/SFA.DAS.Activities.IntegrationTests/ElasticBackupTests/ActivitiesIntegrationTestsConfiguration.cs
749
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.ChangeSignature { internal abstract class ChangeSignatureAnalyzedContext { } internal sealed class ChangeSignatureAnalysisSucceededContext : ChangeSignatureAnalyzedContext { public readonly Document Document; public readonly ISymbol Symbol; public readonly ParameterConfiguration ParameterConfiguration; public readonly int PositionForTypeBinding; public Solution Solution => Document.Project.Solution; public ChangeSignatureAnalysisSucceededContext( Document document, int positionForTypeBinding, ISymbol symbol, ParameterConfiguration parameterConfiguration ) { Document = document; Symbol = symbol; ParameterConfiguration = parameterConfiguration; PositionForTypeBinding = positionForTypeBinding; } } internal sealed class CannotChangeSignatureAnalyzedContext : ChangeSignatureAnalyzedContext { public readonly ChangeSignatureFailureKind CannotChangeSignatureReason; public CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind reason) { CannotChangeSignatureReason = reason; } } }
33.772727
98
0.711306
[ "MIT" ]
belav/roslyn
src/Features/Core/Portable/ChangeSignature/ChangeSignatureAnalyzedContext.cs
1,488
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FlightManager.Web { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.888889
70
0.646638
[ "MIT" ]
aalishov/SimpleApps
FlightManager/FlightManager.Web/Program.cs
699
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GenericDotNetSupportLibrary NET40")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("GenericDotNetSupportLibrary NET40")] [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("949d2f1b-5607-4300-ac36-ffcc558246b5")] // 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("2014.1.0.23")] [assembly: AssemblyFileVersion("2014.1.0.23")]
39.567568
84
0.756148
[ "MIT" ]
mikejr83/GenericDotNetSupportLibrary
GenericDotNetSupportLibrary.NET40/Properties/AssemblyInfo.cs
1,465
C#
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/) // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0 // Template File Name: methodTemplate.tt // Build date: 2017-10-08 // C# generater version: 1.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // About // // Unoffical sample for the Compute beta API for C#. // This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client) // // API Description: Creates and runs virtual machines on Google Cloud Platform. // API Documentation Link https://developers.google.com/compute/docs/reference/latest/ // // Discovery Doc https://www.googleapis.com/discovery/v1/apis/Compute/beta/rest // //------------------------------------------------------------------------------ // Installation // // This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client) // // NuGet package: // // Location: https://www.nuget.org/packages/Google.Apis.Compute.beta/ // Install Command: PM> Install-Package Google.Apis.Compute.beta // //------------------------------------------------------------------------------ using Google.Apis.Compute.beta; using Google.Apis.Compute.beta.Data; using System; namespace GoogleSamplecSharpSample.Computebeta.Methods { public static class ZoneOperationsSample { /// <summary> /// Deletes the specified zone-specific Operations resource. /// Documentation https://developers.google.com/compute/beta/reference/zoneOperations/delete /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Compute service.</param> /// <param name="project">Project ID for this request.</param> /// <param name="zone">Name of the zone for this request.</param> /// <param name="operation">Name of the Operations resource to delete.</param> public static void Delete(ComputeService service, string project, string zone, string operation) { try { // Initial validation. if (service == null) throw new ArgumentNullException("service"); if (project == null) throw new ArgumentNullException(project); if (zone == null) throw new ArgumentNullException(zone); if (operation == null) throw new ArgumentNullException(operation); // Make the request. service.ZoneOperations.Delete(project, zone, operation).Execute(); } catch (Exception ex) { throw new Exception("Request ZoneOperations.Delete failed.", ex); } } /// <summary> /// Retrieves the specified zone-specific Operations resource. /// Documentation https://developers.google.com/compute/beta/reference/zoneOperations/get /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Compute service.</param> /// <param name="project">Project ID for this request.</param> /// <param name="zone">Name of the zone for this request.</param> /// <param name="operation">Name of the Operations resource to return.</param> /// <returns>OperationResponse</returns> public static Operation Get(ComputeService service, string project, string zone, string operation) { try { // Initial validation. if (service == null) throw new ArgumentNullException("service"); if (project == null) throw new ArgumentNullException(project); if (zone == null) throw new ArgumentNullException(zone); if (operation == null) throw new ArgumentNullException(operation); // Make the request. return service.ZoneOperations.Get(project, zone, operation).Execute(); } catch (Exception ex) { throw new Exception("Request ZoneOperations.Get failed.", ex); } } public class ZoneOperationsListOptionalParms { /// Sets a filter {expression} for filtering listed resources. Your {expression} must be in the format: field_name comparison_string literal_string.The field_name is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The comparison_string must be either eq (equals) or ne (not equals). The literal_string is the string value to filter to. The literal value must be valid for the type of field you are filtering by (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field.For example, to filter for instances that do not have a name of example-instance, you would use name ne example-instance.You can filter on nested fields. For example, you could filter on instances that have set the scheduling.automaticRestart field to true. Use filtering on nested fields to take advantage of labels to organize and search for results based on label values.To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple expressions are treated as AND expressions, meaning that resources must match all expressions to pass the filters. public string Filter { get; set; } /// The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500) public int? MaxResults { get; set; } /// Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.Currently, only sorting by name or creationTimestamp desc is supported. public string OrderBy { get; set; } /// Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. public string PageToken { get; set; } } /// <summary> /// Retrieves a list of Operation resources contained within the specified zone. /// Documentation https://developers.google.com/compute/beta/reference/zoneOperations/list /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Compute service.</param> /// <param name="project">Project ID for this request.</param> /// <param name="zone">Name of the zone for request.</param> /// <param name="optional">Optional paramaters.</param> /// <returns>OperationListResponse</returns> public static OperationList List(ComputeService service, string project, string zone, ZoneOperationsListOptionalParms optional = null) { try { // Initial validation. if (service == null) throw new ArgumentNullException("service"); if (project == null) throw new ArgumentNullException(project); if (zone == null) throw new ArgumentNullException(zone); // Building the initial request. var request = service.ZoneOperations.List(project, zone); // Applying optional parameters to the request. request = (ZoneOperationsResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional); // Requesting data. return request.Execute(); } catch (Exception ex) { throw new Exception("Request ZoneOperations.List failed.", ex); } } } public static class SampleHelpers { /// <summary> /// Using reflection to apply optional parameters to the request. /// /// If the optonal parameters are null then we will just return the request as is. /// </summary> /// <param name="request">The request. </param> /// <param name="optional">The optional parameters. </param> /// <returns></returns> public static object ApplyOptionalParms(object request, object optional) { if (optional == null) return request; System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties(); foreach (System.Reflection.PropertyInfo property in optionalProperties) { // Copy value from optional parms to the request. They should have the same names and datatypes. System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name); if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null piShared.SetValue(request, property.GetValue(optional, null), null); } return request; } } }
55.663317
1,311
0.63194
[ "Apache-2.0" ]
AhmerRaza/Google-Dotnet-Samples
Samples/Compute Engine API/beta/ZoneOperationsSample.cs
11,079
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 JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.EntityFrameworkCore.Storage { /// <summary> /// <para> /// The primary point where a database provider can tell EF that it has been selected for the current context /// and provide the services required for it to function. /// </para> /// <para> /// This type is typically used by database providers (and other extensions). It is generally /// not used in application code. /// </para> /// <para> /// The service lifetime is <see cref="ServiceLifetime.Singleton"/>. This means a single instance /// is used by many <see cref="DbContext"/> instances. The implementation must be thread-safe. /// This service cannot depend on services registered as <see cref="ServiceLifetime.Scoped"/>. /// </para> /// </summary> public interface IDatabaseProvider { /// <summary> /// The unique name used to identify the database provider. This should be the same as the NuGet package name /// for the providers runtime. /// </summary> string Name { get; } /// <summary> /// Gets a value indicating whether this database provider has been configured for a given context. /// </summary> /// <param name="options"> The options for the context. </param> /// <returns> True if the database provider has been configured, otherwise false. </returns> bool IsConfigured([NotNull] IDbContextOptions options); } }
45.317073
121
0.642088
[ "Apache-2.0" ]
BionStt/EntityFrameworkCore
src/EFCore/Storage/IDatabaseProvider.cs
1,858
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using CompoundInterestCalculator.Web.Models; using CompoundInterestCalculator.Web.Services; using Microsoft.AspNetCore.Components; using Microsoft.JSInterop; namespace CompoundInterestCalculator.Web.Pages { public class IndexBase : ComponentBase { [Inject] ICalculatorService CalculatorService { get; set; } [Inject] IJSRuntime JSRuntime { get; set; } protected CalculationInput input = new CalculationInput(); protected Dictionary<string, CompoundInterval> compoundIntervals = new Dictionary<string, CompoundInterval> { { "Monthly", CompoundInterval.Monthly }, { "Quarterly", CompoundInterval.Quarterly }, { "Semi-annually", CompoundInterval.SemiAnnually }, { "Annually", CompoundInterval.Annually } }; protected bool totalDepositsColVisible; protected CalculationResult[] result = Array.Empty<CalculationResult>(); protected async Task Calculate() { if (input.IsValid()) { totalDepositsColVisible = input.MonthlyDeposit.HasValue && input.MonthlyDeposit.Value > 0; input.BaseAmount ??= 0; input.MonthlyDeposit ??= 0; result = CalculatorService.Calculate( input.BaseAmount.Value, input.InterestRatePercent.Value, input.CompoundInterval, input.MonthlyDeposit.Value, input.CalcPeriodYrs.Value); await JSRuntime.InvokeVoidAsync("jsFunctions.scrollToResults"); } } } }
35.708333
115
0.634189
[ "MIT" ]
davidtimovski/compound-interest-calculator
Source/CompoundInterestCalculator.Web/Pages/IndexBase.cs
1,716
C#