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
namespace Microsoft.Maui.Platform { public static class StrokeExtensions { public static void UpdateStrokeShape(this object platformView, IBorderStroke border) { } public static void UpdateStroke(this object platformView, IBorderStroke border) { } public static void UpdateStrokeThickness(this object platformView, IBorderStroke border) { } public static void UpdateStrokeDashPattern(this object platformView, IBorderStroke border) { } public static void UpdateStrokeDashOffset(this object platformView, IBorderStroke border) { } public static void UpdateStrokeMiterLimit(this object platformView, IBorderStroke border) { } public static void UpdateStrokeLineCap(this object platformView, IBorderStroke border) { } public static void UpdateStrokeLineJoin(this object platformView, IBorderStroke border) { } } }
38.090909
96
0.805489
[ "MIT" ]
10088/maui
src/Core/src/Platform/Standard/StrokeExtensions.cs
840
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class ETModel_MessageDispatcherComponent_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(ETModel.MessageDispatcherComponent); args = new Type[]{typeof(System.UInt16), typeof(ETModel.IMHandler)}; method = type.GetMethod("RegisterHandler", flag, null, args, null); app.RegisterCLRMethodRedirection(method, RegisterHandler_0); } static StackObject* RegisterHandler_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ETModel.IMHandler @handler = (ETModel.IMHandler)typeof(ETModel.IMHandler).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.UInt16 @opcode = (ushort)ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 3); ETModel.MessageDispatcherComponent instance_of_this_method = (ETModel.MessageDispatcherComponent)typeof(ETModel.MessageDispatcherComponent).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.RegisterHandler(@opcode, @handler); return __ret; } } }
38.220339
228
0.716186
[ "MIT" ]
13294029724/ET
Unity/Assets/Model/ILBinding/ETModel_MessageDispatcherComponent_Binding.cs
2,255
C#
// Author: // Brian Faust <brian@ark.io> // // Copyright (c) 2018 Ark Ecosystem <info@ark.io> // // 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.IO; namespace ArkEcosystem.Crypto.Serializers { public static class DelegateResignation { public static void Serialize(BinaryWriter writer, TransactionModel transaction) { // } } }
40.514286
87
0.736248
[ "MIT" ]
supaiku0/dotnet-crypto
ArkEcosystem.Crypto/ArkEcosystem.Crypto/ArkEcosystem.Crypto/Serializers/DelegateResignation.cs
1,418
C#
using Replikit.Abstractions.Attachments.Models; using Replikit.Abstractions.Common.Models; using Replikit.Abstractions.Messages.Models; using Replikit.Abstractions.Messages.Models.Options; using Replikit.Abstractions.Messages.Services; using Replikit.Adapters.Common.Models; using Replikit.Adapters.Telegram.Exceptions; using Replikit.Adapters.Telegram.Internal; using Telegram.Bot; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; using Message = Replikit.Abstractions.Messages.Models.Message; using TelegramMessage = Telegram.Bot.Types.Message; namespace Replikit.Adapters.Telegram.Services; internal class TelegramMessageService : IMessageService { private readonly ITelegramBotClient _backend; private readonly TelegramMessageResolver _telegramMessageResolver; private readonly TelegramEntityFactory _telegramEntityFactory; public TelegramMessageService(ITelegramBotClient backend, TelegramMessageResolver telegramMessageResolver, TelegramEntityFactory telegramEntityFactory) { _backend = backend; _telegramMessageResolver = telegramMessageResolver; _telegramEntityFactory = telegramEntityFactory; } public MessageServiceFeatures Features => MessageServiceFeatures.Send | MessageServiceFeatures.Edit | MessageServiceFeatures.Delete | MessageServiceFeatures.Pin | MessageServiceFeatures.Unpin | MessageServiceFeatures.AnswerInlineButtonRequest; private const int MaxAttachmentCount = 10; public async Task<Message> SendAsync(Identifier channelId, OutMessage message, SendMessageOptions? options = null, CancellationToken cancellationToken = default) { var chatId = new ChatId((long) channelId); var (text, attachments) = await _telegramMessageResolver.ResolveMessageAsync(message, cancellationToken); var messageBuilder = new TelegramMessageBuilder(_telegramEntityFactory, message); if (!string.IsNullOrEmpty(text)) { var result = await _backend.SendTextMessageAsync(chatId, text, ParseMode.Html, replyToMessageId: messageBuilder.ReplyToMessageId, replyMarkup: messageBuilder.ReplyMarkup, cancellationToken: cancellationToken); messageBuilder.ApplyResult(result); } var mediaAttachments = new List<IAlbumInputMedia>(MaxAttachmentCount); async Task SendMediaAttachments() { var results = await _backend.SendMediaGroupAsync(chatId, mediaAttachments, replyToMessageId: messageBuilder.ReplyToMessageId, cancellationToken: cancellationToken); foreach (var result in results) { messageBuilder.ApplyResult(result); } } foreach (var (original, source) in attachments) { IAlbumInputMedia? inputMedia = original.Type switch { AttachmentType.Photo => new InputMediaPhoto(source) { Caption = original.Caption }, AttachmentType.Video => new InputMediaVideo(source) { Caption = original.Caption }, _ => null }; if (inputMedia is not null) { mediaAttachments.Add(inputMedia); } if (mediaAttachments.Count == MaxAttachmentCount) { await SendMediaAttachments(); mediaAttachments.Clear(); } } if (mediaAttachments.Count > 0) { await SendMediaAttachments(); } foreach (var (attachment, source) in attachments) { var result = attachment.Type switch { AttachmentType.Document => await _backend.SendDocumentAsync(chatId, source, caption: attachment.Caption, replyToMessageId: messageBuilder.ReplyToMessageId, replyMarkup: messageBuilder.ReplyMarkup, cancellationToken: cancellationToken), AttachmentType.Audio => await _backend.SendAudioAsync(chatId, source, attachment.Caption, replyToMessageId: messageBuilder.ReplyToMessageId, replyMarkup: messageBuilder.ReplyMarkup, cancellationToken: cancellationToken), AttachmentType.Voice => await _backend.SendVoiceAsync(chatId, source, attachment.Caption, replyToMessageId: messageBuilder.ReplyToMessageId, replyMarkup: messageBuilder.ReplyMarkup, cancellationToken: cancellationToken), AttachmentType.Sticker => await _backend.SendStickerAsync(chatId, source, replyToMessageId: messageBuilder.ReplyToMessageId, replyMarkup: messageBuilder.ReplyMarkup, cancellationToken: cancellationToken), _ => null }; if (result is not null) { messageBuilder.ApplyResult(result); } } foreach (var forwardedMessage in message.ForwardedMessages) { foreach (var messageIdentifier in forwardedMessage.Identifier.Identifiers) { var result = await _backend.ForwardMessageAsync(chatId, (long) forwardedMessage.ChannelId, messageIdentifier, cancellationToken: cancellationToken); messageBuilder.ApplyResult(result); } } return messageBuilder.Build(); } public Task<Message> EditAsync(Identifier channelId, MessageIdentifier messageId, OutMessage message, OutMessage? oldMessage = null, CancellationToken cancellationToken = default) { var chatId = new ChatId((long) channelId); if (messageId.Identifiers.Count == 1) { return EditSingleMessageAsync(chatId, messageId.Identifiers[0], message, cancellationToken); } if (oldMessage is null) { throw new TelegramAdapterException("Telegram adapter cannot edit complex message without oldMessage"); } return EditComplexMessageAsync(chatId, messageId, message, oldMessage, cancellationToken); } private Task<Message> EditComplexMessageAsync(ChatId chatId, MessageIdentifier messageId, OutMessage message, OutMessage oldMessage, CancellationToken cancellationToken) { throw new TelegramAdapterException("Editing complex messages is currently unsupported"); } private async Task<Message> EditSingleMessageAsync(ChatId chatId, Identifier messageId, OutMessage message, CancellationToken cancellationToken) { var (text, attachments) = await _telegramMessageResolver.ResolveMessageAsync(message, cancellationToken); var messageBuilder = new TelegramMessageBuilder(_telegramEntityFactory, message); if (!string.IsNullOrEmpty(text) && attachments.Count > 0 || attachments.Count > 1) { throw new TelegramAdapterException( "OutMessage was expected to be single since singular identifier was provided"); } if (!string.IsNullOrEmpty(text)) { var result = await _backend.EditMessageTextAsync(chatId, messageId, text, ParseMode.Html, replyMarkup: messageBuilder.ReplyMarkup as InlineKeyboardMarkup, cancellationToken: cancellationToken); messageBuilder.ApplyResult(result); return messageBuilder.Build(); } if (attachments.Count == 1) { var result = await EditAttachmentMessage(chatId, messageId, attachments[0], cancellationToken); if (result is not null) { messageBuilder.ApplyResult(result); } return messageBuilder.Build(); } throw new TelegramAdapterException("Empty message"); } private async Task<TelegramMessage?> EditAttachmentMessage(ChatId chatId, Identifier messageId, ResolvedAttachment<InputMedia> attachment, CancellationToken cancellationToken) { var (original, source) = attachment; InputMediaBase? inputMedia = original.Type switch { AttachmentType.Photo => new InputMediaPhoto(source) { Caption = original.Caption }, AttachmentType.Video => new InputMediaVideo(source) { Caption = original.Caption }, AttachmentType.Audio => new InputMediaAudio(source) { Caption = original.Caption }, AttachmentType.Document => new InputMediaDocument(source) { Caption = original.Caption }, _ => null }; if (inputMedia is null) return null; return await _backend.EditMessageMediaAsync(chatId, messageId, inputMedia, cancellationToken: cancellationToken); } public Task DeleteAsync(Identifier channelId, Identifier messageId, CancellationToken cancellationToken = default) { return _backend.DeleteMessageAsync((long) channelId, messageId, cancellationToken); } public Task PinAsync(Identifier channelId, MessageIdentifier messageId, CancellationToken cancellationToken = default) { return _backend.PinChatMessageAsync((long) channelId, messageId.Identifiers[0], cancellationToken: cancellationToken); } public Task UnpinAsync(Identifier channelId, MessageIdentifier messageId, CancellationToken cancellationToken = default) { return _backend.UnpinChatMessageAsync((long) channelId, messageId.Identifiers[0], cancellationToken); } public Task AnswerInlineButtonRequestAsync(Identifier requestId, string message, CancellationToken cancellationToken = default) { return _backend.AnswerCallbackQueryAsync(requestId, message, cancellationToken: cancellationToken); } }
39.147287
118
0.662871
[ "MIT" ]
Replikit/Replikit
src/adapters/Replikit.Adapters.Telegram/src/Replikit.Adapters.Telegram/Services/TelegramMessageService.cs
10,102
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.md file in the project root for more information. namespace System.Collections.Concurrent { internal interface IConcurrentHashSet<T> : IEnumerable<T> { /// <summary> /// The number of elements contained in the System.Collections.Concurrent.IConcurrentHashSet`1. /// </summary> int Count { get; } /// <summary> /// Adds an item to the System.Collections.Concurrent.IConcurrentHashSet`1. /// </summary> /// <param name="item">The object to add to the System.Collections.Concurrent.IConcurrentHashSet`1</param> /// <returns> /// <c>true</c> if the item was added to the System.Collections.Concurrent.IConcurrentHashSet`1; otherwise, <c>false</c> /// </returns> bool Add(T item); /// <summary> /// Determines whether the System.Collections.Concurrent.IConcurrentHashSet`1 contains the specified item. /// </summary> /// <param name="item">The item to locate in the System.Collections.Concurrent.IConcurrentHashSet`1.</param> /// <returns> /// <c>true</c> if the System.Collections.Concurrent.IConcurrentHashSet`1 contains the item; otherwise, <c>false</c>. /// </returns> bool Contains(T item); /// <summary> /// Removes a specific object from the System.Collections.Concurrent.IConcurrentHashSet`1 /// </summary> /// <param name="item">The object to remove from the System.Collections.Concurrent.IConcurrentHashSet`1.</param> /// <returns> /// <c>true</c> if item was successfully removed from the System.Collections.Concurrent.IConcurrentHashSet`1; /// otherwise, <c>false</c>. This method also returns <c>false</c> if item is not found in the /// System.Collections.Concurrent.IConcurrentHashSet`1. /// </returns> bool Remove(T item); /// <summary> /// Adds all the elements in a sequence to the set. /// </summary> /// <param name="elements">The objects to add to the System.Collections.Concurrent.IConcurrentHashSet`1</param> /// <returns> /// <c>true</c> if at least one item was added to the System.Collections.Concurrent.IConcurrentHashSet`1; /// otherwise, <c>false</c> /// </returns> public bool AddRange(IEnumerable<T> elements); } }
49.461538
201
0.629471
[ "MIT" ]
brunom/project-system
src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/Collections/IConcurrentHashSet.cs
2,523
C#
using System.Collections.Generic; using UnityEngine; namespace VH { /// <summary> /// Utility Functions for Grid Opertaions /// </summary> public static class GridUtility { #region Tile Utils /// <summary> /// Find the Tile Instance from a Position in the World /// </summary> public static Tile GetTileFromWorldPosition(this Tilemap grid, Vector3 worldPosition) { float fPositionX = ((worldPosition.x) + grid.Rows * 0.5f); float fPositionY = ((worldPosition.y) + grid.Columns * 0.5f); fPositionX = Mathf.Clamp(fPositionX, 0, grid.Rows - 1); fPositionY = Mathf.Clamp(fPositionY, 0, grid.Columns - 1); int x = Mathf.FloorToInt(fPositionX); int y = Mathf.FloorToInt(fPositionY); return grid.Tiles[x, y]; } /// <summary> /// Find the Tile Instance from a Position in the World /// </summary> public static Tile GetTileFromWorldPosition(this Tilemap grid, float worldX, float worldY) { float fPositionX = (worldX + grid.Rows * 0.5f); float fPositionY = (worldY + grid.Columns * 0.5f); fPositionX = Mathf.Clamp(fPositionX, 0, grid.Rows - 1); fPositionY = Mathf.Clamp(fPositionY, 0, grid.Columns - 1); int x = Mathf.FloorToInt(fPositionX); int y = Mathf.FloorToInt(fPositionY); return grid.Tiles[x, y]; } /// <summary> /// Checks if a Given tile in the Grid is Walkable by an Agent /// </summary> /// <param name="grid"></param> /// <param name="tile"></param> /// <param name="agentWidth"></param> /// <param name="agentHeight"></param> /// <returns></returns> public static bool IsTileWalkableByAgent(this Tilemap grid, Tile tile, NavigationAgent agent) { int xLimit = Mathf.Clamp(tile.x + agent.width, 0, grid.Columns); int yLimit = Mathf.Clamp(tile.y - agent.height, 0, grid.Rows); for (int y = tile.y; y > yLimit; y--) { for (int x = tile.x; x < xLimit; x++) { if (!grid.Tiles[x, y].walkable) { return false; } } } return true; } #endregion #region Intersection Utils /// <summary> /// Find the Intersection from a Position in the World, with a Favoured Direction /// </summary> public static Intersection GetNearestIntersection(this Tilemap grid, Vector3 worldPosition, Direction favouredDirection = Direction.NorthEast) { short modifierX, modifierY; switch (favouredDirection) { case Direction.South: modifierX = 0; modifierY = -1; break; case Direction.West: modifierX = -1; modifierY = 0; break; case Direction.NorthWest: modifierX = -1; modifierY = 0; break; case Direction.SouthWest: modifierX = -1; modifierY = -1; break; case Direction.SouthEast: modifierX = 0; modifierY = -1; break; default: modifierX = modifierY = 0; break; } if (worldPosition.x % 0.5f == 0) worldPosition.x += modifierX; if (worldPosition.y % 0.5f == 0) worldPosition.y += modifierY; float fPositionX = ((worldPosition.x) + (grid.Rows + 1) * 0.5f); float fPositionY = ((worldPosition.y) + (grid.Columns + 1) * 0.5f); fPositionX = Mathf.Clamp(fPositionX, 0, grid.Rows + 1); fPositionY = Mathf.Clamp(fPositionY, 0, grid.Columns + 1); int x = Mathf.FloorToInt(fPositionX); int y = Mathf.FloorToInt(fPositionY); if (x <= grid.Columns && y <= grid.Rows) return grid.Intersections[x, y]; else return default; } /// <summary> /// Get the Tile That is Encompassed by the Intersection with respect to another Intersection /// </summary> /// <param name="intersection"></param> /// <param name="grid"></param> /// <param name="reference"></param> /// <returns></returns> public static Tile GetEncompassedTile(this Tilemap grid, Intersection intersection, Intersection reference) { int x = intersection.x == reference.x ? 0 : (intersection.x < reference.x ? 1 : -1); int y = intersection.y == reference.y ? 0 : (intersection.y < reference.y ? 1 : -1); return grid.GetTileFromWorldPosition(intersection.position.x + x * 0.5f, intersection.position.y + y * 0.5f); } #endregion #region Distances /// <summary> /// returns the Distance between two tiles in a grid /// </summary> /// <param name="tileA"></param> /// <param name="tileB"></param> /// <returns></returns> public static int GetDistanceBetweenTiles(Tile tileA, Tile tileB) { return GridUtility.GetDistance(Mathf.Abs(tileA.x - tileB.x), Mathf.Abs(tileA.y - tileB.y)); } /// <summary> /// returns the Distance between two Intersections in a grid /// </summary> /// <param name="interA"></param> /// <param name="interB"></param> /// <returns></returns> public static int GetDistanceBetweenIntersections(Intersection interA, Intersection interB) { return GridUtility.GetDistance(Mathf.Abs(interA.x - interB.x), Mathf.Abs(interA.y - interB.y)); } private static readonly float InverseAdjacentDistance = 1f / (float)TemporaryConstants.AdjacentDistance; /// <summary> /// Returns the Pathfinder Distance between Two Nodes /// By Default the Primary Four Directions are 5 Foot away and Diagonal Movement costs 7.5 Foot /// Reference : https://wiki.roll20.net/Ruler /// </summary> /// <param name="distanceX"></param> /// <param name="distanceY"></param> /// <returns></returns> private static int GetDistance(int distanceX, int distanceY) { if (distanceX > distanceY) { return (TemporaryConstants.AdjacentDistance * Mathf.FloorToInt((TemporaryConstants.DiagonalDistance * distanceY) * InverseAdjacentDistance)) + (TemporaryConstants.AdjacentDistance * (distanceX - distanceY)); } return (TemporaryConstants.AdjacentDistance * Mathf.FloorToInt((TemporaryConstants.DiagonalDistance * distanceX) * InverseAdjacentDistance)) + (TemporaryConstants.AdjacentDistance * (distanceY - distanceX)); } #endregion #region Neighbours /// <summary> /// Returns all the Walkable Neighboring Tiles for a Given Tile /// This also Checks for Cutting Corners, where a Diagonal move is perfecly legal /// But results in Awkward Visuals on Screen /// </summary> /// <param name="grid"></param> /// <param name="tile"></param> /// <returns></returns> public static List<Tile> GetNeighbouringTiles(this Tilemap grid, Tile tile) { List<Tile> neighbours = new List<Tile>(); int checkX, checkY; for (int y = -1; y <= 1; y++) { for (int x = -1; x <= 1; x++) { if (x == 0 && y == 0) { continue; } checkX = tile.x + x; checkY = tile.y + y; if ((checkX >= 0 && checkX < grid.Rows) && (checkY >= 0 && checkY < grid.Columns)) { //Checking for Cutting Corners //if the Neighbour is a diagonal if (Mathf.Abs(x) == 1 && Mathf.Abs(y) == 1) { //Bottom-Right and Top-Left Corners if (x == y) { //If x = 1 and y = 1 if (x > 0) { //x+1,y and x, y+1 if (grid.Tiles[tile.x + 1, tile.y].walkable && grid.Tiles[tile.x, tile.y + 1].walkable) { neighbours.Add(grid.Tiles[checkX, checkY]); } } // else If x = -1 and y = -1 else { //x,y-1 and x-1, y if (grid.Tiles[tile.x - 1, tile.y].walkable && grid.Tiles[tile.x, tile.y - 1].walkable) { neighbours.Add(grid.Tiles[checkX, checkY]); } } } //Top-Right and Bottom-Left Corners else { //If x == -1 and y == 1 if (x < 0 && y > 0) { //x-1,y and x, y+1 if (grid.Tiles[tile.x - 1, tile.y].walkable && grid.Tiles[tile.x, tile.y + 1].walkable) { neighbours.Add(grid.Tiles[checkX, checkY]); } } //else If x == 1 and y == -1 else { //x,y-1 and x+1, y if (grid.Tiles[tile.x, tile.y - 1].walkable && grid.Tiles[tile.x + 1, tile.y].walkable) { neighbours.Add(grid.Tiles[checkX, checkY]); } } } } else { neighbours.Add(grid.Tiles[checkX, checkY]); } } } } return neighbours; } #endregion } }
36.643791
150
0.448408
[ "MIT" ]
fishingGrapes/Grid-Utiilities
Assets/Sources/World Grid/GridUtility.cs
11,215
C#
namespace Plivo.Objects { public class SubAccountMeta { public object Previous { get; set; } public int TotalCount { get; set; } public int Offset { get; set; } public int Limit { get; set; } public string Next { get; set; } } }
25.545455
44
0.569395
[ "MIT" ]
EIrwin/plivo-dotnet
Plivo/Objects/SubAccountMeta.cs
283
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http.Dependencies; namespace Web.IoC { public class WebDependencies { public IDependencyResolver HttpDependencyResolver { get; private set; } public WebDependencies(IDependencyResolver httpDependencyResolver) { HttpDependencyResolver = httpDependencyResolver; } } }
23.666667
79
0.71831
[ "MIT" ]
dicehead3/Kaartenbak
Web2/IoC/WebDependencies.cs
428
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("MonkeyOthello.OpeningBook")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonkeyOthello.OpeningBook")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("3a6fd040-5a2a-4b57-a611-36e35809d813")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.459459
84
0.748419
[ "MIT" ]
coolcode/MonkeyOthello
MonkeyOthello.OpeningBook/Properties/AssemblyInfo.cs
1,426
C#
using System; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using System.Globalization; using System.Resources; using System.Net; using System.Collections; using Flurl; using Flurl.Http; using Newtonsoft.Json.Linq; using System.Net.Http; namespace JohnsonControls.Metasys.BasicServices { /// <summary> /// An HTTP client for consuming the most commonly used endpoints of the Metasys API. /// </summary> public class MetasysClient : IMetasysClient { /// <summary>The http client.</summary> protected FlurlClient Client; /// <summary>The current session token.</summary> protected AccessToken AccessToken; /// <summary>The flag used to control automatic session refreshing.</summary> protected bool RefreshToken; /// <summary>Resource Manager to provide localized translations.</summary> protected static ResourceManager Resource = new ResourceManager("JohnsonControls.Metasys.BasicServices.Resources.MetasysResources", typeof(MetasysClient).Assembly); /// <summary>Dictionary to provide keys from the commandIdEnumSet.</summary> /// <value>Keys as en-US translations, values as the commandIdEnumSet Enumerations.</value> protected static Dictionary<string, string> CommandEnumerations; /// <summary>Dictionaries to provide keys from the objectTypeEnumSet since there are duplicate keys.</summary> /// <value>Keys as en-US translations, values as the objectTypeEnumSet Enumerations.</value> protected static List<Dictionary<string, string>> ObjectTypeEnumerations; /// <summary>The current Culture Used for Metasys client localization.</summary> public CultureInfo Culture { get; set; } private static CultureInfo CultureEnUS = new CultureInfo(1033); /// <summary> /// Creates a new MetasysClient. /// </summary> /// <remarks> /// Takes an optional boolean flag for ignoring certificate errors by bypassing certificate verification steps. /// Verification bypass is not recommended due to security concerns. If your Metasys server is missing a valid certificate it is /// recommended to add one to protect your private data from attacks over external networks. /// Takes an optional flag for the api version of your Metasys server. /// Takes an optional CultureInfo which is useful for formatting numbers and localization of strings. If not specified, /// the machine's current culture is used. /// </remarks> /// <param name="hostname">The hostname of the Metasys server.</param> /// <param name="ignoreCertificateErrors">Use to bypass server certificate verification.</param> /// <param name="version">The server's Api version.</param> /// <param name="cultureInfo">Localization culture for Metasys enumeration translations.</param> public MetasysClient(string hostname, bool ignoreCertificateErrors = false, ApiVersion version = ApiVersion.V2, CultureInfo cultureInfo = null) { // Set Metasys culture if specified, otherwise use current machine Culture. Culture = cultureInfo ?? CultureInfo.CurrentCulture; // Initialize the HTTP client with a base URL AccessToken = new AccessToken(null, DateTime.UtcNow); if (ignoreCertificateErrors) { HttpClientHandler httpClientHandler = new HttpClientHandler(); httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; HttpClient httpClient = new HttpClient(httpClientHandler); httpClient.BaseAddress = new Uri($"https://{hostname}" .AppendPathSegments("api", version)); Client = new FlurlClient(httpClient); } else { Client = new FlurlClient($"https://{hostname}" .AppendPathSegments("api", version)); } } /// <summary> /// Localizes the specified resource key for the current MetasysClient locale or specified culture. /// </summary> /// <remarks> /// The resource parameter must be the key of a Metasys enumeration resource, /// otherwise no translation will be found. /// </remarks> /// <param name="resource">The key for the localization resource.</param> /// <param name="cultureInfo">Optional culture specification.</param> /// <returns> /// Localized string if the resource was found, the default en-US localized string if not found, /// or the resource parameter value if neither resource is found. /// </returns> public string Localize(string resource, CultureInfo cultureInfo = null) { // Priority is the cultureInfo parameter if available, otherwise MetasysClient culture. return StaticLocalize(resource, cultureInfo ?? Culture); } /// <summary> /// Localizes the specified resource key for the specified culture. /// Static method for exposure to outside classes. /// </summary> /// <param name="resource">The key for the localization resource.</param> /// <param name="cultureInfo">The culture specification.</param> /// <returns> /// Localized string if the resource was found, the default en-US localized string if not found, /// or the resource parameter value if neither resource is found. /// </returns> public static string StaticLocalize(string resource, CultureInfo cultureInfo) { try { return Resource.GetString(resource, cultureInfo); } catch (MissingManifestResourceException) { try { // Fallback to en-US language if no resource found. return Resource.GetString(resource, CultureEnUS); } catch (MissingManifestResourceException) { // Just return resource placeholder when no translation found. return resource; } } } /// <summary> /// Attempts to get the enumeration key of a given en-US localized command. /// </summary> /// <remarks> /// The resource parameter must be the value of a Metasys commandIdEnumSet en-US value, /// otherwise no key will be found. /// </remarks> /// <param name="resource">The en-US value for the localization resource.</param> /// <returns> /// The enumeration key of the en-US command if found, original resource if not. /// </returns> public string GetCommandEnumeration(string resource) { // Priority is the cultureInfo parameter if available, otherwise MetasysClient culture. return StaticGetCommandEnumeration(resource); } /// <summary> /// Attempts to get the enumeration key of a given en-US localized command. /// </summary> /// <remarks> /// The resource parameter must be the value of a Metasys commandIdEnumSet en-US value, /// otherwise no key will be found. /// </remarks> /// <param name="resource">The en-US value for the localization resource.</param> /// <returns> /// The enumeration key of the en-US command if found, original resource if not. /// </returns> public static string StaticGetCommandEnumeration(string resource) { if (CommandEnumerations == null) { SetEnumerationDictionaries(); } if (CommandEnumerations.TryGetValue(resource, out string value)) { return value; } return resource; } /// <summary> /// Attempts to get the enumeration key of a given en-US localized objectType. /// </summary> /// <remarks> /// The resource parameter must be the value of a Metasys objectTypeEnumSet en-US value, /// otherwise no key will be found. /// </remarks> /// <param name="resource">The en-US value for the localization resource.</param> /// <returns> /// The enumeration key of the en-US objectType if found, original resource if not. /// </returns> public string GetObjectTypeEnumeration(string resource) { // Priority is the cultureInfo parameter if available, otherwise MetasysClient culture. return StaticGetObjectTypeEnumeration(resource); } /// <summary> /// Attempts to get the enumeration key of a given en-US localized objectType. /// </summary> /// <remarks> /// The resource parameter must be the value of a Metasys objectTypeEnumSet en-US value, /// otherwise no key will be found. /// </remarks> /// <param name="resource">The en-US value for the localization resource.</param> /// <returns> /// The enumeration key of the en-US objectType if found, original resource if not. /// </returns> public static string StaticGetObjectTypeEnumeration(string resource) { if (ObjectTypeEnumerations == null) { SetEnumerationDictionaries(); } foreach(var dict in ObjectTypeEnumerations) { if (dict.TryGetValue(resource, out string value)) { return value; } } return resource; } /// <summary> /// Populates the needed enumeration Dictionaries for translating en-US strings by /// transversing the en-US resource file and finding the appropriate EnumSets. /// </summary> /// <remarks> /// This method should be faster than using the enumSets/{id}/members api endpoint. /// This method has a potential for value mismatch if the local enumeration values differ /// from the server. This will cause the translation functionality to fail since no matching /// enumeration key will be found in dictionaries. /// </remarks> private static void SetEnumerationDictionaries() { // First time setup, there are about 349 values in the command set, 800 in the objectType set CommandEnumerations = new Dictionary<string, string>(); ObjectTypeEnumerations = new List<Dictionary<string, string>>(); var ObjectTypeEnumerations1 = new Dictionary<string, string>(); var ObjectTypeEnumerations2 = new Dictionary<string, string>(); ResourceSet ResourcesEnUS = Resource.GetResourceSet(CultureEnUS, true, true); IDictionaryEnumerator ide = ResourcesEnUS.GetEnumerator(); while (ide.MoveNext()) { if (ide.Key.ToString().Contains("commandIdEnumSet.")) { CommandEnumerations.Add(ide.Value.ToString(), ide.Key.ToString()); } else if (ide.Key.ToString().Contains("objectTypeEnumSet.")) { try { ObjectTypeEnumerations1.Add(ide.Value.ToString(), ide.Key.ToString()); } catch { ObjectTypeEnumerations2.Add(ide.Value.ToString(), ide.Key.ToString()); } } } ObjectTypeEnumerations.Add(ObjectTypeEnumerations1); ObjectTypeEnumerations.Add(ObjectTypeEnumerations2); } /// <summary> /// Throws a Metasys Exception from a Flurl.Http exception. /// </summary> /// <exception cref="MetasysHttpParsingException"></exception> /// <exception cref="MetasysHttpTimeoutException"></exception> /// <exception cref="MetasysHttpException"></exception> private void ThrowHttpException(Flurl.Http.FlurlHttpException e) { if (e.GetType() == typeof(Flurl.Http.FlurlParsingException)) { throw new MetasysHttpParsingException((Flurl.Http.FlurlParsingException)e); } else if (e.GetType() == typeof(Flurl.Http.FlurlHttpTimeoutException)) { throw new MetasysHttpTimeoutException((Flurl.Http.FlurlHttpTimeoutException)e); } else { throw new MetasysHttpException(e); } } /// <summary>Use to log an error message from an asynchronous context.</summary> private async Task LogErrorAsync(String message) { await Console.Error.WriteLineAsync(message).ConfigureAwait(false); } /// <summary> /// Attempts to login to the given host and retrieve an access token. /// </summary> /// <returns>Access Token.</returns> /// <param name="username"></param> /// <param name="password"></param> /// <param name="refresh">Flag to set automatic access token refreshing to keep session active.</param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysTokenException"></exception> public AccessToken TryLogin(string username, string password, bool refresh = true) { return TryLoginAsync(username, password, refresh).GetAwaiter().GetResult(); } /// <summary> /// Attempts to login to the given host and retrieve an access token asynchronously. /// </summary> /// <returns>Asynchronous Task Result as Access Token.</returns> /// <param name="username"></param> /// <param name="password"></param> /// <param name="refresh">Flag to set automatic access token refreshing to keep session active.</param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysTokenException"></exception> public async Task<AccessToken> TryLoginAsync(string username, string password, bool refresh = true) { this.RefreshToken = refresh; try { var response = await Client.Request("login") .PostJsonAsync(new { username, password }) .ReceiveJson<JToken>() .ConfigureAwait(false); CreateAccessToken(response); } catch (FlurlHttpException e) { ThrowHttpException(e); } return this.AccessToken; } /// <summary> /// Requests a new access token from the server before the current token expires. /// </summary> /// <returns>Access Token.</returns> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysTokenException"></exception> public AccessToken Refresh() { return RefreshAsync().GetAwaiter().GetResult(); } /// <summary> /// Requests a new access token from the server before the current token expires asynchronously. /// </summary> /// <returns>Asynchronous Task Result as Access Token.</returns> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysTokenException"></exception> public async Task<AccessToken> RefreshAsync() { try { var response = await Client.Request("refreshToken") .GetJsonAsync<JToken>() .ConfigureAwait(false); CreateAccessToken(response); } catch (FlurlHttpException e) { ThrowHttpException(e); } return this.AccessToken; } /// <summary> /// Creates a new AccessToken from a JToken and sets the client's authorization header if successful. /// On failure leaves the AccessToken and authorization header in previous state. /// </summary> /// <param name="token"></param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysTokenException"></exception> private void CreateAccessToken(JToken token) { try { var accessTokenValue = token["accessToken"]; var expires = token["expires"]; var accessToken = $"Bearer {accessTokenValue.Value<string>()}"; var date = expires.Value<DateTime>(); this.AccessToken = new AccessToken(accessToken, date); Client.Headers.Remove("Authorization"); Client.Headers.Add("Authorization", this.AccessToken.Token); if (RefreshToken) { ScheduleRefresh(); } } catch (Exception e) when (e is System.ArgumentNullException || e is System.NullReferenceException || e is System.FormatException) { throw new MetasysTokenException(token.ToString(), e); } } /// <summary> /// Will call Refresh() a minute before the token expires. /// </summary> private void ScheduleRefresh() { DateTime now = DateTime.UtcNow; TimeSpan delay = AccessToken.Expires - now; delay.Subtract(new TimeSpan(0, 1, 0)); if (delay <= TimeSpan.Zero) { delay = TimeSpan.Zero; } int delayms = (int)delay.TotalMilliseconds; // If the time in milliseconds is greater than max int delayms will be negative and will not schedule a refresh. if (delayms >= 0) { System.Threading.Tasks.Task.Delay(delayms).ContinueWith(_ => Refresh()); } } /// <summary> /// Returns the current session access token. /// </summary> /// <returns>Current session's Access Token.</returns> public AccessToken GetAccessToken() { return this.AccessToken; } /// <summary> /// Given the Item Reference of an object, returns the object identifier. /// </summary> /// <remarks> /// The itemReference will be automatically URL encoded. /// </remarks> /// <returns>A Guid representing the id, or an empty Guid if errors occurred.</returns> /// <param name="itemReference"></param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysGuidException"></exception> public Guid? GetObjectIdentifier(string itemReference) { return GetObjectIdentifierAsync(itemReference).GetAwaiter().GetResult(); } /// <summary> /// Given the Item Reference of an object, returns the object identifier asynchronously. /// </summary> /// <remarks> /// The itemReference will be automatically URL encoded. /// </remarks> /// <param name="itemReference"></param> /// <returns> /// Asynchronous Task Result as a Guid representing the id, or an empty Guid if errors occurred. /// </returns> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysGuidException"></exception> public async Task<Guid?> GetObjectIdentifierAsync(string itemReference) { try { var response = await Client.Request("objectIdentifiers") .SetQueryParam("fqr", itemReference) .GetJsonAsync<JToken>() .ConfigureAwait(false); string str = null; try { str = response.Value<string>(); var id = new Guid(str); return id; } catch (Exception e) when (e is System.ArgumentNullException || e is System.ArgumentException || e is System.FormatException) { throw new MetasysGuidException(str, e); } } catch (FlurlHttpException e) { ThrowHttpException(e); } return null; } /// <summary> /// Read one attribute value given the Guid of the object. /// </summary> /// <returns> /// Variant if the attribute exists, null if does not exist. /// </returns> /// <param name="id"></param> /// <param name="attributeName"></param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysPropertyException"></exception> public Variant? ReadProperty(Guid id, string attributeName) { return ReadPropertyAsync(id, attributeName).GetAwaiter().GetResult(); } /// <summary> /// Read one attribute value given the Guid of the object asynchronously. /// </summary> /// <param name="id"></param> /// <param name="attributeName"></param> /// <returns> /// Asynchronous Task Result as Variant if the attribute exists, null if does not exist. /// </returns> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysPropertyException"></exception> public async Task<Variant?> ReadPropertyAsync(Guid id, string attributeName) { JToken response = null; try { response = await Client.Request(new Url("objects") .AppendPathSegments(id, "attributes", attributeName)) .GetJsonAsync<JToken>() .ConfigureAwait(false); var attribute = response["item"][attributeName]; return new Variant(id, attribute, attributeName, Culture); } catch (FlurlHttpException e) { // Just return null when object is not found, for all other responses an exception is raised if (e.Call.Response.StatusCode == HttpStatusCode.NotFound) { return null; } ThrowHttpException(e); } catch (System.NullReferenceException e) { throw new MetasysPropertyException(response.ToString(), e); } return null; } /// <summary> /// Read many attribute values given the Guids of the objects. /// </summary> /// <returns> /// A list of VariantMultiple with all the specified attributes (if existing). /// </returns> /// <param name="ids"></param> /// <param name="attributeNames"></param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysPropertyException"></exception> public IEnumerable<VariantMultiple> ReadPropertyMultiple(IEnumerable<Guid> ids, IEnumerable<string> attributeNames) { return ReadPropertyMultipleAsync(ids, attributeNames).GetAwaiter().GetResult(); } /// <summary> /// Read many attribute values given the Guids of the objects asynchronously. /// </summary> /// <remarks> /// In order to allow method to run to completion without error, this will ignore properties that do not exist on a given object. /// </remarks> /// <returns> /// Asynchronous Task Result as list of VariantMultiple with all the specified attributes (if existing). /// </returns> /// <param name="ids"></param> /// <param name="attributeNames"></param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysPropertyException"></exception> public async Task<IEnumerable<VariantMultiple>> ReadPropertyMultipleAsync(IEnumerable<Guid> ids, IEnumerable<string> attributeNames) { if (ids == null || attributeNames == null) { return null; } List<VariantMultiple> results = new List<VariantMultiple>(); var taskList = new List<Task<Variant?>>(); // Prepare Tasks to Read attributes list. In Metasys 11 this will be implemented server side foreach (var id in ids) { foreach (string attributeName in attributeNames) { // Much faster reading single property than the entire object, even though we have more server calls taskList.Add(ReadPropertyAsync(id, attributeName)); } } await Task.WhenAll(taskList).ConfigureAwait(false); foreach (var id in ids) { // Get attributes of the specific Id List<Task<Variant?>> attributeList = taskList.Where(w => (w.Result != null && w.Result.Value.Id == id)).ToList(); List<Variant> variants = new List<Variant>(); foreach (var t in attributeList) { if (t.Result != null) // Something went wrong if the result is unknown { variants.Add(t.Result.Value); // Prepare variants list } } if (variants.Count > 0 || attributeNames.Count() == 0) { // Aggregate results only when objects was found or no attributes specified results.Add(new VariantMultiple(id, variants)); } } return results.AsEnumerable(); } /// <summary> /// Write a single attribute given the Guid of the object. /// </summary> /// <param name="id"></param> /// <param name="attributeName"></param> /// <param name="newValue"></param> /// <param name="priority">Write priority as an enumeration from the writePriorityEnumSet.</param> /// <exception cref="MetasysHttpException"></exception> public void WriteProperty(Guid id, string attributeName, object newValue, string priority = null) { WritePropertyAsync(id, attributeName, newValue, priority).GetAwaiter().GetResult(); } /// <summary> /// Write a single attribute given the Guid of the object asynchronously. /// </summary> /// <param name="id"></param> /// <param name="attributeName"></param> /// <param name="newValue"></param> /// <param name="priority">Write priority as an enumeration from the writePriorityEnumSet.</param> /// <exception cref="MetasysHttpException"></exception> /// <returns>Asynchronous Task Result.</returns> public async Task WritePropertyAsync(Guid id, string attributeName, object newValue, string priority = null) { List<(string Attribute, object Value)> list = new List<(string Attribute, object Value)>(); list.Add((Attribute: attributeName, Value: newValue)); var item = GetWritePropertyBody(list, priority); await WritePropertyRequestAsync(id, item).ConfigureAwait(false); } /// <summary> /// Write to many attribute values given the Guids of the objects. /// </summary> /// <param name="ids"></param> /// <param name="attributeValues">The (attribute, value) pairs.</param> /// <param name="priority">Write priority as an enumeration from the writePriorityEnumSet.</param> /// <exception cref="MetasysHttpException"></exception> public void WritePropertyMultiple(IEnumerable<Guid> ids, IEnumerable<(string Attribute, object Value)> attributeValues, string priority = null) { WritePropertyMultipleAsync(ids, attributeValues, priority).GetAwaiter().GetResult(); } /// <summary> /// Write to many attribute values given the Guids of the objects asynchronously. /// </summary> /// <param name="ids"></param> /// <param name="attributeValues">The (attribute, value) pairs.</param> /// <param name="priority">Write priority as an enumeration from the writePriorityEnumSet.</param> /// <exception cref="MetasysHttpException"></exception> /// <returns>Asynchronous Task Result.</returns> public async Task WritePropertyMultipleAsync(IEnumerable<Guid> ids, IEnumerable<(string Attribute, object Value)> attributeValues, string priority = null) { if (ids == null || attributeValues == null) { return; } var item = GetWritePropertyBody(attributeValues, priority); var taskList = new List<Task>(); foreach (var id in ids) { taskList.Add(WritePropertyRequestAsync(id, item)); } await Task.WhenAll(taskList).ConfigureAwait(false); } /// <summary> /// Creates the body for the WriteProperty and WritePropertyMultiple requests as a dictionary. /// </summary> /// <param name="attributeValues">The (attribute, value) pairs.</param> /// <param name="priority">Write priority as an enumeration from the writePriorityEnumSet.</param> /// <returns>Dictionary of the attribute, value pairs.</returns> private Dictionary<string, object> GetWritePropertyBody( IEnumerable<(string Attribute, object Value)> attributeValues, string priority) { Dictionary<string, object> pairs = new Dictionary<string, object>(); foreach (var attribute in attributeValues) { pairs.Add(attribute.Attribute, attribute.Value); } if (priority != null) { pairs.Add("priority", priority); } return pairs; } /// <summary> /// Write one or many attribute values in the provided json given the Guid of the object asynchronously. /// </summary> /// <param name="id"></param> /// <param name="body"></param> /// <exception cref="MetasysHttpException"></exception> /// <returns>Asynchronous Task Result.</returns> private async Task WritePropertyRequestAsync(Guid id, Dictionary<string, object> body) { var json = new { item = body }; try { var response = await Client.Request(new Url("objects") .AppendPathSegment(id)) .PatchJsonAsync(json) .ConfigureAwait(false); } catch (FlurlHttpException e) { ThrowHttpException(e); } } /// <summary> /// Get all available commands given the Guid of the object. /// </summary> /// <param name="id"></param> /// <returns>List of Commands.</returns> public IEnumerable<Command> GetCommands(Guid id) { return GetCommandsAsync(id).GetAwaiter().GetResult(); } /// <summary> /// Get all available commands given the Guid of the object asynchronously. /// </summary> /// <param name="id"></param> /// <exception cref="MetasysHttpException"></exception> /// <returns>Asynchronous Task Result as list of Commands.</returns> public async Task<IEnumerable<Command>> GetCommandsAsync(Guid id) { try { var token = await Client.Request(new Url("objects") .AppendPathSegments(id, "commands")) .GetJsonAsync<JToken>() .ConfigureAwait(false); List<Command> commands = new List<Command>(); var array = token as JArray; if (array != null) { foreach (JObject command in array) { Command c = new Command(command, Culture); commands.Add(c); } } return commands; } catch (FlurlHttpException e) { ThrowHttpException(e); } return null; } /// <summary> /// Send a command to an object. /// </summary> /// <param name="id"></param> /// <param name="command"></param> /// <param name="values"></param> /// <exception cref="MetasysHttpException"></exception> public void SendCommand(Guid id, string command, IEnumerable<object> values = null) { SendCommandAsync(id, command, values).GetAwaiter().GetResult(); } /// <summary> /// Send a command to an object asynchronously. /// </summary> /// <param name="id"></param> /// <param name="command"></param> /// <param name="values"></param> /// <exception cref="MetasysHttpException"></exception> /// <returns>Asynchronous Task Result.</returns> public async Task SendCommandAsync(Guid id, string command, IEnumerable<object> values = null) { if (values == null) { await SendCommandRequestAsync(id, command, new string[0]).ConfigureAwait(false); } else { await SendCommandRequestAsync(id, command, values).ConfigureAwait(false); } } /// <summary> /// Send a command to an object asynchronously. /// </summary> /// <param name="id"></param> /// <param name="command"></param> /// <param name="values"></param> /// <exception cref="MetasysHttpException"></exception> /// <returns>Asynchronous Task Result.</returns> private async Task SendCommandRequestAsync(Guid id, string command, IEnumerable<object> values) { try { var response = await Client.Request(new Url("objects") .AppendPathSegments(id, "commands", command)) .PutJsonAsync(values) .ConfigureAwait(false); } catch (FlurlHttpException e) { ThrowHttpException(e); } } /// <summary> /// Gets all network devices. /// </summary> /// <param name="type">Optional type number as a string</param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysHttpParsingException"></exception> public IEnumerable<MetasysObject> GetNetworkDevices(string type = null) { return GetNetworkDevicesAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all network devices asynchronously by requesting each available page. /// </summary> /// <param name="type">Optional type number as a string</param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysHttpParsingException"></exception> public async Task<IEnumerable<MetasysObject>> GetNetworkDevicesAsync(string type = null) { List<MetasysObject> devices = new List<MetasysObject>() { }; bool hasNext = true; int page = 1; while (hasNext) { hasNext = false; var response = await GetNetworkDevicesRequestAsync(type, page).ConfigureAwait(false); try { var list = response["items"] as JArray; foreach (var item in list) { MetasysObject device = new MetasysObject(item); devices.Add(device); } if (!(response["next"] == null || response["next"].Type == JTokenType.Null)) { hasNext = true; page++; } } catch (System.NullReferenceException e) { throw new MetasysHttpParsingException(response.ToString(), e); } } return devices; } /// <summary> /// Gets all network devices asynchronously. /// </summary> /// <param name="type"></param> /// <param name="page"></param> /// <exception cref="MetasysHttpException"></exception> private async Task<JToken> GetNetworkDevicesRequestAsync(string type = null, int page = 1) { Url url = new Url("networkDevices"); url.SetQueryParam("page", page); if (type != null) { url.SetQueryParam("type", type); } try { var response = await Client.Request(url) .GetJsonAsync<JToken>() .ConfigureAwait(false); return response; } catch (FlurlHttpException e) { ThrowHttpException(e); } return null; } /// <summary> /// Gets all available network device types. /// </summary> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysHttpParsingException"></exception> public IEnumerable<MetasysObjectType> GetNetworkDeviceTypes() { return GetNetworkDeviceTypesAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all available network device types asynchronously. /// </summary> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysHttpParsingException"></exception> public async Task<IEnumerable<MetasysObjectType>> GetNetworkDeviceTypesAsync() { List<MetasysObjectType> types = new List<MetasysObjectType>() { }; try { var response = await Client.Request(new Url("networkDevices") .AppendPathSegment("availableTypes")) .GetJsonAsync<JToken>() .ConfigureAwait(false); try { // The response is a list of typeUrls, not the type data var list = response["items"] as JArray; foreach (var item in list) { try { var type = await GetType(item).ConfigureAwait(false); if (type != null) { types.Add(type.Value); } } catch (System.ArgumentNullException e) { throw new MetasysHttpParsingException(response.ToString(), e); } } } catch (System.NullReferenceException e) { throw new MetasysHttpParsingException(response.ToString(), e); } } catch (FlurlHttpException e) { ThrowHttpException(e); } return types; } /// <summary> /// Gets the type from a token with a typeUrl by requesting the actual description asynchronously. /// </summary> /// <param name="item"></param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysObjectTypeException"></exception> private async Task<MetasysObjectType?> GetType(JToken item) { JToken typeToken = null; try { var url = item["typeUrl"].Value<string>(); typeToken = await GetWithFullUrl(url).ConfigureAwait(false); string description = typeToken["description"].Value<string>(); int id = typeToken["id"].Value<int>(); string key = GetObjectTypeEnumeration(description); string translation = Localize(key); if (translation != key) { // A translation was found return new MetasysObjectType(id, key, translation); } else { // A translation could not be found return new MetasysObjectType(id, key, description); } } catch (Exception e) when (e is System.ArgumentNullException || e is System.NullReferenceException || e is System.FormatException) { throw new MetasysObjectTypeException(typeToken.ToString(), e); } } /// <summary> /// Creates a new Flurl client and gets a resource given the url asynchronously. /// </summary> /// <param name="url"></param> /// <exception cref="MetasysHttpException"></exception> private async Task<JToken> GetWithFullUrl(string url) { using (var temporaryClient = new FlurlClient(new Url(url))) { temporaryClient.Headers.Add("Authorization", this.AccessToken.Token); try { var item = await temporaryClient.Request() .GetJsonAsync<JToken>() .ConfigureAwait(false); return item; } catch (FlurlHttpException e) { ThrowHttpException(e); } return null; } } /// <summary> /// Gets all child objects given a parent Guid. /// Level indicates how deep to retrieve objects. /// </summary> /// <remarks> /// A level of 1 only retrieves immediate children of the parent object. /// </remarks> /// <param name="id"></param> /// <param name="levels">The depth of the children to retrieve.</param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysHttpParsingException"></exception> public IEnumerable<MetasysObject> GetObjects(Guid id, int levels = 1) { return GetObjectsAsync(id, levels).GetAwaiter().GetResult(); } /// <summary> /// Gets all child objects given a parent Guid asynchronously by requesting each available page. /// Level indicates how deep to retrieve objects. /// </summary> /// <remarks> /// A level of 1 only retrieves immediate children of the parent object. /// </remarks> /// <param name="id"></param> /// <param name="levels">The depth of the children to retrieve</param> /// <exception cref="MetasysHttpException"></exception> /// <exception cref="MetasysHttpParsingException"></exception> public async Task<IEnumerable<MetasysObject>> GetObjectsAsync(Guid id, int levels = 1) { if (levels < 1) { return null; } List<MetasysObject> objects = new List<MetasysObject>() { }; bool hasNext = true; int page = 1; while (hasNext) { hasNext = false; var response = await GetObjectsRequestAsync(id, page).ConfigureAwait(false); try { var total = response["total"].Value<int>(); if (total > 0) { var list = response["items"] as JArray; foreach (var item in list) { if (levels - 1 > 0) { try { var str = item["id"].Value<string>(); var objId = new Guid(str); var children = await GetObjectsAsync(objId, levels - 1).ConfigureAwait(false); MetasysObject obj = new MetasysObject(item, children); objects.Add(obj); } catch (System.ArgumentNullException) { MetasysObject obj = new MetasysObject(item); objects.Add(obj); } } else { MetasysObject obj = new MetasysObject(item); objects.Add(obj); } } if (!(response["next"] == null || response["next"].Type == JTokenType.Null)) { hasNext = true; page++; } } } catch (System.NullReferenceException e) { throw new MetasysHttpParsingException(response.ToString(), e); } } return objects; } /// <summary> /// Gets all child objects given a parent Guid asynchronously with the given page number. /// </summary> /// <param name="id"></param> /// <param name="page"></param> /// <exception cref="MetasysHttpException"></exception> private async Task<JToken> GetObjectsRequestAsync(Guid id, int page = 1) { Url url = new Url("objects") .AppendPathSegments(id, "objects") .SetQueryParam("page", page); try { var response = await Client.Request(url) .GetJsonAsync<JToken>() .ConfigureAwait(false); return response; } catch (FlurlHttpException e) { ThrowHttpException(e); } return null; } } }
41.184188
151
0.543742
[ "BSD-3-Clause" ]
SavannahEvans/basic-services-dotnet
MetasysServices/MetasysClient.cs
47,405
C#
using System; using System.Text; using System.Linq; using Umbraco.Core.Logging; using Umbraco.Core; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Xml; using Umbraco.Web.PublishedCache; namespace Umbraco.Web.Routing { /// <summary> /// Provides an implementation of <see cref="IContentFinder"/> that handles page aliases. /// </summary> /// <remarks> /// <para>Handles <c>/just/about/anything</c> where <c>/just/about/anything</c> is contained in the <c>umbracoUrlAlias</c> property of a document.</para> /// <para>The alias is the full path to the document. There can be more than one alias, separated by commas.</para> /// </remarks> public class ContentFinderByUrlAlias : IContentFinder { protected ILogger Logger { get; } public ContentFinderByUrlAlias(ILogger logger) { Logger = logger; } /// <summary> /// Tries to find and assign an Umbraco document to a <c>PublishedContentRequest</c>. /// </summary> /// <param name="frequest">The <c>PublishedContentRequest</c>.</param> /// <returns>A value indicating whether an Umbraco document was found and assigned.</returns> public bool TryFindContent(PublishedRequest frequest) { IPublishedContent node = null; if (frequest.Uri.AbsolutePath != "/") // no alias if "/" { node = FindContentByAlias(frequest.UmbracoContext.ContentCache, frequest.HasDomain ? frequest.Domain.ContentId : 0, frequest.Culture.Name, frequest.Uri.GetAbsolutePathDecoded()); if (node != null) { frequest.PublishedContent = node; Logger.Debug<ContentFinderByUrlAlias>("Path '{UriAbsolutePath}' is an alias for id={PublishedContentId}", frequest.Uri.AbsolutePath, frequest.PublishedContent.Id); } } return node != null; } private static IPublishedContent FindContentByAlias(IPublishedContentCache cache, int rootNodeId, string culture, string alias) { if (alias == null) throw new ArgumentNullException(nameof(alias)); // the alias may be "foo/bar" or "/foo/bar" // there may be spaces as in "/foo/bar, /foo/nil" // these should probably be taken care of earlier on // TODO // can we normalize the values so that they contain no whitespaces, and no leading slashes? // and then the comparisons in IsMatch can be way faster - and allocate way less strings const string propertyAlias = Constants.Conventions.Content.UrlAlias; var test1 = alias.TrimStart('/') + ","; var test2 = ",/" + test1; // test2 is ",/alias," test1 = "," + test1; // test1 is ",alias," bool IsMatch(IPublishedContent c, string a1, string a2) { // this basically implements the original XPath query ;-( // // "//* [@isDoc and (" + // "contains(concat(',',translate(umbracoUrlAlias, ' ', ''),','),',{0},')" + // " or contains(concat(',',translate(umbracoUrlAlias, ' ', ''),','),',/{0},')" + // ")]" if (!c.HasProperty(propertyAlias)) return false; var p = c.GetProperty(propertyAlias); var varies = p.PropertyType.VariesByCulture(); string v; if (varies) { if (!c.HasCulture(culture)) return false; v = c.Value<string>(propertyAlias, culture); } else { v = c.Value<string>(propertyAlias); } if (string.IsNullOrWhiteSpace(v)) return false; v = "," + v.Replace(" ", "") + ","; return v.InvariantContains(a1) || v.InvariantContains(a2); } // fixme - even with Linq, what happens below has to be horribly slow // but the only solution is to entirely refactor url providers to stop being dynamic if (rootNodeId > 0) { var rootNode = cache.GetById(rootNodeId); return rootNode?.Descendants().FirstOrDefault(x => IsMatch(x, test1, test2)); } foreach (var rootContent in cache.GetAtRoot()) { var c = rootContent.DescendantsOrSelf().FirstOrDefault(x => IsMatch(x, test1, test2)); if (c != null) return c; } return null; } } }
40.186441
183
0.553353
[ "MIT" ]
bharanijayasuri/umbraco8
src/Umbraco.Web/Routing/ContentFinderByUrlAlias.cs
4,744
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BenchmarkingDemos.Facades.Second { public class CheckoutPageAssertions { private readonly CheckoutPageElements _elements; public CheckoutPageAssertions(CheckoutPageElements elements) { _elements = elements; } public void AssertOrderReceived() { Assert.AreEqual(_elements.ReceivedMessage.Text, "Order received"); } } }
23.8
78
0.670168
[ "Apache-2.0" ]
nadvolod/Design-Patterns-for-High-Quality-Automated-Tests-CSharp-Edition
Chapter 9- Benchmarking/BenchmarkingDemos/Facades/CheckoutPage/CheckoutPageAssertions.cs
478
C#
namespace LoggingKata { /// <summary> /// Parses a POI file to locate all the Taco Bells /// </summary> public class TacoParser { readonly ILog logger = new TacoLogger(); public ITrackable Parse(string line) { logger.LogInfo("Begin parsing"); // Take your line and use line.Split(',') to split it up into an array of strings, separated by the char ',' // will look like this in an array { "34.07345", "-84.03434", "Taco Bell Acwort..."} var cells = line.Split(','); // If your array.Length is less than 3, something went wrong if (cells.Length < 3) { // Log that and return null // Do not fail if one record parsing fails, return null return null; // TODO Implement } // grab the latitude from your array at index 0 var latitude = double.Parse(cells[0]); // grab the longitude from your array at index 1 var longitude = double.Parse(cells[1]); // grab the name from your array at index 2 var name = cells[2]; //DONE Your going to need to parse your string as a `double` // which is similar to parsing a string as an `int` // You'll need to create a TacoBell class // that conforms to ITrackable // Then, you'll need an instance of the TacoBell class // With the name and point set correctly var location = new Point(); location.Latitude = latitude; location.Longitude = longitude; var tacoBell = new TacoBell() { Name = name, Location = location }; // Then, return the instance of your TacoBell class // Since it conforms to ITrackable return tacoBell; } } }
31.03125
120
0.528701
[ "MIT" ]
Kaford777/TacoParser
LoggingKata/TacoParser.cs
1,988
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Runtime.Remoting.Messaging; using AutoVisor.Classes; using AutoVisor.Managers; using Dalamud.Plugin; using ImGuiNET; namespace AutoVisor.GUI { public class AutoVisorUi { private const string PluginName = "AutoVisor"; private const string LabelEnabled = "Enable AutoVisor"; private static readonly Job[] Jobs = Enum.GetValues(typeof(Job)).Cast<Job>().ToArray(); private static readonly string[] JobNames = Enum.GetNames(typeof(Job)); private static readonly VisorChangeStates[] VisorStates = Enum.GetValues(typeof(VisorChangeStates)).Cast<VisorChangeStates>().ToArray(); private static readonly string[] VisorStateNames = Enum.GetNames(typeof(VisorChangeStates)); private static readonly string[] PoseOptions = { "Default", "Unchanged", "Pose 1", "Pose 2", "Pose 3", "Pose 4", "Pose 5", "Pose 6", "Pose 7", }; private static readonly VisorChangeStates[] VisorStatesWeapon = VisorStates.Where(v => VisorManager.ValidStatesForWeapon[v]).ToArray(); private static readonly string[] VisorStateWeaponNames = VisorStateNames.Where((v, i) => VisorManager.ValidStatesForWeapon[VisorStates[i]]).ToArray(); private readonly string _configHeader; private readonly AutoVisor _plugin; private readonly DalamudPluginInterface _pi; private readonly AutoVisorConfiguration _config; public bool Visible; private readonly List<string> _players; private int _currentPlayer = 0; private int _currentJob = 0; private Vector2 _horizontalSpace = Vector2.Zero; public AutoVisorUi(AutoVisor plugin, DalamudPluginInterface pi, AutoVisorConfiguration config) { _plugin = plugin; _configHeader = AutoVisor.Version.Length > 0 ? $"{PluginName} v{AutoVisor.Version}" : PluginName; _pi = pi; _config = config; _players = _config.States.Select(kvp => kvp.Key).ToList(); var idx = Array.IndexOf(VisorStateNames, "Drawn"); if (idx < 0) return; VisorStateNames[idx] = "W. Drawn"; } private bool AddPlayer(PlayerConfig config) { var name = _pi.ClientState.LocalPlayer?.Name ?? ""; if (name.Length == 0 || _config.States.ContainsKey(name)) return false; _players.Add(name); _config.States[name] = config.Clone(); Save(); return true; } private bool AddPlayer() => AddPlayer(new PlayerConfig()); private void RemovePlayer(string name) { _players.Remove(name); _config.States.Remove(name); Save(); } private void Save() { _pi.SavePluginConfig(_config); _plugin.VisorManager!.ResetState(); } private void DrawEnabledCheckbox() { var tmp = _config.Enabled; if (!ImGui.Checkbox(LabelEnabled, ref tmp) || _config.Enabled == tmp) return; _config.Enabled = tmp; if (tmp) _plugin.VisorManager!.Activate(); else _plugin.VisorManager!.Deactivate(); Save(); } private ImGuiRaii? DrawTableHeader(int type) { const ImGuiTableFlags flags = ImGuiTableFlags.Hideable | ImGuiTableFlags.BordersOuter | ImGuiTableFlags.BordersInner | ImGuiTableFlags.SizingFixedSame; var list = type switch { 2 => VisorStateWeaponNames, 3 => CPoseManager.PoseNames, _ => VisorStateNames, }; var imgui = new ImGuiRaii(); if (!imgui.Begin(() => ImGui.BeginTable($"##table_{type}_{_currentPlayer}", list.Length + 1, flags), ImGui.EndTable)) return null; ImGui.TableSetupColumn($"Job##empty_{type}_{_currentPlayer}", ImGuiTableColumnFlags.NoHide); foreach (var name in list) ImGui.TableSetupColumn(name); ImGui.TableHeadersRow(); return imgui; } private static readonly string[] PoseTooltips = new string[] { "Change your default pose when standing upright.\nDefault sets the pose from login with that character.\nUnchanged does not change the pose at all.", "Change your default pose when standing with your weapon drawn.\nDefault sets the pose from login with that character.\nUnchanged does not change the pose at all.", "Change your default pose when sitting on the ground.\nDefault sets the pose from login with that character.\nUnchanged does not change the pose at all.", "Change your default pose when sitting on an object.\nDefault sets the pose from login with that character.\nUnchanged does not change the pose at all.", "Change your default pose when dozing in a bed.\nDefault sets the pose from login with that character.\nUnchanged does not change the pose at all.", }; public void DrawPoseTableContent(PlayerConfig settings, Job job, VisorChangeGroup jobSettings) { for (var i = 0; i < CPoseManager.PoseNames.Length; ++i) { ImGui.TableNextColumn(); int tmp = i switch { 0 => jobSettings.StandingPose, 1 => jobSettings.WeaponDrawnPose, 2 => jobSettings.SittingPose, 3 => jobSettings.GroundSittingPose, 4 => jobSettings.DozingPose, _ => throw new NotImplementedException("There are no more Cpose targets."), }; tmp = tmp switch { CPoseManager.DefaultPose => 0, CPoseManager.UnchangedPose => 1, _ => tmp + 2, }; var copy = tmp; ImGui.SetNextItemWidth(-1); if (ImGui.Combo($"##03_{_currentPlayer}_{_currentJob}_pose_{i}", ref tmp, PoseOptions, CPoseManager.NumPoses[i] + 2) && tmp != copy) { var value = (byte) (tmp switch { 0 => CPoseManager.DefaultPose, 1 => CPoseManager.UnchangedPose, _ => tmp - 2, }); switch (i) { case 0: jobSettings.StandingPose = value; break; case 1: jobSettings.WeaponDrawnPose = value; break; case 2: jobSettings.SittingPose = value; break; case 3: jobSettings.GroundSittingPose = value; break; case 4: jobSettings.DozingPose = value; break; } settings.PerJob[job] = jobSettings; Save(); } if (ImGui.IsItemHovered()) ImGui.SetTooltip(PoseTooltips[i]); } } private void DrawTableContent(PlayerConfig settings, int type) { var jobSettings = settings.PerJob.ElementAt(_currentJob); var job = jobSettings.Key; var name = JobNames[(int) jobSettings.Key]; var group = jobSettings.Value; var (set, state, tooltip1, tooltip2) = type switch { 0 => (group.VisorSet, group.VisorState, "Enable visor toggle on this state.", "Visor off/on."), 1 => (group.HideHatSet, group.HideHatState, "Enable headslot toggle on this state.", "Headslot off/on."), _ => (group.HideWeaponSet, group.HideWeaponState, "Enable weapon toggle on this state.", "Weapon off / on."), }; ImGui.TableNextRow(); ImGui.TableNextColumn(); using var imgui = new ImGuiRaii() .PushStyle(ImGuiStyleVar.ItemSpacing, new Vector2(2 * ImGui.GetIO().FontGlobalScale, 0)); if (job != Job.Default) { if (ImGui.Button($"−##0{_currentPlayer}_{_currentJob}_{type}", new Vector2(20, 20) * ImGui.GetIO().FontGlobalScale)) { settings.PerJob.Remove(settings.PerJob.ElementAt(_currentJob).Key); _currentJob = Math.Max(0, _currentJob - 1); Save(); } if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Delete the job specific settings for {name}."); ImGui.SameLine(); } else { ImGui.AlignTextToFramePadding(); } ImGui.Text(name); imgui.PopStyles(); if (type == 3) { DrawPoseTableContent(settings, job, group); return; } foreach (var v in type == 2 ? VisorStatesWeapon : VisorStates) { ImGui.TableNextColumn(); var tmp1 = set.HasFlag(v); ImGui.Checkbox($"##0{type}_{_currentPlayer}_{_currentJob}_{v}", ref tmp1); if (ImGui.IsItemHovered()) ImGui.SetTooltip(tooltip1); if (!tmp1) imgui.PushStyle(ImGuiStyleVar.Alpha, 0.35f); var tmp2 = tmp1 && state.HasFlag(v); ImGui.SameLine(); ImGui.Checkbox($"##1{type}_{_currentPlayer}_{_currentJob}_{v}", ref tmp2); if (!tmp1) { tmp2 = false; imgui.PopStyles(); } if (ImGui.IsItemHovered()) ImGui.SetTooltip(tooltip2); if (tmp1 != set.HasFlag(v) || tmp2 != state.HasFlag(v)) { switch (type) { case 0: group.VisorSet = tmp1 ? set | v : set & ~v; group.VisorState = tmp2 ? state | v : state & ~v; break; case 1: group.HideHatSet = tmp1 ? set | v : set & ~v; group.HideHatState = tmp2 ? state | v : state & ~v; break; default: group.HideWeaponSet = tmp1 ? set | v : set & ~v; group.HideWeaponState = tmp2 ? state | v : state & ~v; break; } settings.PerJob[job] = group; Save(); } } } private void DrawTable(PlayerConfig settings, int type) { using var table = DrawTableHeader(type); if (table == null) return; for (_currentJob = 0; _currentJob < settings.PerJob.Count; ++_currentJob) DrawTableContent(settings, type); } private void DrawAddJobSelector(PlayerConfig settings) { if (settings.PerJob.Count == JobNames.Length) return; var availableJobsAndIndices = JobNames.Select((j, i) => (j, i)).Where(p => !settings.PerJob.ContainsKey(Jobs[p.i])); using var combo = new ImGuiRaii(); if (!combo.Begin(() => ImGui.BeginCombo($"Add Job##{_currentPlayer}", "", ImGuiComboFlags.NoPreview), ImGui.EndCombo)) return; foreach (var (job, index) in availableJobsAndIndices) { if (!ImGui.Selectable($"{job}##{_currentPlayer}", false)) continue; settings.PerJob.Add(Jobs[index], VisorChangeGroup.Empty); Save(); } } private void DrawPlayerGroup() { var name = _players.ElementAt(_currentPlayer); if (!ImGui.CollapsingHeader(name)) return; ImGui.Dummy(_horizontalSpace); var playerConfig = _config.States[name]; var tmp = playerConfig.Enabled; if (ImGui.Checkbox($"Enabled##{name}", ref tmp) && tmp != playerConfig.Enabled) { playerConfig.Enabled = tmp; Save(); } ImGui.SameLine(); if (ImGui.Button($"Delete##{name}")) { RemovePlayer(name); --_currentPlayer; ImGui.Columns(1); return; } if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Delete all settings for the character {name}."); if (name != (_pi.ClientState.LocalPlayer?.Name ?? "")) { ImGui.SameLine(); if (ImGui.Button($"Duplicate##{name}")) AddPlayer(_config.States[name]); if (ImGui.IsItemHovered()) ImGui.SetTooltip($"Duplicate the settings for this character to your current character."); } ImGui.SameLine(); DrawAddJobSelector(playerConfig); ImGui.Dummy(_horizontalSpace); var cursor = ImGui.GetCursorPosX(); if (ImGui.TreeNode($"Visor State##{name}")) { ImGui.SetCursorPosX(cursor); DrawTable(playerConfig, 0); ImGui.TreePop(); } if (ImGui.TreeNode($"Headslot State##{name}")) { ImGui.SetCursorPosX(cursor); DrawTable(playerConfig, 1); ImGui.TreePop(); } if (ImGui.TreeNode($"Weapon State##{name}")) { ImGui.SetCursorPosX(cursor); DrawTable(playerConfig, 2); ImGui.TreePop(); } if (ImGui.TreeNode($"Poses##{name}")) { ImGui.SetCursorPosX(cursor); DrawTable(playerConfig, 3); ImGui.TreePop(); } } private static void DrawHelp() { if (!ImGui.CollapsingHeader("Help", ImGuiTreeNodeFlags.DefaultOpen)) return; ImGui.TextWrapped("AutoVisor allows you to automatically use /visor, /displayhead or /displayarms on certain conditions. " + "The configuration is character-name and job-specific, with a default job that triggers if no specific job is active. " + "The first checkbox per column activates automatic changing for the specific condition, the second indicates to which state the setting should be changed.\n" + "Precedences are:\n" + "\t1. Fishing\n" + "\t2. Gathering ~ Crafting\n" + "\t3. In Flight ~ Diving\n" + "\t4. Mounted ~ Swimming ~ Wearing Fashion Accessories\n" + "\t5. Casting\n" + "\t6. In Combat\n" + "\t7. Weapon Drawn\n" + "\t8. In Duty\n" + "\t9. Normal."); } private void DrawPlayerAdd() { var name = _pi.ClientState.LocalPlayer?.Name ?? ""; if (name.Length == 0 || _config.States.ContainsKey(name)) return; if (ImGui.Button("Add settings for this character...")) AddPlayer(); } public void Draw() { if (!Visible) return; ImGui.SetNextWindowSizeConstraints(new Vector2(980, 500) * ImGui.GetIO().FontGlobalScale, new Vector2(4000, 4000)); if (!ImGui.Begin(_configHeader, ref Visible)) return; try { DrawEnabledCheckbox(); ImGui.SameLine(); DrawPlayerAdd(); _horizontalSpace = new Vector2(0, 5 * ImGui.GetIO().FontGlobalScale); ImGui.Dummy(_horizontalSpace * 2); DrawHelp(); ImGui.Dummy(_horizontalSpace * 2); for (_currentPlayer = 0; _currentPlayer < _players.Count; ++_currentPlayer) { DrawPlayerGroup(); ImGui.Dummy(_horizontalSpace); } } finally { ImGui.End(); } } } }
36.685106
176
0.498956
[ "Apache-2.0" ]
notsonks/AutoVisor
GUI/AutoVisorUi.cs
17,244
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveonPathScript : MonoBehaviour { public EditofPathScript PathToFollow; // Establishment of variables public GameObject NPC; public UnityEngine.AI.NavMeshAgent agent; public int CurrentWayPointID = 0; public float speed; private float reachDistance = 1.0f; public float rotationSpeed = 5.0f; public string pathName; Vector3 last_position; Vector3 current_position; // Use this for initialization void Start() { //additional randomised waypoints that I couldn't get working //PathToFollow = GameObject.Find(pathName).GetComponent<EditofPathScript>(); last_position = transform.position; //NavMesh agent tutorial setting up the agent with NavMeshAgent agent = NPC.GetComponent<UnityEngine.AI.NavMeshAgent>(); } // Update is called once per frame void Update() { // Find waypoint ID float distance = Vector3.Distance(PathToFollow.path_objs[CurrentWayPointID].position, transform.position); // Move to waypoint at speed transform.position = Vector3.MoveTowards(transform.position, PathToFollow.path_objs[CurrentWayPointID].position, Time.deltaTime * speed); // Rotate agent to face the waypoint //var rotation = Quaternion.LookRotation(PathToFollow.path_objs[CurrentWayPointID].position - transform.position); //transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationSpeed); //tutorial example given of how to attach waypoints to the navmesh agent agent.SetDestination(PathToFollow.path_objs[CurrentWayPointID].transform.position); // send agent to next waypoint if (distance <= reachDistance) { CurrentWayPointID++; } // Loop waypoints once the end is reached if (CurrentWayPointID >= PathToFollow.path_objs.Count) { CurrentWayPointID = 0; } } }
30.26087
145
0.685345
[ "MIT" ]
MyopicMuppet/Cert4-Artifical-Intelligence
Assets/Arcade Project/Scripts/MoveonPathScript.cs
2,090
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.ApplicationModel.AppExtensions { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class AppExtensionPackageInstalledEventArgs { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public string AppExtensionName { get { throw new global::System.NotImplementedException("The member string AppExtensionPackageInstalledEventArgs.AppExtensionName is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public global::System.Collections.Generic.IReadOnlyList<global::Windows.ApplicationModel.AppExtensions.AppExtension> Extensions { get { throw new global::System.NotImplementedException("The member IReadOnlyList<AppExtension> AppExtensionPackageInstalledEventArgs.Extensions is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public global::Windows.ApplicationModel.Package Package { get { throw new global::System.NotImplementedException("The member Package AppExtensionPackageInstalledEventArgs.Package is not implemented in Uno."); } } #endif // Forced skipping of method Windows.ApplicationModel.AppExtensions.AppExtensionPackageInstalledEventArgs.AppExtensionName.get // Forced skipping of method Windows.ApplicationModel.AppExtensions.AppExtensionPackageInstalledEventArgs.Package.get // Forced skipping of method Windows.ApplicationModel.AppExtensions.AppExtensionPackageInstalledEventArgs.Extensions.get } }
49.288889
171
0.770063
[ "Apache-2.0" ]
AbdalaMask/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.AppExtensions/AppExtensionPackageInstalledEventArgs.cs
2,218
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.CostManagement.V20180801Preview.Outputs { /// <summary> /// The aggregation expression to be used in the report. /// </summary> [OutputType] public sealed class ReportAggregationResponse { /// <summary> /// The name of the aggregation function to use. /// </summary> public readonly string Function; /// <summary> /// The name of the column to aggregate. /// </summary> public readonly string Name; [OutputConstructor] private ReportAggregationResponse( string function, string name) { Function = function; Name = name; } } }
26.384615
81
0.620991
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/CostManagement/V20180801Preview/Outputs/ReportAggregationResponse.cs
1,029
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. namespace Elastic.Clients.Elasticsearch.AsyncSearch { public partial class GetAsyncSearchRequest { // Any request may contain aggregations so we force typed_keys in order to successfully deserialise them. internal override void BeforeRequest() => TypedKeys = true; } public sealed partial class GetAsyncSearchRequestDescriptor<TDocument> { // Any request may contain aggregations so we force typed_keys in order to successfully deserialise them. internal override void BeforeRequest() => TypedKeys(true); } public sealed partial class GetAsyncSearchRequestDescriptor { // Any request may contain aggregations so we force typed_keys in order to successfully deserialise them. internal override void BeforeRequest() => TypedKeys(true); } }
38.72
107
0.788223
[ "Apache-2.0" ]
SimonCropp/elasticsearch-net
src/Elastic.Clients.Elasticsearch/Api/AsyncSearch/GetAsyncSearchRequest.cs
968
C#
using System; using System.Collections; namespace System.Text.RegularExpressions { internal class GroupEnumerator : IEnumerator { #region Fields internal int _curindex = -1; internal GroupCollection _rgc; #endregion #region Constructor internal GroupEnumerator(GroupCollection rgc) { this._rgc = rgc; } #endregion #region Methods public bool MoveNext() { int count = this._rgc.Count; if (this._curindex >= count) { return false; } return (++this._curindex < count); } public void Reset() { this._curindex = -1; } #endregion #region Properties public Capture Capture { get { if ((this._curindex < 0) || (this._curindex >= this._rgc.Count)) { throw new InvalidOperationException("EnumNotStarted"); } return this._rgc[this._curindex]; } } public object Current { get { return this.Capture; } } #endregion } }
20.279412
81
0.437999
[ "Apache-2.0" ]
AustinWise/Netduino-Micro-Framework
Framework/Core/System/RegularExpressions/Collections/GroupEnumerator.cs
1,379
C#
using EPlast.DataAccess.Entities.Event; namespace EPlast.DataAccess.Repositories.Interfaces.Events { public interface IEventSectionRepository: IRepositoryBase<EventSection> { } }
21.444444
75
0.787565
[ "MIT" ]
Toxa2202/plast
EPlast/EPlast.DataAccess/Repositories/Interfaces/Events/IEventSectionRepository.cs
195
C#
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2018 // // 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. // This file was automatically generated and should not be edited directly. using System; using System.Runtime.InteropServices; namespace SharpVk.Interop { /// <summary> /// /// </summary> [StructLayout(LayoutKind.Sequential)] public unsafe partial struct PhysicalDeviceProperties2 { /// <summary> /// /// </summary> public SharpVk.StructureType SType; /// <summary> /// /// </summary> public void* Next; /// <summary> /// /// </summary> public SharpVk.Interop.PhysicalDeviceProperties Properties; } }
34.865385
81
0.688362
[ "MIT" ]
sebastianulm/SharpVk
src/SharpVk/Interop/PhysicalDeviceProperties2.gen.cs
1,813
C#
using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Tsarev.Analyzer.Helpers; using System.Linq; namespace Tsarev.Analyzer.Web { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class AsyncControllerAnalyzer : DiagnosticAnalyzer { private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.AnalyzerTitle), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.AnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.AnalyzerDescription), Resources.ResourceManager, typeof(Resources)); private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( nameof(AsyncControllerAnalyzer), Title, MessageFormat, "WebPerfomance", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule, StandartRules.FailedRule); public override void Initialize(AnalysisContext context) => context.RegisterSafeSyntaxNodeAction(AnalyzeMethod, SyntaxKind.MethodDeclaration); private void AnalyzeMethod(SyntaxNodeAnalysisContext context) { var node = (MethodDeclarationSyntax) context.Node; if (node.Identifier.Text == "Dispose") { return; } var classNode = node.GetContainingClass(); if ( classNode != null && classNode.GetClassNamesToTop(context) .Any(type => IsClassNameSignifiesController(type.Name)) && !IsTrivialMethod(node) && node.IsPublic() && !node.ReturnType.IsTask(context) ) { context.ReportDiagnostic(Diagnostic.Create(Rule, node.Identifier.GetLocation(), classNode.Identifier.ToString(), node.Identifier.ToString())); } } private bool IsClassNameSignifiesController(string className) => className.ToLowerInvariant().Contains("controller"); private bool IsTrivialMethod(MethodDeclarationSyntax methodNode) { if (methodNode.ExpressionBody != null) { return IsWebTrivialExpression(methodNode.ExpressionBody.Expression); } if (methodNode.Body != null) { return IsWebTrivialBody(methodNode); } return true; } private static bool IsWebTrivialBody(MethodDeclarationSyntax methodNode) { foreach (var statement in methodNode.Body.Statements) { if (statement is ReturnStatementSyntax returnStatement && IsWebTrivialExpression(returnStatement.Expression)) { return true; } if (statement is ExpressionStatementSyntax assigmentStatement && IsWebTrivialExpression(assigmentStatement.Expression)) { continue; } return false; } return true; } private static bool IsWebTrivialExpression(ExpressionSyntax syntax) { if (syntax is AssignmentExpressionSyntax assigment) { return IsWebTrivialExpression(assigment.Left) && IsWebTrivialExpression(assigment.Right); } if (syntax is ArrayCreationExpressionSyntax array) { return array.Initializer.IsConstant(); } if (syntax is MemberAccessExpressionSyntax memberAccess && (memberAccess.Expression as IdentifierNameSyntax)?.Identifier.ToString() == "ViewBag") { return true; } if (syntax is ConditionalExpressionSyntax conditionalExpressionSyntax) { return IsWebTrivialExpression(conditionalExpressionSyntax.Condition) && IsWebTrivialExpression(conditionalExpressionSyntax.WhenFalse) && IsWebTrivialExpression(conditionalExpressionSyntax.WhenTrue); } return syntax.IsConstant() || IsConstViewInvoke(syntax); } private static readonly string[] ResultMethodNames = {"View", "PartialView", "File"}; private static bool IsConstViewInvoke(ExpressionSyntax syntax) { if (!(syntax is InvocationExpressionSyntax invokeExpression)) return false; var methodName = invokeExpression.GetMethodName(); var arguments = invokeExpression.ArgumentList.Arguments; return ResultMethodNames.Contains(methodName) && arguments.All(argument => IsWebTrivialExpression(argument.Expression)); } } }
34.91791
179
0.715751
[ "MIT" ]
leotsarev/hardcode-analyzer
Tsarev.Analyzer.Web/AsyncControllerAnalyzer.cs
4,679
C#
using System; using System.Collections.Generic; 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; using GingerCore.Variables; namespace Ginger.Variables { /// <summary> /// Interaction logic for VariableStopWatchEditPage.xaml /// </summary> public partial class VariableTimerPage : Page { public VariableTimerPage(VariableTimer variableTimer) { InitializeComponent(); xTimerUnitCombo.Init(variableTimer, nameof(variableTimer.TimerUnit), typeof(VariableTimer.eTimerUnit)); } } }
25.636364
115
0.735225
[ "Apache-2.0" ]
DebasmitaGhosh/Ginger
Ginger/Ginger/Variables/VariableTimerPage.xaml.cs
848
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Text { /// <summary> /// Discriminated union of a string and a char array/offset/count. Enables looking up /// a portion of a char array as a key in a dictionary of string keys without having to /// allocate/copy the chars into a new string. This comes at the expense of an extra /// reference field + two Int32s per key in the size of the dictionary's Entry array. /// </summary> internal readonly struct StringOrCharArray : IEquatable<StringOrCharArray> { public readonly string String; public readonly char[] CharArray; public readonly int CharArrayOffset; public readonly int CharArrayCount; public StringOrCharArray(string s) { String = s; CharArray = null; CharArrayOffset = 0; CharArrayCount = 0; DebugValidate(); } public StringOrCharArray(char[] charArray, int charArrayIndex, int charArrayOffset) { String = null; CharArray = charArray; CharArrayOffset = charArrayIndex; CharArrayCount = charArrayOffset; DebugValidate(); } public static implicit operator StringOrCharArray(string value) { return new StringOrCharArray(value); } public int Length { get { DebugValidate(); return String != null ? String.Length : CharArrayCount; } } public override bool Equals(object obj) { return obj is StringOrCharArray && Equals((StringOrCharArray)obj); } public unsafe bool Equals(StringOrCharArray other) { this.DebugValidate(); other.DebugValidate(); if (this.String != null) { // String vs String if (other.String != null) { return StringComparer.Ordinal.Equals(this.String, other.String); } // String vs CharArray if (this.String.Length != other.CharArrayCount) return false; for (int i = 0; i < this.String.Length; i++) { if (this.String[i] != other.CharArray[other.CharArrayOffset + i]) return false; } return true; } // CharArray vs CharArray if (other.CharArray != null) { if (this.CharArrayCount != other.CharArrayCount) return false; for (int i = 0; i < this.CharArrayCount; i++) { if (this.CharArray[this.CharArrayOffset + i] != other.CharArray[other.CharArrayOffset + i]) return false; } return true; } // CharArray vs String if (this.CharArrayCount != other.String.Length) return false; for (int i = 0; i < this.CharArrayCount; i++) { if (this.CharArray[this.CharArrayOffset + i] != other.String[i]) return false; } return true; } public override unsafe int GetHashCode() { DebugValidate(); if (String != null) { fixed (char* s = String) { return GetHashCode(s, String.Length); } } else { fixed (char* s = CharArray) { return GetHashCode(s + CharArrayOffset, CharArrayCount); } } } private static unsafe int GetHashCode(char* s, int count) { // This hash code is a simplified version of some of the code in String, // when not using randomized hash codes. We don't use string's GetHashCode // because we need to be able to use the exact same algorithms on a char[]. // As such, this should not be used anywhere there are concerns around // hash-based attacks that would require a better code. int hash1 = (5381 << 16) + 5381; int hash2 = hash1; for (int i = 0; i < count; ++i) { int c = *s++; hash1 = unchecked((hash1 << 5) + hash1) ^ c; if (++i >= count) break; c = *s++; hash2 = unchecked((hash2 << 5) + hash2) ^ c; } return unchecked(hash1 + (hash2 * 1566083941)); } [Conditional("DEBUG")] private void DebugValidate() { Debug.Assert((String != null) ^ (CharArray != null)); if (CharArray != null) { Debug.Assert(CharArrayCount >= 0); Debug.Assert(CharArrayOffset >= 0); Debug.Assert(CharArrayOffset <= CharArray.Length - CharArrayCount); } } } }
30.266667
111
0.497797
[ "MIT" ]
2E0PGS/corefx
src/Common/src/System/Text/StringOrCharArray.cs
5,448
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace System.Drawing { public partial class Image { } }
12.5
33
0.766667
[ "MIT" ]
HolisticWare/HolisticWare.Core.MarkDown.MarkDownDeep
source/MonoVersal.MarkDown.MarkDownDeep.WP71/patches/System.Drawing/Image.cs
150
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.Diagnostics.Monitoring.WebApi { public enum DiagnosticPortConnectionMode { Connect, Listen } }
26.769231
71
0.724138
[ "MIT" ]
ScriptBox21/dotnet-monitor
src/Microsoft.Diagnostics.Monitoring.Options/DiagnosticPortConnectionMode.cs
350
C#
using System; namespace Microsoft.DwayneNeed.Win32.User32 { // It would be great to use the HWND type for hwnd, but this is not // possible because you will get a MarshalDirectiveException complaining // that the unmanaged code cannot pass in a SafeHandle. Instead, most // classes that use a WNDPROC will expose its own virtual that creates // new HWND instances for the incomming handles. public delegate IntPtr WNDPROC(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam); }
45.727273
87
0.747515
[ "MIT" ]
PresetMagician/PresetMagician
Microsoft.DwayneNeed.Win32/User32/WNDPROC.cs
505
C#
using System.Reflection; using Android.App; using Android.OS; using Xamarin.Android.NUnitLite; namespace Xamarin.Android.LocaleTests { [Activity (Label = "Xamarin.Android.Locale-Tests", MainLauncher = true)] public class MainActivity : TestSuiteActivity { protected override void OnCreate (Bundle bundle) { // tests can be inside the main assembly AddTest (Assembly.GetExecutingAssembly ()); // or in any reference assemblies // AddTest (typeof (Your.Library.TestClass).Assembly); // Once you called base.OnCreate(), you cannot add more assemblies. base.OnCreate (bundle); } } }
25.416667
73
0.736066
[ "MIT" ]
06051979/xamarin-android
tests/locales/Xamarin.Android.Locale-Tests/MainActivity.cs
610
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ using NMF.Collections.Generic; using NMF.Collections.ObjectModel; using NMF.Expressions; using NMF.Expressions.Linq; using NMF.Models; using NMF.Models.Collections; using NMF.Models.Expressions; using NMF.Models.Meta; using NMF.Models.Repository; using NMF.Serialization; using NMF.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Linq; using TTC2017.SmartGrids.SubstationStandard.Enumerations; namespace TTC2017.SmartGrids.SubstationStandard.Dataclasses { /// <summary> /// The default implementation of the DPS class /// </summary> [XmlNamespaceAttribute("http://www.transformation-tool-contest.eu/2017/smartGrids/dataclasses")] [XmlNamespacePrefixAttribute("data")] [ModelRepresentationClassAttribute("http://www.transformation-tool-contest.eu/2017/smartGrids/substationStandard#//Da" + "taclasses/DPS")] public partial class DPS : ModelElement, IDPS, IModelElement { /// <summary> /// The backing field for the SubEna property /// </summary> private Nullable<bool> _subEna; private static Lazy<ITypedElement> _subEnaAttribute = new Lazy<ITypedElement>(RetrieveSubEnaAttribute); /// <summary> /// The backing field for the SubID property /// </summary> private string _subID; private static Lazy<ITypedElement> _subIDAttribute = new Lazy<ITypedElement>(RetrieveSubIDAttribute); private static Lazy<ITypedElement> _stValReference = new Lazy<ITypedElement>(RetrieveStValReference); /// <summary> /// The backing field for the StVal property /// </summary> private IDPStatus _stVal; private static Lazy<ITypedElement> _qReference = new Lazy<ITypedElement>(RetrieveQReference); /// <summary> /// The backing field for the Q property /// </summary> private IQuality _q; private static Lazy<ITypedElement> _subValReference = new Lazy<ITypedElement>(RetrieveSubValReference); /// <summary> /// The backing field for the SubVal property /// </summary> private IDPStatus _subVal; private static Lazy<ITypedElement> _subQReference = new Lazy<ITypedElement>(RetrieveSubQReference); /// <summary> /// The backing field for the SubQ property /// </summary> private IQuality _subQ; private static IClass _classInstance; /// <summary> /// The subEna property /// </summary> [XmlElementNameAttribute("subEna")] [XmlAttributeAttribute(true)] public virtual Nullable<bool> SubEna { get { return this._subEna; } set { if ((this._subEna != value)) { Nullable<bool> old = this._subEna; ValueChangedEventArgs e = new ValueChangedEventArgs(old, value); this.OnSubEnaChanging(e); this.OnPropertyChanging("SubEna", e, _subEnaAttribute); this._subEna = value; this.OnSubEnaChanged(e); this.OnPropertyChanged("SubEna", e, _subEnaAttribute); } } } /// <summary> /// The subID property /// </summary> [XmlElementNameAttribute("subID")] [XmlAttributeAttribute(true)] public virtual string SubID { get { return this._subID; } set { if ((this._subID != value)) { string old = this._subID; ValueChangedEventArgs e = new ValueChangedEventArgs(old, value); this.OnSubIDChanging(e); this.OnPropertyChanging("SubID", e, _subIDAttribute); this._subID = value; this.OnSubIDChanged(e); this.OnPropertyChanged("SubID", e, _subIDAttribute); } } } /// <summary> /// The stVal property /// </summary> [XmlElementNameAttribute("stVal")] [XmlAttributeAttribute(true)] public virtual IDPStatus StVal { get { return this._stVal; } set { if ((this._stVal != value)) { IDPStatus old = this._stVal; ValueChangedEventArgs e = new ValueChangedEventArgs(old, value); this.OnStValChanging(e); this.OnPropertyChanging("StVal", e, _stValReference); this._stVal = value; if ((old != null)) { old.Deleted -= this.OnResetStVal; } if ((value != null)) { value.Deleted += this.OnResetStVal; } this.OnStValChanged(e); this.OnPropertyChanged("StVal", e, _stValReference); } } } /// <summary> /// The q property /// </summary> [XmlElementNameAttribute("q")] [XmlAttributeAttribute(true)] public virtual IQuality Q { get { return this._q; } set { if ((this._q != value)) { IQuality old = this._q; ValueChangedEventArgs e = new ValueChangedEventArgs(old, value); this.OnQChanging(e); this.OnPropertyChanging("Q", e, _qReference); this._q = value; if ((old != null)) { old.Deleted -= this.OnResetQ; } if ((value != null)) { value.Deleted += this.OnResetQ; } this.OnQChanged(e); this.OnPropertyChanged("Q", e, _qReference); } } } /// <summary> /// The subVal property /// </summary> [XmlElementNameAttribute("subVal")] [XmlAttributeAttribute(true)] public virtual IDPStatus SubVal { get { return this._subVal; } set { if ((this._subVal != value)) { IDPStatus old = this._subVal; ValueChangedEventArgs e = new ValueChangedEventArgs(old, value); this.OnSubValChanging(e); this.OnPropertyChanging("SubVal", e, _subValReference); this._subVal = value; if ((old != null)) { old.Deleted -= this.OnResetSubVal; } if ((value != null)) { value.Deleted += this.OnResetSubVal; } this.OnSubValChanged(e); this.OnPropertyChanged("SubVal", e, _subValReference); } } } /// <summary> /// The subQ property /// </summary> [XmlElementNameAttribute("subQ")] [XmlAttributeAttribute(true)] public virtual IQuality SubQ { get { return this._subQ; } set { if ((this._subQ != value)) { IQuality old = this._subQ; ValueChangedEventArgs e = new ValueChangedEventArgs(old, value); this.OnSubQChanging(e); this.OnPropertyChanging("SubQ", e, _subQReference); this._subQ = value; if ((old != null)) { old.Deleted -= this.OnResetSubQ; } if ((value != null)) { value.Deleted += this.OnResetSubQ; } this.OnSubQChanged(e); this.OnPropertyChanged("SubQ", e, _subQReference); } } } /// <summary> /// Gets the referenced model elements of this model element /// </summary> public override IEnumerableExpression<IModelElement> ReferencedElements { get { return base.ReferencedElements.Concat(new DPSReferencedElementsCollection(this)); } } /// <summary> /// Gets the Class model for this type /// </summary> public new static IClass ClassInstance { get { if ((_classInstance == null)) { _classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://www.transformation-tool-contest.eu/2017/smartGrids/substationStandard#//Da" + "taclasses/DPS"))); } return _classInstance; } } /// <summary> /// Gets fired before the SubEna property changes its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> SubEnaChanging; /// <summary> /// Gets fired when the SubEna property changed its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> SubEnaChanged; /// <summary> /// Gets fired before the SubID property changes its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> SubIDChanging; /// <summary> /// Gets fired when the SubID property changed its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> SubIDChanged; /// <summary> /// Gets fired before the StVal property changes its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> StValChanging; /// <summary> /// Gets fired when the StVal property changed its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> StValChanged; /// <summary> /// Gets fired before the Q property changes its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> QChanging; /// <summary> /// Gets fired when the Q property changed its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> QChanged; /// <summary> /// Gets fired before the SubVal property changes its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> SubValChanging; /// <summary> /// Gets fired when the SubVal property changed its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> SubValChanged; /// <summary> /// Gets fired before the SubQ property changes its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> SubQChanging; /// <summary> /// Gets fired when the SubQ property changed its value /// </summary> public event System.EventHandler<ValueChangedEventArgs> SubQChanged; private static ITypedElement RetrieveSubEnaAttribute() { return ((ITypedElement)(((ModelElement)(DPS.ClassInstance)).Resolve("subEna"))); } /// <summary> /// Raises the SubEnaChanging event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnSubEnaChanging(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.SubEnaChanging; if ((handler != null)) { handler.Invoke(this, eventArgs); } } /// <summary> /// Raises the SubEnaChanged event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnSubEnaChanged(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.SubEnaChanged; if ((handler != null)) { handler.Invoke(this, eventArgs); } } private static ITypedElement RetrieveSubIDAttribute() { return ((ITypedElement)(((ModelElement)(DPS.ClassInstance)).Resolve("subID"))); } /// <summary> /// Raises the SubIDChanging event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnSubIDChanging(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.SubIDChanging; if ((handler != null)) { handler.Invoke(this, eventArgs); } } /// <summary> /// Raises the SubIDChanged event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnSubIDChanged(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.SubIDChanged; if ((handler != null)) { handler.Invoke(this, eventArgs); } } private static ITypedElement RetrieveStValReference() { return ((ITypedElement)(((ModelElement)(DPS.ClassInstance)).Resolve("stVal"))); } /// <summary> /// Raises the StValChanging event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnStValChanging(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.StValChanging; if ((handler != null)) { handler.Invoke(this, eventArgs); } } /// <summary> /// Raises the StValChanged event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnStValChanged(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.StValChanged; if ((handler != null)) { handler.Invoke(this, eventArgs); } } /// <summary> /// Handles the event that the StVal property must reset /// </summary> /// <param name="sender">The object that sent this reset request</param> /// <param name="eventArgs">The event data for the reset event</param> private void OnResetStVal(object sender, System.EventArgs eventArgs) { this.StVal = null; } private static ITypedElement RetrieveQReference() { return ((ITypedElement)(((ModelElement)(DPS.ClassInstance)).Resolve("q"))); } /// <summary> /// Raises the QChanging event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnQChanging(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.QChanging; if ((handler != null)) { handler.Invoke(this, eventArgs); } } /// <summary> /// Raises the QChanged event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnQChanged(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.QChanged; if ((handler != null)) { handler.Invoke(this, eventArgs); } } /// <summary> /// Handles the event that the Q property must reset /// </summary> /// <param name="sender">The object that sent this reset request</param> /// <param name="eventArgs">The event data for the reset event</param> private void OnResetQ(object sender, System.EventArgs eventArgs) { this.Q = null; } private static ITypedElement RetrieveSubValReference() { return ((ITypedElement)(((ModelElement)(DPS.ClassInstance)).Resolve("subVal"))); } /// <summary> /// Raises the SubValChanging event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnSubValChanging(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.SubValChanging; if ((handler != null)) { handler.Invoke(this, eventArgs); } } /// <summary> /// Raises the SubValChanged event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnSubValChanged(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.SubValChanged; if ((handler != null)) { handler.Invoke(this, eventArgs); } } /// <summary> /// Handles the event that the SubVal property must reset /// </summary> /// <param name="sender">The object that sent this reset request</param> /// <param name="eventArgs">The event data for the reset event</param> private void OnResetSubVal(object sender, System.EventArgs eventArgs) { this.SubVal = null; } private static ITypedElement RetrieveSubQReference() { return ((ITypedElement)(((ModelElement)(DPS.ClassInstance)).Resolve("subQ"))); } /// <summary> /// Raises the SubQChanging event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnSubQChanging(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.SubQChanging; if ((handler != null)) { handler.Invoke(this, eventArgs); } } /// <summary> /// Raises the SubQChanged event /// </summary> /// <param name="eventArgs">The event data</param> protected virtual void OnSubQChanged(ValueChangedEventArgs eventArgs) { System.EventHandler<ValueChangedEventArgs> handler = this.SubQChanged; if ((handler != null)) { handler.Invoke(this, eventArgs); } } /// <summary> /// Handles the event that the SubQ property must reset /// </summary> /// <param name="sender">The object that sent this reset request</param> /// <param name="eventArgs">The event data for the reset event</param> private void OnResetSubQ(object sender, System.EventArgs eventArgs) { this.SubQ = null; } /// <summary> /// Resolves the given attribute name /// </summary> /// <returns>The attribute value or null if it could not be found</returns> /// <param name="attribute">The requested attribute name</param> /// <param name="index">The index of this attribute</param> protected override object GetAttributeValue(string attribute, int index) { if ((attribute == "SUBENA")) { return this.SubEna; } if ((attribute == "SUBID")) { return this.SubID; } return base.GetAttributeValue(attribute, index); } /// <summary> /// Sets a value to the given feature /// </summary> /// <param name="feature">The requested feature</param> /// <param name="value">The value that should be set to that feature</param> protected override void SetFeature(string feature, object value) { if ((feature == "STVAL")) { this.StVal = ((IDPStatus)(value)); return; } if ((feature == "Q")) { this.Q = ((IQuality)(value)); return; } if ((feature == "SUBVAL")) { this.SubVal = ((IDPStatus)(value)); return; } if ((feature == "SUBQ")) { this.SubQ = ((IQuality)(value)); return; } if ((feature == "SUBENA")) { this.SubEna = ((bool)(value)); return; } if ((feature == "SUBID")) { this.SubID = ((string)(value)); return; } base.SetFeature(feature, value); } /// <summary> /// Gets the property expression for the given attribute /// </summary> /// <returns>An incremental property expression</returns> /// <param name="attribute">The requested attribute in upper case</param> protected override NMF.Expressions.INotifyExpression<object> GetExpressionForAttribute(string attribute) { if ((attribute == "StVal")) { return new StValProxy(this); } if ((attribute == "Q")) { return new QProxy(this); } if ((attribute == "SubVal")) { return new SubValProxy(this); } if ((attribute == "SubQ")) { return new SubQProxy(this); } return base.GetExpressionForAttribute(attribute); } /// <summary> /// Gets the property expression for the given reference /// </summary> /// <returns>An incremental property expression</returns> /// <param name="reference">The requested reference in upper case</param> protected override NMF.Expressions.INotifyExpression<NMF.Models.IModelElement> GetExpressionForReference(string reference) { if ((reference == "StVal")) { return new StValProxy(this); } if ((reference == "Q")) { return new QProxy(this); } if ((reference == "SubVal")) { return new SubValProxy(this); } if ((reference == "SubQ")) { return new SubQProxy(this); } return base.GetExpressionForReference(reference); } /// <summary> /// Gets the Class for this model element /// </summary> public override IClass GetClass() { if ((_classInstance == null)) { _classInstance = ((IClass)(MetaRepository.Instance.Resolve("http://www.transformation-tool-contest.eu/2017/smartGrids/substationStandard#//Da" + "taclasses/DPS"))); } return _classInstance; } /// <summary> /// The collection class to to represent the children of the DPS class /// </summary> public class DPSReferencedElementsCollection : ReferenceCollection, ICollectionExpression<IModelElement>, ICollection<IModelElement> { private DPS _parent; /// <summary> /// Creates a new instance /// </summary> public DPSReferencedElementsCollection(DPS parent) { this._parent = parent; } /// <summary> /// Gets the amount of elements contained in this collection /// </summary> public override int Count { get { int count = 0; if ((this._parent.StVal != null)) { count = (count + 1); } if ((this._parent.Q != null)) { count = (count + 1); } if ((this._parent.SubVal != null)) { count = (count + 1); } if ((this._parent.SubQ != null)) { count = (count + 1); } return count; } } protected override void AttachCore() { this._parent.StValChanged += this.PropagateValueChanges; this._parent.QChanged += this.PropagateValueChanges; this._parent.SubValChanged += this.PropagateValueChanges; this._parent.SubQChanged += this.PropagateValueChanges; } protected override void DetachCore() { this._parent.StValChanged -= this.PropagateValueChanges; this._parent.QChanged -= this.PropagateValueChanges; this._parent.SubValChanged -= this.PropagateValueChanges; this._parent.SubQChanged -= this.PropagateValueChanges; } /// <summary> /// Adds the given element to the collection /// </summary> /// <param name="item">The item to add</param> public override void Add(IModelElement item) { if ((this._parent.StVal == null)) { IDPStatus stValCasted = item.As<IDPStatus>(); if ((stValCasted != null)) { this._parent.StVal = stValCasted; return; } } if ((this._parent.Q == null)) { IQuality qCasted = item.As<IQuality>(); if ((qCasted != null)) { this._parent.Q = qCasted; return; } } if ((this._parent.SubVal == null)) { IDPStatus subValCasted = item.As<IDPStatus>(); if ((subValCasted != null)) { this._parent.SubVal = subValCasted; return; } } if ((this._parent.SubQ == null)) { IQuality subQCasted = item.As<IQuality>(); if ((subQCasted != null)) { this._parent.SubQ = subQCasted; return; } } } /// <summary> /// Clears the collection and resets all references that implement it. /// </summary> public override void Clear() { this._parent.StVal = null; this._parent.Q = null; this._parent.SubVal = null; this._parent.SubQ = null; } /// <summary> /// Gets a value indicating whether the given element is contained in the collection /// </summary> /// <returns>True, if it is contained, otherwise False</returns> /// <param name="item">The item that should be looked out for</param> public override bool Contains(IModelElement item) { if ((item == this._parent.StVal)) { return true; } if ((item == this._parent.Q)) { return true; } if ((item == this._parent.SubVal)) { return true; } if ((item == this._parent.SubQ)) { return true; } return false; } /// <summary> /// Copies the contents of the collection to the given array starting from the given array index /// </summary> /// <param name="array">The array in which the elements should be copied</param> /// <param name="arrayIndex">The starting index</param> public override void CopyTo(IModelElement[] array, int arrayIndex) { if ((this._parent.StVal != null)) { array[arrayIndex] = this._parent.StVal; arrayIndex = (arrayIndex + 1); } if ((this._parent.Q != null)) { array[arrayIndex] = this._parent.Q; arrayIndex = (arrayIndex + 1); } if ((this._parent.SubVal != null)) { array[arrayIndex] = this._parent.SubVal; arrayIndex = (arrayIndex + 1); } if ((this._parent.SubQ != null)) { array[arrayIndex] = this._parent.SubQ; arrayIndex = (arrayIndex + 1); } } /// <summary> /// Removes the given item from the collection /// </summary> /// <returns>True, if the item was removed, otherwise False</returns> /// <param name="item">The item that should be removed</param> public override bool Remove(IModelElement item) { if ((this._parent.StVal == item)) { this._parent.StVal = null; return true; } if ((this._parent.Q == item)) { this._parent.Q = null; return true; } if ((this._parent.SubVal == item)) { this._parent.SubVal = null; return true; } if ((this._parent.SubQ == item)) { this._parent.SubQ = null; return true; } return false; } /// <summary> /// Gets an enumerator that enumerates the collection /// </summary> /// <returns>A generic enumerator</returns> public override IEnumerator<IModelElement> GetEnumerator() { return Enumerable.Empty<IModelElement>().Concat(this._parent.StVal).Concat(this._parent.Q).Concat(this._parent.SubVal).Concat(this._parent.SubQ).GetEnumerator(); } } /// <summary> /// Represents a proxy to represent an incremental access to the subEna property /// </summary> private sealed class SubEnaProxy : ModelPropertyChange<IDPS, Nullable<bool>> { /// <summary> /// Creates a new observable property access proxy /// </summary> /// <param name="modelElement">The model instance element for which to create the property access proxy</param> public SubEnaProxy(IDPS modelElement) : base(modelElement, "subEna") { } /// <summary> /// Gets or sets the value of this expression /// </summary> public override Nullable<bool> Value { get { return this.ModelElement.SubEna; } set { this.ModelElement.SubEna = value; } } } /// <summary> /// Represents a proxy to represent an incremental access to the subID property /// </summary> private sealed class SubIDProxy : ModelPropertyChange<IDPS, string> { /// <summary> /// Creates a new observable property access proxy /// </summary> /// <param name="modelElement">The model instance element for which to create the property access proxy</param> public SubIDProxy(IDPS modelElement) : base(modelElement, "subID") { } /// <summary> /// Gets or sets the value of this expression /// </summary> public override string Value { get { return this.ModelElement.SubID; } set { this.ModelElement.SubID = value; } } } /// <summary> /// Represents a proxy to represent an incremental access to the stVal property /// </summary> private sealed class StValProxy : ModelPropertyChange<IDPS, IDPStatus> { /// <summary> /// Creates a new observable property access proxy /// </summary> /// <param name="modelElement">The model instance element for which to create the property access proxy</param> public StValProxy(IDPS modelElement) : base(modelElement, "stVal") { } /// <summary> /// Gets or sets the value of this expression /// </summary> public override IDPStatus Value { get { return this.ModelElement.StVal; } set { this.ModelElement.StVal = value; } } } /// <summary> /// Represents a proxy to represent an incremental access to the q property /// </summary> private sealed class QProxy : ModelPropertyChange<IDPS, IQuality> { /// <summary> /// Creates a new observable property access proxy /// </summary> /// <param name="modelElement">The model instance element for which to create the property access proxy</param> public QProxy(IDPS modelElement) : base(modelElement, "q") { } /// <summary> /// Gets or sets the value of this expression /// </summary> public override IQuality Value { get { return this.ModelElement.Q; } set { this.ModelElement.Q = value; } } } /// <summary> /// Represents a proxy to represent an incremental access to the subVal property /// </summary> private sealed class SubValProxy : ModelPropertyChange<IDPS, IDPStatus> { /// <summary> /// Creates a new observable property access proxy /// </summary> /// <param name="modelElement">The model instance element for which to create the property access proxy</param> public SubValProxy(IDPS modelElement) : base(modelElement, "subVal") { } /// <summary> /// Gets or sets the value of this expression /// </summary> public override IDPStatus Value { get { return this.ModelElement.SubVal; } set { this.ModelElement.SubVal = value; } } } /// <summary> /// Represents a proxy to represent an incremental access to the subQ property /// </summary> private sealed class SubQProxy : ModelPropertyChange<IDPS, IQuality> { /// <summary> /// Creates a new observable property access proxy /// </summary> /// <param name="modelElement">The model instance element for which to create the property access proxy</param> public SubQProxy(IDPS modelElement) : base(modelElement, "subQ") { } /// <summary> /// Gets or sets the value of this expression /// </summary> public override IQuality Value { get { return this.ModelElement.SubQ; } set { this.ModelElement.SubQ = value; } } } } }
34.975719
177
0.481166
[ "MIT" ]
georghinkel/ttc2017smartGrids
generator/61850/Dataclasses/DPS.cs
38,895
C#
// Copyright Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; public class LODSunReceiver : MonoBehaviour { public Transform Sun; public Material planetLod; private Vector4 originalSunPosition; private void Awake() { originalSunPosition = planetLod.GetVector("_SunPosition"); } private void Update() { if (Sun) { planetLod.SetVector("_SunPosition", Sun.position); } } private void OnDestroy() { planetLod.SetVector("_SunPosition", originalSunPosition); } }
22.3
91
0.663677
[ "MIT" ]
BrunoCooper17/DannyHoloLens
Assets/SolarSystem/Planets/LODs/LODSunReceiver.cs
671
C#
namespace QOAM.Website.Models { using System; using System.ComponentModel.DataAnnotations; using Core.Helpers; [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class IssnsAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value == null) { return ValidationResult.Success; } var issns = value.ToString().ToLinesSet(); foreach (var issn in issns) { if (!issn.IsValidISSN()) { return new ValidationResult("\"" + issn + "\" is not a valid ISSN."); } } return ValidationResult.Success; } } }
28.966667
102
0.55351
[ "MIT" ]
QOAM/qoam
src/Website/Models/IssnsAttribute.cs
871
C#
using Cysharp.Threading.Tasks.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Cysharp.Threading.Tasks.Linq { public static partial class UniTaskAsyncEnumerable { public static IUniTaskAsyncEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector) { Error.ThrowArgumentNullException(outer, nameof(outer)); Error.ThrowArgumentNullException(inner, nameof(inner)); Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new GroupJoin<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer<TKey>.Default); } public static IUniTaskAsyncEnumerable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector, IEqualityComparer<TKey> comparer) { Error.ThrowArgumentNullException(outer, nameof(outer)); Error.ThrowArgumentNullException(inner, nameof(inner)); Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); Error.ThrowArgumentNullException(comparer, nameof(comparer)); return new GroupJoin<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); } public static IUniTaskAsyncEnumerable<TResult> GroupJoinAwait<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, UniTask<TKey>> outerKeySelector, Func<TInner, UniTask<TKey>> innerKeySelector, Func<TOuter, IEnumerable<TInner>, UniTask<TResult>> resultSelector) { Error.ThrowArgumentNullException(outer, nameof(outer)); Error.ThrowArgumentNullException(inner, nameof(inner)); Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new GroupJoinAwait<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer<TKey>.Default); } public static IUniTaskAsyncEnumerable<TResult> GroupJoinAwait<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, UniTask<TKey>> outerKeySelector, Func<TInner, UniTask<TKey>> innerKeySelector, Func<TOuter, IEnumerable<TInner>, UniTask<TResult>> resultSelector, IEqualityComparer<TKey> comparer) { Error.ThrowArgumentNullException(outer, nameof(outer)); Error.ThrowArgumentNullException(inner, nameof(inner)); Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); Error.ThrowArgumentNullException(comparer, nameof(comparer)); return new GroupJoinAwait<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); } public static IUniTaskAsyncEnumerable<TResult> GroupJoinAwaitWithCancellation<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, CancellationToken, UniTask<TKey>> outerKeySelector, Func<TInner, CancellationToken, UniTask<TKey>> innerKeySelector, Func<TOuter, IEnumerable<TInner>, CancellationToken, UniTask<TResult>> resultSelector) { Error.ThrowArgumentNullException(outer, nameof(outer)); Error.ThrowArgumentNullException(inner, nameof(inner)); Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); return new GroupJoinAwaitWithCancellation<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer<TKey>.Default); } public static IUniTaskAsyncEnumerable<TResult> GroupJoinAwaitWithCancellation<TOuter, TInner, TKey, TResult>(this IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, CancellationToken, UniTask<TKey>> outerKeySelector, Func<TInner, CancellationToken, UniTask<TKey>> innerKeySelector, Func<TOuter, IEnumerable<TInner>, CancellationToken, UniTask<TResult>> resultSelector, IEqualityComparer<TKey> comparer) { Error.ThrowArgumentNullException(outer, nameof(outer)); Error.ThrowArgumentNullException(inner, nameof(inner)); Error.ThrowArgumentNullException(outerKeySelector, nameof(outerKeySelector)); Error.ThrowArgumentNullException(innerKeySelector, nameof(innerKeySelector)); Error.ThrowArgumentNullException(resultSelector, nameof(resultSelector)); Error.ThrowArgumentNullException(comparer, nameof(comparer)); return new GroupJoinAwaitWithCancellation<TOuter, TInner, TKey, TResult>(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer); } } internal sealed class GroupJoin<TOuter, TInner, TKey, TResult> : IUniTaskAsyncEnumerable<TResult> { readonly IUniTaskAsyncEnumerable<TOuter> outer; readonly IUniTaskAsyncEnumerable<TInner> inner; readonly Func<TOuter, TKey> outerKeySelector; readonly Func<TInner, TKey> innerKeySelector; readonly Func<TOuter, IEnumerable<TInner>, TResult> resultSelector; readonly IEqualityComparer<TKey> comparer; public GroupJoin(IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector, IEqualityComparer<TKey> comparer) { this.outer = outer; this.inner = inner; this.outerKeySelector = outerKeySelector; this.innerKeySelector = innerKeySelector; this.resultSelector = resultSelector; this.comparer = comparer; } public IUniTaskAsyncEnumerator<TResult> GetAsyncEnumerator(CancellationToken cancellationToken = default) { return new _GroupJoin(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); } sealed class _GroupJoin : MoveNextSource, IUniTaskAsyncEnumerator<TResult> { static readonly Action<object> MoveNextCoreDelegate = MoveNextCore; readonly IUniTaskAsyncEnumerable<TOuter> outer; readonly IUniTaskAsyncEnumerable<TInner> inner; readonly Func<TOuter, TKey> outerKeySelector; readonly Func<TInner, TKey> innerKeySelector; readonly Func<TOuter, IEnumerable<TInner>, TResult> resultSelector; readonly IEqualityComparer<TKey> comparer; CancellationToken cancellationToken; ILookup<TKey, TInner> lookup; IUniTaskAsyncEnumerator<TOuter> enumerator; UniTask<bool>.Awaiter awaiter; public _GroupJoin(IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, IEnumerable<TInner>, TResult> resultSelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken) { this.outer = outer; this.inner = inner; this.outerKeySelector = outerKeySelector; this.innerKeySelector = innerKeySelector; this.resultSelector = resultSelector; this.comparer = comparer; this.cancellationToken = cancellationToken; TaskTracker.TrackActiveTask(this, 3); } public TResult Current { get; private set; } public UniTask<bool> MoveNextAsync() { cancellationToken.ThrowIfCancellationRequested(); completionSource.Reset(); if (lookup == null) { CreateLookup().Forget(); } else { SourceMoveNext(); } return new UniTask<bool>(this, completionSource.Version); } async UniTaskVoid CreateLookup() { try { lookup = await inner.ToLookupAsync(innerKeySelector, comparer, cancellationToken); enumerator = outer.GetAsyncEnumerator(cancellationToken); } catch (Exception ex) { completionSource.TrySetException(ex); return; } SourceMoveNext(); } void SourceMoveNext() { try { awaiter = enumerator.MoveNextAsync().GetAwaiter(); if (awaiter.IsCompleted) { MoveNextCore(this); } else { awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); } } catch (Exception ex) { completionSource.TrySetException(ex); } } static void MoveNextCore(object state) { var self = (_GroupJoin)state; if (self.TryGetResult(self.awaiter, out var result)) { if (result) { var outer = self.enumerator.Current; var key = self.outerKeySelector(outer); var values = self.lookup[key]; self.Current = self.resultSelector(outer, values); self.completionSource.TrySetResult(true); } else { self.completionSource.TrySetResult(false); } } } public UniTask DisposeAsync() { TaskTracker.RemoveTracking(this); if (enumerator != null) { return enumerator.DisposeAsync(); } return default; } } } internal sealed class GroupJoinAwait<TOuter, TInner, TKey, TResult> : IUniTaskAsyncEnumerable<TResult> { readonly IUniTaskAsyncEnumerable<TOuter> outer; readonly IUniTaskAsyncEnumerable<TInner> inner; readonly Func<TOuter, UniTask<TKey>> outerKeySelector; readonly Func<TInner, UniTask<TKey>> innerKeySelector; readonly Func<TOuter, IEnumerable<TInner>, UniTask<TResult>> resultSelector; readonly IEqualityComparer<TKey> comparer; public GroupJoinAwait(IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, UniTask<TKey>> outerKeySelector, Func<TInner, UniTask<TKey>> innerKeySelector, Func<TOuter, IEnumerable<TInner>, UniTask<TResult>> resultSelector, IEqualityComparer<TKey> comparer) { this.outer = outer; this.inner = inner; this.outerKeySelector = outerKeySelector; this.innerKeySelector = innerKeySelector; this.resultSelector = resultSelector; this.comparer = comparer; } public IUniTaskAsyncEnumerator<TResult> GetAsyncEnumerator(CancellationToken cancellationToken = default) { return new _GroupJoinAwait(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); } sealed class _GroupJoinAwait : MoveNextSource, IUniTaskAsyncEnumerator<TResult> { static readonly Action<object> MoveNextCoreDelegate = MoveNextCore; readonly static Action<object> ResultSelectCoreDelegate = ResultSelectCore; readonly static Action<object> OuterKeySelectCoreDelegate = OuterKeySelectCore; readonly IUniTaskAsyncEnumerable<TOuter> outer; readonly IUniTaskAsyncEnumerable<TInner> inner; readonly Func<TOuter, UniTask<TKey>> outerKeySelector; readonly Func<TInner, UniTask<TKey>> innerKeySelector; readonly Func<TOuter, IEnumerable<TInner>, UniTask<TResult>> resultSelector; readonly IEqualityComparer<TKey> comparer; CancellationToken cancellationToken; ILookup<TKey, TInner> lookup; IUniTaskAsyncEnumerator<TOuter> enumerator; TOuter outerValue; UniTask<bool>.Awaiter awaiter; UniTask<TKey>.Awaiter outerKeyAwaiter; UniTask<TResult>.Awaiter resultAwaiter; public _GroupJoinAwait(IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, UniTask<TKey>> outerKeySelector, Func<TInner, UniTask<TKey>> innerKeySelector, Func<TOuter, IEnumerable<TInner>, UniTask<TResult>> resultSelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken) { this.outer = outer; this.inner = inner; this.outerKeySelector = outerKeySelector; this.innerKeySelector = innerKeySelector; this.resultSelector = resultSelector; this.comparer = comparer; this.cancellationToken = cancellationToken; TaskTracker.TrackActiveTask(this, 3); } public TResult Current { get; private set; } public UniTask<bool> MoveNextAsync() { cancellationToken.ThrowIfCancellationRequested(); completionSource.Reset(); if (lookup == null) { CreateLookup().Forget(); } else { SourceMoveNext(); } return new UniTask<bool>(this, completionSource.Version); } async UniTaskVoid CreateLookup() { try { lookup = await inner.ToLookupAwaitAsync(innerKeySelector, comparer, cancellationToken); enumerator = outer.GetAsyncEnumerator(cancellationToken); } catch (Exception ex) { completionSource.TrySetException(ex); return; } SourceMoveNext(); } void SourceMoveNext() { try { awaiter = enumerator.MoveNextAsync().GetAwaiter(); if (awaiter.IsCompleted) { MoveNextCore(this); } else { awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); } } catch (Exception ex) { completionSource.TrySetException(ex); } } static void MoveNextCore(object state) { var self = (_GroupJoinAwait)state; if (self.TryGetResult(self.awaiter, out var result)) { if (result) { try { self.outerValue = self.enumerator.Current; self.outerKeyAwaiter = self.outerKeySelector(self.outerValue).GetAwaiter(); if (self.outerKeyAwaiter.IsCompleted) { OuterKeySelectCore(self); } else { self.outerKeyAwaiter.SourceOnCompleted(OuterKeySelectCoreDelegate, self); } } catch (Exception ex) { self.completionSource.TrySetException(ex); } } else { self.completionSource.TrySetResult(false); } } } static void OuterKeySelectCore(object state) { var self = (_GroupJoinAwait)state; if (self.TryGetResult(self.outerKeyAwaiter, out var result)) { try { var values = self.lookup[result]; self.resultAwaiter = self.resultSelector(self.outerValue, values).GetAwaiter(); if (self.resultAwaiter.IsCompleted) { ResultSelectCore(self); } else { self.resultAwaiter.SourceOnCompleted(ResultSelectCoreDelegate, self); } } catch (Exception ex) { self.completionSource.TrySetException(ex); } } } static void ResultSelectCore(object state) { var self = (_GroupJoinAwait)state; if (self.TryGetResult(self.resultAwaiter, out var result)) { self.Current = result; self.completionSource.TrySetResult(true); } } public UniTask DisposeAsync() { TaskTracker.RemoveTracking(this); if (enumerator != null) { return enumerator.DisposeAsync(); } return default; } } } internal sealed class GroupJoinAwaitWithCancellation<TOuter, TInner, TKey, TResult> : IUniTaskAsyncEnumerable<TResult> { readonly IUniTaskAsyncEnumerable<TOuter> outer; readonly IUniTaskAsyncEnumerable<TInner> inner; readonly Func<TOuter, CancellationToken, UniTask<TKey>> outerKeySelector; readonly Func<TInner, CancellationToken, UniTask<TKey>> innerKeySelector; readonly Func<TOuter, IEnumerable<TInner>, CancellationToken, UniTask<TResult>> resultSelector; readonly IEqualityComparer<TKey> comparer; public GroupJoinAwaitWithCancellation(IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, CancellationToken, UniTask<TKey>> outerKeySelector, Func<TInner, CancellationToken, UniTask<TKey>> innerKeySelector, Func<TOuter, IEnumerable<TInner>, CancellationToken, UniTask<TResult>> resultSelector, IEqualityComparer<TKey> comparer) { this.outer = outer; this.inner = inner; this.outerKeySelector = outerKeySelector; this.innerKeySelector = innerKeySelector; this.resultSelector = resultSelector; this.comparer = comparer; } public IUniTaskAsyncEnumerator<TResult> GetAsyncEnumerator(CancellationToken cancellationToken = default) { return new _GroupJoinAwaitWithCancellation(outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer, cancellationToken); } sealed class _GroupJoinAwaitWithCancellation : MoveNextSource, IUniTaskAsyncEnumerator<TResult> { static readonly Action<object> MoveNextCoreDelegate = MoveNextCore; readonly static Action<object> ResultSelectCoreDelegate = ResultSelectCore; readonly static Action<object> OuterKeySelectCoreDelegate = OuterKeySelectCore; readonly IUniTaskAsyncEnumerable<TOuter> outer; readonly IUniTaskAsyncEnumerable<TInner> inner; readonly Func<TOuter, CancellationToken, UniTask<TKey>> outerKeySelector; readonly Func<TInner, CancellationToken, UniTask<TKey>> innerKeySelector; readonly Func<TOuter, IEnumerable<TInner>, CancellationToken, UniTask<TResult>> resultSelector; readonly IEqualityComparer<TKey> comparer; CancellationToken cancellationToken; ILookup<TKey, TInner> lookup; IUniTaskAsyncEnumerator<TOuter> enumerator; TOuter outerValue; UniTask<bool>.Awaiter awaiter; UniTask<TKey>.Awaiter outerKeyAwaiter; UniTask<TResult>.Awaiter resultAwaiter; public _GroupJoinAwaitWithCancellation(IUniTaskAsyncEnumerable<TOuter> outer, IUniTaskAsyncEnumerable<TInner> inner, Func<TOuter, CancellationToken, UniTask<TKey>> outerKeySelector, Func<TInner, CancellationToken, UniTask<TKey>> innerKeySelector, Func<TOuter, IEnumerable<TInner>, CancellationToken, UniTask<TResult>> resultSelector, IEqualityComparer<TKey> comparer, CancellationToken cancellationToken) { this.outer = outer; this.inner = inner; this.outerKeySelector = outerKeySelector; this.innerKeySelector = innerKeySelector; this.resultSelector = resultSelector; this.comparer = comparer; this.cancellationToken = cancellationToken; TaskTracker.TrackActiveTask(this, 3); } public TResult Current { get; private set; } public UniTask<bool> MoveNextAsync() { cancellationToken.ThrowIfCancellationRequested(); completionSource.Reset(); if (lookup == null) { CreateLookup().Forget(); } else { SourceMoveNext(); } return new UniTask<bool>(this, completionSource.Version); } async UniTaskVoid CreateLookup() { try { lookup = await inner.ToLookupAwaitWithCancellationAsync(innerKeySelector, comparer, cancellationToken); enumerator = outer.GetAsyncEnumerator(cancellationToken); } catch (Exception ex) { completionSource.TrySetException(ex); return; } SourceMoveNext(); } void SourceMoveNext() { try { awaiter = enumerator.MoveNextAsync().GetAwaiter(); if (awaiter.IsCompleted) { MoveNextCore(this); } else { awaiter.SourceOnCompleted(MoveNextCoreDelegate, this); } } catch (Exception ex) { completionSource.TrySetException(ex); } } static void MoveNextCore(object state) { var self = (_GroupJoinAwaitWithCancellation)state; if (self.TryGetResult(self.awaiter, out var result)) { if (result) { try { self.outerValue = self.enumerator.Current; self.outerKeyAwaiter = self.outerKeySelector(self.outerValue, self.cancellationToken).GetAwaiter(); if (self.outerKeyAwaiter.IsCompleted) { OuterKeySelectCore(self); } else { self.outerKeyAwaiter.SourceOnCompleted(OuterKeySelectCoreDelegate, self); } } catch (Exception ex) { self.completionSource.TrySetException(ex); } } else { self.completionSource.TrySetResult(false); } } } static void OuterKeySelectCore(object state) { var self = (_GroupJoinAwaitWithCancellation)state; if (self.TryGetResult(self.outerKeyAwaiter, out var result)) { try { var values = self.lookup[result]; self.resultAwaiter = self.resultSelector(self.outerValue, values, self.cancellationToken).GetAwaiter(); if (self.resultAwaiter.IsCompleted) { ResultSelectCore(self); } else { self.resultAwaiter.SourceOnCompleted(ResultSelectCoreDelegate, self); } } catch (Exception ex) { self.completionSource.TrySetException(ex); } } } static void ResultSelectCore(object state) { var self = (_GroupJoinAwaitWithCancellation)state; if (self.TryGetResult(self.resultAwaiter, out var result)) { self.Current = result; self.completionSource.TrySetResult(true); } } public UniTask DisposeAsync() { TaskTracker.RemoveTracking(this); if (enumerator != null) { return enumerator.DisposeAsync(); } return default; } } } }
45.99183
451
0.564749
[ "MIT" ]
coding2233/UnityGameFramework
Libraries/UniTask/Runtime/Linq/GroupJoin.cs
28,149
C#
using System; using System.IO; using System.Linq; using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.Android; using Xamarin.UITest.Queries; namespace AnalyticsSample.UITests { [TestFixture] public class Tests { AndroidApp app; [SetUp] public void BeforeEachTest () { app = ConfigureApp .Android .ApkFile ("app.apk") .PreferIdeSettings () .StartApp (); } //[Test] public void Repl () { app.Repl (); } [Test] public void AppLaunches () { app.Screenshot ("Launch"); } } }
18.725
39
0.473965
[ "MIT" ]
4brunu/GooglePlayServicesComponents
samples/com.google.android.gms/play-services-analytics/AnalyticsSample.UITests/Tests.cs
751
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace server.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.193548
152
0.563703
[ "Apache-2.0" ]
sdlylshl/Gateway
Gateway_CS/server/Properties/Settings.Designer.cs
1,093
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicTests : ExpressionCompilerTestBase { [Fact] public void Local_Simple() { var source = @"class C { static void M() { dynamic d = 1; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Local_Array() { var source = @"class C { static void M() { dynamic[] d = new dynamic[1]; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic[] V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Local_Generic() { var source = @"class C { static void M() { System.Collections.Generic.List<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments().Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Collections.Generic.List<dynamic> V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Simple() { var source = @"class C { static void M() { const dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Array() { var source = @"class C { static void M() { const dynamic[] d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Generic() { var source = @"class C { static void M() { const Generic<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } } class Generic<T> { } "; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments().Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndNonConstantDynamic() { var source = @"class C { static void M() { { #line 799 dynamic a = null; const dynamic b = null; } { const dynamic[] a = null; #line 899 dynamic[] b = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[0], "a", 0x01); } else { VerifyCustomTypeInfo(locals[0], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[1], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "b", 0x02); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndNonConstantNonDynamic() { var source = @"class C { static void M() { { #line 799 object a = null; const dynamic b = null; } { const dynamic[] a = null; #line 899 object[] b = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "a", null); VerifyCustomTypeInfo(locals[1], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "b", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndConstantDynamic() { var source = @"class C { static void M() { { const dynamic a = null; const dynamic b = null; #line 799 object e = null; } { const dynamic[] a = null; const dynamic[] c = null; #line 899 object[] e = null; } { #line 999 object e = null; const dynamic a = null; const dynamic c = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[2], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); VerifyCustomTypeInfo(locals[2], "c", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); VerifyCustomTypeInfo(locals[2], "c", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndConstantNonDynamic() { var source = @"class C { static void M() { { const dynamic a = null; const object c = null; #line 799 object e = null; } { const dynamic[] b = null; #line 899 object[] e = null; } { const object[] a = null; #line 999 object e = null; const dynamic[] c = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[2], "c", null); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); VerifyCustomTypeInfo(locals[1], "b", 0x02); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); VerifyCustomTypeInfo(locals[1], "a", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[2], "c", 0x02); } else { VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [Fact] public void LocalsWithLongAndShortNames() { var source = @"class C { static void M() { const dynamic a123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars const dynamic b = null; dynamic c123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(4, locals.Count); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", 0x01); VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", 0x01); } else { VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped } VerifyCustomTypeInfo(locals[1], "d", 0x01); VerifyCustomTypeInfo(locals[3], "b", 0x01); locals.Free(); }); } [Fact] public void Parameter_Simple() { var source = @"class C { static void M(dynamic d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Parameter_Array() { var source = @"class C { static void M(dynamic[] d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Parameter_Generic() { var source = @"class C { static void M(System.Collections.Generic.List<dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments().Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void ComplexDynamicType() { var source = @"class C { static void M(Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } } public class Outer<T, U> { public class Inner<V, W> { } } "; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); VerifyCustomTypeInfo(locals[0], "d", 0x04, 0x03); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); string error; var result = context.CompileExpression("d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, 0x04, 0x03); // Note that the method produced by CompileAssignment returns void // so there is never custom type info. result = context.CompileAssignment("d", "d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, null); ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); result = context.CompileExpression( "var dd = d;", DkmEvaluationFlags.None, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 60 (0x3c) .maxstack 6 IL_0000: ldtoken ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""dd"" IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1"" IL_0014: newobj ""System.Guid..ctor(string)"" IL_0019: ldc.i4.3 IL_001a: newarr ""byte"" IL_001f: dup IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=3 <PrivateImplementationDetails>.A4E591DA7617172655FE45FC3878ECC8CC0D44B3"" IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])"" IL_002f: ldstr ""dd"" IL_0034: call ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>>(string)"" IL_0039: ldarg.0 IL_003a: stind.ref IL_003b: ret }"); locals.Free(); }); } [Fact] public void DynamicAliases() { var source = @"class C { static void M() { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( Alias( DkmClrAliasKind.Variable, "d1", "d1", typeof(object).AssemblyQualifiedName, MakeCustomTypeInfo(true)), Alias( DkmClrAliasKind.Variable, "d2", "d2", typeof(Dictionary<Dictionary<dynamic, Dictionary<object[], dynamic[]>>, object>).AssemblyQualifiedName, MakeCustomTypeInfo(false, false, true, false, false, false, false, true, false))); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var diagnostics = DiagnosticBag.GetInstance(); var testData = new CompilationTestData(); context.CompileGetLocals( locals, argumentsOnly: false, aliases: aliases, diagnostics: diagnostics, typeName: out typeName, testData: testData); diagnostics.Free(); Assert.Equal(locals.Count, 2); VerifyCustomTypeInfo(locals[0], "d1", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d1", expectedILOpt: @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""d1"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: ret }"); VerifyCustomTypeInfo(locals[1], "d2", 0x84, 0x00); // Note: read flags right-to-left in each byte: 0010 0001 0(000 0000) VerifyLocal(testData, typeName, locals[1], "<>m1", "d2", expectedILOpt: @"{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr ""d2"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""System.Collections.Generic.Dictionary<System.Collections.Generic.Dictionary<dynamic, System.Collections.Generic.Dictionary<object[], dynamic[]>>, object>"" IL_000f: ret }"); locals.Free(); }); } private static ReadOnlyCollection<byte> MakeCustomTypeInfo(params bool[] flags) { Assert.NotNull(flags); var builder = ArrayBuilder<bool>.GetInstance(); builder.AddRange(flags); var bytes = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); return CustomTypeInfo.Encode(bytes, null); } [Fact] public void DynamicAttribute_NotAvailable() { var source = @"class C { static void M() { dynamic d = 1; } }"; var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: false); VerifyCustomTypeInfo(locals[0], "d", null); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void DynamicCall() { var source = @" class C { void M() { dynamic d = this; d.M(); } } "; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("d.M()", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(TypeKind.Dynamic, methodData.Method.ReturnType.TypeKind); methodData.VerifyIL(@" { // Code size 77 (0x4d) .maxstack 9 .locals init (dynamic V_0) //d IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0037 IL_0007: ldc.i4.0 IL_0008: ldstr ""M"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.1 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0032: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_003c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldloc.0 IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: ret } "); }); } [WorkItem(1160855, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1160855")] [Fact] public void AwaitDynamic() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class C { dynamic d; void M(int p) { d.Test(); // Force reference to runtime binder. } static void G(Func<Task<object>> f) { } } "; var comp = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("G(async () => await d())", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); var methodData = testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()"); methodData.VerifyIL(@" { // Code size 542 (0x21e) .maxstack 10 .locals init (int V_0, <>x.<>c__DisplayClass0_0 V_1, object V_2, object V_3, System.Runtime.CompilerServices.ICriticalNotifyCompletion V_4, System.Runtime.CompilerServices.INotifyCompletion V_5, System.Exception V_6) IL_0000: ldarg.0 IL_0001: ldfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldfld ""<>x.<>c__DisplayClass0_0 <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>4__this"" IL_000d: stloc.1 .try { IL_000e: ldloc.0 IL_000f: brfalse IL_018a IL_0014: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0019: brtrue.s IL_004b IL_001b: ldc.i4.0 IL_001c: ldstr ""GetAwaiter"" IL_0021: ldnull IL_0022: ldtoken ""C"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: ldc.i4.1 IL_002d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0032: dup IL_0033: ldc.i4.0 IL_0034: ldc.i4.0 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0050: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_005f: brtrue.s IL_008b IL_0061: ldc.i4.0 IL_0062: ldtoken ""C"" IL_0067: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006c: ldc.i4.1 IL_006d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0072: dup IL_0073: ldc.i4.0 IL_0074: ldc.i4.0 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0081: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0086: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0090: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_009a: ldloc.1 IL_009b: ldfld ""C <>x.<>c__DisplayClass0_0.<>4__this"" IL_00a0: ldfld ""dynamic C.d"" IL_00a5: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00aa: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00af: stloc.3 IL_00b0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00b5: brtrue.s IL_00dc IL_00b7: ldc.i4.s 16 IL_00b9: ldtoken ""bool"" IL_00be: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c3: ldtoken ""C"" IL_00c8: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00cd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_00d2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00e1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_00e6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00eb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_00f0: brtrue.s IL_0121 IL_00f2: ldc.i4.0 IL_00f3: ldstr ""IsCompleted"" IL_00f8: ldtoken ""C"" IL_00fd: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0102: ldc.i4.1 IL_0103: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0108: dup IL_0109: ldc.i4.0 IL_010a: ldc.i4.0 IL_010b: ldnull IL_010c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0111: stelem.ref IL_0112: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0117: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_011c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_0121: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_0126: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_012b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_0130: ldloc.3 IL_0131: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0136: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_013b: brtrue.s IL_01a1 IL_013d: ldarg.0 IL_013e: ldc.i4.0 IL_013f: dup IL_0140: stloc.0 IL_0141: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0146: ldarg.0 IL_0147: ldloc.3 IL_0148: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_014d: ldloc.3 IL_014e: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion"" IL_0153: stloc.s V_4 IL_0155: ldloc.s V_4 IL_0157: brtrue.s IL_0174 IL_0159: ldloc.3 IL_015a: castclass ""System.Runtime.CompilerServices.INotifyCompletion"" IL_015f: stloc.s V_5 IL_0161: ldarg.0 IL_0162: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0167: ldloca.s V_5 IL_0169: ldarg.0 IL_016a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.INotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)"" IL_016f: ldnull IL_0170: stloc.s V_5 IL_0172: br.s IL_0182 IL_0174: ldarg.0 IL_0175: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_017a: ldloca.s V_4 IL_017c: ldarg.0 IL_017d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)"" IL_0182: ldnull IL_0183: stloc.s V_4 IL_0185: leave IL_021d IL_018a: ldarg.0 IL_018b: ldfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_0190: stloc.3 IL_0191: ldarg.0 IL_0192: ldnull IL_0193: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_0198: ldarg.0 IL_0199: ldc.i4.m1 IL_019a: dup IL_019b: stloc.0 IL_019c: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_01a1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01a6: brtrue.s IL_01d8 IL_01a8: ldc.i4.0 IL_01a9: ldstr ""GetResult"" IL_01ae: ldnull IL_01af: ldtoken ""C"" IL_01b4: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01b9: ldc.i4.1 IL_01ba: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01bf: dup IL_01c0: ldc.i4.0 IL_01c1: ldc.i4.0 IL_01c2: ldnull IL_01c3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01c8: stelem.ref IL_01c9: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01ce: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01d3: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01d8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01dd: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_01e2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01e7: ldloc.3 IL_01e8: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_01ed: stloc.2 IL_01ee: leave.s IL_0209 } catch System.Exception { IL_01f0: stloc.s V_6 IL_01f2: ldarg.0 IL_01f3: ldc.i4.s -2 IL_01f5: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_01fa: ldarg.0 IL_01fb: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0200: ldloc.s V_6 IL_0202: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0207: leave.s IL_021d } IL_0209: ldarg.0 IL_020a: ldc.i4.s -2 IL_020c: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0211: ldarg.0 IL_0212: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0217: ldloc.2 IL_0218: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_021d: ret } "); }); } [WorkItem(1072296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072296")] [Fact] public void InvokeStaticMemberInLambda() { var source = @" class C { static dynamic x; static void Goo(dynamic y) { System.Action a = () => Goo(x); } } "; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Goo"); var testData = new CompilationTestData(); string error; var result = context.CompileAssignment("a", "() => Goo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); testData.GetMethodData("<>x.<>c.<<>m0>b__0_0").VerifyIL(@" { // Code size 106 (0x6a) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0055: ldtoken ""<>x"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldsfld ""dynamic C.x"" IL_0064: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0069: ret }"); context = CreateMethodContext(runtime, "C.<>c.<Goo>b__1_0"); testData = new CompilationTestData(); result = context.CompileExpression("Goo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 102 (0x66) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Goo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldsfld ""dynamic C.x"" IL_0060: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0065: ret }"); }); } [WorkItem(1095613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095613")] [Fact] public void HoistedLocalsLoseDynamicAttribute() { var source = @" class C { static void M(dynamic x) { dynamic y = 3; System.Func<dynamic> a = () => x + y; } static void Goo(int x) { M(x); } } "; var comp = CreateStandardCompilation(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("Goo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 103 (0x67) .maxstack 9 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<dynamic> V_1) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Goo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldloc.0 IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.x"" IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0066: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("Goo(y)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 103 (0x67) .maxstack 9 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<dynamic> V_1) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Goo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldloc.0 IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.y"" IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0066: ret }"); }); } private static void VerifyCustomTypeInfo(LocalAndMethod localAndMethod, string expectedName, params byte[] expectedBytes) { Assert.Equal(localAndMethod.LocalName, expectedName); ReadOnlyCollection<byte> customTypeInfo; Guid customTypeInfoId = localAndMethod.GetCustomTypeInfo(out customTypeInfo); VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes); } private static void VerifyCustomTypeInfo(CompileResult compileResult, params byte[] expectedBytes) { ReadOnlyCollection<byte> customTypeInfo; Guid customTypeInfoId = compileResult.GetCustomTypeInfo(out customTypeInfo); VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes); } private static void VerifyCustomTypeInfo(Guid customTypeInfoId, ReadOnlyCollection<byte> customTypeInfo, params byte[] expectedBytes) { if (expectedBytes == null) { Assert.Equal(Guid.Empty, customTypeInfoId); Assert.Null(customTypeInfo); } else { Assert.Equal(CustomTypeInfo.PayloadTypeId, customTypeInfoId); // Include leading count byte. var builder = ArrayBuilder<byte>.GetInstance(); builder.Add((byte)expectedBytes.Length); builder.AddRange(expectedBytes); expectedBytes = builder.ToArrayAndFree(); Assert.Equal(expectedBytes, customTypeInfo); } } } }
48.25
341
0.642734
[ "Apache-2.0" ]
JieCarolHu/roslyn
src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/DynamicTests.cs
72,763
C#
// ----------------------------------------------------------------------- // <copyright file="UnitOfWorkManager.cs" company="柳柳软件"> // Copyright (c) 2016-2018 66SOFT. All rights reserved. // </copyright> // <site>http://www.66soft.net</site> // <last-editor>郭明锋</last-editor> // <last-date>2018-08-31 21:33</last-date> // ----------------------------------------------------------------------- using System; using System.Collections.Concurrent; using System.Linq; using Microsoft.Extensions.DependencyInjection; using OSharp.Core.Options; using OSharp.Dependency; using OSharp.Entity.Transactions; using OSharp.Exceptions; using OSharp.Extensions; namespace OSharp.Entity { /// <summary> /// 工作单元管理器 /// </summary> [Dependency(ServiceLifetime.Scoped, TryAdd = true)] public class UnitOfWorkManager : IUnitOfWorkManager { private readonly IServiceProvider _serviceProvider; /// <summary> /// 以数据库连接字符串为键,工作单元为值的字典 /// </summary> private readonly ConcurrentDictionary<string, IUnitOfWork> _connStringUnitOfWorks = new ConcurrentDictionary<string, IUnitOfWork>(); private readonly ConcurrentDictionary<Type, IUnitOfWork> _entityTypeUnitOfWorks = new ConcurrentDictionary<Type, IUnitOfWork>(); /// <summary> /// 初始化一个<see cref="UnitOfWorkManager"/>类型的新实例 /// </summary> public UnitOfWorkManager(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <summary> /// 获取 服务提供器 /// </summary> public IServiceProvider ServiceProvider => _serviceProvider; /// <summary> /// 获取 事务是否已提交 /// </summary> public bool HasCommited { get { return _connStringUnitOfWorks.Values.All(m => m.HasCommited); } } /// <summary> /// 获取指定实体所在的工作单元对象 /// </summary> /// <typeparam name="TEntity">实体类型</typeparam> /// <typeparam name="TKey">实体主键类型</typeparam> /// <returns>工作单元对象</returns> public IUnitOfWork GetUnitOfWork<TEntity, TKey>() where TEntity : IEntity<TKey> { Type entityType = typeof(TEntity); return GetUnitOfWork(entityType); } /// <summary> /// 获取指定实体所在的工作单元对象 /// </summary> /// <param name="entityType">实体类型</param> /// <returns>工作单元对象</returns> public IUnitOfWork GetUnitOfWork(Type entityType) { if (!entityType.IsEntityType()) { throw new OsharpException($"类型“{entityType}”不是实体类型"); } IUnitOfWork unitOfWork = _entityTypeUnitOfWorks.GetOrDefault(entityType); if (unitOfWork != null) { return unitOfWork; } IEntityConfigurationTypeFinder typeFinder = _serviceProvider.GetService<IEntityConfigurationTypeFinder>(); Type dbContextType = typeFinder.GetDbContextTypeForEntity(entityType); if (dbContextType == null) { throw new OsharpException($"实体类“{entityType}”的所属上下文类型无法找到"); } OSharpDbContextOptions dbContextOptions = GetDbContextResolveOptions(dbContextType); DbContextResolveOptions resolveOptions = new DbContextResolveOptions(dbContextOptions); unitOfWork = _connStringUnitOfWorks.GetOrDefault(resolveOptions.ConnectionString); if (unitOfWork != null) { return unitOfWork; } unitOfWork = ActivatorUtilities.CreateInstance<UnitOfWork>(_serviceProvider, resolveOptions); _entityTypeUnitOfWorks.TryAdd(entityType, unitOfWork); _connStringUnitOfWorks.TryAdd(resolveOptions.ConnectionString, unitOfWork); return unitOfWork; } /// <summary> /// 获取指定实体类所属的上下文类型 /// </summary> /// <param name="entityType">实体类型</param> /// <returns>上下文类型</returns> public Type GetDbContextType(Type entityType) { IEntityConfigurationTypeFinder typeFinder = _serviceProvider.GetService<IEntityConfigurationTypeFinder>(); return typeFinder.GetDbContextTypeForEntity(entityType); } /// <summary> /// 获取数据上下文选项 /// </summary> /// <param name="dbContextType">数据上下文类型</param> /// <returns>数据上下文选项</returns> public OSharpDbContextOptions GetDbContextResolveOptions(Type dbContextType) { OSharpDbContextOptions dbContextOptions = _serviceProvider.GetOSharpOptions()?.GetDbContextOptions(dbContextType); if (dbContextOptions == null) { throw new OsharpException($"无法找到数据上下文“{dbContextType}”的配置信息"); } return dbContextOptions; } /// <summary> /// 提交所有工作单元的事务更改 /// </summary> public void Commit() { foreach (IUnitOfWork unitOfWork in _connStringUnitOfWorks.Values) { unitOfWork.Commit(); } } /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { foreach (IUnitOfWork unitOfWork in _connStringUnitOfWorks.Values) { unitOfWork.Dispose(); } _connStringUnitOfWorks.Clear(); } } }
35.33758
135
0.592646
[ "Apache-2.0" ]
liaokui900/osharp-ns20
src/OSharp.EntityFrameworkCore/UnitOfWorkManager.cs
5,992
C#
//---------------------------------------------------------------------------- // Copyright (C) 2004-2016 by EMGU Corporation. All rights reserved. //---------------------------------------------------------------------------- using System; using System.Diagnostics; using System.Runtime.InteropServices; using Emgu.CV; using Emgu.CV.Util; using Emgu.Util; namespace Emgu.CV.Features2D { /// <summary> /// Descriptor matcher /// </summary> public abstract class DescriptorMatcher : UnmanagedObject, IAlgorithm { /// <summary> /// The pointer to the Descriptor matcher /// </summary> protected IntPtr _descriptorMatcherPtr; /// <summary> /// Find the k-nearest match /// </summary> /// <param name="queryDescriptor">An n x m matrix of descriptors to be query for nearest neighbours. n is the number of descriptor and m is the size of the descriptor</param> /// <param name="k">Number of nearest neighbors to search for</param> /// <param name="mask">Can be null if not needed. An n x 1 matrix. If 0, the query descriptor in the corresponding row will be ignored.</param> /// <param name="matches">Matches. Each matches[i] is k or less matches for the same query descriptor.</param> public void KnnMatch(IInputArray queryDescriptor, VectorOfVectorOfDMatch matches, int k, IInputArray mask) { using (InputArray iaQueryDesccriptor = queryDescriptor.GetInputArray()) using (InputArray iaMask = mask == null ? InputArray.GetEmpty() : mask.GetInputArray()) DescriptorMatcherInvoke.CvDescriptorMatcherKnnMatch(_descriptorMatcherPtr, iaQueryDesccriptor, matches, k, iaMask); } /// <summary> /// Add the model descriptors /// </summary> /// <param name="modelDescriptors">The model descriptors</param> public void Add(IInputArray modelDescriptors) { using (InputArray iaModelDescriptors = modelDescriptors.GetInputArray()) DescriptorMatcherInvoke.CvDescriptorMatcherAdd(_descriptorMatcherPtr, iaModelDescriptors); } IntPtr IAlgorithm.AlgorithmPtr { get { return DescriptorMatcherInvoke.CvDescriptorMatcherGetAlgorithm(_ptr); } } /// <summary> /// Reset the native pointer upon object disposal /// </summary> protected override void DisposeObject() { _descriptorMatcherPtr = IntPtr.Zero; } } internal static partial class DescriptorMatcherInvoke { static DescriptorMatcherInvoke() { CvInvoke.CheckLibraryLoaded(); } [DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)] internal extern static void CvDescriptorMatcherAdd(IntPtr matcher, IntPtr trainDescriptor); [DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)] internal extern static void CvDescriptorMatcherKnnMatch(IntPtr matcher, IntPtr queryDescriptors, IntPtr matches, int k, IntPtr mask); [DllImport(CvInvoke.ExternLibrary, CallingConvention = CvInvoke.CvCallingConvention)] internal extern static IntPtr CvDescriptorMatcherGetAlgorithm(IntPtr matcher); } }
41.790123
182
0.635746
[ "MIT" ]
rlabrecque/RLSolitaireBot
Emgu.CV/Emgu.CV/Features2D/DescriptorMatcher.cs
3,387
C#
namespace MO.Design3d.Camera.Forms { partial class QDsCameraDesignForm { /// <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.SuspendLayout(); // // QDsCameraDesignForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(990, 624); this.Name = "QDsCameraDesignForm"; this.Text = "QDsCameraDesignForm"; this.ResumeLayout(false); } #endregion } }
30.697674
105
0.60303
[ "Apache-2.0" ]
favedit/MoCross
Tools/2 - Core/MoDesign3d/Camera/Forms/QDsCameraDesignForm.Designer.cs
1,322
C#
namespace SystemWrapper.Security.Certificate { using System.IO; using System.Security.Cryptography.X509Certificates; using SystemInterface.Security.Certificate; /// <summary> /// Factory Creating a X509Certificate to avoid bugg in X509Certificate that does not delete tmp files /// </summary> public class X509CertificateFactory : IX509CertificateFactory { #region Public Methods and Operators /// <summary> /// Creating an X509Certificate from a byte array /// </summary> /// <param name="certificateAsBytes"> /// The certificate as bytes. /// </param> /// <param name="password"> /// The password needed to access private key. Can be null if the certificate specified as bytes does not require password decryption. /// </param> /// <returns> /// X509Certificate of the given byte Array /// </returns> public X509Certificate Create(byte[] certificateAsBytes, string password = null) { var filename = Path.GetTempFileName(); try { File.WriteAllBytes(filename, certificateAsBytes); if (password == null) { return new X509Certificate(filename); } return new X509Certificate(filename, password); } finally { File.Delete(filename); } } #endregion } }
31.26
142
0.557901
[ "MIT" ]
TechSmith/SystemWrapper.Core
SystemWrapper/SystemWrapper/Security/Certificate/X509CertificateFactory.cs
1,565
C#
// using System; // using System.Linq; // using MediatR; // using Microsoft.Extensions.DependencyInjection; // using Moq; // using WeeControl.Backend.Application.BoundContexts.Garbag.GetClaimsV1; // using WeeControl.Backend.Application.Exceptions; // using WeeControl.Backend.Application.Interfaces; // using WeeControl.Backend.Persistence; // using WeeControl.Common.SharedKernel.EntityGroups.Employee.Attributes; // using WeeControl.Common.SharedKernel.EntityGroups.Employee.Interfaces; // using Xunit; // // namespace WeeControl.Backend.Application.Test.EntityGroup.Employee.V1.Queries // { // public class GetEmployeeClaimsV1HandlerTesters : IDisposable // { // private readonly IEmployeeAttribute sharedValues = new EmployeeAttribute(); // private IMySystemDbContext dbContext; // private Mock<ICurrentUserInfo> userInfoMock; // private Mock<IMediator> mediatRMock; // // private GetEmployeeClaimsHandler handler; // // // public GetEmployeeClaimsV1HandlerTesters() // { // dbContext = new ServiceCollection().AddPersistenceAsInMemory(new Random().NextDouble().ToString()).BuildServiceProvider().GetService<IMySystemDbContext>(); // userInfoMock = new Mock<ICurrentUserInfo>(); // // mediatRMock = new Mock<IMediator>(); // // handler = new GetEmployeeClaimsHandler(dbContext, userInfoMock.Object, sharedValues, mediatRMock.Object); // } // // public void Dispose() // { // dbContext = null; // userInfoMock = null; // // handler = null; // } // // #region Constructor // [Fact] // public void WhenFirstParameterIsNull_ThrowArgumentNullException() // { // Assert.Throws<ArgumentNullException>(() => new GetEmployeeClaimsHandler(null, userInfoMock.Object, sharedValues, mediatRMock.Object)); // } // // [Fact] // public void WhenSecondParameterIsNull_ThrowArgumentNullException() // { // Assert.Throws<ArgumentNullException>(() => new GetEmployeeClaimsHandler(dbContext, null, sharedValues, mediatRMock.Object)); // } // // [Fact] // public void WhenThridParameterIsNull_ThrowArgumentNullException() // { // Assert.Throws<ArgumentNullException>(() => new GetEmployeeClaimsHandler(dbContext, userInfoMock.Object, null, mediatRMock.Object)); // } // // [Fact] // public void WhenFourthParameterIsNull_ThrowArgumentNullException() // { // Assert.Throws<ArgumentNullException>(() => new GetEmployeeClaimsHandler(dbContext, userInfoMock.Object, sharedValues, null)); // } // #endregion // // // #region Query // // [Fact] // // public async void WhenQueryIsNull_ThrowArgumentNullExceptino() // // { // // await Assert.ThrowsAsync<ArgumentNullException>(async () => await handler.Handle(null, default)); // // } // // // // [Fact] // // public async void WhenAllQueryPropertiesWhereSupplied_ThrowBadRequest() // // { // // var query = new GetEmployeeClaimsQuery() { Username = "admin", Password = "admin", Device = "device", EmployeeId = Guid.NewGuid() }; // // // // await Assert.ThrowsAsync<BadRequestException>(async () => await handler.Handle(query, default)); // // } // // // // [Fact] // // public async void WhenNitherOfAnyQueryPropertiesWhereSupplied_ThrowBadRequest() // // { // // var query = new GetEmployeeClaimsQuery(); // // // // await Assert.ThrowsAsync<BadRequestException>(async () => await handler.Handle(query, default)); // // } // // // // [Theory] // // [InlineData("username", "password", null)] // // [InlineData("username", "password", "")] // // [InlineData("username", null, "device")] // // [InlineData("username", "", "device")] // // [InlineData(null, "password", "device")] // // [InlineData("", "password", "device")] // // public async void WhenCombinationOfUsernameAndPasswordAndDeviceAreNotSuppliedTogether_ThrowBadRequestException(string username, string password, string device) // // { // // var query = new GetEmployeeClaimsQuery() { Username = username, Password = password, Device = device }; // // // // await Assert.ThrowsAsync<BadRequestException>(async () => await handler.Handle(query, default)); // // } // // #endregion // // // // #region Security Username And Password // // [Theory] // // [InlineData("admin", "admin", true)] // // [InlineData("admin", "admin1", false)] // // [InlineData("admin1", "admin", false)] // // public async void UsernameAndPasswordTheoryTests(string username, string password, bool isCorrect) // // { // // var query = new GetEmployeeClaimsQuery() { Username = username, Password = password, Device = "device" }; // // // // if (isCorrect) // // { // // var claims = await handler.Handle(query, default); // // Assert.Single(claims); // // } // // else // // { // // await Assert.ThrowsAsync<NotFoundException>(async () => await handler.Handle(query, default)); // // } // // } // // // // [Fact] // // public async void WhenCorrectUsernameAndPasswordButUserHasLockArgument_ThrowNotAllowedException() // // { // // var employee = await dbContext.Employees.FirstOrDefaultAsync(x => x.Username == "admin"); // // employee.AccountLockArgument = "locked"; // // await dbContext.SaveChangesAsync(default); // // // // var query = new GetEmployeeClaimsQuery() { Username = "admin", Password = "admin", Device = "device"}; // // // // await Assert.ThrowsAsync<NotAllowedException>(async () => await handler.Handle(query, default)); // // } // // #endregion // // #region Query Device // [Fact] // public async void WhenDeviceIsSuppliedButTokenDoNotCarryValidSessionId_ThrowNotFoundException() // { // var query = new GetEmployeeClaimsQuery() { Device = "device"}; // // await Assert.ThrowsAsync<NotAllowedException>(async () => await handler.Handle(query, default)); // } // // [Theory] // [InlineData(true, true, true, false)] // [InlineData(true, true, false, true)] // [InlineData(true, false, true, true)] // [InlineData(false, true, true, true)] // public async void WhenDeviceOnlyIsSuppliedTheoryTests(bool isSessionActive, bool isSameDevice, bool isEmployeeNotLocked, bool throwNotAllowedException) // { // var device = "device"; // var query = new GetEmployeeClaimsQuery() { Device = device }; // var employee = await dbContext.Employees.FirstOrDefaultAsync(x => x.Username == "admin"); // // var session = new EmployeeSessionDbo() { DeviceId = isSameDevice ? device : device + "other", EmployeeId = employee.Id }; // session.TerminationTs = isSessionActive ? null : DateTime.UtcNow; // await dbContext.EmployeeSessions.AddAsync(session); // await dbContext.SaveChangesAsync(default); // // userInfoMock.Setup(x => x.SessionId).Returns(session.Id); // // if (isEmployeeNotLocked == false) // { // employee.AccountLockArgument = "locked"; // await dbContext.SaveChangesAsync(default); // } // // var handler = new GetEmployeeClaimsHandler(dbContext, userInfoMock.Object, sharedValues, mediatRMock.Object); // // if (throwNotAllowedException) // { // await Assert.ThrowsAsync<NotAllowedException>(async () => await handler.Handle(query, default)); // } // else // { // var claims = await handler.Handle(query, default); // Assert.True(claims.Count() > 1, "At least session claim with another stored clam must be returned."); // } // } // #endregion // // #region Query EmployeeId // [Fact] // public async void WhenInvalidEmployeeIdIsSupplied_ThrowNotFoundException() // { // // var query = new GetEmployeeClaimsQuery() { EmployeeId = Guid.NewGuid()}; // // var claim = new Claim(sharedValues.GetClaimType(ClaimTypeEnum.HumanResources), sharedValues.GetClaimTag(ClaimTagEnum.Read)); // // userInfoMock.Setup(x => x.Claims).Returns(new List<Claim>() { claim }); // // // // var handler = new GetEmployeeClaimsHandler(dbContext, userInfoMock.Object, sharedValues, mediatRMock.Object); // // // // await Assert.ThrowsAsync<NotFoundException>(async () => await handler.Handle(query, default)); // } // // [Theory] // [InlineData(true, true, false)] // [InlineData(true, false, true)] // [InlineData(false, true, true)] // public async void WhenEmployeeIdIsSuppliedTheories(bool hasCorrectClaimType, bool hasCorrectClaimTag, bool throwNotFoundException) // { // // var employee = await dbContext.Employees.FirstOrDefaultAsync(x => x.Username == "admin"); // // var query = new GetEmployeeClaimsQuery() { EmployeeId = employee.Id }; // // // // string type = hasCorrectClaimType ? sharedValues.GetClaimType(ClaimTypeEnum.HumanResources) : sharedValues.GetClaimType(ClaimTypeEnum.Territory); // // string tag = hasCorrectClaimTag ? sharedValues.GetClaimTag(ClaimTagEnum.Read) : sharedValues.GetClaimTag(ClaimTagEnum.Senior); // // var claim = new Claim(type, tag); // // userInfoMock.Setup(x => x.Claims).Returns(new List<Claim>() { claim }); // // // // var handler = new GetEmployeeClaimsHandler(dbContext, userInfoMock.Object, sharedValues, mediatRMock.Object); // // // // if (throwNotFoundException) // // { // // await Assert.ThrowsAsync<NotAllowedException>(async () => await handler.Handle(query, default)); // // } // // else // // { // // var list = await handler.Handle(query, default); // // // // Assert.NotEmpty(list); // // } // } // #endregion // } // }
46.974026
173
0.583817
[ "MIT" ]
sayedmhussein/ControlSystem
src/Backend/Application.Test/Garbag/HumanResources/V1/Queries/GetEmployeeClaimsV1HandlerTesters.cs
10,853
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Timing; using osu.Game.Beatmaps; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Scoring; using osu.Game.Screens.Play; namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate { /// <summary> /// Provides an area for and manages the hierarchy of a spectated player within a <see cref="MultiSpectatorScreen"/>. /// </summary> public class PlayerArea : CompositeDrawable { /// <summary> /// Raised after <see cref="Player.StartGameplay"/> is called on <see cref="Player"/>. /// </summary> public event Action OnGameplayStarted; /// <summary> /// Whether a <see cref="Player"/> is loaded in the area. /// </summary> public bool PlayerLoaded => (stack?.CurrentScreen as Player)?.IsLoaded == true; /// <summary> /// The user id this <see cref="PlayerArea"/> corresponds to. /// </summary> public readonly int UserId; /// <summary> /// The <see cref="ISpectatorPlayerClock"/> used to control the gameplay running state of a loaded <see cref="Player"/>. /// </summary> [NotNull] public readonly ISpectatorPlayerClock GameplayClock = new CatchUpSpectatorPlayerClock(); /// <summary> /// The currently-loaded score. /// </summary> [CanBeNull] public Score Score { get; private set; } [Resolved] private BeatmapManager beatmapManager { get; set; } private readonly BindableDouble volumeAdjustment = new BindableDouble(); private readonly Container gameplayContent; private readonly LoadingLayer loadingLayer; private OsuScreenStack stack; public PlayerArea(int userId, IFrameBasedClock masterClock) { UserId = userId; RelativeSizeAxes = Axes.Both; Masking = true; AudioContainer audioContainer; InternalChildren = new Drawable[] { audioContainer = new AudioContainer { RelativeSizeAxes = Axes.Both, Child = gameplayContent = new DrawSizePreservingFillContainer { RelativeSizeAxes = Axes.Both }, }, loadingLayer = new LoadingLayer(true) { State = { Value = Visibility.Visible } } }; audioContainer.AddAdjustment(AdjustableProperty.Volume, volumeAdjustment); GameplayClock.Source = masterClock; } public void LoadScore([NotNull] Score score) { if (Score != null) throw new InvalidOperationException($"Cannot load a new score on a {nameof(PlayerArea)} that has an existing score."); Score = score; gameplayContent.Child = new PlayerIsolationContainer(beatmapManager.GetWorkingBeatmap(Score.ScoreInfo.BeatmapInfo), Score.ScoreInfo.Ruleset, Score.ScoreInfo.Mods) { RelativeSizeAxes = Axes.Both, Child = stack = new OsuScreenStack { Name = nameof(PlayerArea), } }; stack.Push(new MultiSpectatorPlayerLoader(Score, () => { var player = new MultiSpectatorPlayer(Score, GameplayClock); player.OnGameplayStarted += () => OnGameplayStarted?.Invoke(); return player; })); loadingLayer.Hide(); } private bool mute = true; public bool Mute { get => mute; set { mute = value; volumeAdjustment.Value = value ? 0 : 1; } } // Player interferes with global input, so disable input for now. public override bool PropagatePositionalInputSubTree => false; public override bool PropagateNonPositionalInputSubTree => false; /// <summary> /// Isolates each player instance from the game-wide ruleset/beatmap/mods (to allow for different players having different settings). /// </summary> private class PlayerIsolationContainer : Container { [Cached] private readonly Bindable<RulesetInfo> ruleset = new Bindable<RulesetInfo>(); [Cached] private readonly Bindable<WorkingBeatmap> beatmap = new Bindable<WorkingBeatmap>(); [Cached] private readonly Bindable<IReadOnlyList<Mod>> mods = new Bindable<IReadOnlyList<Mod>>(); public PlayerIsolationContainer(WorkingBeatmap beatmap, RulesetInfo ruleset, IReadOnlyList<Mod> mods) { this.beatmap.Value = beatmap; this.ruleset.Value = ruleset; this.mods.Value = mods; } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { var dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); dependencies.CacheAs(ruleset.BeginLease(false)); dependencies.CacheAs(beatmap.BeginLease(false)); dependencies.CacheAs(mods.BeginLease(false)); return dependencies; } } } }
37.194969
175
0.593338
[ "MIT" ]
20PercentRendered/osu
osu.Game/Screens/OnlinePlay/Multiplayer/Spectate/PlayerArea.cs
5,756
C#
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using OpenData.Domain.Models; namespace OpenData.Resources { public class NewDataSourceResource { [Required] public Guid MetadataUuid { get; set; } [Required] [MaxLength(2048)] public string Url { get; set; } [Required] public string Description { get; set; } [Required] public string DataFormatMimeType { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } } }
22.925926
54
0.638126
[ "Apache-2.0" ]
OpenDataNTNU/OpenData
backend/Resources/NewDataSourceResource.cs
621
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace addressbook_wt.tests { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { double total = 1500; bool vipclient = false; if (total > 1000 && vipclient) { total = total * 0.9; System.Console.Out.Write("Скидка 10%, общая сумма " + total); } else { System.Console.Out.Write("Скидки нет, общая сумма " + total); } } } }
21.892857
77
0.49429
[ "Apache-2.0" ]
dmkad/cs_train
addressbook_wt/addressbook_wt/tests/UnitTest1.cs
650
C#
using harbor.Shell; namespace harbor.Commands { public class BaseCommand { protected Docker _docker { get; set; } public BaseCommand() { this._docker = new Docker(); } } }
16.928571
54
0.531646
[ "MIT" ]
andersmandersen/harbor
Commands/BaseCommand.cs
237
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace bucketizer_proto { interface IRules { string[] Cards { get; } int[] CardCounts { get; } double Equity(int[] range1, int[] range2); } }
14.217391
50
0.519878
[ "MIT" ]
ivan-alles/poker-acpc
proto/bucketizer/IRules.cs
329
C#
using System.Collections; using Handelabra.Sentinels.Engine.Controller; using Handelabra.Sentinels.Engine.Model; namespace Cauldron.TangoOne { public class GhostReactorCardController : TangoOneBaseCardController { //============================================================== // {TangoOne} is immune to psychic damage. // Power: Draw a card. Increase the next damage dealt by {TangoOne} by 2. //============================================================== public static readonly string Identifier = "GhostReactor"; private const int DamageIncrease = 2; public GhostReactorCardController(Card card, TurnTakerController turnTakerController) : base(card, turnTakerController) { } public override void AddTriggers() { base.AddImmuneToDamageTrigger((DealDamageAction action) => action.DamageType == DamageType.Psychic && action.Target == base.CharacterCard); } public override IEnumerator UsePower(int index = 0) { // Draw a card IEnumerator drawCardRoutine = base.DrawCard(this.HeroTurnTaker); if (base.UseUnityCoroutines) { yield return base.GameController.StartCoroutine(drawCardRoutine); } else { base.GameController.ExhaustCoroutine(drawCardRoutine); } // Increase the next damage dealt by {TangoOne} by 2 int powerNumeral = GetPowerNumeral(0, DamageIncrease); var effect = new IncreaseDamageStatusEffect(powerNumeral); effect.SourceCriteria.IsSpecificCard = base.CharacterCard; effect.CardSource = Card; effect.Identifier = IncreaseDamageIdentifier; effect.NumberOfUses = 1; IEnumerator increaseDamageRoutine = base.AddStatusEffect(effect, true); if (base.UseUnityCoroutines) { yield return base.GameController.StartCoroutine(increaseDamageRoutine); } else { base.GameController.ExhaustCoroutine(increaseDamageRoutine); } } } }
36.916667
151
0.589616
[ "MIT" ]
SotMSteamMods/CauldronMods
CauldronMods/Controller/Heroes/TangoOne/Cards/GhostReactorCardController.cs
2,217
C#
using System.IO; using System.IO.Compression; using MCLib.NBT.Tags; using IOFile = System.IO.File; namespace MCLib.NBT { public class File { #region Fields /// <summary> /// Path of the file /// </summary> public string Path { get; set; } /// <summary> /// Root tag for the file /// </summary> public Compound Root { get; private set; } #endregion #region Constructor public File(string path) { Path = path; } #endregion #region Public methods public void Load() { using(var file = IOFile.OpenRead(Path)) { Load(file); } } /// <summary> /// Load from given stream /// </summary> /// <param name="stream">Stream to load from</param> public void Load(Stream stream) { using (var decStream = new GZipStream(stream, CompressionMode.Decompress)) { using (var memStream = new MemoryStream((int)stream.Length)) { var buffer = new byte[4096]; int bytesRead; while ((bytesRead = decStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } LoadInternal(memStream); } } } public void Save() { using (var file = IOFile.OpenWrite(Path)) { Save(file); } } /// <summary> /// Saves into stream /// </summary> /// <param name="stream">stream to save into</param> public void Save(Stream stream) { using (var comStream = new GZipStream(stream, CompressionMode.Compress)) { SaveInternal(comStream); } } #endregion #region Private methods private void LoadInternal(Stream stream) { stream.Seek(0, SeekOrigin.Begin); var bstream = new BinaryReaderMC(stream); if ((Enums.Tag) bstream.ReadByte() != Enums.Tag.Compound) return; Root = new Compound(); Root.Read(bstream); } private void SaveInternal(Stream stream) { var bstream = new BinaryWriterMC(stream); bstream.Write((byte)Enums.Tag.Compound); Root.Write(bstream); } #endregion } }
23.362832
87
0.472727
[ "Unlicense" ]
pollyzoid/mclib
NBT/File.cs
2,642
C#
using Baraka.Models; using Baraka.Models.Quran; using Baraka.Utils.MVVM.ViewModel; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Baraka.ViewModels.UserControls.Player.Pages.Design { public class SuraTabDesignViewModel : NotifiableBase { public ObservableCollection<SuraModel> SuraList { get { return new ObservableCollection<SuraModel>() { new SuraModel(1, 7, "Al-Fatiha", "Prologue", SuraRevelationType.M), new SuraModel(2, 286, "Al-Baqarah", "La vache", SuraRevelationType.H), new SuraModel(3, 200, "Al-Imran", "La famille d'Imran", SuraRevelationType.H), new SuraModel(4, 176, "An-Nisa", "Les femmes", SuraRevelationType.H), new SuraModel(5, 120, "Al-Ma'ida", "La table servie", SuraRevelationType.H), new SuraModel(6, 165, "Al-Anam", "Les bestiaux", SuraRevelationType.M), new SuraModel(7, 206, "Al-Araf", "Le purgatoire", SuraRevelationType.M), new SuraModel(8, 75, "Al-Anfal", "Le butin", SuraRevelationType.H), new SuraModel(9, 129, "At-Tawbah", "Le repentir", SuraRevelationType.H), new SuraModel(10, 109, "Yunus", "Jonas", SuraRevelationType.M), new SuraModel(11, 123, "Hud", "Hud", SuraRevelationType.M), new SuraModel(12, 111, "Yusuf", "Joseph", SuraRevelationType.M), new SuraModel(13, 43, "Ar-Ra'd", "Le tonnerre", SuraRevelationType.M), new SuraModel(14, 52, "Ibrahim", "Abraham", SuraRevelationType.M), new SuraModel(15, 99, "Al-Hijr", "La vallée des pierres", SuraRevelationType.M), new SuraModel(16, 128, "An-Nahl", "Les abeilles", SuraRevelationType.M), new SuraModel(17, 111, "Al-Isra", "Le voyage nocturne", SuraRevelationType.M), }; } } public SuraTabDesignViewModel() { } } }
54.583333
114
0.488931
[ "BSD-3-Clause" ]
Jomtek/Baraka
Baraka/ViewModels/UserControls/Player/Pages/Design/SuraTabDesignViewModel.cs
2,623
C#
using System; using System.IO; using System.Runtime.InteropServices; namespace SkiaSharp { // TODO: `MakeCrossContextFromEncoded` // TODO: `MakeFromYUVTexturesCopy` and `MakeFromNV12TexturesCopy` // TODO: `FromPicture` with bit depth and color space // TODO: `IsValid` // TODO: `GetTextureHandle` // TODO: `ToTextureImage` // TODO: `MakeColorSpace` public class SKImage : SKObject { protected override void Dispose (bool disposing) { if (Handle != IntPtr.Zero && OwnsHandle) { SkiaApi.sk_image_unref (Handle); } base.Dispose (disposing); } [Preserve] internal SKImage (IntPtr x, bool owns) : base (x, owns) { } // create brand new image public static SKImage Create (SKImageInfo info) { var pixels = Marshal.AllocCoTaskMem (info.BytesSize); using (var pixmap = new SKPixmap (info, pixels)) { // don't use the managed version as that is just extra overhead which isn't necessary return GetObject<SKImage> (SkiaApi.sk_image_new_raster (pixmap.Handle, DelegateProxies.SKImageRasterReleaseDelegateProxyForCoTaskMem, IntPtr.Zero)); } } // create a new image from a copy of pixel data public static SKImage FromPixelCopy (SKImageInfo info, SKStream pixels) => FromPixelCopy (info, pixels, info.RowBytes); public static SKImage FromPixelCopy (SKImageInfo info, SKStream pixels, int rowBytes) { if (pixels == null) throw new ArgumentNullException (nameof (pixels)); using (var data = SKData.Create (pixels)) { return FromPixelData (info, data, rowBytes); } } public static SKImage FromPixelCopy (SKImageInfo info, Stream pixels) => FromPixelCopy (info, pixels, info.RowBytes); public static SKImage FromPixelCopy (SKImageInfo info, Stream pixels, int rowBytes) { if (pixels == null) throw new ArgumentNullException (nameof (pixels)); using (var data = SKData.Create (pixels)) { return FromPixelData (info, data, rowBytes); } } public static SKImage FromPixelCopy (SKImageInfo info, byte[] pixels) => FromPixelCopy (info, pixels, info.RowBytes); public static SKImage FromPixelCopy (SKImageInfo info, byte[] pixels, int rowBytes) { if (pixels == null) throw new ArgumentNullException (nameof (pixels)); using (var data = SKData.CreateCopy (pixels)) { return FromPixelData (info, data, rowBytes); } } public static SKImage FromPixelCopy (SKImageInfo info, IntPtr pixels) => FromPixelCopy (info, pixels, info.RowBytes); public static SKImage FromPixelCopy (SKImageInfo info, IntPtr pixels, int rowBytes) { if (pixels == IntPtr.Zero) throw new ArgumentNullException (nameof (pixels)); var nInfo = SKImageInfoNative.FromManaged (ref info); return GetObject<SKImage> (SkiaApi.sk_image_new_raster_copy (ref nInfo, pixels, (IntPtr)rowBytes)); } [Obsolete ("The Index8 color type and color table is no longer supported. Use FromPixelCopy(SKImageInfo, IntPtr, int) instead.")] public static SKImage FromPixelCopy (SKImageInfo info, IntPtr pixels, int rowBytes, SKColorTable ctable) => FromPixelCopy (info, pixels, rowBytes); public static SKImage FromPixelCopy (SKPixmap pixmap) { if (pixmap == null) throw new ArgumentNullException (nameof (pixmap)); return GetObject<SKImage> (SkiaApi.sk_image_new_raster_copy_with_pixmap (pixmap.Handle)); } public static SKImage FromPixelCopy (SKImageInfo info, ReadOnlySpan<byte> pixels) => FromPixelCopy (info, pixels, info.RowBytes); public static SKImage FromPixelCopy (SKImageInfo info, ReadOnlySpan<byte> pixels, int rowBytes) { if (pixels == null) throw new ArgumentNullException (nameof (pixels)); using (var data = SKData.CreateCopy (pixels)) { return FromPixelData (info, data, rowBytes); } } // create a new image around existing pixel data public static SKImage FromPixelData (SKImageInfo info, SKData data, int rowBytes) { if (data == null) throw new ArgumentNullException (nameof (data)); var cinfo = SKImageInfoNative.FromManaged (ref info); return GetObject<SKImage> (SkiaApi.sk_image_new_raster_data (ref cinfo, data.Handle, (IntPtr)rowBytes)); } public static SKImage FromPixels (SKImageInfo info, SKData data, int rowBytes) { if (data == null) throw new ArgumentNullException (nameof (data)); var cinfo = SKImageInfoNative.FromManaged (ref info); return GetObject<SKImage> (SkiaApi.sk_image_new_raster_data (ref cinfo, data.Handle, (IntPtr)rowBytes)); } public static SKImage FromPixels (SKImageInfo info, IntPtr pixels) { using (var pixmap = new SKPixmap (info, pixels, info.RowBytes)) { return FromPixels (pixmap, null, null); } } public static SKImage FromPixels (SKImageInfo info, IntPtr pixels, int rowBytes) { using (var pixmap = new SKPixmap (info, pixels, rowBytes)) { return FromPixels (pixmap, null, null); } } public static SKImage FromPixels (SKPixmap pixmap) { return FromPixels (pixmap, null, null); } public static SKImage FromPixels (SKPixmap pixmap, SKImageRasterReleaseDelegate releaseProc) { return FromPixels (pixmap, releaseProc, null); } public static SKImage FromPixels (SKPixmap pixmap, SKImageRasterReleaseDelegate releaseProc, object releaseContext) { if (pixmap == null) throw new ArgumentNullException (nameof (pixmap)); var del = releaseProc != null && releaseContext != null ? new SKImageRasterReleaseDelegate ((addr, _) => releaseProc (addr, releaseContext)) : releaseProc; var proxy = DelegateProxies.Create (del, DelegateProxies.SKImageRasterReleaseDelegateProxy, out _, out var ctx); return GetObject<SKImage> (SkiaApi.sk_image_new_raster (pixmap.Handle, proxy, ctx)); } // create a new image from encoded data public static SKImage FromEncodedData (SKData data, SKRectI subset) { if (data == null) throw new ArgumentNullException (nameof (data)); var handle = SkiaApi.sk_image_new_from_encoded (data.Handle, ref subset); return GetObject<SKImage> (handle); } public static SKImage FromEncodedData (SKData data) { if (data == null) throw new ArgumentNullException (nameof (data)); var handle = SkiaApi.sk_image_new_from_encoded (data.Handle, IntPtr.Zero); return GetObject<SKImage> (handle); } public static SKImage FromEncodedData (ReadOnlySpan<byte> data) { if (data == null) throw new ArgumentNullException (nameof (data)); if (data.Length == 0) throw new ArgumentException ("The data buffer was empty."); unsafe { fixed (byte* b = data) { using (var skdata = SKData.Create ((IntPtr)b, data.Length)) { return FromEncodedData (skdata); } } } } public static SKImage FromEncodedData (byte[] data) { if (data == null) throw new ArgumentNullException (nameof (data)); if (data.Length == 0) throw new ArgumentException ("The data buffer was empty."); unsafe { fixed (byte* b = data) { using (var skdata = SKData.Create ((IntPtr)b, data.Length)) { return FromEncodedData (skdata); } } } } public static SKImage FromEncodedData (SKStream data) { if (data == null) throw new ArgumentNullException (nameof (data)); using (var codec = SKCodec.Create (data)) { if (codec == null) return null; var bitmap = SKBitmap.Decode (codec, codec.Info); if (bitmap == null) return null; bitmap.SetImmutable (); return FromPixels (bitmap.PeekPixels (), delegate { bitmap.Dispose (); bitmap = null; }); } } public static SKImage FromEncodedData (Stream data) { if (data == null) throw new ArgumentNullException (nameof (data)); using (var codec = SKCodec.Create (data)) { if (codec == null) return null; var bitmap = SKBitmap.Decode (codec, codec.Info); if (bitmap == null) return null; bitmap.SetImmutable (); return FromPixels (bitmap.PeekPixels (), delegate { bitmap.Dispose (); bitmap = null; }); } } public static SKImage FromEncodedData (string filename) { if (filename == null) throw new ArgumentNullException (nameof (filename)); using (var codec = SKCodec.Create (filename)) { if (codec == null) return null; var bitmap = SKBitmap.Decode (codec, codec.Info); if (bitmap == null) return null; bitmap.SetImmutable (); return FromPixels (bitmap.PeekPixels (), delegate { bitmap.Dispose (); bitmap = null; }); } } // create a new image from a bitmap public static SKImage FromBitmap (SKBitmap bitmap) { if (bitmap == null) throw new ArgumentNullException (nameof (bitmap)); var handle = SkiaApi.sk_image_new_from_bitmap (bitmap.Handle); return GetObject<SKImage> (handle); } // create a new image from a GPU texture [Obsolete ("Use FromTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType) instead.")] public static SKImage FromTexture (GRContext context, GRBackendTextureDesc desc) { return FromTexture (context, desc, SKAlphaType.Premul, null, null); } [Obsolete ("Use FromTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType, SKAlphaType) instead.")] public static SKImage FromTexture (GRContext context, GRBackendTextureDesc desc, SKAlphaType alpha) { return FromTexture (context, desc, alpha, null, null); } [Obsolete ("Use FromTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType, SKAlphaType, SKColorSpace, SKImageTextureReleaseDelegate) instead.")] public static SKImage FromTexture (GRContext context, GRBackendTextureDesc desc, SKAlphaType alpha, SKImageTextureReleaseDelegate releaseProc) { return FromTexture (context, desc, alpha, releaseProc, null); } [Obsolete ("Use FromTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType, SKAlphaType, SKColorSpace, SKImageTextureReleaseDelegate, object) instead.")] public static SKImage FromTexture (GRContext context, GRBackendTextureDesc desc, SKAlphaType alpha, SKImageTextureReleaseDelegate releaseProc, object releaseContext) { if (context == null) throw new ArgumentNullException (nameof (context)); var texture = new GRBackendTexture (desc); return FromTexture (context, texture, desc.Origin, desc.Config.ToColorType (), alpha, null, releaseProc, releaseContext); } [Obsolete ("Use FromTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType) instead.")] public static SKImage FromTexture (GRContext context, GRGlBackendTextureDesc desc) { return FromTexture (context, desc, SKAlphaType.Premul, null, null); } [Obsolete ("Use FromTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType, SKAlphaType) instead.")] public static SKImage FromTexture (GRContext context, GRGlBackendTextureDesc desc, SKAlphaType alpha) { return FromTexture (context, desc, alpha, null, null); } [Obsolete ("Use FromTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType, SKAlphaType, SKColorSpace, SKImageTextureReleaseDelegate) instead.")] public static SKImage FromTexture (GRContext context, GRGlBackendTextureDesc desc, SKAlphaType alpha, SKImageTextureReleaseDelegate releaseProc) { return FromTexture (context, desc, alpha, releaseProc, null); } [Obsolete ("Use FromTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType, SKAlphaType, SKColorSpace, SKImageTextureReleaseDelegate, object) instead.")] public static SKImage FromTexture (GRContext context, GRGlBackendTextureDesc desc, SKAlphaType alpha, SKImageTextureReleaseDelegate releaseProc, object releaseContext) { var texture = new GRBackendTexture (desc); return FromTexture (context, texture, desc.Origin, desc.Config.ToColorType (), alpha, null, releaseProc, releaseContext); } public static SKImage FromTexture (GRContext context, GRBackendTexture texture, SKColorType colorType) { return FromTexture (context, texture, GRSurfaceOrigin.BottomLeft, colorType, SKAlphaType.Premul, null, null, null); } public static SKImage FromTexture (GRContext context, GRBackendTexture texture, GRSurfaceOrigin origin, SKColorType colorType) { return FromTexture (context, texture, origin, colorType, SKAlphaType.Premul, null, null, null); } public static SKImage FromTexture (GRContext context, GRBackendTexture texture, GRSurfaceOrigin origin, SKColorType colorType, SKAlphaType alpha) { return FromTexture (context, texture, origin, colorType, alpha, null, null, null); } public static SKImage FromTexture (GRContext context, GRBackendTexture texture, GRSurfaceOrigin origin, SKColorType colorType, SKAlphaType alpha, SKColorSpace colorspace) { return FromTexture (context, texture, origin, colorType, alpha, colorspace, null, null); } public static SKImage FromTexture (GRContext context, GRBackendTexture texture, GRSurfaceOrigin origin, SKColorType colorType, SKAlphaType alpha, SKColorSpace colorspace, SKImageTextureReleaseDelegate releaseProc) { return FromTexture (context, texture, origin, colorType, alpha, colorspace, releaseProc, null); } public static SKImage FromTexture (GRContext context, GRBackendTexture texture, GRSurfaceOrigin origin, SKColorType colorType, SKAlphaType alpha, SKColorSpace colorspace, SKImageTextureReleaseDelegate releaseProc, object releaseContext) { if (context == null) throw new ArgumentNullException (nameof (context)); if (texture == null) throw new ArgumentNullException (nameof (texture)); var cs = colorspace == null ? IntPtr.Zero : colorspace.Handle; var del = releaseProc != null && releaseContext != null ? new SKImageTextureReleaseDelegate ((_) => releaseProc (releaseContext)) : releaseProc; var proxy = DelegateProxies.Create (del, DelegateProxies.SKImageTextureReleaseDelegateProxy, out _, out var ctx); return GetObject<SKImage> (SkiaApi.sk_image_new_from_texture (context.Handle, texture.Handle, origin, colorType, alpha, cs, proxy, ctx)); } [Obsolete ("Use FromAdoptedTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType) instead.")] public static SKImage FromAdoptedTexture (GRContext context, GRBackendTextureDesc desc) { return FromAdoptedTexture (context, desc, SKAlphaType.Premul); } [Obsolete ("Use FromAdoptedTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType, SKAlphaType) instead.")] public static SKImage FromAdoptedTexture (GRContext context, GRBackendTextureDesc desc, SKAlphaType alpha) { var texture = new GRBackendTexture (desc); return FromAdoptedTexture (context, texture, desc.Origin, desc.Config.ToColorType (), alpha, null); } [Obsolete ("Use FromAdoptedTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType) instead.")] public static SKImage FromAdoptedTexture (GRContext context, GRGlBackendTextureDesc desc) { return FromAdoptedTexture (context, desc, SKAlphaType.Premul); } [Obsolete ("Use FromAdoptedTexture(GRContext, GRBackendTexture, GRSurfaceOrigin, SKColorType, SKAlphaType) instead.")] public static SKImage FromAdoptedTexture (GRContext context, GRGlBackendTextureDesc desc, SKAlphaType alpha) { var texture = new GRBackendTexture (desc); return FromAdoptedTexture (context, texture, desc.Origin, desc.Config.ToColorType (), alpha, null); } public static SKImage FromAdoptedTexture (GRContext context, GRBackendTexture texture, SKColorType colorType) { return FromAdoptedTexture (context, texture, GRSurfaceOrigin.BottomLeft, colorType, SKAlphaType.Premul, null); } public static SKImage FromAdoptedTexture (GRContext context, GRBackendTexture texture, GRSurfaceOrigin origin, SKColorType colorType) { return FromAdoptedTexture (context, texture, origin, colorType, SKAlphaType.Premul, null); } public static SKImage FromAdoptedTexture (GRContext context, GRBackendTexture texture, GRSurfaceOrigin origin, SKColorType colorType, SKAlphaType alpha) { return FromAdoptedTexture (context, texture, origin, colorType, alpha, null); } public static SKImage FromAdoptedTexture (GRContext context, GRBackendTexture texture, GRSurfaceOrigin origin, SKColorType colorType, SKAlphaType alpha, SKColorSpace colorspace) { if (context == null) throw new ArgumentNullException (nameof (context)); if (texture == null) throw new ArgumentNullException (nameof (texture)); var cs = colorspace == null ? IntPtr.Zero : colorspace.Handle; return GetObject<SKImage> (SkiaApi.sk_image_new_from_adopted_texture (context.Handle, texture.Handle, origin, colorType, alpha, cs)); } // create a new image from a picture public static SKImage FromPicture (SKPicture picture, SKSizeI dimensions) { return FromPicture (picture, dimensions, null); } public static SKImage FromPicture (SKPicture picture, SKSizeI dimensions, SKMatrix matrix) { return FromPicture (picture, dimensions, matrix, null); } public static SKImage FromPicture (SKPicture picture, SKSizeI dimensions, SKPaint paint) { if (picture == null) throw new ArgumentNullException (nameof (picture)); var p = (paint == null ? IntPtr.Zero : paint.Handle); return GetObject<SKImage> (SkiaApi.sk_image_new_from_picture (picture.Handle, ref dimensions, IntPtr.Zero, p)); } public static SKImage FromPicture (SKPicture picture, SKSizeI dimensions, SKMatrix matrix, SKPaint paint) { if (picture == null) throw new ArgumentNullException (nameof (picture)); var p = (paint == null ? IntPtr.Zero : paint.Handle); return GetObject<SKImage> (SkiaApi.sk_image_new_from_picture (picture.Handle, ref dimensions, ref matrix, p)); } public SKData Encode () { return GetObject<SKData> (SkiaApi.sk_image_encode (Handle)); } [Obsolete] public SKData Encode (SKPixelSerializer serializer) { if (serializer == null) throw new ArgumentNullException (nameof (serializer)); // try old data var encoded = EncodedData; if (encoded != null) { if (serializer.UseEncodedData (encoded.Data, (ulong)encoded.Size)) { return encoded; } else { encoded.Dispose (); encoded = null; } } // get new data (raster) if (!IsTextureBacked) { using (var pixmap = PeekPixels ()) { return serializer.Encode (pixmap); } } // get new data (texture / gpu) // this involves a copy from gpu to cpu first if (IsTextureBacked) { var info = new SKImageInfo (Width, Height, ColorType, AlphaType, ColorSpace); using (var temp = new SKBitmap (info)) using (var pixmap = temp.PeekPixels ()) { if (pixmap != null && ReadPixels (pixmap, 0, 0)) { return serializer.Encode (pixmap); } } } // some error return null; } public SKData Encode (SKEncodedImageFormat format, int quality) { return GetObject<SKData> (SkiaApi.sk_image_encode_specific (Handle, format, quality)); } public int Width => SkiaApi.sk_image_get_width (Handle); public int Height => SkiaApi.sk_image_get_height (Handle); public uint UniqueId => SkiaApi.sk_image_get_unique_id (Handle); public SKAlphaType AlphaType => SkiaApi.sk_image_get_alpha_type (Handle); public SKColorType ColorType => SkiaApi.sk_image_get_color_type (Handle); public SKColorSpace ColorSpace => GetObject<SKColorSpace> (SkiaApi.sk_image_get_colorspace (Handle)); public bool IsAlphaOnly => SkiaApi.sk_image_is_alpha_only (Handle); public SKData EncodedData => GetObject<SKData> (SkiaApi.sk_image_ref_encoded (Handle)); public SKShader ToShader (SKShaderTileMode tileX, SKShaderTileMode tileY) { return GetObject<SKShader> (SkiaApi.sk_image_make_shader (Handle, tileX, tileY, IntPtr.Zero)); } public SKShader ToShader (SKShaderTileMode tileX, SKShaderTileMode tileY, SKMatrix localMatrix) { return GetObject<SKShader> (SkiaApi.sk_image_make_shader (Handle, tileX, tileY, ref localMatrix)); } public bool PeekPixels (SKPixmap pixmap) { if (pixmap == null) throw new ArgumentNullException (nameof (pixmap)); return SkiaApi.sk_image_peek_pixels (Handle, pixmap.Handle); } public SKPixmap PeekPixels () { var pixmap = new SKPixmap (); if (!PeekPixels (pixmap)) { pixmap.Dispose (); pixmap = null; } return pixmap; } public bool IsTextureBacked => SkiaApi.sk_image_is_texture_backed (Handle); public bool IsLazyGenerated => SkiaApi.sk_image_is_lazy_generated (Handle); public bool ReadPixels (SKImageInfo dstInfo, IntPtr dstPixels, int dstRowBytes, int srcX, int srcY) { return ReadPixels (dstInfo, dstPixels, dstRowBytes, srcX, srcY, SKImageCachingHint.Allow); } public bool ReadPixels (SKImageInfo dstInfo, IntPtr dstPixels, int dstRowBytes, int srcX, int srcY, SKImageCachingHint cachingHint) { var cinfo = SKImageInfoNative.FromManaged (ref dstInfo); return SkiaApi.sk_image_read_pixels (Handle, ref cinfo, dstPixels, (IntPtr)dstRowBytes, srcX, srcY, cachingHint); } public bool ReadPixels (SKPixmap pixmap, int srcX, int srcY) { return ReadPixels (pixmap, srcX, srcY, SKImageCachingHint.Allow); } public bool ReadPixels (SKPixmap pixmap, int srcX, int srcY, SKImageCachingHint cachingHint) { if (pixmap == null) throw new ArgumentNullException (nameof (pixmap)); return SkiaApi.sk_image_read_pixels_into_pixmap (Handle, pixmap.Handle, srcX, srcY, cachingHint); } public bool ScalePixels (SKPixmap dst, SKFilterQuality quality) { return ScalePixels (dst, quality, SKImageCachingHint.Allow); } public bool ScalePixels (SKPixmap dst, SKFilterQuality quality, SKImageCachingHint cachingHint) { if (dst == null) throw new ArgumentNullException (nameof (dst)); return SkiaApi.sk_image_scale_pixels (Handle, dst.Handle, quality, cachingHint); } public SKImage Subset (SKRectI subset) { return GetObject<SKImage> (SkiaApi.sk_image_make_subset (Handle, ref subset)); } public SKImage ToRasterImage () { return GetObject<SKImage> (SkiaApi.sk_image_make_non_texture_image (Handle)); } public SKImage ApplyImageFilter (SKImageFilter filter, SKRectI subset, SKRectI clipBounds, out SKRectI outSubset, out SKPoint outOffset) { if (filter == null) throw new ArgumentNullException (nameof (filter)); return GetObject<SKImage> (SkiaApi.sk_image_make_with_filter (Handle, filter.Handle, ref subset, ref clipBounds, out outSubset, out outOffset)); } } }
36.362013
238
0.733961
[ "MIT" ]
CollegiumXR/SkiaSharp-Unity-Integration
Assets/SkiaSharpUnity/Scripts/SkiaSharp-Bindings/SKImage.cs
22,401
C#
/* Copyright (c) 2019 Denis Zykov, GameDevWare.com This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. This source code is distributed via Unity Asset Store, to use it in your project you should accept Terms of Service and EULA https://unity3d.com/ru/legal/as_terms */ using System; using GameDevWare.Serialization.MessagePack; // ReSharper disable once CheckNamespace namespace GameDevWare.Serialization.Serializers { public sealed class GuidSerializer : TypeSerializer { public override Type SerializedType { get { return typeof(Guid); } } public override object Deserialize(IJsonReader reader) { if (reader == null) throw new ArgumentNullException("reader"); var guidStr = reader.ReadString(false); var value = new Guid(guidStr); return value; } public override void Serialize(IJsonWriter writer, object value) { if (writer == null) throw new ArgumentNullException("writer"); if (value == null) throw new ArgumentNullException("value"); var messagePackWriter = writer as MsgPackWriter; if (messagePackWriter != null) { // try to write it as Message Pack extension type var extensionType = default(sbyte); var buffer = messagePackWriter.GetWriteBuffer(); if (messagePackWriter.Context.ExtensionTypeHandler.TryWrite(value, out extensionType, ref buffer)) { messagePackWriter.Write(extensionType, buffer); return; } // if not, continue default serialization } var guid = (Guid)value; var guidStr = guid.ToString(); writer.Write(guidStr); } } }
33.633333
116
0.745788
[ "Apache-2.0" ]
FromSeabedOfReverie/SubmarineMirageFrameworkForUnity
Assets/Plugins/ExternalAssets/Systems/GameDevWare.Serialization/Serializers/GuidSerializer.cs
2,018
C#
/** Copyright (c) blueback Released under the MIT License @brief デバッグツール。自動生成。 */ /** BlueBack.Audio */ namespace BlueBack.Audio { /** DebugTool */ public static class DebugTool { /** assertproc */ #if(DEF_BLUEBACK_AUDIO_ASSERT) public static void DefaultAssertProc(System.Exception a_exception,string a_message) { if(a_message != null){ UnityEngine.Debug.LogError(a_message); } if(a_exception != null){ UnityEngine.Debug.LogError(a_exception.ToString()); } UnityEngine.Debug.Assert(false); } public delegate void AssertProcType(System.Exception a_exception,string a_message); public static AssertProcType assertproc = DefaultAssertProc; #endif /** logproc */ #if(DEF_BLUEBACK_AUDIO_LOG) public static void DefaultLogProc(string a_message) { UnityEngine.Debug.Log(a_message); } public delegate void LogProcType(string a_message); public static LogProcType logproc = DebugTool.DefaultLogProc; #endif /** Assert */ #if(DEF_BLUEBACK_AUDIO_ASSERT) public static void Assert(bool a_flag,System.Exception a_exception = null) { if(a_flag != true){ DebugTool.assertproc(a_exception,null); } } #endif /** Assert */ #if(DEF_BLUEBACK_AUDIO_ASSERT) public static void Assert(bool a_flag,string a_message) { if(a_flag != true){ DebugTool.assertproc(null,a_message); } } #endif #if(DEF_BLUEBACK_AUDIO_LOG) public static void Log(string a_message) { DebugTool.logproc(a_message); } #endif /** EditorLog */ #if(UNITY_EDITOR) public static void EditorLog(string a_text) { UnityEngine.Debug.Log(a_text); } #endif /** EditorLogError */ #if(UNITY_EDITOR) public static void EditorLogError(string a_text) { UnityEngine.Debug.LogError(a_text); } #endif } }
19.680412
86
0.665794
[ "MIT" ]
bluebackblue/Audio
BlueBackAudio/Assets/UPM/Runtime/BlueBack/Audio/DebugTool.cs
1,935
C#
#region License /* CryptSharp Copyright (c) 2013 James F. Bellinger <http://www.zer7.com/software/cryptsharp> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #endregion using System; namespace CryptSharp.Internal { static class Exceptions { public static ArgumentException Argument (string valueName, string message, params object[] args) { message = string.Format(message, args); ArgumentException e = valueName == null ? new ArgumentException(message) : new ArgumentException(message, valueName); return e; } public static ArgumentNullException ArgumentNull(string valueName) { ArgumentNullException e = valueName == null ? new ArgumentNullException() : new ArgumentNullException(valueName); return e; } public static ArgumentOutOfRangeException ArgumentOutOfRange (string valueName, string message, params object[] args) { message = string.Format(message, args); ArgumentOutOfRangeException e = valueName == null ? new ArgumentOutOfRangeException(message, (Exception)null) : new ArgumentOutOfRangeException(valueName, message); return e; } public static InvalidOperationException InvalidOperation() { InvalidOperationException e = new InvalidOperationException(); return e; } public static NotSupportedException NotSupported() { return new NotSupportedException(); } } }
35.121212
79
0.670837
[ "MIT" ]
JomaCorpFX/Insane
CryptSharp.SCrypt/Internal/Exceptions.cs
2,320
C#
using System.Threading; using System.Threading.Tasks; namespace Furion.DatabaseAccessor { /// <summary> /// 可写仓储接口 /// </summary> /// <typeparam name="TEntity">实体类型</typeparam> public partial interface IWritableRepository<TEntity> : IWritableRepository<TEntity, MasterDbContextLocator> , IInsertableRepository<TEntity> , IUpdateableRepository<TEntity> , IDeletableRepository<TEntity> , IOperableRepository<TEntity> where TEntity : class, IPrivateEntity, new() { } /// <summary> /// 可写仓储接口 /// </summary> /// <typeparam name="TEntity">实体类型</typeparam> /// <typeparam name="TDbContextLocator">数据库上下文定位器</typeparam> public partial interface IWritableRepository<TEntity, TDbContextLocator> : IInsertableRepository<TEntity, TDbContextLocator> , IUpdateableRepository<TEntity, TDbContextLocator> , IDeletableRepository<TEntity, TDbContextLocator> , IOperableRepository<TEntity, TDbContextLocator> , IPrivateRepository where TEntity : class, IPrivateEntity, new() where TDbContextLocator : class, IDbContextLocator { /// <summary> /// 接受所有更改 /// </summary> void AcceptAllChanges(); /// <summary> /// 保存数据库上下文池中所有已更改的数据库上下文 /// </summary> /// <returns></returns> int SavePoolNow(); /// <summary> /// 保存数据库上下文池中所有已更改的数据库上下文 /// </summary> /// <param name="acceptAllChangesOnSuccess"></param> /// <returns></returns> int SavePoolNow(bool acceptAllChangesOnSuccess); /// <summary> /// 保存数据库上下文池中所有已更改的数据库上下文 /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> Task<int> SavePoolNowAsync(CancellationToken cancellationToken = default); /// <summary> /// 保存数据库上下文池中所有已更改的数据库上下文 /// </summary> /// <param name="acceptAllChangesOnSuccess"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task<int> SavePoolNowAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default); /// <summary> /// 提交更改操作 /// </summary> /// <returns></returns> int SaveNow(); /// <summary> /// 提交更改操作 /// </summary> /// <param name="acceptAllChangesOnSuccess"></param> /// <returns></returns> int SaveNow(bool acceptAllChangesOnSuccess); /// <summary> /// 提交更改操作(异步) /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> Task<int> SaveNowAsync(CancellationToken cancellationToken = default); /// <summary> /// 提交更改操作(异步) /// </summary> /// <param name="acceptAllChangesOnSuccess"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task<int> SaveNowAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default); } }
32.852632
114
0.602051
[ "Apache-2.0" ]
15000775075/Furion
framework/Furion/DatabaseAccessor/Repositories/Dependencies/IWritableRepository.cs
3,433
C#
using Amazon; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; using Amazon.Runtime; namespace CloudOps.SimpleNotificationService { public class ListSubscriptionsOperation : Operation { public override string Name => "ListSubscriptions"; public override string Description => "Returns a list of the requester&#39;s subscriptions. Each call returns a limited list of subscriptions, up to 100. If there are more subscriptions, a NextToken is also returned. Use the NextToken parameter in a new ListSubscriptions call to get further results. This action is throttled at 30 transactions per second (TPS)."; public override string RequestURI => "/"; public override string Method => "POST"; public override string ServiceName => "SimpleNotificationService"; public override string ServiceID => "SNS"; public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems) { AmazonSimpleNotificationServiceConfig config = new AmazonSimpleNotificationServiceConfig(); config.RegionEndpoint = region; ConfigureClient(config); AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient(creds, config); ListSubscriptionsResponse resp = new ListSubscriptionsResponse(); do { ListSubscriptionsRequest req = new ListSubscriptionsRequest { NextToken = resp.NextToken }; resp = client.ListSubscriptions(req); CheckError(resp.HttpStatusCode, "200"); foreach (var obj in resp.Subscriptions) { AddObject(obj); } } while (!string.IsNullOrEmpty(resp.NextToken)); } } }
40.32
372
0.62004
[ "MIT" ]
austindimmer/AWSRetriever
CloudOps/Generated/SimpleNotificationService/ListSubscriptionsOperation.cs
2,016
C#
using System; using System.Threading; using commands.tools; using commands.tools.builders; namespace commands.extensions { public static class BuildExtensions { public static IBuilder StartBuilder(this Action action) => new RootBuilder(action.ToCommand()); public static IBuilder StartBuilder(this ICommand command) => new RootBuilder(command); public static IBuilder<TResult> StartBuilder<TResult>(this Func<TResult> func) => new RootBuilder<TResult>(func.ToCommand()); public static IBuilder<TResult> StartBuilder<TResult>(this ICommandOut<TResult> command) => new RootBuilder<TResult>(command); public static IBuilder Add(this IBuilder builder, Action action) => builder.Add(action.ToCommand()); public static IBuilder Add(this IBuilder builder, Action<CancellationToken> action) => builder.Add(action.ToCommand()); public static IBuilder<TResult> Add<TResult>(this IBuilder builder, Func<TResult> func) => builder.Add(func.ToCommand()); public static IBuilder<TResult> Add<TResult>(this IBuilder builder, Func<CancellationToken, TResult> func) => builder.Add(func.ToCommand()); public static IBuilder Add<TArgument>(this IBuilder<TArgument> builder, Action<TArgument> action) => builder.Add(action.ToCommand()); public static IBuilder Add<TArgument>(this IBuilder<TArgument> builder, Action<TArgument, CancellationToken> action) => builder.Add(action.ToCommand()); public static IBuilder<TResult> Add<TArgument, TResult>(this IBuilder<TArgument> builder, Func<TArgument, TResult> func) => builder.Add(func.ToCommand()); public static IBuilder<TResult> Add<TArgument, TResult>(this IBuilder<TArgument> builder, Func<TArgument, CancellationToken, TResult> func) => builder.Add(func.ToCommand()); public static IBuilder Chain(this IBuilder builder, ICommand command, UInt64 count) => builder.Repeat((b, _) => b.Add(command), count); public static IBuilder Chain(this IBuilder builder, Func<UInt64, ICommand> generator, UInt64 count) => builder.Repeat((b, i) => b.Add(generator(i)), count); public static IBuilder<TChain> Chain<TChain>(this IBuilder<TChain> builder, ICommand<TChain, TChain> command, UInt64 count) => builder.Repeat((b, _) => b.Add(command), count); public static IBuilder<TChain> Chain<TChain>(this IBuilder<TChain> builder, Func<UInt64, ICommand<TChain, TChain>> generator, UInt64 count) => builder.Repeat((b, i) => b.Add(generator(i)), count); private static TBuilder Repeat<TBuilder>(this TBuilder builder, Func<TBuilder, UInt64, TBuilder> repetition, UInt64 count) { for(UInt64 iteration = 0; iteration < count; ++iteration) { builder = repetition(builder, iteration); } return builder; } } }
83.264706
204
0.719181
[ "MIT" ]
atmoos/commands
commands/extensions/BuildExtensions.cs
2,831
C#
namespace SGM.SAC.Api.Constants { public static class Routes { public const string PropertyTaxRoute = "getPropertyTax"; } }
18.125
64
0.668966
[ "MIT" ]
wgamagomes/sgm-sac-backend
containers/api-sac/src/Constants/Routes.cs
147
C#
#region Using directives using System; using System.Data; using System.Data.Common; using System.Collections; using System.Collections.Generic; using Nettiers.AdventureWorks.Entities; using Nettiers.AdventureWorks.Data; #endregion namespace Nettiers.AdventureWorks.Data.Bases { ///<summary> /// This class is the base class for any <see cref="TransactionHistoryProviderBase"/> implementation. /// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures. ///</summary> public abstract partial class TransactionHistoryProviderBaseCore : EntityProviderBase<Nettiers.AdventureWorks.Entities.TransactionHistory, Nettiers.AdventureWorks.Entities.TransactionHistoryKey> { #region Get from Many To Many Relationship Functions #endregion #region Delete Methods /// <summary> /// Deletes a row from the DataSource. /// </summary> /// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param> /// <param name="key">The unique identifier of the row to delete.</param> /// <returns>Returns true if operation suceeded.</returns> public override bool Delete(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.TransactionHistoryKey key) { return Delete(transactionManager, key.TransactionId); } /// <summary> /// Deletes a row from the DataSource. /// </summary> /// <param name="_transactionId">Primary key for TransactionHistory records.. Primary Key.</param> /// <remarks>Deletes based on primary key(s).</remarks> /// <returns>Returns true if operation suceeded.</returns> public bool Delete(System.Int32 _transactionId) { return Delete(null, _transactionId); } /// <summary> /// Deletes a row from the DataSource. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_transactionId">Primary key for TransactionHistory records.. Primary Key.</param> /// <remarks>Deletes based on primary key(s).</remarks> /// <returns>Returns true if operation suceeded.</returns> public abstract bool Delete(TransactionManager transactionManager, System.Int32 _transactionId); #endregion Delete Methods #region Get By Foreign Key Functions #endregion #region Get By Index Functions /// <summary> /// Gets a row from the DataSource based on its primary key. /// </summary> /// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param> /// <param name="key">The unique identifier of the row to retrieve.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <returns>Returns an instance of the Entity class.</returns> public override Nettiers.AdventureWorks.Entities.TransactionHistory Get(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.TransactionHistoryKey key, int start, int pageLength) { return GetByTransactionId(transactionManager, key.TransactionId, start, pageLength); } /// <summary> /// Gets rows from the datasource based on the primary key IX_TransactionHistory_ProductID index. /// </summary> /// <param name="_productId">Product identification number. Foreign key to Product.ProductID.</param> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public TList<TransactionHistory> GetByProductId(System.Int32 _productId) { int count = -1; return GetByProductId(null,_productId, 0, int.MaxValue, out count); } /// <summary> /// Gets rows from the datasource based on the IX_TransactionHistory_ProductID index. /// </summary> /// <param name="_productId">Product identification number. Foreign key to Product.ProductID.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public TList<TransactionHistory> GetByProductId(System.Int32 _productId, int start, int pageLength) { int count = -1; return GetByProductId(null, _productId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the IX_TransactionHistory_ProductID index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_productId">Product identification number. Foreign key to Product.ProductID.</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public TList<TransactionHistory> GetByProductId(TransactionManager transactionManager, System.Int32 _productId) { int count = -1; return GetByProductId(transactionManager, _productId, 0, int.MaxValue, out count); } /// <summary> /// Gets rows from the datasource based on the IX_TransactionHistory_ProductID index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_productId">Product identification number. Foreign key to Product.ProductID.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public TList<TransactionHistory> GetByProductId(TransactionManager transactionManager, System.Int32 _productId, int start, int pageLength) { int count = -1; return GetByProductId(transactionManager, _productId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the IX_TransactionHistory_ProductID index. /// </summary> /// <param name="_productId">Product identification number. Foreign key to Product.ProductID.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">out parameter to get total records for query</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public TList<TransactionHistory> GetByProductId(System.Int32 _productId, int start, int pageLength, out int count) { return GetByProductId(null, _productId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the IX_TransactionHistory_ProductID index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_productId">Product identification number. Foreign key to Product.ProductID.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">The total number of records.</param> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public abstract TList<TransactionHistory> GetByProductId(TransactionManager transactionManager, System.Int32 _productId, int start, int pageLength, out int count); /// <summary> /// Gets rows from the datasource based on the primary key IX_TransactionHistory_ReferenceOrderID_ReferenceOrderLineID index. /// </summary> /// <param name="_referenceOrderId">Purchase order, sales order, or work order identification number.</param> /// <param name="_referenceOrderLineId">Line number associated with the purchase order, sales order, or work order.</param> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public TList<TransactionHistory> GetByReferenceOrderIdReferenceOrderLineId(System.Int32 _referenceOrderId, System.Int32 _referenceOrderLineId) { int count = -1; return GetByReferenceOrderIdReferenceOrderLineId(null,_referenceOrderId, _referenceOrderLineId, 0, int.MaxValue, out count); } /// <summary> /// Gets rows from the datasource based on the IX_TransactionHistory_ReferenceOrderID_ReferenceOrderLineID index. /// </summary> /// <param name="_referenceOrderId">Purchase order, sales order, or work order identification number.</param> /// <param name="_referenceOrderLineId">Line number associated with the purchase order, sales order, or work order.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public TList<TransactionHistory> GetByReferenceOrderIdReferenceOrderLineId(System.Int32 _referenceOrderId, System.Int32 _referenceOrderLineId, int start, int pageLength) { int count = -1; return GetByReferenceOrderIdReferenceOrderLineId(null, _referenceOrderId, _referenceOrderLineId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the IX_TransactionHistory_ReferenceOrderID_ReferenceOrderLineID index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_referenceOrderId">Purchase order, sales order, or work order identification number.</param> /// <param name="_referenceOrderLineId">Line number associated with the purchase order, sales order, or work order.</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public TList<TransactionHistory> GetByReferenceOrderIdReferenceOrderLineId(TransactionManager transactionManager, System.Int32 _referenceOrderId, System.Int32 _referenceOrderLineId) { int count = -1; return GetByReferenceOrderIdReferenceOrderLineId(transactionManager, _referenceOrderId, _referenceOrderLineId, 0, int.MaxValue, out count); } /// <summary> /// Gets rows from the datasource based on the IX_TransactionHistory_ReferenceOrderID_ReferenceOrderLineID index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_referenceOrderId">Purchase order, sales order, or work order identification number.</param> /// <param name="_referenceOrderLineId">Line number associated with the purchase order, sales order, or work order.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public TList<TransactionHistory> GetByReferenceOrderIdReferenceOrderLineId(TransactionManager transactionManager, System.Int32 _referenceOrderId, System.Int32 _referenceOrderLineId, int start, int pageLength) { int count = -1; return GetByReferenceOrderIdReferenceOrderLineId(transactionManager, _referenceOrderId, _referenceOrderLineId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the IX_TransactionHistory_ReferenceOrderID_ReferenceOrderLineID index. /// </summary> /// <param name="_referenceOrderId">Purchase order, sales order, or work order identification number.</param> /// <param name="_referenceOrderLineId">Line number associated with the purchase order, sales order, or work order.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">out parameter to get total records for query</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public TList<TransactionHistory> GetByReferenceOrderIdReferenceOrderLineId(System.Int32 _referenceOrderId, System.Int32 _referenceOrderLineId, int start, int pageLength, out int count) { return GetByReferenceOrderIdReferenceOrderLineId(null, _referenceOrderId, _referenceOrderLineId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the IX_TransactionHistory_ReferenceOrderID_ReferenceOrderLineID index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_referenceOrderId">Purchase order, sales order, or work order identification number.</param> /// <param name="_referenceOrderLineId">Line number associated with the purchase order, sales order, or work order.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">The total number of records.</param> /// <returns>Returns an instance of the <see cref="TList&lt;TransactionHistory&gt;"/> class.</returns> public abstract TList<TransactionHistory> GetByReferenceOrderIdReferenceOrderLineId(TransactionManager transactionManager, System.Int32 _referenceOrderId, System.Int32 _referenceOrderLineId, int start, int pageLength, out int count); /// <summary> /// Gets rows from the datasource based on the primary key PK_TransactionHistory_TransactionID index. /// </summary> /// <param name="_transactionId">Primary key for TransactionHistory records.</param> /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> class.</returns> public Nettiers.AdventureWorks.Entities.TransactionHistory GetByTransactionId(System.Int32 _transactionId) { int count = -1; return GetByTransactionId(null,_transactionId, 0, int.MaxValue, out count); } /// <summary> /// Gets rows from the datasource based on the PK_TransactionHistory_TransactionID index. /// </summary> /// <param name="_transactionId">Primary key for TransactionHistory records.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> class.</returns> public Nettiers.AdventureWorks.Entities.TransactionHistory GetByTransactionId(System.Int32 _transactionId, int start, int pageLength) { int count = -1; return GetByTransactionId(null, _transactionId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the PK_TransactionHistory_TransactionID index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_transactionId">Primary key for TransactionHistory records.</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> class.</returns> public Nettiers.AdventureWorks.Entities.TransactionHistory GetByTransactionId(TransactionManager transactionManager, System.Int32 _transactionId) { int count = -1; return GetByTransactionId(transactionManager, _transactionId, 0, int.MaxValue, out count); } /// <summary> /// Gets rows from the datasource based on the PK_TransactionHistory_TransactionID index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_transactionId">Primary key for TransactionHistory records.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> class.</returns> public Nettiers.AdventureWorks.Entities.TransactionHistory GetByTransactionId(TransactionManager transactionManager, System.Int32 _transactionId, int start, int pageLength) { int count = -1; return GetByTransactionId(transactionManager, _transactionId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the PK_TransactionHistory_TransactionID index. /// </summary> /// <param name="_transactionId">Primary key for TransactionHistory records.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">out parameter to get total records for query</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> class.</returns> public Nettiers.AdventureWorks.Entities.TransactionHistory GetByTransactionId(System.Int32 _transactionId, int start, int pageLength, out int count) { return GetByTransactionId(null, _transactionId, start, pageLength, out count); } /// <summary> /// Gets rows from the datasource based on the PK_TransactionHistory_TransactionID index. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_transactionId">Primary key for TransactionHistory records.</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">The total number of records.</param> /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> class.</returns> public abstract Nettiers.AdventureWorks.Entities.TransactionHistory GetByTransactionId(TransactionManager transactionManager, System.Int32 _transactionId, int start, int pageLength, out int count); #endregion "Get By Index Functions" #region Custom Methods #endregion #region Helper Functions /// <summary> /// Fill a TList&lt;TransactionHistory&gt; From a DataReader. /// </summary> /// <param name="reader">Datareader</param> /// <param name="rows">The collection to fill</param> /// <param name="start">Row number at which to start reading, the first row is 0.</param> /// <param name="pageLength">number of rows.</param> /// <returns>a <see cref="TList&lt;TransactionHistory&gt;"/></returns> public static TList<TransactionHistory> Fill(IDataReader reader, TList<TransactionHistory> rows, int start, int pageLength) { NetTiersProvider currentProvider = DataRepository.Provider; bool useEntityFactory = currentProvider.UseEntityFactory; bool enableEntityTracking = currentProvider.EnableEntityTracking; LoadPolicy currentLoadPolicy = currentProvider.CurrentLoadPolicy; Type entityCreationFactoryType = currentProvider.EntityCreationalFactoryType; // advance to the starting row for (int i = 0; i < start; i++) { if (!reader.Read()) return rows; // not enough rows, just return } for (int i = 0; i < pageLength; i++) { if (!reader.Read()) break; // we are done string key = null; Nettiers.AdventureWorks.Entities.TransactionHistory c = null; if (useEntityFactory) { key = new System.Text.StringBuilder("TransactionHistory") .Append("|").Append((System.Int32)reader[((int)TransactionHistoryColumn.TransactionId - 1)]).ToString(); c = EntityManager.LocateOrCreate<TransactionHistory>( key.ToString(), // EntityTrackingKey "TransactionHistory", //Creational Type entityCreationFactoryType, //Factory used to create entity enableEntityTracking); // Track this entity? } else { c = new Nettiers.AdventureWorks.Entities.TransactionHistory(); } if (!enableEntityTracking || c.EntityState == EntityState.Added || (enableEntityTracking && ( (currentLoadPolicy == LoadPolicy.PreserveChanges && c.EntityState == EntityState.Unchanged) || (currentLoadPolicy == LoadPolicy.DiscardChanges && c.EntityState != EntityState.Unchanged) ) )) { c.SuppressEntityEvents = true; c.TransactionId = (System.Int32)reader[((int)TransactionHistoryColumn.TransactionId - 1)]; c.ProductId = (System.Int32)reader[((int)TransactionHistoryColumn.ProductId - 1)]; c.ReferenceOrderId = (System.Int32)reader[((int)TransactionHistoryColumn.ReferenceOrderId - 1)]; c.ReferenceOrderLineId = (System.Int32)reader[((int)TransactionHistoryColumn.ReferenceOrderLineId - 1)]; c.TransactionDate = (System.DateTime)reader[((int)TransactionHistoryColumn.TransactionDate - 1)]; c.TransactionType = (System.String)reader[((int)TransactionHistoryColumn.TransactionType - 1)]; c.Quantity = (System.Int32)reader[((int)TransactionHistoryColumn.Quantity - 1)]; c.ActualCost = (System.Decimal)reader[((int)TransactionHistoryColumn.ActualCost - 1)]; c.ModifiedDate = (System.DateTime)reader[((int)TransactionHistoryColumn.ModifiedDate - 1)]; c.EntityTrackingKey = key; c.AcceptChanges(); c.SuppressEntityEvents = false; } rows.Add(c); } return rows; } /// <summary> /// Refreshes the <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> object from the <see cref="IDataReader"/>. /// </summary> /// <param name="reader">The <see cref="IDataReader"/> to read from.</param> /// <param name="entity">The <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> object to refresh.</param> public static void RefreshEntity(IDataReader reader, Nettiers.AdventureWorks.Entities.TransactionHistory entity) { if (!reader.Read()) return; entity.TransactionId = (System.Int32)reader[((int)TransactionHistoryColumn.TransactionId - 1)]; entity.ProductId = (System.Int32)reader[((int)TransactionHistoryColumn.ProductId - 1)]; entity.ReferenceOrderId = (System.Int32)reader[((int)TransactionHistoryColumn.ReferenceOrderId - 1)]; entity.ReferenceOrderLineId = (System.Int32)reader[((int)TransactionHistoryColumn.ReferenceOrderLineId - 1)]; entity.TransactionDate = (System.DateTime)reader[((int)TransactionHistoryColumn.TransactionDate - 1)]; entity.TransactionType = (System.String)reader[((int)TransactionHistoryColumn.TransactionType - 1)]; entity.Quantity = (System.Int32)reader[((int)TransactionHistoryColumn.Quantity - 1)]; entity.ActualCost = (System.Decimal)reader[((int)TransactionHistoryColumn.ActualCost - 1)]; entity.ModifiedDate = (System.DateTime)reader[((int)TransactionHistoryColumn.ModifiedDate - 1)]; entity.AcceptChanges(); } /// <summary> /// Refreshes the <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> object from the <see cref="DataSet"/>. /// </summary> /// <param name="dataSet">The <see cref="DataSet"/> to read from.</param> /// <param name="entity">The <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> object.</param> public static void RefreshEntity(DataSet dataSet, Nettiers.AdventureWorks.Entities.TransactionHistory entity) { DataRow dataRow = dataSet.Tables[0].Rows[0]; entity.TransactionId = (System.Int32)dataRow["TransactionID"]; entity.ProductId = (System.Int32)dataRow["ProductID"]; entity.ReferenceOrderId = (System.Int32)dataRow["ReferenceOrderID"]; entity.ReferenceOrderLineId = (System.Int32)dataRow["ReferenceOrderLineID"]; entity.TransactionDate = (System.DateTime)dataRow["TransactionDate"]; entity.TransactionType = (System.String)dataRow["TransactionType"]; entity.Quantity = (System.Int32)dataRow["Quantity"]; entity.ActualCost = (System.Decimal)dataRow["ActualCost"]; entity.ModifiedDate = (System.DateTime)dataRow["ModifiedDate"]; entity.AcceptChanges(); } #endregion #region DeepLoad Methods /// <summary> /// Deep Loads the <see cref="IEntity"/> object with criteria based of the child /// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>. /// </summary> /// <remarks> /// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph. /// </remarks> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="entity">The <see cref="Nettiers.AdventureWorks.Entities.TransactionHistory"/> object to load.</param> /// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param> /// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param> /// <param name="childTypes">Nettiers.AdventureWorks.Entities.TransactionHistory Property Collection Type Array To Include or Exclude from Load</param> /// <param name="innerList">A collection of child types for easy access.</param> /// <exception cref="ArgumentNullException">entity or childTypes is null.</exception> /// <exception cref="ArgumentException">deepLoadType has invalid value.</exception> public override void DeepLoad(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.TransactionHistory entity, bool deep, DeepLoadType deepLoadType, System.Type[] childTypes, DeepSession innerList) { if(entity == null) return; #region ProductIdSource if (CanDeepLoad(entity, "Product|ProductIdSource", deepLoadType, innerList) && entity.ProductIdSource == null) { object[] pkItems = new object[1]; pkItems[0] = entity.ProductId; Product tmpEntity = EntityManager.LocateEntity<Product>(EntityLocator.ConstructKeyFromPkItems(typeof(Product), pkItems), DataRepository.Provider.EnableEntityTracking); if (tmpEntity != null) entity.ProductIdSource = tmpEntity; else entity.ProductIdSource = DataRepository.ProductProvider.GetByProductId(transactionManager, entity.ProductId); #if NETTIERS_DEBUG System.Diagnostics.Debug.WriteLine("- property 'ProductIdSource' loaded. key " + entity.EntityTrackingKey); #endif if (deep && entity.ProductIdSource != null) { innerList.SkipChildren = true; DataRepository.ProductProvider.DeepLoad(transactionManager, entity.ProductIdSource, deep, deepLoadType, childTypes, innerList); innerList.SkipChildren = false; } } #endregion ProductIdSource //used to hold DeepLoad method delegates and fire after all the local children have been loaded. Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>(); //Fire all DeepLoad Items foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values) { pair.Key.DynamicInvoke((object[])pair.Value); } deepHandles = null; } #endregion #region DeepSave Methods /// <summary> /// Deep Save the entire object graph of the Nettiers.AdventureWorks.Entities.TransactionHistory object with criteria based of the child /// Type property array and DeepSaveType. /// </summary> /// <param name="transactionManager">The transaction manager.</param> /// <param name="entity">Nettiers.AdventureWorks.Entities.TransactionHistory instance</param> /// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param> /// <param name="childTypes">Nettiers.AdventureWorks.Entities.TransactionHistory Property Collection Type Array To Include or Exclude from Save</param> /// <param name="innerList">A Hashtable of child types for easy access.</param> public override bool DeepSave(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.TransactionHistory entity, DeepSaveType deepSaveType, System.Type[] childTypes, DeepSession innerList) { if (entity == null) return false; #region Composite Parent Properties //Save Source Composite Properties, however, don't call deep save on them. //So they only get saved a single level deep. #region ProductIdSource if (CanDeepSave(entity, "Product|ProductIdSource", deepSaveType, innerList) && entity.ProductIdSource != null) { DataRepository.ProductProvider.Save(transactionManager, entity.ProductIdSource); entity.ProductId = entity.ProductIdSource.ProductId; } #endregion #endregion Composite Parent Properties // Save Root Entity through Provider if (!entity.IsDeleted) this.Save(transactionManager, entity); //used to hold DeepSave method delegates and fire after all the local children have been saved. Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>(); //Fire all DeepSave Items foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values) { pair.Key.DynamicInvoke((object[])pair.Value); } // Save Root Entity through Provider, if not already saved in delete mode if (entity.IsDeleted) this.Save(transactionManager, entity); deepHandles = null; return true; } #endregion } // end class #region TransactionHistoryChildEntityTypes ///<summary> /// Enumeration used to expose the different child entity types /// for child properties in <c>Nettiers.AdventureWorks.Entities.TransactionHistory</c> ///</summary> public enum TransactionHistoryChildEntityTypes { ///<summary> /// Composite Property for <c>Product</c> at ProductIdSource ///</summary> [ChildEntityType(typeof(Product))] Product, } #endregion TransactionHistoryChildEntityTypes #region TransactionHistoryFilterBuilder /// <summary> /// A strongly-typed instance of the <see cref="SqlFilterBuilder&lt;TransactionHistoryColumn&gt;"/> class /// that is used exclusively with a <see cref="TransactionHistory"/> object. /// </summary> [CLSCompliant(true)] public class TransactionHistoryFilterBuilder : SqlFilterBuilder<TransactionHistoryColumn> { #region Constructors /// <summary> /// Initializes a new instance of the TransactionHistoryFilterBuilder class. /// </summary> public TransactionHistoryFilterBuilder() : base() { } /// <summary> /// Initializes a new instance of the TransactionHistoryFilterBuilder class. /// </summary> /// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param> public TransactionHistoryFilterBuilder(bool ignoreCase) : base(ignoreCase) { } /// <summary> /// Initializes a new instance of the TransactionHistoryFilterBuilder class. /// </summary> /// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param> /// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param> public TransactionHistoryFilterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { } #endregion Constructors } #endregion TransactionHistoryFilterBuilder #region TransactionHistoryParameterBuilder /// <summary> /// A strongly-typed instance of the <see cref="ParameterizedSqlFilterBuilder&lt;TransactionHistoryColumn&gt;"/> class /// that is used exclusively with a <see cref="TransactionHistory"/> object. /// </summary> [CLSCompliant(true)] public class TransactionHistoryParameterBuilder : ParameterizedSqlFilterBuilder<TransactionHistoryColumn> { #region Constructors /// <summary> /// Initializes a new instance of the TransactionHistoryParameterBuilder class. /// </summary> public TransactionHistoryParameterBuilder() : base() { } /// <summary> /// Initializes a new instance of the TransactionHistoryParameterBuilder class. /// </summary> /// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param> public TransactionHistoryParameterBuilder(bool ignoreCase) : base(ignoreCase) { } /// <summary> /// Initializes a new instance of the TransactionHistoryParameterBuilder class. /// </summary> /// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param> /// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param> public TransactionHistoryParameterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { } #endregion Constructors } #endregion TransactionHistoryParameterBuilder #region TransactionHistorySortBuilder /// <summary> /// A strongly-typed instance of the <see cref="SqlSortBuilder&lt;TransactionHistoryColumn&gt;"/> class /// that is used exclusively with a <see cref="TransactionHistory"/> object. /// </summary> [CLSCompliant(true)] public class TransactionHistorySortBuilder : SqlSortBuilder<TransactionHistoryColumn> { #region Constructors /// <summary> /// Initializes a new instance of the TransactionHistorySqlSortBuilder class. /// </summary> public TransactionHistorySortBuilder() : base() { } #endregion Constructors } #endregion TransactionHistorySortBuilder } // end namespace
51.217066
250
0.723146
[ "MIT" ]
aqua88hn/netTiers
Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Data/Bases/TransactionHistoryProviderBase.generatedCore.cs
34,215
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; namespace Allocations.Data { public class AllocationDataGateway : IAllocationDataGateway { private readonly AllocationContext _context; public AllocationDataGateway(AllocationContext context) { _context = context; } public AllocationRecord Create(long projectId, long userId, DateTime firstDay, DateTime lastDay) { var recordToCreate = new AllocationRecord(projectId, userId, firstDay, lastDay); _context.AllocationRecords.Add(recordToCreate); _context.SaveChanges(); return recordToCreate; } public List<AllocationRecord> FindBy(long projectId) => _context.AllocationRecords .AsNoTracking() .Where(a => a.ProjectId == projectId) .ToList(); } }
28.9375
104
0.663067
[ "BSD-2-Clause" ]
vmware-tanzu-learning/pal-tracker-distributed-dotnet
Components/Allocations/Data/AllocationDataGateway.cs
926
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("12.IndexOfLetters")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("12.IndexOfLetters")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("0f2585e9-b5ec-408c-8ffe-e94e6684a6c7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027027
84
0.745558
[ "MIT" ]
owolp/Telerik-Academy
Module-1/CSharp-Part-2/Homework/01-Arrays/12.IndexOfLetters/Properties/AssemblyInfo.cs
1,410
C#
using System; using Android.App; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace PortoTurismo.Droid { [Activity(Label = "PortoTurismo", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } } }
28.571429
189
0.69
[ "MIT" ]
felipehfreire/PortoTurismo
PortoTurismo/PortoTurismo.Android/MainActivity.cs
802
C#
namespace SIL.Pa.UI.Dialogs { partial class OptionsDlgPageBase { /// <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 Component 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() { components = new System.ComponentModel.Container(); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; } #endregion } }
25.184211
102
0.656217
[ "MIT" ]
sillsdev/phonology-assistant
src/Pa/UI/Dialogs/Options/OptionsDlgPageBase.Designer.cs
959
C#
using TinaX.XComponent.Internal.Adaptor; namespace TinaX.XILRuntime.Registers { public static class XComponentILRTRegisterExtend { public static IXILRuntime RegisterXComponent(this IXILRuntime xil) { xil.RegisterCrossBindingAdaptor(new XBehaviourAdaptor()); return xil; } } }
24.142857
74
0.683432
[ "MIT" ]
yomunsam/TinaX.XComponent.ILRuntime
Runtime/Scripts/XComponentILRTRegisterExtend.cs
340
C#
namespace PlayGen.ITAlert.Simulation.Components.EntityTypes { public class NPC : IEntityType { } }
15.571429
61
0.724771
[ "Apache-2.0" ]
playgen/it-alert
Simulation/PlayGen.ITAlert.Simulation/Components/EntityTypes/Npc.cs
111
C#
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Firestorm.Endpoints.Formatting.Json { /// <remarks> /// Taken from http://stackoverflow.com/a/12641541/369247 and abstracted to <see cref="JsonGenericReadOnlyConverterBase{T}"/>. /// </remarks> public abstract class JsonCreationConverter<T> : JsonGenericReadOnlyConverterBase<T> { /// <summary> /// Create an instance of objectType, based properties in the JSON object /// </summary> /// <param name="objectType">type of object expected</param> /// <param name="jObject">contents of JSON object that will be deserialized</param> /// <returns></returns> protected abstract T Create(Type objectType, JObject jObject); protected override T ReadFromJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return default(T); JObject jObject = JObject.Load(reader); T target = Create(objectType, jObject); serializer.Populate(jObject.CreateReader(), target); return target; } } }
38.3125
130
0.643556
[ "MIT" ]
connellw/Firestorm
src/Firestorm.Endpoints.Formatting/Json/JsonCreationConverter.cs
1,226
C#
using System; using System.Collections.Concurrent; using System.Text; using System.Threading; using System.Threading.Tasks; using EasyNetQ.Events; using EasyNetQ.FluentConfiguration; using EasyNetQ.Topology; using Newtonsoft.Json; namespace EasyNetQ.Producer { /// <summary> /// Default implementation of EasyNetQ's request-response pattern /// </summary> public class Rpc : IRpc { private readonly ConnectionConfiguration connectionConfiguration; protected readonly IAdvancedBus advancedBus; protected readonly IConventions conventions; protected readonly IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy; protected readonly IMessageDeliveryModeStrategy messageDeliveryModeStrategy; private readonly ITimeoutStrategy timeoutStrategy; private readonly ITypeNameSerializer typeNameSerializer; private readonly object responseQueuesAddLock = new object(); private readonly ConcurrentDictionary<RpcKey, string> responseQueues = new ConcurrentDictionary<RpcKey, string>(); private readonly ConcurrentDictionary<string, ResponseAction> responseActions = new ConcurrentDictionary<string, ResponseAction>(); protected readonly TimeSpan disablePeriodicSignaling = TimeSpan.FromMilliseconds(-1); protected const string isFaultedKey = "IsFaulted"; protected const string exceptionMessageKey = "ExceptionMessage"; public Rpc( ConnectionConfiguration connectionConfiguration, IAdvancedBus advancedBus, IEventBus eventBus, IConventions conventions, IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy, IMessageDeliveryModeStrategy messageDeliveryModeStrategy, ITimeoutStrategy timeoutStrategy, ITypeNameSerializer typeNameSerializer) { Preconditions.CheckNotNull(connectionConfiguration, "configuration"); Preconditions.CheckNotNull(advancedBus, "advancedBus"); Preconditions.CheckNotNull(eventBus, "eventBus"); Preconditions.CheckNotNull(conventions, "conventions"); Preconditions.CheckNotNull(publishExchangeDeclareStrategy, "publishExchangeDeclareStrategy"); Preconditions.CheckNotNull(messageDeliveryModeStrategy, "messageDeliveryModeStrategy"); Preconditions.CheckNotNull(timeoutStrategy, "timeoutStrategy"); Preconditions.CheckNotNull(typeNameSerializer, "typeNameSerializer"); this.connectionConfiguration = connectionConfiguration; this.advancedBus = advancedBus; this.conventions = conventions; this.publishExchangeDeclareStrategy = publishExchangeDeclareStrategy; this.messageDeliveryModeStrategy = messageDeliveryModeStrategy; this.timeoutStrategy = timeoutStrategy; this.typeNameSerializer = typeNameSerializer; eventBus.Subscribe<ConnectionCreatedEvent>(OnConnectionCreated); } private void OnConnectionCreated(ConnectionCreatedEvent @event) { var copyOfResponseActions = responseActions.Values; responseActions.Clear(); responseQueues.Clear(); // retry in-flight requests. foreach (var responseAction in copyOfResponseActions) { responseAction.OnFailure(); } } public virtual Task<TResponse> Request<TRequest, TResponse>(TRequest request, Action<IRequestConfiguration> configure) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(request, "request"); var correlationId = Guid.NewGuid(); var requestType = typeof(TRequest); var configuration = new RequestConfiguration(); configure(configuration); var tcs = new TaskCompletionSource<TResponse>(); var timeout = timeoutStrategy.GetTimeoutSeconds(requestType); Timer timer = null; if (timeout > 0) { timer = new Timer(state => { ((Timer)state)?.Dispose(); tcs.TrySetException(new TimeoutException(string.Format("Request timed out. CorrelationId: {0}", correlationId.ToString()))); }, null, TimeSpan.FromSeconds(timeout), disablePeriodicSignaling); } RegisterErrorHandling(correlationId, timer, tcs); var queueName = SubscribeToResponse<TRequest, TResponse>(); var routingKey = configuration.QueueName ?? conventions.RpcRoutingKeyNamingConvention(requestType); RequestPublish(request, routingKey, queueName, correlationId); return tcs.Task; } protected void RegisterErrorHandling<TResponse>(Guid correlationId, Timer timer, TaskCompletionSource<TResponse> tcs) where TResponse : class { responseActions.TryAdd(correlationId.ToString(), new ResponseAction { OnSuccess = message => { timer?.Dispose(); var msg = ((IMessage<TResponse>)message); bool isFaulted = false; string exceptionMessage = "The exception message has not been specified."; if(msg.Properties.HeadersPresent) { if(msg.Properties.Headers.ContainsKey(isFaultedKey)) { isFaulted = Convert.ToBoolean(msg.Properties.Headers[isFaultedKey]); } if(msg.Properties.Headers.ContainsKey(exceptionMessageKey)) { exceptionMessage = Encoding.UTF8.GetString((byte[])msg.Properties.Headers[exceptionMessageKey]); } } if(isFaulted) { tcs.TrySetException(new EasyNetQResponderException(exceptionMessage)); } else { tcs.TrySetResult(msg.Body); } }, OnFailure = () => { timer?.Dispose(); tcs.TrySetException(new EasyNetQException("Connection lost while request was in-flight. CorrelationId: {0}", correlationId.ToString())); } }); } protected virtual string SubscribeToResponse<TRequest, TResponse>() where TResponse : class { var responseType = typeof(TResponse); var rpcKey = new RpcKey { Request = typeof(TRequest), Response = responseType }; string queueName; if (responseQueues.TryGetValue(rpcKey, out queueName)) return queueName; lock (responseQueuesAddLock) { if (responseQueues.TryGetValue(rpcKey, out queueName)) return queueName; var queue = advancedBus.QueueDeclare( conventions.RpcReturnQueueNamingConvention(), passive: false, durable: false, exclusive: true, autoDelete: true); var exchange = DeclareRpcExchange(conventions.RpcResponseExchangeNamingConvention(responseType)); advancedBus.Bind(exchange, queue, queue.Name); advancedBus.Consume<TResponse>(queue, (message, messageReceivedInfo) => Task.Factory.StartNew(() => { ResponseAction responseAction; if(responseActions.TryRemove(message.Properties.CorrelationId, out responseAction)) { responseAction.OnSuccess(message); } })); responseQueues.TryAdd(rpcKey, queue.Name); return queue.Name; } } protected struct RpcKey { public Type Request; public Type Response; } protected class ResponseAction { public Action<object> OnSuccess { get; set; } public Action OnFailure { get; set; } } protected virtual void RequestPublish<TRequest>(TRequest request, string routingKey, string returnQueueName, Guid correlationId) where TRequest : class { var requestType = typeof(TRequest); var exchange = publishExchangeDeclareStrategy.DeclareExchange(advancedBus, conventions.RpcRequestExchangeNamingConvention(requestType), ExchangeType.Direct); var requestMessage = new Message<TRequest>(request) { Properties = { ReplyTo = returnQueueName, CorrelationId = correlationId.ToString(), Expiration = (timeoutStrategy.GetTimeoutSeconds(requestType) * 1000).ToString(), DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(requestType) } }; advancedBus.Publish(exchange, routingKey, false, requestMessage); } public virtual IDisposable Respond<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder) where TRequest : class where TResponse : class { return Respond(responder, c => { }); } public virtual IDisposable Respond<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder, Action<IResponderConfiguration> configure) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(responder, "responder"); Preconditions.CheckNotNull(configure, "configure"); // We're explicitely validating TResponse here because the type won't be used directly. // It'll only be used when executing a successful responder, which will silently fail if TResponse serialized length exceeds the limit. Preconditions.CheckShortString(typeNameSerializer.Serialize(typeof(TResponse)), "TResponse"); var requestType = typeof(TRequest); var configuration = new ResponderConfiguration(connectionConfiguration.PrefetchCount); configure(configuration); var routingKey = configuration.QueueName ?? conventions.RpcRoutingKeyNamingConvention(requestType); var exchange = advancedBus.ExchangeDeclare(conventions.RpcRequestExchangeNamingConvention(requestType), ExchangeType.Direct); var queue = advancedBus.QueueDeclare(routingKey); advancedBus.Bind(exchange, queue, routingKey); return advancedBus.Consume<TRequest>(queue, (requestMessage, messageReceivedInfo) => ExecuteResponder(responder, requestMessage), c => c.WithPrefetchCount(configuration.PrefetchCount)); } protected Task ExecuteResponder<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder, IMessage<TRequest> requestMessage) where TRequest : class where TResponse : class { var tcs = new TaskCompletionSource<object>(); try { responder(requestMessage.Body).ContinueWith(task => { if (task.IsFaulted || task.IsCanceled) { var exception = task.IsCanceled ? new EasyNetQResponderException("The responder task was cancelled.") : task.Exception?.InnerException ?? new EasyNetQResponderException("The responder faulted while dispatching the message."); OnResponderFailure<TRequest, TResponse>(requestMessage, exception.Message, exception); tcs.SetException(exception); } else { OnResponderSuccess(requestMessage, task.Result); tcs.SetResult(null); } }); } catch (Exception e) { OnResponderFailure<TRequest, TResponse>(requestMessage, e.Message, e); tcs.SetException(e); } return tcs.Task; } protected virtual void OnResponderSuccess<TRequest, TResponse>(IMessage<TRequest> requestMessage, TResponse response) where TRequest : class where TResponse : class { var responseMessage = new Message<TResponse>(response) { Properties = { CorrelationId = requestMessage.Properties.CorrelationId, DeliveryMode = MessageDeliveryMode.NonPersistent } }; var exchange = DeclareRpcExchange(conventions.RpcResponseExchangeNamingConvention(typeof(TResponse))); advancedBus.Publish(exchange, requestMessage.Properties.ReplyTo, false, responseMessage); } protected virtual void OnResponderFailure<TRequest, TResponse>(IMessage<TRequest> requestMessage, string exceptionMessage, Exception exception) where TRequest : class where TResponse : class { // HACK: I think we can live with this, because it will run only on exception, // it tries to preserve the default serialization behavior, // being able to also deserialize POCO objects that has constructors with parameters // this avoids to introduce a custom class wraper that will change the message payload var body = JsonConvert.DeserializeObject<TResponse>(typeof(TResponse) == typeof(string) ? "''" : "{}"); var responseMessage = new Message<TResponse>(body); responseMessage.Properties.Headers.Add(isFaultedKey, true); responseMessage.Properties.Headers.Add(exceptionMessageKey, exceptionMessage); responseMessage.Properties.CorrelationId = requestMessage.Properties.CorrelationId; responseMessage.Properties.DeliveryMode = MessageDeliveryMode.NonPersistent; var exchange = DeclareRpcExchange(conventions.RpcResponseExchangeNamingConvention(typeof(TResponse))); advancedBus.Publish(exchange, requestMessage.Properties.ReplyTo, false, responseMessage); } private IExchange DeclareRpcExchange(string exchangeName) { return publishExchangeDeclareStrategy.DeclareExchange(advancedBus, exchangeName, ExchangeType.Direct); } } }
44.936747
196
0.613982
[ "MIT" ]
nazmul1985/EasyNetQ
Source/EasyNetQ/Producer/Rpc.cs
14,921
C#
using System; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DefensiveProgrammingFramework.Test.Files { [TestClass] public class IsExtensionsTest { #region Public Methods [TestMethod] public void DoesDirectoryExist() { if (!Directory.Exists(@".\Temp")) { Directory.CreateDirectory(@".\Temp"); } Assert.AreEqual(true, @".\Temp".DoesDirectoryExist()); if (Directory.Exists(@".\Temp")) { Directory.Delete(@".\Temp"); } Assert.AreEqual(false, @".\Temp".DoesDirectoryExist()); } [TestMethod] public void DoesFileExist() { if (!File.Exists(@".\Temp.txt")) { File.WriteAllText(@".\Temp.txt", "tmp"); } Assert.AreEqual(true, @".\Temp.txt".DoesFileExist()); if (File.Exists(@".\Temp.txt")) { File.Delete(@".\Temp.txt"); } Assert.AreEqual(false, @".\Temp.txt".DoesFileExist()); } [DataRow(null, true)] [DataRow(".", false)] [DataRow(@".\bin\Debug", false)] [DataRow(@"c:\", true)] [DataRow(@"c:", false)] [DataRow(@"c:\apps\MyApp\bin\Debug", true)] [DataRow(@"d:\apps\MyApp\bin\Debug", true)] [DataRow(@"e:\apps\MyApp\bin\Debug", true)] [DataTestMethod] public void IsAbsoluteDirectoryPath(string filePath, bool expected) { Assert.AreEqual(expected, filePath.IsAbsoluteDirectoryPath()); } [DataRow("")] [DataRow(@"e:\apps\M|yApp\bin\Debug")] [DataTestMethod] public void IsAbsoluteDirectoryPathFail(string filePath) { try { filePath.IsAbsoluteDirectoryPath(); Assert.Fail(); } catch (ArgumentException ex) { Assert.AreEqual("Value must be a valid directory path.", ex.Message); } } [DataRow(null, true)] [DataRow(@".\file.exe", false)] [DataRow(@".\bin\Debug\file.exe", false)] [DataRow(@"c:\file.exe", true)] [DataRow(@"c:\apps\MyApp\bin\Debug\file.exe", true)] [DataRow(@"d:\apps\MyApp\bin\Debug\file.exe", true)] [DataRow(@"e:\apps\MyApp\bin\Debug\file.exe", true)] [DataTestMethod] public void IsAbsoluteFilePath(string filePath, bool expected) { Assert.AreEqual(expected, filePath.IsAbsoluteFilePath()); } [DataRow(@"")] [DataRow(@"e:\apps\M|yApp\bin\Debug\file.exe")] [DataTestMethod] public void IsAbsoluteFilePathFail(string filePath) { try { filePath.IsAbsoluteFilePath(); Assert.Fail(); } catch (ArgumentException ex) { Assert.AreEqual("Value must be a valid file path.", ex.Message); } } [TestMethod] public void IsEmptyDirectory() { string directoryPath = @".\Tmp5"; string filePath = Path.Combine(directoryPath, "tmp.txt"); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } Assert.IsTrue((null as string).IsEmptyDirectory()); Assert.IsFalse(string.Empty.IsEmptyDirectory()); Assert.IsTrue(@".\aaa".IsEmptyDirectory()); Assert.IsTrue(directoryPath.IsEmptyDirectory()); File.WriteAllText(filePath, "text"); Assert.IsFalse(directoryPath.IsEmptyDirectory()); File.Delete(filePath); Directory.Delete(directoryPath); } [DataRow(null, true)] [DataRow("", false)] [DataRow("f", true)] [DataRow("file", true)] [DataRow("file.exe", true)] [DataRow(@"C:\Users\User1\source\repos\WpfApp1\WpfApp1\bin\Debug", true)] [DataRow(@"C:\Users\User1\source\repos\WpfApp1\WpfApp1\bin\Debug\", true)] [DataRow(@"C:\Users\User1\source\repos\WpfApp1\WpfApp1\bin\Debug\file.exe", true)] [DataRow("exe.file", true)] [DataRow("exe.sdfsfsdfsdfsdf", true)] [DataRow("file>1.exe", false)] [DataRow("file|1.ex'", false)] [DataTestMethod] public void IsValidDirectoryPath(string filePath, bool expected) { Assert.AreEqual(expected, filePath.IsValidDirectoryPath()); } [DataRow(null, true)] [DataRow("", false)] [DataRow("f", true)] [DataRow("file", true)] [DataRow("file.exe", true)] [DataRow("exe.file", true)] [DataRow("exe.sdfsfsdfsdfsdf", true)] [DataRow("file>1.exe", false)] [DataRow("file?1.ex'", false)] [DataTestMethod] public void IsValidFileName(string filePath, bool expected) { Assert.AreEqual(expected, filePath.IsValidFileName()); } [DataRow(null, true)] [DataRow("", false)] [DataRow("f", true)] [DataRow("file", true)] [DataRow("file.exe", true)] [DataRow("exe.file", true)] [DataRow(@"C:\Users\User1\source\repos\WpfApp1\WpfApp1\bin\Debug\file.exe", true)] [DataRow("exe.sdfsfsdfsdfsdf", true)] [DataRow("file>1.exe", false)] [DataRow("file|1.ex'", false)] [DataTestMethod] public void IsValidFilePath(string filePath, bool expected) { Assert.AreEqual(expected, filePath.IsValidFilePath()); } #endregion Public Methods } }
31.423913
90
0.534936
[ "MIT" ]
aljazsim/defensive-programming-framework-for-.net
Test/DefensiveProgrammingFramework.Test/File/IsExtensionsTest.cs
5,784
C#
namespace Mapbox.Unity.Map { using UnityEngine; public interface ITileProviderOptions { } public interface ICameraBoundsExtentOptions : ITileProviderOptions { void SetOptions(); } public class ExtentOptions : ITileProviderOptions { public virtual void SetOptions(ExtentOptions extentOptions) { } } }
15.333333
67
0.763975
[ "Apache-2.0" ]
483759/Next-Place
unity/NextPlace/Assets/Mapbox/Unity/DataContainers/ExtentOptions.cs
324
C#
#region License // Distributed under the BSD License // ================================= // // Copyright (c) 2010, Hadi Hariri // 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 Hadi Hariri 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 <COPYRIGHT HOLDER> 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. // ============================================================= // // // Parts of this Software use JsonFX Serialization Library which is distributed under the MIT License: // // Distributed under the terms of an MIT-style license: // // The MIT License // // Copyright (c) 2006-2009 Stephen M. McKamey // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using System.Net; using EasyHttp.Http; using EasyHttp.Specs.Helpers; using Machine.Specifications; namespace EasyHttp.Specs.Specs { [Subject("HttpClient")] public class when_making_any_type_of_request_to_invalid_host { Establish context = () => { httpClient = new HttpClient(); }; Because of = () => { exception = Catch.Exception( () => httpClient.Get("http://somethinginvalid") ); }; It should_throw_web_exception = () => exception.ShouldBeOfType<WebException>(); static HttpClient httpClient; static Exception exception; } [Subject("HttpClient")] public class when_making_a_DELETE_request_with_a_valid_uri { Establish context = () => { httpClient = new HttpClient { Request = {Accept = HttpContentTypes.ApplicationJson} }; // First create customer in order to then delete it guid = Guid.NewGuid(); httpClient.Put(string.Format("{0}/{1}", TestSettings.CouchDbDatabaseUrl, guid), new Customer() {Name = "ToDelete", Email = "test@test.com"}, HttpContentTypes.ApplicationJson); response = httpClient.Response; rev = response.DynamicBody.rev; }; Because of = () => { httpClient.Delete(String.Format("{0}/{1}?rev={2}", TestSettings.CouchDbDatabaseUrl, guid, rev)); response = httpClient.Response; }; It should_delete_the_specified_resource = () => { bool ok = response.DynamicBody.ok; string id = response.DynamicBody.id; ok.ShouldBeTrue(); id.ShouldNotBeEmpty(); }; static HttpClient httpClient; static dynamic response; static string rev; static Guid guid; } [Subject("HttpClient")] public class when_making_a_GET_request_with_valid_uri { Establish context = () => { httpClient = new HttpClient(); }; Because of = () => { httpResponse = httpClient.Get("http://localhost:5984"); }; It should_return_body_with_rawtext = () => httpResponse.RawText.ShouldNotBeEmpty(); static HttpClient httpClient; static HttpResponse httpResponse; } [Subject("HttpClient")] public class when_making_a_GET_request_with_valid_uri_and_content_type_set_to_application_json { Establish context = () => { httpClient = new HttpClient(); httpClient.Request.Accept = HttpContentTypes.ApplicationJson; }; Because of = () => { response = httpClient.Get(TestSettings.CouchDbRootUrl); }; It should_return_dynamic_body_with_json_object = () => { dynamic body = response.DynamicBody; string couchdb = body.couchdb; string version = body.version; couchdb.ShouldEqual("Welcome"); version.ShouldNotBeEmpty(); }; It should_return_static_body_with_json_object = () => { var couchInformation = response.StaticBody<CouchInformation>(); couchInformation.message.ShouldEqual("Welcome"); couchInformation.version.ShouldNotBeEmpty(); }; static HttpClient httpClient; static HttpResponse response; } [Subject("HttpClient")] public class when_making_a_HEAD_request_with_valid_uri { Establish context = () => { httpClient = new HttpClient(); }; Because of = () => { httpClient.Head(TestSettings.CouchDbRootUrl); httpResponse = httpClient.Response; }; It should_return_OK_response = () => httpResponse.StatusDescription.ShouldEqual("OK"); static HttpClient httpClient; static HttpResponse httpResponse; } [Subject("HttpClient")] public class when_making_a_POST_request_with_valid_uri_and_valid_data_and_content_type_set_to_application_json { Establish context = () => { httpClient = new HttpClient(); httpClient.Request.Accept = HttpContentTypes.ApplicationJson; }; Because of = () => { httpClient.Post(TestSettings.CouchDbDatabaseUrl, new Customer() { Name = "Hadi", Email = "test@test.com" }, HttpContentTypes.ApplicationJson); response = httpClient.Response; }; It should_succeed = () => { bool ok = response.DynamicBody.ok; string id = response.DynamicBody.id; ok.ShouldBeTrue(); id.ShouldNotBeEmpty(); }; static HttpClient httpClient; static dynamic response; } [Subject("HttpClient")] public class when_making_a_PUT_request_with_valid_uri_and_valid_data_and_content_type_set_to_application_json { Establish context = () => { httpClient = new HttpClient(); httpClient.Request.Accept = HttpContentTypes.ApplicationJson; }; Because of = () => { Guid guid = Guid.NewGuid(); httpClient.Put(string.Format("{0}/{1}", TestSettings.CouchDbDatabaseUrl, guid), new Customer() { Name = "Put", Email = "test@test.com" }, HttpContentTypes.ApplicationJson); response = httpClient.Response; }; It should_succeed = () => { bool ok = response.DynamicBody.ok; string id = response.DynamicBody.id; ok.ShouldBeTrue(); id.ShouldNotBeEmpty(); }; static HttpClient httpClient; static dynamic response; } }
31.486486
155
0.607296
[ "BSD-3-Clause" ]
holytshirt/EasyHttp
src/EasyHttp.Specs/Specs/HttpRequestSpecs.cs
9,322
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Actors; using Microsoft.ServiceFabric.Actors.Runtime; using Microsoft.ServiceFabric.Actors.Client; using Actor2.Interfaces; namespace Actor2 { /// <remarks> /// This class represents an actor. /// Every ActorID maps to an instance of this class. /// The StatePersistence attribute determines persistence and replication of actor state: /// - Persisted: State is written to disk and replicated. /// - Volatile: State is kept in memory only and replicated. /// - None: State is kept in memory only and not replicated. /// </remarks> [StatePersistence(StatePersistence.Persisted)] internal class Actor2 : Actor, IActor2 { /// <summary> /// Initializes a new instance of Actor /// </summary> /// <param name="actorService">The Microsoft.ServiceFabric.Actors.Runtime.ActorService that will host this actor instance.</param> /// <param name="actorId">The Microsoft.ServiceFabric.Actors.ActorId for this actor instance.</param> public Actor2(ActorService actorService, ActorId actorId) : base(actorService, actorId) { } /// <summary> /// This method is called whenever an actor is activated. /// An actor is activated the first time any of its methods are invoked. /// </summary> protected override Task OnActivateAsync() { ActorEventSource.Current.ActorMessage(this, "Actor activated."); // The StateManager is this actor's private state store. // Data stored in the StateManager will be replicated for high-availability for actors that use volatile or persisted state storage. // Any serializable object can be saved in the StateManager. // For more information, see https://aka.ms/servicefabricactorsstateserialization return this.StateManager.TryAddStateAsync("count", 0); } /// <summary> /// TODO: Replace with your own actor method. /// </summary> /// <returns></returns> Task<int> IActor2.GetCountAsync(CancellationToken cancellationToken) { return this.StateManager.GetStateAsync<int>("count", cancellationToken); } /// <summary> /// TODO: Replace with your own actor method. /// </summary> /// <param name="count"></param> /// <returns></returns> Task IActor2.SetCountAsync(int count, CancellationToken cancellationToken) { // Requests are not guaranteed to be processed in order nor at most once. // The update function here verifies that the incoming count is greater than the current count to preserve order. return this.StateManager.AddOrUpdateStateAsync("count", count, (key, value) => count > value ? count : value, cancellationToken); } } }
42.097222
144
0.657869
[ "MIT" ]
aL3891/ServiceFabricSdk-Contrib
TestSolution2/Actor/Actor.cs
3,033
C#
namespace Microsoft.ApplicationInsights.DataContracts { using System; /// <summary> /// Possible item types for sampling evaluation. /// </summary> [Flags] public enum SamplingTelemetryItemTypes { /// <summary> /// Unknown Telemetry Item Type /// </summary> None = 0, /// <summary> /// Event Telemetry type /// </summary> Event = 1, /// <summary> /// Exception Telemetry type /// </summary> Exception = 2, /// <summary> /// Message Telemetry type /// </summary> Message = 4, /// <summary> /// Metric Telemetry type /// </summary> Metric = 8, /// <summary> /// PageView Telemetry type /// </summary> PageView = 16, /// <summary> /// PageViewPerformance Telemetry type /// </summary> PageViewPerformance = 32, /// <summary> /// PerformanceCounter Telemetry type /// </summary> PerformanceCounter = 64, /// <summary> /// RemoteDependency Telemetry type /// </summary> RemoteDependency = 128, /// <summary> /// Request Telemetry type /// </summary> Request = 256, /// <summary> /// SessionState Telemetry type /// </summary> SessionState = 512, /// <summary> /// Availability Telemetry type /// </summary> Availability = 1024, } /// <summary> /// Represents sampling decision. /// </summary> public enum SamplingDecision { /// <summary> /// Sampling decision has not been made. /// </summary> None = 0, /// <summary> /// Item is sampled in. This may change as item flows through the pipeline. /// </summary> SampledIn = 1, /// <summary> /// Item is sampled out. This may not change. /// </summary> SampledOut = 2, } /// <summary> /// Represent objects that support advanced sampling features. /// </summary> public interface ISupportAdvancedSampling : ISupportSampling { /// <summary> /// Gets the flag indicating item's telemetry type to consider in sampling evaluation. /// </summary> SamplingTelemetryItemTypes ItemTypeFlag { get; } /// <summary> /// Gets or sets a value indicating whether item sampling decision was made pro-actively and result of this decision. /// </summary> SamplingDecision ProactiveSamplingDecision { get; set; } } }
24.833333
125
0.524609
[ "MIT" ]
304NotModified/ApplicationInsights-dotnet
BASE/src/Microsoft.ApplicationInsights/DataContracts/ISupportAdvancedSampling.cs
2,684
C#
namespace Lykke.OneSky.Json { public interface IAccount { string Name { get; } string ApiKey { get; } string ApiSecret { get; } } }
15.545455
34
0.54386
[ "MIT" ]
LykkeCity/Lykke.OneSky
OneSky.CSharp/OneSky.CSharp/Json/Objects/IAccount.cs
173
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.CommandLine; using System.CommandLine.Invocation; using System.Reflection; using System.Runtime.InteropServices; using System.Threading.Tasks; using Internal.IL; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.CommandLine; using System.Linq; using System.IO; namespace ILCompiler { internal class Program { private const string DefaultSystemModule = "System.Private.CoreLib"; private CommandLineOptions _commandLineOptions; public TargetOS _targetOS; public TargetArchitecture _targetArchitecture; public OptimizationMode _optimizationMode; private Dictionary<string, string> _inputFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private Dictionary<string, string> _referenceFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private Program(CommandLineOptions commandLineOptions) { _commandLineOptions = commandLineOptions; } private void Help(string helpText) { Console.WriteLine(); Console.Write("Microsoft (R) CoreCLR Native Image Generator"); Console.Write(" "); Console.Write(typeof(Program).GetTypeInfo().Assembly.GetName().Version); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(helpText); } private void InitializeDefaultOptions() { // We could offer this as a command line option, but then we also need to // load a different RyuJIT, so this is a future nice to have... if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) _targetOS = TargetOS.Windows; else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) _targetOS = TargetOS.Linux; else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) _targetOS = TargetOS.OSX; else throw new NotImplementedException(); switch (RuntimeInformation.ProcessArchitecture) { case Architecture.X86: _targetArchitecture = TargetArchitecture.X86; break; case Architecture.X64: _targetArchitecture = TargetArchitecture.X64; break; case Architecture.Arm: _targetArchitecture = TargetArchitecture.ARM; break; case Architecture.Arm64: _targetArchitecture = TargetArchitecture.ARM64; break; default: throw new NotImplementedException(); } // Workaround for https://github.com/dotnet/corefx/issues/25267 // If pointer size is 8, we're obviously not an X86 process... if (_targetArchitecture == TargetArchitecture.X86 && IntPtr.Size == 8) _targetArchitecture = TargetArchitecture.X64; } private void ProcessCommandLine() { AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName(); if (_commandLineOptions.WaitForDebugger) { Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue"); Console.ReadLine(); } if (_commandLineOptions.CompileBubbleGenerics) { if (!_commandLineOptions.InputBubble) { Console.WriteLine("Warning: ignoring --compilebubblegenerics because --inputbubble was not specified"); _commandLineOptions.CompileBubbleGenerics = false; } } _optimizationMode = OptimizationMode.None; if (_commandLineOptions.OptimizeSpace) { if (_commandLineOptions.OptimizeTime) Console.WriteLine("Warning: overriding -Ot with -Os"); _optimizationMode = OptimizationMode.PreferSize; } else if (_commandLineOptions.OptimizeTime) _optimizationMode = OptimizationMode.PreferSpeed; else if (_commandLineOptions.Optimize) _optimizationMode = OptimizationMode.Blended; foreach (var input in _commandLineOptions.InputFilePaths ?? Enumerable.Empty<FileInfo>()) Helpers.AppendExpandedPaths(_inputFilePaths, input.FullName, true); foreach (var reference in _commandLineOptions.Reference ?? Enumerable.Empty<string>()) Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false); } private int Run() { InitializeDefaultOptions(); ProcessCommandLine(); if (_commandLineOptions.OutputFilePath == null) throw new CommandLineException("Output filename must be specified (/out <file>)"); // // Set target Architecture and OS // if (_commandLineOptions.TargetArch != null) { if (_commandLineOptions.TargetArch.Equals("x86", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.X86; else if (_commandLineOptions.TargetArch.Equals("x64", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.X64; else if (_commandLineOptions.TargetArch.Equals("arm", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARM; else if (_commandLineOptions.TargetArch.Equals("armel", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARM; else if (_commandLineOptions.TargetArch.Equals("arm64", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARM64; else throw new CommandLineException("Target architecture is not supported"); } if (_commandLineOptions.TargetOS != null) { if (_commandLineOptions.TargetOS.Equals("windows", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.Windows; else if (_commandLineOptions.TargetOS.Equals("linux", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.Linux; else if (_commandLineOptions.TargetOS.Equals("osx", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.OSX; else throw new CommandLineException("Target OS is not supported"); } using (PerfEventSource.StartStopEvents.CompilationEvents()) { ICompilation compilation; using (PerfEventSource.StartStopEvents.LoadingEvents()) { // // Initialize type system context // SharedGenericsMode genericsMode = SharedGenericsMode.CanonicalReferenceTypes; var targetDetails = new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT, SimdVectorLength.None); CompilerTypeSystemContext typeSystemContext = new ReadyToRunCompilerContext(targetDetails, genericsMode); // // TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since // some tests contain a mixture of both managed and native binaries. // // See: https://github.com/dotnet/corert/issues/2785 // // When we undo this this hack, replace this foreach with // typeSystemContext.InputFilePaths = _inputFilePaths; // Dictionary<string, string> inputFilePaths = new Dictionary<string, string>(); foreach (var inputFile in _inputFilePaths) { try { var module = typeSystemContext.GetModuleFromPath(inputFile.Value); inputFilePaths.Add(inputFile.Key, inputFile.Value); } catch (TypeSystemException.BadImageFormatException) { // Keep calm and carry on. } } typeSystemContext.InputFilePaths = inputFilePaths; typeSystemContext.ReferenceFilePaths = _referenceFilePaths; string systemModuleName = _commandLineOptions.SystemModule ?? DefaultSystemModule; typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(systemModuleName)); if (typeSystemContext.InputFilePaths.Count == 0) throw new CommandLineException("No input files specified"); // // Initialize compilation group and compilation roots // // Single method mode? MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext); var logger = new Logger(Console.Out, _commandLineOptions.Verbose); List<ModuleDesc> referenceableModules = new List<ModuleDesc>(); foreach (var inputFile in inputFilePaths) { try { referenceableModules.Add(typeSystemContext.GetModuleFromPath(inputFile.Value)); } catch { } // Ignore non-managed pe files } foreach (var referenceFile in _referenceFilePaths.Values) { try { referenceableModules.Add(typeSystemContext.GetModuleFromPath(referenceFile)); } catch { } // Ignore non-managed pe files } ProfileDataManager profileDataManager = new ProfileDataManager(logger, referenceableModules); CompilationModuleGroup compilationGroup; List<ICompilationRootProvider> compilationRoots = new List<ICompilationRootProvider>(); if (singleMethod != null) { // Compiling just a single method compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod); compilationRoots.Add(new SingleMethodRootProvider(singleMethod)); } else { // Either single file, or multifile library, or multifile consumption. EcmaModule entrypointModule = null; foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (module.PEReader.PEHeaders.IsExe) { if (entrypointModule != null) throw new Exception("Multiple EXE modules"); entrypointModule = module; } } List<EcmaModule> inputModules = new List<EcmaModule>(); foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); compilationRoots.Add(new ReadyToRunRootProvider(module, profileDataManager)); inputModules.Add(module); if (!_commandLineOptions.InputBubble) { break; } } List<ModuleDesc> versionBubbleModules = new List<ModuleDesc>(); if (_commandLineOptions.InputBubble) { // In large version bubble mode add reference paths to the compilation group foreach (string referenceFile in _referenceFilePaths.Values) { try { // Currently SimpleTest.targets has no easy way to filter out non-managed assemblies // from the reference list. EcmaModule module = typeSystemContext.GetModuleFromPath(referenceFile); versionBubbleModules.Add(module); } catch (TypeSystemException.BadImageFormatException ex) { Console.WriteLine("Warning: cannot open reference assembly '{0}': {1}", referenceFile, ex.Message); } } } compilationGroup = new ReadyToRunSingleAssemblyCompilationModuleGroup( typeSystemContext, inputModules, versionBubbleModules, _commandLineOptions.CompileBubbleGenerics, _commandLineOptions.Partial ? profileDataManager : null); } // // Compile // string inputFilePath = ""; foreach (var input in typeSystemContext.InputFilePaths) { inputFilePath = input.Value; break; } CompilationBuilder builder = new ReadyToRunCodegenCompilationBuilder(typeSystemContext, compilationGroup, inputFilePath, ibcTuning: _commandLineOptions.Tuning, resilient: _commandLineOptions.Resilient); string compilationUnitPrefix = ""; builder.UseCompilationUnitPrefix(compilationUnitPrefix); ILProvider ilProvider = new ReadyToRunILProvider(); DependencyTrackingLevel trackingLevel = _commandLineOptions.DgmlLogFileName == null ? DependencyTrackingLevel.None : (_commandLineOptions.GenerateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); builder .UseILProvider(ilProvider) .UseJitPath(_commandLineOptions.JitPath) .UseBackendOptions(_commandLineOptions.CodegenOptions) .UseLogger(logger) .UseDependencyTracking(trackingLevel) .UseCompilationRoots(compilationRoots) .UseOptimizationMode(_optimizationMode); compilation = builder.ToCompilation(); } compilation.Compile(_commandLineOptions.OutputFilePath.FullName); if (_commandLineOptions.DgmlLogFileName != null) compilation.WriteDependencyLog(_commandLineOptions.DgmlLogFileName.FullName); } return 0; } private TypeDesc FindType(CompilerTypeSystemContext context, string typeName) { ModuleDesc systemModule = context.SystemModule; TypeDesc foundType = systemModule.GetTypeByCustomAttributeTypeName(typeName, false, (typeDefName, module, throwIfNotFound) => { return (MetadataType)context.GetCanonType(typeDefName) ?? CustomAttributeTypeNameParser.ResolveCustomAttributeTypeDefinitionName(typeDefName, module, throwIfNotFound); }); if (foundType == null) throw new CommandLineException($"Type '{typeName}' not found"); return foundType; } private MethodDesc CheckAndParseSingleMethodModeArguments(CompilerTypeSystemContext context) { if (_commandLineOptions.SingleMethodName == null && _commandLineOptions.SingleMethodTypeName == null && _commandLineOptions.SingleMethodGenericArgs == null) return null; if (_commandLineOptions.SingleMethodName == null || _commandLineOptions.SingleMethodTypeName == null) throw new CommandLineException("Both method name and type name are required parameters for single method mode"); TypeDesc owningType = FindType(context, _commandLineOptions.SingleMethodTypeName); // TODO: allow specifying signature to distinguish overloads MethodDesc method = owningType.GetMethod(_commandLineOptions.SingleMethodName, null); if (method == null) throw new CommandLineException($"Method '{_commandLineOptions.SingleMethodName}' not found in '{_commandLineOptions.SingleMethodTypeName}'"); if (method.HasInstantiation != (_commandLineOptions.SingleMethodGenericArgs != null) || (method.HasInstantiation && (method.Instantiation.Length != _commandLineOptions.SingleMethodGenericArgs.Length))) { throw new CommandLineException( $"Expected {method.Instantiation.Length} generic arguments for method '{_commandLineOptions.SingleMethodName}' on type '{_commandLineOptions.SingleMethodTypeName}'"); } if (method.HasInstantiation) { List<TypeDesc> genericArguments = new List<TypeDesc>(); foreach (var argString in _commandLineOptions.SingleMethodGenericArgs) genericArguments.Add(FindType(context, argString)); method = method.MakeInstantiatedMethod(genericArguments.ToArray()); } return method; } private static bool DumpReproArguments(CodeGenerationFailedException ex) { Console.WriteLine("To repro, add following arguments to the command line:"); MethodDesc failingMethod = ex.Method; var formatter = new CustomAttributeTypeNameFormatter((IAssemblyDesc)failingMethod.Context.SystemModule); Console.Write($"--singlemethodtypename \"{formatter.FormatName(failingMethod.OwningType, true)}\""); Console.Write($" --singlemethodname {failingMethod.Name}"); for (int i = 0; i < failingMethod.Instantiation.Length; i++) Console.Write($" --singlemethodgenericarg \"{formatter.FormatName(failingMethod.Instantiation[i], true)}\""); return false; } public static async Task<int> Main(string[] args) { var command = CommandLineOptions.RootCommand(); command.Handler = CommandHandler.Create<CommandLineOptions>((CommandLineOptions options) => InnerMain(options)); return await command.InvokeAsync(args); } private static int InnerMain(CommandLineOptions buildOptions) { #if DEBUG try { return new Program(buildOptions).Run(); } catch (CodeGenerationFailedException ex) when (DumpReproArguments(ex)) { throw new NotSupportedException(); // Unreachable } #else try { return new Program(buildOptions).Run(); } catch (Exception e) { Console.Error.WriteLine("Error: " + e.Message); Console.Error.WriteLine(e.ToString()); return 1; } #endif } } }
46.031461
186
0.570152
[ "MIT" ]
AndyAyersMS/coreclr
src/tools/crossgen2/crossgen2/Program.cs
20,484
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 DocumentSerialization.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; } } } }
34.709677
151
0.585502
[ "MIT" ]
21pages/WPF-Samples
Documents/Fixed Documents/DocumentSerialization/Properties/Settings.Designer.cs
1,078
C#
using DotNetBungieAPI.Attributes; using DotNetBungieAPI.Models.Destiny.Definitions.Common; namespace DotNetBungieAPI.Models.Destiny.Definitions.Bonds; [DestinyDefinition(DefinitionsEnum.DestinyBondDefinition)] public sealed record DestinyBondDefinition : IDestinyDefinition, IDeepEquatable<DestinyBondDefinition> { [JsonPropertyName("displayProperties")] public DestinyDisplayPropertiesDefinition DisplayProperties { get; init; } [JsonPropertyName("providedUnlockHash")] public uint ProvidedUnlockHash { get; init; } [JsonPropertyName("providedUnlockValueHash")] public uint ProvidedUnlockValueHash { get; init; } public bool DeepEquals(DestinyBondDefinition other) { return other != null && DisplayProperties.DeepEquals(other.DisplayProperties) && ProvidedUnlockHash == other.ProvidedUnlockHash && ProvidedUnlockValueHash == other.ProvidedUnlockValueHash && Blacklisted == other.Blacklisted && Hash == other.Hash && Index == other.Index && Redacted == other.Redacted; } public DefinitionsEnum DefinitionEnumValue => DefinitionsEnum.DestinyBondDefinition; [JsonPropertyName("blacklisted")] public bool Blacklisted { get; init; } [JsonPropertyName("hash")] public uint Hash { get; init; } [JsonPropertyName("index")] public int Index { get; init; } [JsonPropertyName("redacted")] public bool Redacted { get; init; } public void MapValues() { } public void SetPointerLocales(BungieLocales locale) { } }
34.891304
102
0.703427
[ "MIT" ]
EndGameGl/.NetBungieAPI
DotNetBungieAPI/Models/Destiny/Definitions/Bonds/DestinyBondDefinition.cs
1,607
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201 { using Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell; /// <summary>The properties used to create a new server.</summary> [System.ComponentModel.TypeConverter(typeof(ServerPropertiesForCreateTypeConverter))] public partial class ServerPropertiesForCreate { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerPropertiesForCreate" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreate" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreate DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new ServerPropertiesForCreate(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerPropertiesForCreate" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreate" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new ServerPropertiesForCreate(content); } /// <summary> /// Creates a new instance of <see cref="ServerPropertiesForCreate" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerPropertiesForCreate" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal ServerPropertiesForCreate(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfile = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IStorageProfile) content.GetValueForProperty("StorageProfile",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfile, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.StorageProfileTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).Version = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion?) content.GetValueForProperty("Version",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).Version, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).SslEnforcement = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum?) content.GetValueForProperty("SslEnforcement",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).SslEnforcement, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).MinimalTlsVersion = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum?) content.GetValueForProperty("MinimalTlsVersion",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).MinimalTlsVersion, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).InfrastructureEncryption = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.InfrastructureEncryption?) content.GetValueForProperty("InfrastructureEncryption",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).InfrastructureEncryption, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.InfrastructureEncryption.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).PublicNetworkAccess = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum?) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).PublicNetworkAccess, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreateMode) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreateMode.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileStorageAutogrow = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow?) content.GetValueForProperty("StorageProfileStorageAutogrow",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileStorageAutogrow, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileBackupRetentionDay = (int?) content.GetValueForProperty("StorageProfileBackupRetentionDay",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileBackupRetentionDay, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileGeoRedundantBackup = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup?) content.GetValueForProperty("StorageProfileGeoRedundantBackup",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileGeoRedundantBackup, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileStorageMb = (int?) content.GetValueForProperty("StorageProfileStorageMb",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileStorageMb, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ServerPropertiesForCreate" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal ServerPropertiesForCreate(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfile = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IStorageProfile) content.GetValueForProperty("StorageProfile",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfile, Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.StorageProfileTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).Version = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion?) content.GetValueForProperty("Version",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).Version, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.ServerVersion.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).SslEnforcement = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum?) content.GetValueForProperty("SslEnforcement",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).SslEnforcement, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.SslEnforcementEnum.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).MinimalTlsVersion = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum?) content.GetValueForProperty("MinimalTlsVersion",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).MinimalTlsVersion, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.MinimalTlsVersionEnum.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).InfrastructureEncryption = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.InfrastructureEncryption?) content.GetValueForProperty("InfrastructureEncryption",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).InfrastructureEncryption, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.InfrastructureEncryption.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).PublicNetworkAccess = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum?) content.GetValueForProperty("PublicNetworkAccess",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).PublicNetworkAccess, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.PublicNetworkAccessEnum.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).CreateMode = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreateMode) content.GetValueForProperty("CreateMode",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).CreateMode, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.CreateMode.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileStorageAutogrow = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow?) content.GetValueForProperty("StorageProfileStorageAutogrow",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileStorageAutogrow, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.StorageAutogrow.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileBackupRetentionDay = (int?) content.GetValueForProperty("StorageProfileBackupRetentionDay",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileBackupRetentionDay, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileGeoRedundantBackup = (Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup?) content.GetValueForProperty("StorageProfileGeoRedundantBackup",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileGeoRedundantBackup, Microsoft.Azure.PowerShell.Cmdlets.MySql.Support.GeoRedundantBackup.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileStorageMb = (int?) content.GetValueForProperty("StorageProfileStorageMb",((Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerPropertiesForCreateInternal)this).StorageProfileStorageMb, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// The properties used to create a new server. [System.ComponentModel.TypeConverter(typeof(ServerPropertiesForCreateTypeConverter))] public partial interface IServerPropertiesForCreate { } }
116.07947
502
0.775844
[ "MIT" ]
3quanfeng/azure-powershell
src/MySql/generated/api/Models/Api20171201/ServerPropertiesForCreate.PowerShell.cs
17,378
C#
// Copyright 2018 Google Inc. 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. using Google.Cloud.ClientTesting; using System; using System.Collections.Generic; using System.Linq; using Xunit; using static Google.Apis.Bigquery.v2.JobsResource.ListRequest; namespace Google.Cloud.BigQuery.V2.Snippets { [SnippetOutputCollector] [Collection(nameof(BigQuerySnippetFixture))] public class JobCreationOptionsSnippets { private readonly BigQuerySnippetFixture _fixture; public JobCreationOptionsSnippets(BigQuerySnippetFixture fixture) { _fixture = fixture; } [Fact] public void ListJobs_FilterByLabels() { string bucketName = _fixture.StorageBucketName; string objectName = _fixture.GenerateStorageObjectName(); string projectId = _fixture.ProjectId; string datasetId = _fixture.GameDatasetId; string tableId = _fixture.HistoryTableId; // Snippet: Labels IDictionary<string, string> labels = new Dictionary<string, string>() { {"label-key", "label-value" } }; BigQueryClient client = BigQueryClient.Create(projectId); BigQueryTable table = client.GetTable(projectId, datasetId, tableId); string destinationUri = $"gs://{bucketName}/{objectName}"; // Just a couple examples of jobs marked with labels: // (These jobs will most certainly be created somewhere else.) // Running a query on a given table. BigQueryJob oneLabeledJob = client.CreateQueryJob( $"SELECT * FROM {table}", null, new QueryOptions { Labels = labels }); // Extracting data from a table to GCS. BigQueryJob anotherLabeledJob = client.CreateExtractJob( projectId, datasetId, tableId, destinationUri, new CreateExtractJobOptions { Labels = labels }); // Find jobs marked with a certain label. KeyValuePair<string, string> labelToBeFound = labels.First(); // Specify full projection to make sure that // label information, if it exists, is returned for listed jobs. ListJobsOptions options = new ListJobsOptions { Projection = ProjectionEnum.Full }; List <BigQueryJob> jobs = client .ListJobs(options) .Where(job => job.Resource.Configuration.Labels?.Contains(labelToBeFound) ?? false) .Take(2) .ToList(); foreach (BigQueryJob job in jobs) { Console.WriteLine(job.Reference.JobId); } // End snippet // This test added two jobs with such labels, other tests might have // added more. Assert.True(jobs.Count >= 2); } } }
39.397727
99
0.629651
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.BigQuery.V2/Google.Cloud.BigQuery.V2.Snippets/JobCreationOptionsSnippets.cs
3,469
C#
using DCSoft.Common; using DCSoft.Drawing; using DCSoft.Printing; using DCSoftDotfuscate; using Microsoft.VisualBasic; using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.Runtime.InteropServices; using System.Xml.Serialization; namespace DCSoft.Writer.Dom { /// <summary> /// 文档正文对象 /// </summary> [Serializable] [Guid("0E4176E5-848F-4ECA-A911-47354EDBABD2")] [ClassInterface(ClassInterfaceType.None)] [ComVisible(true)] [ComDefaultInterface(typeof(IXTextDocumentBodyElement))] [DCPublishAPI] [DebuggerDisplay("Body :{ PreviewString }")] [ComClass("0E4176E5-848F-4ECA-A911-47354EDBABD2", "8E21E3CD-581D-4A91-947F-DEFE29EDEE04")] [XmlType("XTextBody")] [DocumentComment] public sealed class XTextDocumentBodyElement : XTextDocumentContentElement, IXTextDocumentBodyElement { internal const string string_14 = "0E4176E5-848F-4ECA-A911-47354EDBABD2"; internal const string string_15 = "8E21E3CD-581D-4A91-947F-DEFE29EDEE04"; [DCInternal] public override string DomDisplayName => "Body"; [DCPublishAPI] public override PageContentPartyStyle ContentPartyStyle => PageContentPartyStyle.Body; /// <summary> /// 返回页面设置中的网格线设置 /// </summary> [XmlIgnore] [Editor(typeof(DCGridLineInfoForPageSettingsUIEditor), typeof(UITypeEditor))] [Browsable(false)] [DCInternal] public override DCGridLineInfo GridLine { get { if (OwnerDocument != null) { return OwnerDocument.PageSettings.RuntimeDocumentGridLine; } return null; } set { } } internal override DCGridLineInfo RuntimeGridLine { get { if (!XTextDocument.smethod_13(GEnum6.const_33)) { return null; } if (OwnerDocument != null) { return OwnerDocument.PageSettings.RuntimeDocumentGridLine; } return null; } } public override float AbsTop { get { XTextDocument ownerDocument = OwnerDocument; if (ownerDocument == null) { return 0f; } return ownerDocument.BodyLayoutOffset + ownerDocument.Top; } } /// <summary> /// 高度 /// </summary> [XmlIgnore] [DCPublishAPI] public override float Height { get { return base.Height; } set { if (base.Height != value) { base.Height = value; } } } /// <summary> /// 获得预览文本 /// </summary> [DCInternal] public override string PreviewString => "Body:" + base.PreviewString; /// <summary> /// 所有的文档节列表 /// </summary> [DCPublishAPI] [Browsable(false)] [XmlIgnore] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public XTextElementList Sections { get { XTextElementList xTextElementList = new XTextElementList(); foreach (XTextElement element in Elements) { if (element is XTextSectionElement) { xTextElementList.Add(element); } } return xTextElementList; } } /// <summary> /// 返回BODY样式 /// </summary> [Browsable(false)] [DCPublishAPI] public override PageContentPartyStyle PagePartyStyle => PageContentPartyStyle.Body; /// <summary> /// 初始化对象 /// </summary> [DCInternal] public XTextDocumentBodyElement() { } /// <summary> /// 获得最后一页中剩余的空白高度,单位是1/300英寸。 /// </summary> /// <returns> /// </returns> [ComVisible(true)] [DCPublishAPI] public float GetRemainSpacingInLastPage() { PrintPage lastPage = OwnerDocument.Pages.LastPage; return lastPage.Top + lastPage.StandartPapeBodyHeight - base.Bottom; } [DCInternal] public bool method_75(DocumentRenderMode documentRenderMode_0) { if (RuntimeGridLine != null && RuntimeGridLine.Visible && RuntimeGridLine.RuntimeGridSpan > 0f) { return true; } bool result = false; if (OwnerDocument.Options.ViewOptions.ShowGridLine) { result = true; if ((documentRenderMode_0 == DocumentRenderMode.Print || documentRenderMode_0 == DocumentRenderMode.ReadPaint) && !OwnerDocument.Options.ViewOptions.PrintGridLine) { result = false; } } return result; } /// <summary> /// 绘制内容 /// </summary> /// <param name="args">参数</param> public override void DrawContent(DocumentPaintEventArgs args) { if (base.PrivateLines == null || base.PrivateLines.Count == 0) { return; } bool flag = method_75(args.RenderMode); base.LineNumberDisplayArea = RectangleF.Empty; if (args.RenderMode == DocumentRenderMode.Paint && OwnerDocument.Options.ViewOptions.ShowLineNumber) { float num = 150f; RectangleF rectangleF = new RectangleF(-150f, args.ClipRectangle.Top, num, args.ClipRectangle.Height); using (DrawStringFormatExt drawStringFormatExt = new DrawStringFormatExt()) { drawStringFormatExt.Alignment = StringAlignment.Center; drawStringFormatExt.LineAlignment = StringAlignment.Center; drawStringFormatExt.FormatFlags = StringFormatFlags.NoWrap; XFontValue font = OwnerDocument.ContentStyles.Default.Font; PrintPage printPage = null; int num2 = 0; foreach (XTextLine privateLine in base.PrivateLines) { RectangleF rectangleF2 = new RectangleF(0f - num, privateLine.AbsTop, num, privateLine.Height); if (!args.PageClipRectangle.IsEmpty) { if (args.PageClipRectangle.Top > rectangleF2.Top + 20f) { continue; } float num3 = Math.Min(args.PageClipRectangle.Bottom, rectangleF2.Bottom); float num5 = rectangleF2.Y = Math.Max(args.PageClipRectangle.Top, rectangleF2.Top); rectangleF2.Height = num3 - num5; } if (RectangleF.Intersect(args.ClipRectangle, rectangleF2).Height > 5f) { if (printPage != privateLine.OwnerPage) { num2 = 0; printPage = privateLine.OwnerPage; } int privateIndexInPage = privateLine.PrivateIndexInPage; if (privateLine.IsPageBreakLine) { num2++; } else { args.Graphics.DrawString(Convert.ToString(privateIndexInPage - num2), font, Color.Black, rectangleF2, drawStringFormatExt); } } } } } DocumentPaintEventArgs args2 = args.Clone(); if (flag) { RectangleF absBounds = AbsBounds; if (args.ViewMode == PageViewMode.Page) { PrintPage printPage = args.Page; float top = args.ClipRectangle.Top; float num6 = printPage.StandartPapeBodyHeight; if (OwnerDocument.Footer.Height > OwnerDocument.PageSettings.ViewFooterHeight) { num6 -= OwnerDocument.Footer.Height - OwnerDocument.PageSettings.ViewFooterHeight; } float num7 = printPage.Top + num6; if (args.RenderMode == DocumentRenderMode.Print) { JumpPrintInfo jumpPrintInfo = null; if (args.Options != null) { jumpPrintInfo = args.Options.JumpPrint; } if (jumpPrintInfo != null && jumpPrintInfo.NativeEndPosition > 0f) { num7 = Math.Min(jumpPrintInfo.NativeEndPosition, num7); } } absBounds.Height = num7 - absBounds.Top; args.ClipRectangle = new RectangleF(absBounds.Left, top + 3f, absBounds.Width, num7 - top - 3f); if (args.Graphics != null) { args.Graphics.ResetClip(); } } args.ViewBounds = absBounds; args.ClientViewBounds = RuntimeStyle.GetClientRectangleF(absBounds); if (!base.HasVisibleDCGridLine) { method_48(args, OwnerDocument.Options.ViewOptions.GridLineColor, bool_22: false, args.ViewMode == PageViewMode.Page, bool_24: true, OwnerDocument.Options.ViewOptions.SpecifyExtenGridLineStep, 0f, 0f, OwnerDocument.Options.ViewOptions.GridLineStyle, bool_25: false); } } base.DrawContent(args2); } /// <summary> /// 获得指定页中包含的文档行对象集合 /// </summary> /// <param name="page">文档页对象</param> /// <returns>文档行对象集合</returns> public XTextLineList GetLinesInPage(PrintPage page) { XTextLineList xTextLineList = new XTextLineList(); foreach (XTextLine line in base.Lines) { if (line.OwnerPage == page) { xTextLineList.Add(line); } } return xTextLineList; } /// <summary> /// 获得指定页中包含的文档行对象集合 /// </summary> /// <param name="pageIndex">页码数,从1开始计算</param> /// <returns>文档行对象集合</returns> public XTextLineList GetLinesInPageIndex(int pageIndex) { pageIndex--; if (pageIndex >= 0 && pageIndex < OwnerDocument.Pages.Count) { return GetLinesInPage(OwnerDocument.Pages[pageIndex]); } return null; } /// <summary> /// 返回调试时显示的文本 /// </summary> /// <returns>文本</returns> [DCInternal] public override string ToDebugString() { int num = 1; string text = "Body"; if (OwnerDocument != null) { text = text + ":" + OwnerDocument.RuntimeTitle; } return text; } } }
26.328402
270
0.663895
[ "MIT" ]
h1213159982/HDF
Example/WinForm/Editor/DCWriter/DCSoft.Writer.Cleaned/DCSoft.Writer.Dom/XTextDocumentBodyElement.cs
9,185
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using Microsoft.Azure.Commands.Dns.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Internal.Network.Common; using ProjectResources = Microsoft.Azure.Commands.Dns.Properties.Resources; namespace Microsoft.Azure.Commands.Dns { /// <summary> /// Updates an existing zone. /// </summary> [Cmdlet("Set", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DnsZone", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium, DefaultParameterSetName = FieldsIdsParameterSetName), OutputType(typeof(DnsZone))] public class SetAzureDnsZone : DnsBaseCmdlet { private const string FieldsIdsParameterSetName = "Fields"; private const string FieldsObjectsParameterSetName = "FieldsObjects"; private const string ObjectParameterSetName = "Object"; [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The full name of the zone (without a terminating dot).", ParameterSetName = FieldsIdsParameterSetName)] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The full name of the zone (without a terminating dot).", ParameterSetName = FieldsObjectsParameterSetName)] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group in which the zone exists.", ParameterSetName = FieldsIdsParameterSetName)] [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group in which the zone exists.", ParameterSetName = FieldsObjectsParameterSetName)] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Alias("Tags")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource tags.", ParameterSetName = FieldsIdsParameterSetName)] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource tags.", ParameterSetName = FieldsObjectsParameterSetName)] public Hashtable Tag { get; set; } [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of virtual network ids that will register virtual machine hostnames records in this DNS zone, only available for private zones.", ParameterSetName = FieldsIdsParameterSetName)] [ValidateNotNull] public List<string> RegistrationVirtualNetworkId { get; set; } [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of virtual network ids able to resolve records in this DNS zone, only available for private zones.", ParameterSetName = FieldsIdsParameterSetName)] [ValidateNotNull] public List<string> ResolutionVirtualNetworkId { get; set; } [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of virtual networks that will register virtual machine hostnames records in this DNS zone, only available for private zones.", ParameterSetName = FieldsObjectsParameterSetName)] [ValidateNotNull] public List<IResourceReference> RegistrationVirtualNetwork { get; set; } [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of virtual networks able to resolve records in this DNS zone, only available for private zones.", ParameterSetName = FieldsObjectsParameterSetName)] [ValidateNotNull] public List<IResourceReference> ResolutionVirtualNetwork { get; set; } [Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The zone object to set.", ParameterSetName = ObjectParameterSetName)] [ValidateNotNullOrEmpty] public DnsZone Zone { get; set; } [Parameter(Mandatory = false, HelpMessage = "Do not use the ETag field of the RecordSet parameter for optimistic concurrency checks.", ParameterSetName = ObjectParameterSetName)] public SwitchParameter Overwrite { get; set; } public override void ExecuteCmdlet() { DnsZone result = null; DnsZone zoneToUpdate = null; if (this.ParameterSetName == FieldsIdsParameterSetName || this.ParameterSetName == FieldsObjectsParameterSetName) { if (this.Name.EndsWith(".")) { this.Name = this.Name.TrimEnd('.'); this.WriteWarning(string.Format("Modifying zone name to remove terminating '.'. Zone name used is \"{0}\".", this.Name)); } zoneToUpdate = this.DnsClient.GetDnsZone(this.Name, this.ResourceGroupName); zoneToUpdate.Etag = "*"; zoneToUpdate.Tags = this.Tag; if (this.ParameterSetName == FieldsIdsParameterSetName) { // Change mutable fields if value is passed if (this.RegistrationVirtualNetworkId != null) { zoneToUpdate.RegistrationVirtualNetworkIds = this.RegistrationVirtualNetworkId; } if (this.ResolutionVirtualNetworkId != null) { zoneToUpdate.ResolutionVirtualNetworkIds = this.ResolutionVirtualNetworkId; } } else { // Change mutable fields if value is passed if (this.RegistrationVirtualNetwork != null) { zoneToUpdate.RegistrationVirtualNetworkIds = this.RegistrationVirtualNetwork.Select(virtualNetwork => virtualNetwork.Id).ToList(); } if (this.ResolutionVirtualNetwork != null) { zoneToUpdate.ResolutionVirtualNetworkIds = this.ResolutionVirtualNetwork.Select(virtualNetwork => virtualNetwork.Id).ToList(); } } } else if (this.ParameterSetName == ObjectParameterSetName) { if ((string.IsNullOrWhiteSpace(this.Zone.Etag) || this.Zone.Etag == "*") && !this.Overwrite.IsPresent) { throw new PSArgumentException(string.Format(ProjectResources.Error_EtagNotSpecified, typeof(DnsZone).Name)); } zoneToUpdate = this.Zone; } if (zoneToUpdate.Name != null && zoneToUpdate.Name.EndsWith(".")) { zoneToUpdate.Name = zoneToUpdate.Name.TrimEnd('.'); this.WriteWarning(string.Format("Modifying zone name to remove terminating '.'. Zone name used is \"{0}\".", zoneToUpdate.Name)); } ConfirmAction( ProjectResources.Progress_Modifying, zoneToUpdate.Name, () => { bool overwrite = this.Overwrite.IsPresent || this.ParameterSetName != ObjectParameterSetName; result = this.DnsClient.UpdateDnsZone(zoneToUpdate, overwrite); WriteVerbose(ProjectResources.Success); WriteObject(result); }); } } }
56.812081
280
0.639102
[ "MIT" ]
3quanfeng/azure-powershell
src/Dns/Dns/Zones/SetAzureDnsZone.cs
8,319
C#
//---------------------------------------------------------------------------------------------- // <copyright file="HttpMultipartFileContent.cs" company="Microsoft Corporation"> // Licensed under the MIT License. See LICENSE.TXT in the project root license information. // </copyright> //---------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Foundation; using Windows.Storage.Streams; using Windows.Web.Http; using Windows.Web.Http.Headers; namespace Microsoft.Tools.WindowsDevicePortal { /// <summary> /// This class mimicks <see cref="HttpMultipartContent"/>, with two main differences /// 1. Simplifies posting files by taking file names instead of managing streams. /// 2. Does not quote the boundaries, due to a bug in the device portal /// </summary> internal sealed class HttpMultipartFileContent : IHttpContent { /// <summary> /// List of items to transfer /// </summary> private List<string> items = new List<string>(); /// <summary> /// Boundary string /// </summary> private string boundaryString; /// <summary> /// Initializes a new instance of the <see cref="HttpMultipartFileContent" /> class. /// </summary> public HttpMultipartFileContent() : this(Guid.NewGuid().ToString()) { } /// <summary> /// Initializes a new instance of the <see cref="HttpMultipartFileContent" /> class. /// </summary> /// <param name="boundary">The boundary string for file content.</param> public HttpMultipartFileContent(string boundary) { this.boundaryString = boundary; this.Headers.ContentType = new HttpMediaTypeHeaderValue(string.Format("multipart/form-data; boundary={0}", this.boundaryString)); } /// <summary> /// Gets the Http Headers /// </summary> public HttpContentHeaderCollection Headers { get; } = new HttpContentHeaderCollection(); /// <summary> /// Adds a file to the list of items to transfer /// </summary> /// <param name="filename">The name of the file to add</param> public void Add(string filename) { if (filename != null) { this.items.Add(filename); } } /// <summary> /// Adds a range of files to the list of items to transfer /// </summary> /// <param name="filenames">List of files to add</param> public void AddRange(IEnumerable<string> filenames) { if (filenames != null) { this.items.AddRange(filenames); } } /// <summary> /// This method is unimplemented. /// </summary> /// <returns>Throws an exception</returns> IAsyncOperationWithProgress<ulong, ulong> IHttpContent.BufferAllAsync() { throw new NotImplementedException(); } /// <summary> /// Dispose method for cleanup /// </summary> void IDisposable.Dispose() { this.items.Clear(); } /// <summary> /// This method is unimplemented. /// </summary> /// <returns>Throws an exception</returns> IAsyncOperationWithProgress<IBuffer, ulong> IHttpContent.ReadAsBufferAsync() { throw new NotImplementedException(); } /// <summary> /// This method is unimplemented. /// </summary> /// <returns>Throws an exception</returns> IAsyncOperationWithProgress<IInputStream, ulong> IHttpContent.ReadAsInputStreamAsync() { throw new NotImplementedException(); } /// <summary> /// This method is unimplemented. /// </summary> /// <returns>Throws an exception</returns> IAsyncOperationWithProgress<string, ulong> IHttpContent.ReadAsStringAsync() { throw new NotImplementedException(); } /// <summary> /// Computes required length for the transfer. /// </summary> /// <param name="length">The computed length value</param> /// <returns>Whether or not the length was successfully computed</returns> bool IHttpContent.TryComputeLength(out ulong length) { length = 0; var boundaryLength = Encoding.ASCII.GetBytes(string.Format("--{0}\r\n", this.boundaryString)).Length; foreach (var item in this.items) { var headerdata = GetFileHeader(new FileInfo(item)); length += (ulong)(boundaryLength + headerdata.Length + new FileInfo(item).Length + 2); } length += (ulong)(boundaryLength + 2); return true; } /// <summary> /// Serializes the stream. /// </summary> /// <param name="outputStream">Serialized Stream</param> /// <returns>Task tracking progress</returns> IAsyncOperationWithProgress<ulong, ulong> IHttpContent.WriteToStreamAsync(IOutputStream outputStream) { return System.Runtime.InteropServices.WindowsRuntime.AsyncInfo.Run<ulong, ulong>((token, progress) => { return WriteToStreamAsyncTask(outputStream, (ulong p) => progress.Report(p)); }); } /// <summary> /// Gets the file header for the transfer /// </summary> /// <param name="info">Information about the file</param> /// <returns>A byte array with the file header information</returns> private static byte[] GetFileHeader(FileInfo info) { string contentType = "application/octet-stream"; if (info.Extension.ToLower() == ".cer") { contentType = "application/x-x509-ca-cert"; } return Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n", info.Name, contentType)); } /// <summary> /// Serializes the stream. /// </summary> /// <param name="outputStream">Serialized Stream</param> /// <param name="progress">Progress tracking</param> /// <returns>Task tracking progress</returns> private async Task<ulong> WriteToStreamAsyncTask(IOutputStream outputStream, Action<ulong> progress) { ulong bytesWritten = 0; var outStream = outputStream.AsStreamForWrite(); var boundary = Encoding.ASCII.GetBytes($"--{boundaryString}\r\n"); var newline = Encoding.ASCII.GetBytes("\r\n"); foreach (var item in this.items) { outStream.Write(boundary, 0, boundary.Length); bytesWritten += (ulong)boundary.Length; var headerdata = GetFileHeader(new FileInfo(item)); outStream.Write(headerdata, 0, headerdata.Length); bytesWritten += (ulong)headerdata.Length; using (var file = File.OpenRead(item)) { await file.CopyToAsync(outStream); bytesWritten += (ulong)file.Position; } outStream.Write(newline, 0, newline.Length); bytesWritten += (ulong)newline.Length; await outStream.FlushAsync(); progress(bytesWritten); } // Close the installation request data. boundary = Encoding.ASCII.GetBytes($"--{boundaryString}--\r\n"); outStream.Write(boundary, 0, boundary.Length); await outStream.FlushAsync(); bytesWritten += (ulong)boundary.Length; return bytesWritten; } } }
37.427907
177
0.564185
[ "MIT" ]
ConnectionMaster/WindowsDevicePortalWrapper
WindowsDevicePortalWrapper/WindowsDevicePortalWrapper.UniversalWindows/HttpRest/HttpMultipartFileContent.cs
8,049
C#
/* * Copyright 2019 Samsung Electronics Co., Ltd. All rights reserved. * * Licensed under the Flora License, Version 1.1 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://floralicense.org/license * * 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.Windows.Input; using Xamarin.Forms; namespace GestureSensor.Tizen.Wearable.Controls { /// <summary> /// Masked image with press, release and tap handling. /// </summary> public class MaskedImageButton : MaskedImage { /// <summary> /// Backing store for the Command bindable property. /// </summary> public static readonly BindableProperty CommandProperty = BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(MaskedImageButton), null); /// <summary> /// Backing store for the PressCommand bindable property. /// </summary> public static readonly BindableProperty PressCommandProperty = BindableProperty.Create(nameof(PressCommand), typeof(ICommand), typeof(MaskedImageButton), null); /// <summary> /// Backing store for the Command bindable property. /// </summary> public static readonly BindableProperty ReleaseCommandProperty = BindableProperty.Create(nameof(ReleaseCommand), typeof(ICommand), typeof(MaskedImageButton), null); /// <summary> /// Gets or sets command executed on click. /// </summary> public ICommand Command { get => (ICommand)GetValue(CommandProperty); set => SetValue(CommandProperty, value); } /// <summary> /// Gets or sets command executed on press. /// </summary> public ICommand PressCommand { get => (ICommand)GetValue(PressCommandProperty); set => SetValue(PressCommandProperty, value); } /// <summary> /// Gets or sets command executed on release. /// </summary> public ICommand ReleaseCommand { get => (ICommand)GetValue(ReleaseCommandProperty); set => SetValue(ReleaseCommandProperty, value); } } }
35.013699
111
0.644366
[ "Apache-2.0" ]
AchoWang/Tizen-CSharp-Samples
Wearable/GestureSensor/src/GestureSensor/GestureSensor/GestureSensor.Tizen.Wearable/Controls/MaskedImageButton.cs
2,558
C#
using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace ByteDev.DotNet.Project.Parsers { internal static class ProjectXmlParser { public static IEnumerable<XElement> GetPropertyGroups(XDocument xDocument) { return xDocument.Root?.Descendants().Where(d => d.Name.LocalName == "PropertyGroup"); } public static IEnumerable<XElement> GetItemGroups(XDocument xDocument) { return xDocument.Root?.Descendants().Where(d => d.Name.LocalName == "ItemGroup"); } } }
30.105263
97
0.66958
[ "MIT" ]
DinkDev/ByteDev.DotNet
src/ByteDev.DotNet/Project/Parsers/ProjectXmlParser.cs
574
C#
using Abp.Reflection.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace WiLSoft.Infrastructure.Core { /// <summary> /// Central point for application version. /// </summary> public class AppVersionHelper { /// <summary> /// Gets current version of the application. /// It's also shown in the web page. /// </summary> public const string Version = "1.0.0.0"; /// <summary> /// Gets release (last build) date of the application. /// It's shown in the web page. /// </summary> public static DateTime ReleaseDate { get { return new FileInfo(typeof(AppVersionHelper).GetAssembly().Location).LastWriteTime; } } } }
26.633333
103
0.604506
[ "Apache-2.0" ]
VentsislavDinev/VProfesional
src/Infrasctructure/WiLSoft.Infrastructure.Core/AppVersionHelper.cs
801
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Dingtalkedu_1_0.Models { public class UpdateRemoteClassCourseResponse : TeaModel { [NameInMap("headers")] [Validation(Required=true)] public Dictionary<string, string> Headers { get; set; } [NameInMap("body")] [Validation(Required=true)] public UpdateRemoteClassCourseResponseBody Body { get; set; } } }
22.782609
69
0.687023
[ "Apache-2.0" ]
aliyun/dingtalk-sdk
dingtalk/csharp/core/edu_1_0/Models/UpdateRemoteClassCourseResponse.cs
524
C#
// Copyright 2020 New Relic, Inc. All rights reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using NewRelic.Agent.IntegrationTestHelpers; using NewRelic.Agent.IntegrationTestHelpers.Models; using NewRelic.Testing.Assertions; using Xunit; using Xunit.Abstractions; namespace NewRelic.Agent.IntegrationTests.RequestHeadersCapture.Owin { [NetFrameworkTest] public abstract class AllowAllHeadersEnabledTestsBase<TFixture> : NewRelicIntegrationTest<TFixture> where TFixture : RemoteServiceFixtures.OwinWebApiFixture { private readonly RemoteServiceFixtures.OwinWebApiFixture _fixture; // The base test class runs tests for Owin 2; the derived classes test Owin 3 and 4 protected AllowAllHeadersEnabledTestsBase(TFixture fixture, ITestOutputHelper output) : base(fixture) { _fixture = fixture; _fixture.TestLogger = output; _fixture.Actions ( setupConfiguration: () => { var configPath = fixture.DestinationNewRelicConfigFilePath; var configModifier = new NewRelicConfigModifier(configPath); configModifier.EnableDistributedTrace(); configModifier.ForceTransactionTraces(); CommonUtils.ModifyOrCreateXmlAttributeInNewRelicConfig(configPath, new[] { "configuration", "log" }, "level", "debug"); CommonUtils.ModifyOrCreateXmlAttributeInNewRelicConfig(configPath, new[] { "configuration", "requestParameters" }, "enabled", "true"); }, exerciseApplication: () => { _fixture.Post(); _fixture.AgentLog.WaitForLogLine(AgentLogBase.HarvestFinishedLogLineRegex, TimeSpan.FromMinutes(2)); } ); _fixture.Initialize(); } [Fact] public void Test() { var expectedTransactionName = "WebTransaction/WebAPI/Values/Post"; var expectedAttributes = new Dictionary<string, object> { { "request.method", "POST" }, { "request.uri", "/api/Values/" }, // Captured headers { "request.headers.connection", "Keep-Alive" }, { "request.headers.accept", "application/json" }, { "request.headers.host", "fakehost" }, { "request.headers.referer", "http://example.com" }, { "request.headers.content-length", "7" }, { "request.headers.user-agent", "FakeUserAgent" }, { "request.headers.foo", "bar" } }; var unexpectedAttributes = new List<string> { "request.headers.cookie", "request.headers.authorization", "request.headers.proxy-authorization", "request.headers.x-forwarded-For" }; var transactionSamples = _fixture.AgentLog.GetTransactionSamples(); //this is the transaction trace that is generally returned, but this //is not necessarily always the case var traceToCheck = transactionSamples .Where(sample => sample.Path == expectedTransactionName) .FirstOrDefault(); var transactionEvent = _fixture.AgentLog.TryGetTransactionEvent(expectedTransactionName); var spanEvent = _fixture.AgentLog.TryGetSpanEvent(expectedTransactionName); NrAssert.Multiple( () => Assert.NotNull(traceToCheck), () => Assertions.TransactionTraceHasAttributes(expectedAttributes, TransactionTraceAttributeType.Agent, traceToCheck), () => Assertions.SpanEventHasAttributes(expectedAttributes, SpanEventAttributeType.Agent, spanEvent), () => Assertions.TransactionEventHasAttributes(expectedAttributes, TransactionEventAttributeType.Agent, transactionEvent), () => Assertions.SpanEventDoesNotHaveAttributes(unexpectedAttributes, SpanEventAttributeType.Agent, spanEvent), () => Assertions.TransactionEventDoesNotHaveAttributes(unexpectedAttributes, TransactionEventAttributeType.Agent, transactionEvent), () => Assertions.TransactionTraceDoesNotHaveAttributes(unexpectedAttributes, TransactionTraceAttributeType.Agent, traceToCheck) ); } } public class OwinWebApiAllowAllHeadersEnabledTest : AllowAllHeadersEnabledTestsBase<RemoteServiceFixtures.OwinWebApiFixture> { public OwinWebApiAllowAllHeadersEnabledTest(RemoteServiceFixtures.OwinWebApiFixture fixture, ITestOutputHelper output) : base(fixture, output) { } } public class Owin3WebApiAllowAllHeadersEnabledTest : AllowAllHeadersEnabledTestsBase<RemoteServiceFixtures.Owin3WebApiFixture> { public Owin3WebApiAllowAllHeadersEnabledTest(RemoteServiceFixtures.Owin3WebApiFixture fixture, ITestOutputHelper output) : base(fixture, output) { } } public class Owin4WebApiAllowAllHeadersEnabledTest : AllowAllHeadersEnabledTestsBase<RemoteServiceFixtures.Owin4WebApiFixture> { public Owin4WebApiAllowAllHeadersEnabledTest(RemoteServiceFixtures.Owin4WebApiFixture fixture, ITestOutputHelper output) : base(fixture, output) { } } }
45.983333
154
0.651685
[ "Apache-2.0" ]
gregorylyons/newrelic-dotnet-agent
tests/Agent/IntegrationTests/IntegrationTests/RequestHeadersCapture/Owin/AllowAllHeadersEnabledTestsBase.cs
5,520
C#
// <auto-generated /> using System; using DatabaseInterface; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace DatabaseInterface.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20200923192522_AddedShowDayNameToSettings")] partial class AddedShowDayNameToSettings { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.0") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("DatabaseInterface.Entities.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("varchar(255) CHARACTER SET utf8mb4"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Email") .HasColumnType("varchar(256) CHARACTER SET utf8mb4") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("tinyint(1)"); b.Property<bool>("LockoutEnabled") .HasColumnType("tinyint(1)"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetime(6)"); b.Property<string>("NormalizedEmail") .HasColumnType("varchar(256) CHARACTER SET utf8mb4") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("varchar(256) CHARACTER SET utf8mb4") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("PhoneNumber") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("tinyint(1)"); b.Property<string>("SecurityStamp") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("TimeZoneId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("tinyint(1)"); b.Property<string>("UserName") .HasColumnType("varchar(256) CHARACTER SET utf8mb4") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("DatabaseInterface.Entities.HourMetric", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("Created") .HasColumnType("datetime(6)"); b.Property<int>("Mode") .HasColumnType("int"); b.Property<long>("RaspberryPiId") .HasColumnType("bigint"); b.Property<int>("RedeliveryNow") .HasColumnType("int"); b.Property<long>("RedeliveryTotalHigh") .HasColumnType("bigint"); b.Property<long>("RedeliveryTotalLow") .HasColumnType("bigint"); b.Property<int>("SolarNow") .HasColumnType("int"); b.Property<long>("SolarTotal") .HasColumnType("bigint"); b.Property<DateTime>("Updated") .HasColumnType("datetime(6)"); b.Property<int>("UsageGasNow") .HasColumnType("int"); b.Property<long>("UsageGasTotal") .HasColumnType("bigint"); b.Property<int>("UsageNow") .HasColumnType("int"); b.Property<long>("UsageTotalHigh") .HasColumnType("bigint"); b.Property<long>("UsageTotalLow") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("Created"); b.HasIndex("RaspberryPiId"); b.ToTable("HourMetrics"); }); modelBuilder.Entity("DatabaseInterface.Entities.MinuteMetric", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("Created") .HasColumnType("datetime(6)"); b.Property<int>("Mode") .HasColumnType("int"); b.Property<long>("RaspberryPiId") .HasColumnType("bigint"); b.Property<int>("RedeliveryNow") .HasColumnType("int"); b.Property<long>("RedeliveryTotalHigh") .HasColumnType("bigint"); b.Property<long>("RedeliveryTotalLow") .HasColumnType("bigint"); b.Property<int>("SolarNow") .HasColumnType("int"); b.Property<long>("SolarTotal") .HasColumnType("bigint"); b.Property<DateTime>("Updated") .HasColumnType("datetime(6)"); b.Property<int>("UsageGasNow") .HasColumnType("int"); b.Property<long>("UsageGasTotal") .HasColumnType("bigint"); b.Property<int>("UsageNow") .HasColumnType("int"); b.Property<long>("UsageTotalHigh") .HasColumnType("bigint"); b.Property<long>("UsageTotalLow") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("Created"); b.HasIndex("RaspberryPiId"); b.ToTable("MinuteMetrics"); }); modelBuilder.Entity("DatabaseInterface.Entities.RaspberryPi", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("Created") .HasColumnType("datetime(6)"); b.Property<string>("RpiKey") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<DateTime>("Updated") .HasColumnType("datetime(6)"); b.Property<string>("UserId") .HasColumnType("varchar(255) CHARACTER SET utf8mb4"); b.HasKey("Id"); b.HasIndex("UserId") .IsUnique(); b.ToTable("RaspberryPis"); }); modelBuilder.Entity("DatabaseInterface.Entities.Settings", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<bool>("ShowDayName") .HasColumnType("tinyint(1)"); b.Property<bool>("SolarSystem") .HasColumnType("tinyint(1)"); b.Property<string>("TimeZoneId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("UserId") .HasColumnType("varchar(255) CHARACTER SET utf8mb4"); b.HasKey("Id"); b.HasIndex("UserId") .IsUnique(); b.ToTable("Settings"); }); modelBuilder.Entity("DatabaseInterface.Entities.TenSecondMetric", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("Created") .HasColumnType("datetime(6)"); b.Property<int>("Mode") .HasColumnType("int"); b.Property<long>("RaspberryPiId") .HasColumnType("bigint"); b.Property<int>("RedeliveryNow") .HasColumnType("int"); b.Property<long>("RedeliveryTotalHigh") .HasColumnType("bigint"); b.Property<long>("RedeliveryTotalLow") .HasColumnType("bigint"); b.Property<int>("SolarNow") .HasColumnType("int"); b.Property<long>("SolarTotal") .HasColumnType("bigint"); b.Property<DateTime>("Updated") .HasColumnType("datetime(6)"); b.Property<int>("UsageGasNow") .HasColumnType("int"); b.Property<long>("UsageGasTotal") .HasColumnType("bigint"); b.Property<int>("UsageNow") .HasColumnType("int"); b.Property<long>("UsageTotalHigh") .HasColumnType("bigint"); b.Property<long>("UsageTotalLow") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("Created"); b.HasIndex("RaspberryPiId"); b.ToTable("TenSecondMetrics"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("varchar(255) CHARACTER SET utf8mb4"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Name") .HasColumnType("varchar(256) CHARACTER SET utf8mb4") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("varchar(256) CHARACTER SET utf8mb4") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ClaimType") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("ClaimValue") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("varchar(255) CHARACTER SET utf8mb4"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ClaimType") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("ClaimValue") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("UserId") .IsRequired() .HasColumnType("varchar(255) CHARACTER SET utf8mb4"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("varchar(128) CHARACTER SET utf8mb4") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("varchar(128) CHARACTER SET utf8mb4") .HasMaxLength(128); b.Property<string>("ProviderDisplayName") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("UserId") .IsRequired() .HasColumnType("varchar(255) CHARACTER SET utf8mb4"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("varchar(255) CHARACTER SET utf8mb4"); b.Property<string>("RoleId") .HasColumnType("varchar(255) CHARACTER SET utf8mb4"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("varchar(255) CHARACTER SET utf8mb4"); b.Property<string>("LoginProvider") .HasColumnType("varchar(128) CHARACTER SET utf8mb4") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("varchar(128) CHARACTER SET utf8mb4") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("DatabaseInterface.Entities.HourMetric", b => { b.HasOne("DatabaseInterface.Entities.RaspberryPi", "RaspberryPi") .WithMany("HourMetrics") .HasForeignKey("RaspberryPiId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("DatabaseInterface.Entities.MinuteMetric", b => { b.HasOne("DatabaseInterface.Entities.RaspberryPi", "RaspberryPi") .WithMany("MinuteMetrics") .HasForeignKey("RaspberryPiId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("DatabaseInterface.Entities.RaspberryPi", b => { b.HasOne("DatabaseInterface.Entities.ApplicationUser", "User") .WithOne("RaspberryPi") .HasForeignKey("DatabaseInterface.Entities.RaspberryPi", "UserId"); }); modelBuilder.Entity("DatabaseInterface.Entities.Settings", b => { b.HasOne("DatabaseInterface.Entities.ApplicationUser", "User") .WithOne("Settings") .HasForeignKey("DatabaseInterface.Entities.Settings", "UserId"); }); modelBuilder.Entity("DatabaseInterface.Entities.TenSecondMetric", b => { b.HasOne("DatabaseInterface.Entities.RaspberryPi", "RaspberryPi") .WithMany("TenSecondMetrics") .HasForeignKey("RaspberryPiId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); 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("DatabaseInterface.Entities.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("DatabaseInterface.Entities.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("DatabaseInterface.Entities.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("DatabaseInterface.Entities.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
37.074212
95
0.45894
[ "MIT" ]
yokovaski/EnergyPortal
DatabaseInterface/Migrations/20200923192522_AddedShowDayNameToSettings.Designer.cs
19,985
C#
// UrlRewriter - A .NET URL Rewriter module // Version 2.0 // // Copyright 2011 Intelligencia // Copyright 2011 Seth Yates // using System; using System.Xml; using Intelligencia.UrlRewriter.Actions; using Intelligencia.UrlRewriter.Configuration; using Intelligencia.UrlRewriter.Utilities; namespace Intelligencia.UrlRewriter.Parsers { /// <summary> /// Parser for forbidden actions. /// </summary> public sealed class NotImplementedActionParser : RewriteActionParserBase { /// <summary> /// The name of the action. /// </summary> public override string Name { get { return Constants.ElementNotImplemented; } } /// <summary> /// Whether the action allows nested actions. /// </summary> public override bool AllowsNestedActions { get { return false; } } /// <summary> /// Whether the action allows attributes. /// </summary> public override bool AllowsAttributes { get { return false; } } /// <summary> /// Parses the node. /// </summary> /// <param name="node">The node to parse.</param> /// <param name="config">The rewriter configuration.</param> /// <returns>The parsed action, or null if no action parsed.</returns> public override IRewriteAction Parse(XmlNode node, RewriterConfiguration config) { return new NotImplementedAction(); } } }
26.964912
88
0.597267
[ "MIT" ]
OptimityAdvisors/Intelligencia.UrlRewriter
Parsers/NotImplementedActionParser.cs
1,537
C#
namespace PrintDesignFinalizer.Engine { public interface INodeOperation { void Apply(INode node); } }
13.5
38
0.759259
[ "MIT" ]
stu-smith/PrintDesignFinalizer
PrintDesignFinalizer/PrintDesignFinalizer.Engine/INodeOperation.cs
110
C#
using GENUtility; using VOCASY; using VOCASY.Common; using System.Collections.Generic; public class SupportTransport : VoiceDataTransport { public List<ulong> DataSentTo = new List<ulong>(); public int DataSent; public int DataReceived; public int MaxDataL = 1024; public VoicePacketInfo Info; public byte[] SentArray; public override int MaxDataLength { get { return MaxDataL; } } public VoiceDataWorkflow Workflow; public override VoicePacketInfo ProcessReceivedData(BytePacket buffer, byte[] dataReceived, int startIndex, int length, ulong netId) { DataReceived = length; buffer.WriteByteData(dataReceived, startIndex, length); return Info; } public bool MessageSent; public override void SendMessageIsMutedTo(ulong receiverID, bool isReceiverMutedByLocal) { MessageSent = true; } public override void SendToAll(BytePacket data, VoicePacketInfo info, List<ulong> receiversIds) { SentArray = new byte[data.Data.Length]; ByteManipulator.Write<byte>(data.Data, 0, SentArray, 0, SentArray.Length); DataSent = data.CurrentLength; for (int i = 0; i < receiversIds.Count; i++) { DataSentTo.Add(receiversIds[i]); } } }
33.684211
136
0.690625
[ "MIT" ]
MatteoNasci/VOCASY
VOCASY/VOCASY.Tests/Assets/Scripts/SupportClasses/SupportTransport.cs
1,282
C#
using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Castle.MicroKernel.Registration; using Castle.Windsor; using Common.Logging; using Jal.HttpClient.Installer; using Shouldly; using System; using Serilog; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading; using Jal.HttpClient.Common.Logging; using Jal.HttpClient.Serilog; using Jal.HttpClient.Polly; using Polly; using Polly.CircuitBreaker; namespace Jal.HttpClient.Tests { [TestClass] public class HttpHandlerBuilderTests { private IHttpFluentHandler _sut; [TestInitialize] public void Setup() { var log = LogManager.GetLogger("logger"); var container = new WindsorContainer(); container.Register(Component.For<ILog>().Instance(log)); container.AddHttpClient(c=> { c.Add<CommonLoggingMiddelware>(); c.Add<SerilogMiddelware>(); c.Add<CircuitBreakerMiddelware>(); c.Add<TimeoutMiddelware>(); c.Add<OnConditionRetryMiddelware>(); }); _sut = container.GetHttpClient(); Log.Logger = new LoggerConfiguration() .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}{Properties}").MinimumLevel.Verbose() .CreateLogger(); } [TestMethod] public async Task Send_Get_Serilog_Ok() { using (var response = await _sut.Get("http://httpbin.org/ip").WithMiddleware(x=>x.UseSerilog()).SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); content.ShouldContain("origin"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_Get_AuthorizedByToken_Ok() { using (var response = await _sut.Get("http://httpbin.org/get").WithMiddleware(x => x.AuthorizedByToken("token","value")).SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); content.ShouldContain("token"); content.ShouldContain("value"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_Get_Middlewares_Ok() { var retries = 0; using (var response = await _sut.Get("http://httpbin.org/get?hi=1").WithMiddleware(x => { x.AddTracing(); x.AuthorizedByToken("token", "value"); x.OnConditionRetry(3, y => y.Message.StatusCode == HttpStatusCode.OK, (z, c) => { retries++; }); x.UseSerilog(); x.UseMemoryCache(30, y => y.Message.RequestUri.AbsoluteUri, z => z.Message.StatusCode == HttpStatusCode.OK); }).SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); retries.ShouldBe(3); content.ShouldContain("token"); content.ShouldContain("value"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_Get_Retry_Ok() { var retries = 0; using (var response = await _sut.Get("http://httpbin.org/get") .WithMiddleware(x => x.OnConditionRetry(3, y => y.Message.StatusCode == HttpStatusCode.OK, (z, c) => { retries++; })) .SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); retries.ShouldBe(3); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_Get_CircuitBreaker_Ok() { AsyncCircuitBreakerPolicy<HttpResponse> breakerPolicy = Policy .HandleResult<HttpResponse>(r => r.Message?.StatusCode!= HttpStatusCode.OK ) .CircuitBreakerAsync(2, TimeSpan.FromSeconds(10)); using (var response = await _sut.Get("http://httpbin.org/status/500").WithMiddleware(x => x.UseCircuitBreaker(breakerPolicy)).SendAsync()) { response.Message.StatusCode.ShouldBe(HttpStatusCode.InternalServerError); } using (var response = await _sut.Get("http://httpbin.org/status/500").WithMiddleware(x => x.UseCircuitBreaker(breakerPolicy)).SendAsync()) { response.Message.StatusCode.ShouldBe(HttpStatusCode.InternalServerError); } using (var response = await _sut.Get("http://httpbin.org/get").WithMiddleware(x => x.UseCircuitBreaker(breakerPolicy)).SendAsync()) { response.Message.ShouldBeNull(); } await Task.Delay(TimeSpan.FromSeconds(15)); using (var response = await _sut.Get("http://httpbin.org/get").WithMiddleware(x => x.UseCircuitBreaker(breakerPolicy)).SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_Get_MemoryCache_Ok() { using (var response = await _sut.Get("http://httpbin.org/get").WithMiddleware(x => { x.UseMemoryCache(30, y => y.Message.RequestUri.AbsoluteUri, z => z.Message.StatusCode == HttpStatusCode.OK); }).WithHeaders(x => x.Add("header", "old")).SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); content.ShouldContain("header"); content.ShouldContain("old"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } using (var response = await _sut.Get("http://httpbin.org/get").WithMiddleware(x => { x.UseCommonLogging(); x.UseMemoryCache(30, y => y.Message.RequestUri.AbsoluteUri, z => z.Message.StatusCode == HttpStatusCode.OK); }).WithHeaders(x => x.Add("header", "new")).SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); content.ShouldContain("header"); content.ShouldContain("old"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Message.Headers.ShouldContain(x => x.Key == "from-cache"); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task SendAsync_Get_Ok() { using (var response = await _sut.Get("http://httpbin.org/ip").SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); content.ShouldContain("origin"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_PostJsonUtf8_Ok() { using (var response = await _sut.Post("http://httpbin.org/post").Json(@"{""message"":""Hello World!!""}").SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); content.ShouldContain("Hello World"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_PostXmlUtf8_Ok() { using (var response = await _sut.Post("http://httpbin.org/post").Xml(@"<message>Hello World!!</message>").SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); content.ShouldContain("Hello World"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_PostFormUrlEncodedArrayUtf8_Ok() { using (var response = await _sut.Post("http://httpbin.org/post").FormUrlEncoded(new[] { new KeyValuePair<string, string>("message", "Hello World"), new KeyValuePair<string, string>("array", "a a"), new KeyValuePair<string, string>("array", "bbb"), new KeyValuePair<string, string>("array", "c c"), }).SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); content.ShouldContain("Hello World"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_PostFormUrlEncodedUtf8_Ok() { using (var response = await _sut.Post("http://httpbin.org/post").FormUrlEncoded(new [] {new KeyValuePair<string, string>("message", "Hello World") }).SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); content.ShouldContain("Hello World"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_PostMultiPartFormDataUtf8_Ok() { using (var response = await _sut.Post("http://httpbin.org/post").MultiPartFormData(x => { x.Json(@"{""message1"":""Hello World1!!""}", "form-data"); x.Json(@"{""message2"":""Hello World2!!""}", "form-data"); x.Xml("<saludo>hola mundo</saludo>", "nombre3", "file.xml"); x.WithContent("message3").WithDisposition("form-data"); x.UrlEncoded("a", "message4"); x.UrlEncoded("b", "message4"); x.UrlEncoded("c c", "message4"); //x.WithContent(new FileStream("file.zip", FileMode.Open, FileAccess.Read)).WithDisposition("file", "file.zip"); }).SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); } } [TestMethod] public async Task Send_GetWithQueryParameters_Ok() { using (var response = await _sut.Get("http://httpbin.org/get").WithQueryParameters(x=>x.Add("parameter","value")).SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); content.ShouldContain("parameter"); content.ShouldContain("value"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_GetWithHeaders_Ok() { using (var response = await _sut.Get("http://httpbin.org/get").WithHeaders(x => x.Add("Header1", "value")).SendAsync()) { var content = await response.Message.Content.ReadAsStringAsync(); content.ShouldContain("Header1"); content.ShouldContain("value"); response.Message.Content.Headers.ContentType.MediaType.ShouldBe("application/json"); response.Message.Content.Headers.ContentLength.Value.ShouldBeGreaterThan(0); response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); response.Exception.ShouldBeNull(); } } [TestMethod] public async Task Send_Delete_Ok() { using (var response = await _sut.Delete("http://httpbin.org/delete").SendAsync()) { response.Message.StatusCode.ShouldBe(HttpStatusCode.OK); } } [TestMethod] public async Task Send_Get_TimeOut() { using (var response = await _sut.Get("https://httpbin.org/delay/5").WithMiddleware(x=>x.UseTimeout(2)).SendAsync()) { response.Message?.Content.ShouldBeNull(); } } [TestMethod] public async Task Send_Get_CancellationToken() { using (var source = new CancellationTokenSource(TimeSpan.FromSeconds(3))) { using (var response = await _sut.Get("https://httpbin.org/delay/5", cancellationtoken: source.Token).SendAsync()) { response.Message?.Content.ShouldBeNull(); } } } } }
37.871981
325
0.598763
[ "Apache-2.0" ]
raulnq/Jal.HttpClient
Jal.HttpClient.Tests/HttpHandlerBuilderTests.cs
15,681
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 lambda-2015-03-31.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.Lambda.Model { ///<summary> /// Lambda exception /// </summary> #if !PCL && !CORECLR [Serializable] #endif public class ResourceInUseException : AmazonLambdaException { /// <summary> /// Constructs a new ResourceInUseException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public ResourceInUseException(string message) : base(message) {} /// <summary> /// Construct instance of ResourceInUseException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public ResourceInUseException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of ResourceInUseException /// </summary> /// <param name="innerException"></param> public ResourceInUseException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of ResourceInUseException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ResourceInUseException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of ResourceInUseException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public ResourceInUseException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !CORECLR /// <summary> /// Constructs a new instance of the ResourceInUseException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected ResourceInUseException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
42.546392
178
0.645263
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Lambda/Generated/Model/ResourceInUseException.cs
4,127
C#
// It's generated file. DO NOT MODIFY IT! using Diablerie.Engine.Datasheets; using Diablerie.Engine.IO.D2Formats; class MagicAffixModLoader : Datasheet.Loader<MagicAffix.Mod> { public void LoadRecord(ref MagicAffix.Mod record, DatasheetStream stream) { stream.Read(ref record.code); stream.Read(ref record.param); stream.Read(ref record.min); stream.Read(ref record.max); } }
25.333333
77
0.649123
[ "MIT" ]
Bia10/Diablerie
Assets/Scripts/Generated/DatasheetLoaders/MagicAffixModLoader.cs
456
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "TextAdventure/InputActions/Inventory")] public class Inventory : InputAction { public override void RespondToInput(GameController controller, string[] separatedInputWords) { controller.interactableItems.DisplayInventory(); } }
28
96
0.766484
[ "MIT" ]
youwho42/jbjt
Assets/Scripts/TextAdventure/Inventory.cs
366
C#
using System.ComponentModel; using System.Windows.Forms; using bv.winclient.BasePanel; using bv.winclient.Core; namespace EIDSS.Reports.BaseControls.Form { internal partial class ReportForm : BvForm, IReportForm { private readonly ComponentResourceManager m_Resources = new ComponentResourceManager(typeof (ReportForm)); public ReportForm() { InitializeComponent(); } public void ShowReport(Control reportKeeper) { reportKeeper.Dock = DockStyle.Fill; Controls.Add(reportKeeper); RtlHelper.SetRTL(reportKeeper); if (Application.OpenForms.Count == 0) { ShowDialog(); } else { object id = null; BaseFormManager.ShowNormal(this, ref id); } } public void ApplyResources() { Text = m_Resources.GetString("$this.Text"); } public override bool IsSingleTone { get { return false; } } } }
26.348837
115
0.539276
[ "BSD-2-Clause" ]
EIDSS/EIDSS-Legacy
EIDSS v6.1/vb/EIDSS/EIDSS.Reports/BaseControls/Form/ReportForm.cs
1,133
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 rds-2014-10-31.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.RDS.Model { /// <summary> /// The version for an option. Option group option versions are returned by the <a>DescribeOptionGroupOptions</a> /// action. /// </summary> public partial class OptionVersion { private bool? _isDefault; private string _version; /// <summary> /// Gets and sets the property IsDefault. /// <para> /// True if the version is the default version of the option; otherwise, false. /// </para> /// </summary> public bool IsDefault { get { return this._isDefault.GetValueOrDefault(); } set { this._isDefault = value; } } // Check to see if IsDefault property is set internal bool IsSetIsDefault() { return this._isDefault.HasValue; } /// <summary> /// Gets and sets the property Version. /// <para> /// The version of the option. /// </para> /// </summary> public string Version { get { return this._version; } set { this._version = value; } } // Check to see if Version property is set internal bool IsSetVersion() { return this._version != null; } } }
28.815789
117
0.613699
[ "Apache-2.0" ]
Bynder/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/OptionVersion.cs
2,190
C#
namespace StockSharp.Algo.Candles.Compression { using System; using System.Linq; using Ecng.Collections; using StockSharp.Algo.Storages; using StockSharp.Localization; using StockSharp.Logging; using StockSharp.Messages; /// <summary> /// Candle builder adapter. /// </summary> public class CandleBuilderMessageAdapter : MessageAdapterWrapper { private sealed class CandleBuildersList : SynchronizedList<ICandleBuilder> { private readonly SynchronizedDictionary<MarketDataTypes, ICandleBuilder> _builders = new SynchronizedDictionary<MarketDataTypes, ICandleBuilder>(); public ICandleBuilder Get(MarketDataTypes type) { var builder = _builders.TryGetValue(type); if (builder == null) throw new ArgumentOutOfRangeException(nameof(type), type, LocalizedStrings.Str1219); return builder; } protected override void OnAdded(ICandleBuilder item) { _builders.Add(item.CandleType, item); base.OnAdded(item); } protected override bool OnRemoving(ICandleBuilder item) { lock (_builders.SyncRoot) _builders.RemoveWhere(p => p.Value == item); return base.OnRemoving(item); } protected override void OnInserted(int index, ICandleBuilder item) { _builders.Add(item.CandleType, item); base.OnInserted(index, item); } protected override bool OnClearing() { _builders.Clear(); return base.OnClearing(); } } private enum SeriesStates { None, Regular, SmallTimeFrame, Compress, } private class SeriesInfo { public SeriesInfo(MarketDataMessage original, MarketDataMessage current) { Original = original ?? throw new ArgumentNullException(nameof(original)); Current = current; } public MarketDataMessage Original { get; } private MarketDataMessage _current; public MarketDataMessage Current { get => _current; set => _current = value ?? throw new ArgumentNullException(nameof(value)); } public SeriesStates State { get; set; } = SeriesStates.None; public BiggerTimeFrameCandleCompressor BigTimeFrameCompressor { get; set; } public ICandleBuilderValueTransform Transform { get; set; } public DateTimeOffset? LastTime { get; set; } public CandleMessage CurrentCandleMessage { get; set; } } private readonly SynchronizedDictionary<long, SeriesInfo> _seriesByTransactionId = new SynchronizedDictionary<long, SeriesInfo>(); private readonly SynchronizedDictionary<SecurityId, CachedSynchronizedList<SeriesInfo>> _seriesBySecurityId = new SynchronizedDictionary<SecurityId, CachedSynchronizedList<SeriesInfo>>(); private readonly SynchronizedSet<long> _unsubscriptions = new SynchronizedSet<long>(); private readonly CandleBuildersList _candleBuilders; private readonly IExchangeInfoProvider _exchangeInfoProvider; /// <summary> /// Initializes a new instance of the <see cref="CandleBuilderMessageAdapter"/>. /// </summary> /// <param name="innerAdapter">Inner message adapter.</param> /// <param name="exchangeInfoProvider">The exchange boards provider.</param> public CandleBuilderMessageAdapter(IMessageAdapter innerAdapter, IExchangeInfoProvider exchangeInfoProvider) : base(innerAdapter) { _exchangeInfoProvider = exchangeInfoProvider ?? throw new ArgumentNullException(nameof(exchangeInfoProvider)); _candleBuilders = new CandleBuildersList { new TimeFrameCandleBuilder(exchangeInfoProvider), new TickCandleBuilder(exchangeInfoProvider), new VolumeCandleBuilder(exchangeInfoProvider), new RangeCandleBuilder(exchangeInfoProvider), new RenkoCandleBuilder(exchangeInfoProvider), new PnFCandleBuilder(exchangeInfoProvider), }; } /// <inheritdoc /> public override void SendInMessage(Message message) { if (message.IsBack) { base.SendInMessage(message); return; } switch (message.Type) { case MessageTypes.Reset: _seriesByTransactionId.Clear(); _seriesBySecurityId.Clear(); _unsubscriptions.Clear(); break; case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; if (mdMsg.DataType != MarketDataTypes.CandleTimeFrame) break; if (mdMsg.IsSubscribe) { var transactionId = mdMsg.TransactionId; var isLoadOnly = mdMsg.BuildMode == MarketDataBuildModes.Load; if (mdMsg.IsCalcVolumeProfile || mdMsg.BuildMode == MarketDataBuildModes.Build) { if (isLoadOnly || !TrySubscribeBuild(mdMsg, transactionId)) { RaiseNewOutMessage(new MarketDataMessage { OriginalTransactionId = transactionId, IsNotSupported = true, }); } return; } var originalTf = (TimeSpan)mdMsg.Arg; var timeFrames = InnerAdapter.GetTimeFrames(mdMsg.SecurityId).ToArray(); if (timeFrames.Contains(originalTf) || InnerAdapter.CheckTimeFrameByRequest) { this.AddInfoLog("Origin tf: {0}", originalTf); var original = (MarketDataMessage)mdMsg.Clone(); _seriesByTransactionId.Add(transactionId, new SeriesInfo(original, original) { State = SeriesStates.Regular, LastTime = original.From, }); break; } if (isLoadOnly) { RaiseNewOutMessage(new MarketDataMessage { OriginalTransactionId = transactionId, IsNotSupported = true, }); return; } if (mdMsg.AllowBuildFromSmallerTimeFrame) { var smaller = timeFrames .FilterSmallerTimeFrames(originalTf) .OrderByDescending() .FirstOr(); if (smaller != null) { this.AddInfoLog("Smaller tf: {0}->{1}", originalTf, smaller); var original = (MarketDataMessage)mdMsg.Clone(); var current = (MarketDataMessage)original.Clone(); current.Arg = smaller; _seriesByTransactionId.Add(transactionId, new SeriesInfo(original, current) { State = SeriesStates.SmallTimeFrame, BigTimeFrameCompressor = new BiggerTimeFrameCandleCompressor(original, new TimeFrameCandleBuilder(_exchangeInfoProvider)), LastTime = original.From, }); base.SendInMessage(current); return; } } if (!TrySubscribeBuild(mdMsg, transactionId)) { RaiseNewOutMessage(new MarketDataMessage { OriginalTransactionId = transactionId, IsNotSupported = true, }); } return; } else { var series = _seriesByTransactionId.TryGetValue(mdMsg.OriginalTransactionId); if (series != null) { RemoveSeries(series); RaiseNewOutMessage(new MarketDataMessage { OriginalTransactionId = mdMsg.TransactionId, }); var transactionId = TransactionIdGenerator.GetNextId(); _unsubscriptions.Add(transactionId); var unsubscribe = (MarketDataMessage)series.Current.Clone(); unsubscribe.TransactionId = transactionId; unsubscribe.OriginalTransactionId = series.Current.TransactionId; unsubscribe.IsSubscribe = false; base.SendInMessage(unsubscribe); return; } break; } } } base.SendInMessage(message); } private MarketDataMessage TryCreateBuildSubscription(MarketDataMessage original, DateTimeOffset? lastTime, Func<long> getTransactionId) { if (original == null) throw new ArgumentNullException(nameof(original)); if (getTransactionId == null) throw new ArgumentNullException(nameof(getTransactionId)); var buildFrom = original.BuildFrom ?? InnerAdapter.SupportedMarketDataTypes.Intersect(CandleHelper.CandleDataSources).OrderBy(t => { // make priority switch (t) { case MarketDataTypes.Trades: return 0; case MarketDataTypes.Level1: return 1; case MarketDataTypes.OrderLog: return 2; case MarketDataTypes.MarketDepth: return 3; default: return 4; } }).FirstOr(); if (buildFrom == null || !InnerAdapter.SupportedMarketDataTypes.Contains(buildFrom.Value)) return null; var current = new MarketDataMessage { DataType = buildFrom.Value, From = original.From, To = original.To, Count = original.Count, MaxDepth = original.MaxDepth, TransactionId = getTransactionId(), BuildField = original.BuildField, IsSubscribe = true, }; original.CopyTo(current, false); this.AddInfoLog("Build tf: {0}->{1}", buildFrom, original.Arg); var series = new SeriesInfo((MarketDataMessage)original.Clone(), current) { LastTime = lastTime, Transform = CreateTransform(current.DataType, current.BuildField), State = SeriesStates.Compress, }; AddSeries(series); return current; } private bool TrySubscribeBuild(MarketDataMessage original, long transactionId) { var current = TryCreateBuildSubscription(original, original.From, () => transactionId); if (current == null) return false; base.SendInMessage(current); return true; } private void AddSeries(SeriesInfo series) { _seriesByTransactionId.Add(series.Current.TransactionId, series); _seriesBySecurityId .SafeAdd(series.Original.SecurityId) .Add(series); } private void RemoveSeries(SeriesInfo series) { lock (_seriesBySecurityId.SyncRoot) { var seriesList = _seriesBySecurityId.TryGetValue(series.Original.SecurityId); if (seriesList == null) return; lock (seriesList.SyncRoot) seriesList.RemoveWhere(s => s.Original.TransactionId == series.Original.TransactionId); if (seriesList.Count == 0) _seriesBySecurityId.Remove(series.Original.SecurityId); } } private static ICandleBuilderValueTransform CreateTransform(MarketDataTypes dataType, Level1Fields? field) { switch (dataType) { case MarketDataTypes.Trades: return new TickCandleBuilderValueTransform(); case MarketDataTypes.MarketDepth: { var t = new QuoteCandleBuilderValueTransform(); if (field != null) t.Type = field.Value; return t; } case MarketDataTypes.Level1: { var t = new Level1CandleBuilderValueTransform(); if (field != null) t.Type = field.Value; return t; } case MarketDataTypes.OrderLog: { var t = new OrderLogCandleBuilderValueTransform(); if (field != null) t.Type = field.Value; return t; } default: throw new ArgumentOutOfRangeException(nameof(dataType), dataType, LocalizedStrings.Str1219); } } /// <inheritdoc /> protected override void OnInnerAdapterNewOutMessage(Message message) { switch (message.Type) { case MessageTypes.MarketData: { if (ProcessMarketDataResponse((MarketDataMessage)message)) return; break; } case MessageTypes.MarketDataFinished: { if (ProcessMarketDataFinished((MarketDataFinishedMessage)message)) return; break; } case MessageTypes.CandleTimeFrame: { var candle = (CandleMessage)message; var series = _seriesByTransactionId.TryGetValue(candle.OriginalTransactionId); if (series == null) break; switch (series.State) { case SeriesStates.Regular: if (ProcessCandle((CandleMessage)message)) return; break; case SeriesStates.SmallTimeFrame: var candles = series.BigTimeFrameCompressor.Process(candle).Where(c => c.State == CandleStates.Finished); foreach (var bigCandle in candles) { bigCandle.OriginalTransactionId = series.Original.TransactionId; bigCandle.Adapter = candle.Adapter; series.LastTime = bigCandle.CloseTime; base.OnInnerAdapterNewOutMessage(bigCandle); } break; // TODO default } return; } case MessageTypes.CandlePnF: case MessageTypes.CandleRange: case MessageTypes.CandleRenko: case MessageTypes.CandleTick: case MessageTypes.CandleVolume: { if (ProcessCandle((CandleMessage)message)) return; break; } case MessageTypes.Execution: { base.OnInnerAdapterNewOutMessage(message); var execMsg = (ExecutionMessage)message; if (execMsg.ExecutionType == ExecutionTypes.Tick || execMsg.ExecutionType == ExecutionTypes.OrderLog) ProcessValue(execMsg.SecurityId, execMsg.OriginalTransactionId, execMsg); return; } case MessageTypes.QuoteChange: { base.OnInnerAdapterNewOutMessage(message); var quoteMsg = (QuoteChangeMessage)message; ProcessValue(quoteMsg.SecurityId, 0, quoteMsg); return; } case MessageTypes.Level1Change: { base.OnInnerAdapterNewOutMessage(message); var l1Msg = (Level1ChangeMessage)message; ProcessValue(l1Msg.SecurityId, 0, l1Msg); return; } } base.OnInnerAdapterNewOutMessage(message); } private bool ProcessMarketDataResponse(MarketDataMessage message) { if (_unsubscriptions.Remove(message.OriginalTransactionId)) return true; if (!_seriesByTransactionId.TryGetValue(message.OriginalTransactionId, out var series)) return false; var isOk = !message.IsNotSupported && message.Error == null; if (isOk) { if (series.Current.TransactionId == message.OriginalTransactionId) RaiseNewOutMessage(message); } else UpgradeSubscription(series, message); return true; } private bool ProcessMarketDataFinished(MarketDataFinishedMessage message) { if (!_seriesByTransactionId.TryGetValue(message.OriginalTransactionId, out var series)) return false; UpgradeSubscription(series, null); return true; } private void UpgradeSubscription(SeriesInfo series, MarketDataMessage response) { if (series == null) throw new ArgumentNullException(nameof(series)); var original = series.Original; void Finish() { RemoveSeries(series); if (response != null && (response.Error != null || response.IsNotSupported)) { response = (MarketDataMessage)response.Clone(); response.OriginalTransactionId = original.TransactionId; RaiseNewOutMessage(response); } else RaiseNewOutMessage(new MarketDataFinishedMessage { OriginalTransactionId = original.TransactionId }); } if (original.To != null && series.LastTime != null && original.To <= series.LastTime) { Finish(); return; } switch (series.State) { case SeriesStates.Regular: { var isLoadOnly = series.Original.BuildMode == MarketDataBuildModes.Load; // upgrate to smaller tf only in case failed subscription if (response != null && original.AllowBuildFromSmallerTimeFrame) { if (isLoadOnly) { Finish(); return; } var smaller = InnerAdapter .TimeFrames .FilterSmallerTimeFrames((TimeSpan)original.Arg) .OrderByDescending() .FirstOr(); if (smaller != null) { series.Current = (MarketDataMessage)original.Clone(); series.Current.Arg = smaller; series.Current.TransactionId = TransactionIdGenerator.GetNextId(); series.BigTimeFrameCompressor = new BiggerTimeFrameCandleCompressor(original, new TimeFrameCandleBuilder(_exchangeInfoProvider)); series.State = SeriesStates.SmallTimeFrame; // loopback series.Current.IsBack = true; RaiseNewOutMessage(series.Current); return; } } if (response == null && isLoadOnly) { Finish(); return; } series.State = SeriesStates.Compress; break; } case SeriesStates.SmallTimeFrame: { series.BigTimeFrameCompressor = null; series.State = SeriesStates.Compress; break; } case SeriesStates.Compress: { Finish(); return; } //case SeriesStates.None: default: throw new ArgumentOutOfRangeException(nameof(series), series.State, LocalizedStrings.Str1219); } if (series.State != SeriesStates.Compress) throw new InvalidOperationException(series.State.ToString()); var current = TryCreateBuildSubscription(original, series.LastTime, TransactionIdGenerator.GetNextId); if (current == null) { Finish(); return; } // loopback current.IsBack = true; RaiseNewOutMessage(current); } private bool ProcessCandle(CandleMessage candleMsg) { if (!_seriesByTransactionId.TryGetValue(candleMsg.OriginalTransactionId, out var info)) return false; if (info.LastTime != null && info.LastTime > candleMsg.OpenTime) return true; SendCandle(info, candleMsg); return true; } private void ProcessValue<TMessage>(SecurityId securityId, long transactionId, TMessage message) where TMessage : Message { var seriesList = _seriesBySecurityId.TryGetValue(securityId); if (seriesList == null) return; foreach (var series in seriesList.Cache) { if (series.Current.TransactionId != transactionId && (transactionId != 0/* || info.IsHistory*/)) continue; var transform = series.Transform; if (transform?.Process(message) != true) continue; var time = transform.Time; var origin = series.Original; if (origin.To != null && origin.To.Value < time) { RemoveSeries(series); RaiseNewOutMessage(new MarketDataFinishedMessage { OriginalTransactionId = origin.TransactionId }); continue; } if (series.LastTime != null && series.LastTime.Value > time) continue; series.LastTime = time; var builder = _candleBuilders.Get(origin.DataType); var result = builder.Process(origin, series.CurrentCandleMessage, transform); foreach (var candleMessage in result) { series.CurrentCandleMessage = candleMessage; SendCandle(series, candleMessage); } } } private void SendCandle(SeriesInfo info, CandleMessage candleMsg) { //if (info.LastTime > candleMsg.OpenTime) // return; info.LastTime = candleMsg.OpenTime; var clone = (CandleMessage)candleMsg.Clone(); clone.Adapter = candleMsg.Adapter; clone.OriginalTransactionId = info.Original.TransactionId; RaiseNewOutMessage(clone); } /// <summary> /// Create a copy of <see cref="CandleBuilderMessageAdapter"/>. /// </summary> /// <returns>Copy.</returns> public override IMessageChannel Clone() { return new CandleBuilderMessageAdapter(InnerAdapter, _exchangeInfoProvider); } } }
25.557851
189
0.684344
[ "Apache-2.0" ]
camiloangel/StockSharp
Algo/Candles/Compression/CandleBuilderMessageAdapter.cs
18,555
C#
using System.IO; using System.Xml; using System.Xml.Linq; namespace Npoi.Core.OpenXmlFormats.Spreadsheet { public class WorkbookDocument { private CT_Workbook workbook = null; public WorkbookDocument() { workbook = new CT_Workbook(); } public static WorkbookDocument Parse(XDocument xmlDoc, XmlNamespaceManager NameSpaceManager) { CT_Workbook obj = CT_Workbook.Parse(xmlDoc.Document.Root, NameSpaceManager); return new WorkbookDocument(obj); } public WorkbookDocument(CT_Workbook workbook) { this.workbook = workbook; } public CT_Workbook Workbook { get { return this.workbook; } } public void Save(Stream stream) { using (StreamWriter sw1 = new StreamWriter(stream)) { workbook.Write(sw1); } } } }
23.186047
100
0.554664
[ "Apache-2.0" ]
Arch/Npoi.Core
src/Npoi.Core.OpenXmlFormats/Spreadsheet/Document/WorkbookDocument.cs
999
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("DllMembership.Lib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DllMembership.Lib")] [assembly: AssemblyCopyright("Copyright © 2008")] [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("a3d0a74b-de29-4ae2-b1e6-a7dd856c7cfa")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027027
84
0.745558
[ "MIT" ]
Code-Inside/Samples
2008/DllMembership/DllMembership.Lib/Properties/AssemblyInfo.cs
1,410
C#
using System; using System.Collections.Generic; namespace async.Model { public class ProductPhoto { public ProductPhoto() { ProductProductPhoto = new HashSet<ProductProductPhoto>(); } public int ProductPhotoID { get; set; } public byte[] ThumbNailPhoto { get; set; } public string ThumbnailPhotoFileName { get; set; } public byte[] LargePhoto { get; set; } public string LargePhotoFileName { get; set; } public DateTime ModifiedDate { get; set; } public virtual ICollection<ProductProductPhoto> ProductProductPhoto { get; set; } } }
29.090909
89
0.639063
[ "MIT" ]
cwoodruff/EFCore3Demos
async/Model/ProductPhoto.cs
642
C#
namespace Magento.RestClient.Tests.Repositories { public class ProductImageTests { } }
12.857143
47
0.788889
[ "BSD-3-Clause" ]
mlof/Magento.RestClient
source/Magento.RestClient.Tests/Repositories/ProductImageTests.cs
90
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** 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.Kubernetes.Types.Inputs.Packages.V1Alpha1 { public class PackageSpecControllerDeploymentSpecTemplateSpecVolumesQuobyteArgs : Pulumi.ResourceArgs { [Input("group")] public Input<string>? Group { get; set; } [Input("readOnly")] public Input<bool>? ReadOnly { get; set; } [Input("registry", required: true)] public Input<string> Registry { get; set; } = null!; [Input("tenant")] public Input<string>? Tenant { get; set; } [Input("user")] public Input<string>? User { get; set; } [Input("volume", required: true)] public Input<string> Volume { get; set; } = null!; public PackageSpecControllerDeploymentSpecTemplateSpecVolumesQuobyteArgs() { } } }
28.552632
104
0.647926
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/crossplane/dotnet/Kubernetes/Crds/Operators/Crossplane/Packages/V1Alpha1/Inputs/PackageSpecControllerDeploymentSpecTemplateSpecVolumesQuobyteArgs.cs
1,085
C#