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
#region File Description //----------------------------------------------------------------------------- // Screen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace Spacewar { /// <summary> /// Screen represents a unit of rendering for the game, generally transitional point such /// as splash screens, selection screens and the actual game levels. /// </summary> abstract public class Screen { /// <summary> /// The root of the scene graph for this screen /// </summary> protected SceneItem scene = null; /// <summary> /// Overlay points to a screen that will be drawn AFTER this one, more than likely overlaying it /// </summary> protected Screen overlay; protected SpriteBatch batch = null; protected Game game = null; public Game GameInstance { get { return game; } } public SpriteBatch SpriteBatch { get { return batch; } } public Screen(Game game) { this.game = game; this.scene = new SceneItem(game); if (game != null) { IGraphicsDeviceService graphicsService = (IGraphicsDeviceService)game.Services.GetService(typeof(IGraphicsDeviceService)); batch = new SpriteBatch(graphicsService.GraphicsDevice); } } /// <summary> /// Update changes the layout and positions based on input or other variables /// Base class updates all items in the scene then calls any overlays to get them to render themselves /// </summary> /// <param name="time">Total game time since it was started</param> /// <param name="elapsedTime">Elapsed game time since the last call to update</param> /// <returns>The next gamestate to transition to. Default is the return value of an overlay or NONE. Override Update if you want to change this behaviour</returns> public virtual GameState Update(TimeSpan time, TimeSpan elapsedTime) { //Update the Scene scene.Update(time, elapsedTime); //Default is no state changes, override the class if you want a different state return (overlay == null) ? GameState.None : overlay.Update(time, elapsedTime); } /// <summary> /// Renders this scene. The base class renders everything in the sceen graph and then calls any overlays to /// get them to render themselves /// </summary> public virtual void Render() { //Render this scene then any overlays scene.Render(); if (overlay != null) overlay.Render(); } /// <summary> /// Tidies up the scene. Base class does nothing but calls the overlays /// </summary> public virtual void Shutdown() { if (overlay != null) overlay.Shutdown(); if (batch != null) { batch.Dispose(); batch = null; } } /// <summary> /// OnCreateDevice is called when the device is created /// </summary> public virtual void OnCreateDevice() { //Re-Create the Sprite Batch! IGraphicsDeviceService graphicsService = (IGraphicsDeviceService)game.Services.GetService(typeof(IGraphicsDeviceService)); batch = new SpriteBatch(graphicsService.GraphicsDevice); } } }
32.390244
171
0.560994
[ "MIT" ]
SimonDarksideJ/XNAGameStudio
Samples/Spacewar_4_0/SceneGraph/Screen.cs
3,984
C#
using FavCat.CustomLists; using VRC.Core; namespace FavCat.Adapters { internal class ApiAvatarAdapter : IPickerElement { private readonly ApiAvatar myAvatar; public ApiAvatarAdapter(ApiAvatar avatar) { myAvatar = avatar; } public string Name => myAvatar.name; public string ImageUrl => myAvatar.thumbnailImageUrl; public string Id => myAvatar.id; public bool IsPrivate => myAvatar.releaseStatus != "public"; public bool SupportsDesktop => myAvatar.supportedPlatforms == ApiModel.SupportedPlatforms.StandaloneWindows || myAvatar.supportedPlatforms == ApiModel.SupportedPlatforms.All; public bool SupportsQuest => myAvatar.supportedPlatforms == ApiModel.SupportedPlatforms.Android || myAvatar.supportedPlatforms == ApiModel.SupportedPlatforms.All; public bool IsInaccessible => IsPrivate && myAvatar.authorId != APIUser.CurrentUser.id; } }
41.391304
182
0.715336
[ "Apache-2.0", "MIT" ]
anon54914/VRCMods
FavCat/Adapters/ApiAvatarAdapter.cs
952
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using VETHarbor.Data; using VETHarbor.Models; using VETHarbor.Models.ManageViewModels; using VETHarbor.Services; namespace VETHarbor.Controllers { [Authorize] [Route("[controller]/[action]")] public class ManageController : Controller { private readonly ApplicationDbContext _context; private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ILogger _logger; private readonly UrlEncoder _urlEncoder; private const string AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6"; private const string RecoveryCodesKey = nameof(RecoveryCodesKey); public ManageController( ApplicationDbContext context, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ILogger<ManageController> logger, UrlEncoder urlEncoder) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _logger = logger; _urlEncoder = urlEncoder; _context = context; } private static string GuidString(ApplicationUser user) { return user.Id.ToString(); } [TempData] public string StatusMessage { get; set; } [HttpGet] public async Task<IActionResult> Index() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } IndexViewModel model = new IndexViewModel { Username = user.UserName, Email = user.Email, OrgName = user.OrgName, OrgCity = user.OrgCity, OrgState = user.OrgState, PhoneNumber = user.PhoneNumber, IsEmailConfirmed = user.EmailConfirmed, StatusMessage = StatusMessage, }; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Index(IndexViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.GetUserAsync(User); _context.Update(user); await _context.SaveChangesAsync(); StatusMessage = "Your profile has been updated"; return RedirectToAction(nameof(Index)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SendVerificationEmail(IndexViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); string id = GuidString(user); var callbackUrl = Url.EmailConfirmationLink(id, code, Request.Scheme); var email = user.Email; await _emailSender.SendEmailConfirmationAsync(email, callbackUrl); StatusMessage = "Verification email sent. Please check your email."; return RedirectToAction(nameof(Index)); } [HttpGet] public async Task<IActionResult> ChangePassword() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var hasPassword = await _userManager.HasPasswordAsync(user); if (!hasPassword) { return RedirectToAction(nameof(SetPassword)); } var model = new ChangePasswordViewModel { StatusMessage = StatusMessage }; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var changePasswordResult = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (!changePasswordResult.Succeeded) { AddErrors(changePasswordResult); return View(model); } await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation("User changed their password successfully."); StatusMessage = "Your password has been changed."; return RedirectToAction(nameof(ChangePassword)); } [HttpGet] public async Task<IActionResult> SetPassword() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var hasPassword = await _userManager.HasPasswordAsync(user); if (hasPassword) { return RedirectToAction(nameof(ChangePassword)); } var model = new SetPasswordViewModel { StatusMessage = StatusMessage }; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var addPasswordResult = await _userManager.AddPasswordAsync(user, model.NewPassword); if (!addPasswordResult.Succeeded) { AddErrors(addPasswordResult); return View(model); } await _signInManager.SignInAsync(user, isPersistent: false); StatusMessage = "Your password has been set."; return RedirectToAction(nameof(SetPassword)); } [HttpGet] public async Task<IActionResult> ExternalLogins() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var model = new ExternalLoginsViewModel { CurrentLogins = await _userManager.GetLoginsAsync(user) }; model.OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()) .Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider)) .ToList(); model.ShowRemoveButton = await _userManager.HasPasswordAsync(user) || model.CurrentLogins.Count > 1; model.StatusMessage = StatusMessage; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LinkLogin(string provider) { // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action(nameof(LinkLoginCallback)); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); return new ChallengeResult(provider, properties); } [HttpGet] public async Task<IActionResult> LinkLoginCallback() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } string id = GuidString(user); var info = await _signInManager.GetExternalLoginInfoAsync(id); if (info == null) { throw new ApplicationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'."); } var result = await _userManager.AddLoginAsync(user, info); if (!result.Succeeded) { throw new ApplicationException($"Unexpected error occurred adding external login for user with ID '{user.Id}'."); } // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); StatusMessage = "The external login was added."; return RedirectToAction(nameof(ExternalLogins)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel model) { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var result = await _userManager.RemoveLoginAsync(user, model.LoginProvider, model.ProviderKey); if (!result.Succeeded) { throw new ApplicationException($"Unexpected error occurred removing external login for user with ID '{user.Id}'."); } await _signInManager.SignInAsync(user, isPersistent: false); StatusMessage = "The external login was removed."; return RedirectToAction(nameof(ExternalLogins)); } [HttpGet] public async Task<IActionResult> TwoFactorAuthentication() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var model = new TwoFactorAuthenticationViewModel { HasAuthenticator = await _userManager.GetAuthenticatorKeyAsync(user) != null, Is2faEnabled = user.TwoFactorEnabled, RecoveryCodesLeft = await _userManager.CountRecoveryCodesAsync(user), }; return View(model); } [HttpGet] public async Task<IActionResult> Disable2faWarning() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } if (!user.TwoFactorEnabled) { throw new ApplicationException($"Unexpected error occured disabling 2FA for user with ID '{user.Id}'."); } return View(nameof(Disable2fa)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Disable2fa() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false); if (!disable2faResult.Succeeded) { throw new ApplicationException($"Unexpected error occured disabling 2FA for user with ID '{user.Id}'."); } _logger.LogInformation("User with ID {UserId} has disabled 2fa.", user.Id); return RedirectToAction(nameof(TwoFactorAuthentication)); } [HttpGet] public async Task<IActionResult> EnableAuthenticator() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var model = new EnableAuthenticatorViewModel(); await LoadSharedKeyAndQrCodeUriAsync(user, model); return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableAuthenticator(EnableAuthenticatorViewModel model) { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } if (!ModelState.IsValid) { await LoadSharedKeyAndQrCodeUriAsync(user, model); return View(model); } // Strip spaces and hypens var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty); var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync( user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode); if (!is2faTokenValid) { ModelState.AddModelError("Code", "Verification code is invalid."); await LoadSharedKeyAndQrCodeUriAsync(user, model); return View(model); } await _userManager.SetTwoFactorEnabledAsync(user, true); _logger.LogInformation("User with ID {UserId} has enabled 2FA with an authenticator app.", user.Id); var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); TempData[RecoveryCodesKey] = recoveryCodes.ToArray(); return RedirectToAction(nameof(ShowRecoveryCodes)); } [HttpGet] public IActionResult ShowRecoveryCodes() { var recoveryCodes = (string[])TempData[RecoveryCodesKey]; if (recoveryCodes == null) { return RedirectToAction(nameof(TwoFactorAuthentication)); } var model = new ShowRecoveryCodesViewModel { RecoveryCodes = recoveryCodes }; return View(model); } [HttpGet] public IActionResult ResetAuthenticatorWarning() { return View(nameof(ResetAuthenticator)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetAuthenticator() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } await _userManager.SetTwoFactorEnabledAsync(user, false); await _userManager.ResetAuthenticatorKeyAsync(user); _logger.LogInformation("User with id '{UserId}' has reset their authentication app key.", user.Id); return RedirectToAction(nameof(EnableAuthenticator)); } [HttpGet] public async Task<IActionResult> GenerateRecoveryCodesWarning() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } if (!user.TwoFactorEnabled) { throw new ApplicationException($"Cannot generate recovery codes for user with ID '{user.Id}' because they do not have 2FA enabled."); } return View(nameof(GenerateRecoveryCodes)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> GenerateRecoveryCodes() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } if (!user.TwoFactorEnabled) { throw new ApplicationException($"Cannot generate recovery codes for user with ID '{user.Id}' as they do not have 2FA enabled."); } var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); _logger.LogInformation("User with ID {UserId} has generated new 2FA recovery codes.", user.Id); var model = new ShowRecoveryCodesViewModel { RecoveryCodes = recoveryCodes.ToArray() }; return View(nameof(ShowRecoveryCodes), model); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private string FormatKey(string unformattedKey) { var result = new StringBuilder(); int currentPosition = 0; while (currentPosition + 4 < unformattedKey.Length) { result.Append(unformattedKey.Substring(currentPosition, 4)).Append(" "); currentPosition += 4; } if (currentPosition < unformattedKey.Length) { result.Append(unformattedKey.Substring(currentPosition)); } return result.ToString().ToLowerInvariant(); } private string GenerateQrCodeUri(string email, string unformattedKey) { return string.Format( AuthenticatorUriFormat, _urlEncoder.Encode("VETHarbor"), _urlEncoder.Encode(email), unformattedKey); } private async Task LoadSharedKeyAndQrCodeUriAsync(ApplicationUser user, EnableAuthenticatorViewModel model) { var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await _userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); } model.SharedKey = FormatKey(unformattedKey); model.AuthenticatorUri = GenerateQrCodeUri(user.Email, unformattedKey); } #endregion } }
36.080146
149
0.593245
[ "MIT" ]
eagobert/CSharp-VetHarborProject
VETHarbor/VETHarbor/Controllers/ManageController.cs
19,810
C#
namespace WebMVC.EntityFramework { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class TRANSACTION_DETAIL { [Key] [Column(Order = 0)] [StringLength(20)] public string TransactionCode { get; set; } [Key] [Column(Order = 1, TypeName = "date")] public DateTime ReportDate { get; set; } [Required] [StringLength(10)] public string MerchantCode { get; set; } [Required] [StringLength(20)] public string TerminalNumber { get; set; } public int FileSource { get; set; } public long? BatchNumber { get; set; } [Column(TypeName = "date")] public DateTime? ExpirationDate { get; set; } [StringLength(10)] public string CardtypeCode { get; set; } [Column(TypeName = "money")] public decimal? TransactionAmount { get; set; } [Column(TypeName = "date")] public DateTime? TransactionDate { get; set; } public TimeSpan? TransactionTime { get; set; } public bool? KeyedEntry { get; set; } [StringLength(20)] public string AuthorizationNumber { get; set; } public TimeSpan? ReportTime { get; set; } [StringLength(50)] public string Description { get; set; } [Required] [StringLength(20)] public string AccountNumber { get; set; } [StringLength(12)] public string FirstTwelveAccountNumber { get; set; } [StringLength(10)] public string TransactionTypeCode { get; set; } [StringLength(10)] public string RegionCode { get; set; } [StringLength(10)] public string MerchantType { get; set; } [StringLength(10)] public string AgentCode { get; set; } public virtual CARD CARD { get; set; } public virtual MERCHANT MERCHANT { get; set; } public virtual TRANSACTION_TYPE TRANSACTION_TYPE { get; set; } } }
26.243902
70
0.597584
[ "MIT" ]
1312602/Quan-Ly-Merchant
WebServer/WebMVC/EntityFramework/TRANSACTION_DETAIL.cs
2,152
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System.Linq; using System.Security.Claims; using System.Text; namespace TransAction.API.Authorization { public class ClaimRequirementAttribute : TypeFilterAttribute { public ClaimRequirementAttribute(string claimValue) : base(typeof(ClaimRequirementFilter)) { Arguments = new object[] { new Claim(AuthorizationTypes.TRA_CLAIM_TYPE, claimValue) }; } } public class ClaimRequirementFilter : IAuthorizationFilter { readonly Claim _claim; public ClaimRequirementFilter(Claim claim) { _claim = claim; } public void OnAuthorization(AuthorizationFilterContext context) { var hasClaim = context.HttpContext.User.Claims.Any(c => c.Type == _claim.Type && c.Value == _claim.Value); if (!hasClaim) { context.Result = new UnauthorizedResult(); HttpResponse response = context.HttpContext.Response; string responseText = "Insufficient permission"; byte[] data = Encoding.UTF8.GetBytes(responseText); response.StatusCode = 403; // forbidden response.Body.Write(data, 0, data.Length); response.Body.FlushAsync(); } } } }
30.06383
118
0.629866
[ "Apache-2.0" ]
DSoLetsDev/TransAction
api/TransAction.API/Authorization/ClaimRequirementAttribute.cs
1,415
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using ThinkGeo.MapSuite.Layers; using ThinkGeo.MapSuite.Shapes; namespace ThinkGeo.MapSuite.WpfDesktop.Extension { public static class ShapeFileFeatureLayerExtension { private static readonly int recordLength = 4; private static readonly int shxHeaderLength = 100; public static int GetRecordCount(this ShapeFileFeatureLayer featureLayer) { return GetRecordCountInternal(featureLayer); } public static Dictionary<int, int> GetRecordsContentLength(this ShapeFileFeatureLayer featureLayer, IEnumerable<int> ids) { return GetRecordContentLengthInternal(featureLayer, ids); } public static Collection<int> GetAvailableFeatureIds(this ShapeFileFeatureLayer featureLayer) { return GetAvailableFeatureIdsInternal(featureLayer); } public static ShapeFileType GetShapeFileType(string shapePathFileName) { return GetShapeFileTypeInternal(shapePathFileName); } public static void RemoveShapeFiles(string shapePathFileName) { IOUtil.RemoveShapeFiles(shapePathFileName); } private static ShapeFileType GetShapeFileTypeInternal(string shapePathFileName) { Stream stream = null; try { stream = File.OpenRead(shapePathFileName); stream.Seek(32, SeekOrigin.Begin); var shapeTypeFlag = IOUtil.ReadIntFromStream(stream, WkbByteOrder.LittleEndian); return ShapeFileHeader.ConvertIntToShapeFileType(shapeTypeFlag); } finally { if (stream != null) stream.Dispose(); } } private static Collection<int> GetAvailableFeatureIdsInternal(ShapeFileFeatureLayer featureLayer) { Collection<int> results = new Collection<int>(); string shxPathFileName = Path.ChangeExtension(featureLayer.ShapePathFilename, ".shx"); ShapeFileIndex shx = null; try { shx = new ShapeFileIndex(shxPathFileName); shx.Open(); var count = shx.GetRecordCount(); for (int i = 1; i <= count; i++) { var contentLength = shx.GetRecordContentLength(i); if (contentLength != 0) { results.Add(i); } } } finally { if (shx != null) shx.Close(); } return results; } private static Dictionary<int, int> GetRecordContentLengthInternal(ShapeFileFeatureLayer featureLayer, IEnumerable<int> ids) { Dictionary<int, int> results = new Dictionary<int, int>(); string shxPathFileName = Path.ChangeExtension(featureLayer.ShapePathFilename, ".shx"); ShapeFileIndex shx = null; try { shx = new ShapeFileIndex(shxPathFileName); shx.Open(); foreach (var id in ids) { int contentLength = shx.GetRecordContentLength(id); results.Add(id, contentLength); } } finally { if (shx != null) shx.Close(); } return results; } private static int GetRecordCountInternal(ShapeFileFeatureLayer featureLayer) { if (featureLayer.RequireIndex && File.Exists(featureLayer.IndexPathFilename)) { using (RtreeSpatialIndex index = new RtreeSpatialIndex(featureLayer.IndexPathFilename)) { index.Open(); int recordCount = index.GetFeatureCount(); index.Close(); return recordCount; } } else { int recordCount = featureLayer.QueryTools.GetCount(); string shxFilePath = Path.ChangeExtension(featureLayer.ShapePathFilename, "shx"); FileStream shxFileStream = File.OpenRead(shxFilePath); BinaryReader shxReader = new BinaryReader(shxFileStream); try { shxReader.BaseStream.Seek(shxHeaderLength, SeekOrigin.Begin); bool needBreak = false; while (shxReader.BaseStream.Position != shxReader.BaseStream.Length) { shxReader.BaseStream.Seek(recordLength, SeekOrigin.Current); int length = 0; if (shxReader.BaseStream.Position != shxReader.BaseStream.Length) length = shxReader.ReadInt32(); else needBreak = true; if (length == 0) recordCount--; if (needBreak) break; } } finally { shxFileStream.Close(); shxReader.Close(); } return recordCount; } } } }
36.5
132
0.565995
[ "Apache-2.0" ]
ThinkGeo/GIS-Editor
MapSuiteGisEditor/WpfDesktopExtension/Shares/Extensions/ShapeFileFeatureLayerExtension.cs
6,205
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("Craigslist8X")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("William Bishop")] [assembly: AssemblyProduct("Craigslist8X")] [assembly: AssemblyCopyright("Copyright © William Bishop 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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.6.4.0")] [assembly: AssemblyFileVersion("1.6.4.0")] [assembly: ComVisible(false)]
36.862069
84
0.746492
[ "MIT" ]
wbish/Craigslist-8X
Win8/Craigslist8X/Craigslist8X/Properties/AssemblyInfo.cs
1,072
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.AwsNative.KinesisAnalytics.Outputs { [OutputType] public sealed class ApplicationReferenceDataSourceRecordFormat { public readonly Outputs.ApplicationReferenceDataSourceMappingParameters? MappingParameters; public readonly string RecordFormatType; [OutputConstructor] private ApplicationReferenceDataSourceRecordFormat( Outputs.ApplicationReferenceDataSourceMappingParameters? mappingParameters, string recordFormatType) { MappingParameters = mappingParameters; RecordFormatType = recordFormatType; } } }
31.2
99
0.733974
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/KinesisAnalytics/Outputs/ApplicationReferenceDataSourceRecordFormat.cs
936
C#
using FoxDb.Interfaces; using System; namespace FoxDb { public class EntityPopulator : IEntityPopulator { public EntityPopulator(IDatabase database, ITableConfig table) { this.Database = database; this.Table = table; } public IDatabase Database { get; private set; } public ITableConfig Table { get; private set; } public void Populate(object item, IDatabaseReaderRecord record) { foreach (var column in this.Table.Columns) { this.Populate(item, column, record); } } public bool Populate(object item, IColumnConfig column, IDatabaseReaderRecord record) { if (column.Setter == null) { return false; } var value = default(object); if (record.TryGetValue(column, out value)) { if (value == null || DBNull.Value.Equals(value)) { value = null; } column.Setter( item, this.Database.Translation.GetLocalValue(column.ColumnType.Type, value) ); return true; } return false; } } }
27.938776
94
0.483565
[ "MIT" ]
Raimusoft/FoxDb
FoxDb.Core/Entity/EntityPopulator.cs
1,371
C#
// <auto-generated /> using System; using Harvest.Core.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using NetTopologySuite.Geometries; namespace Harvest.Core.Migrations.Sqlite { [DbContext(typeof(AppDbContextSqlite))] [Migration("20210413211913_QuoteInitiatorSpelling")] partial class QuoteInitiatorSpelling { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "5.0.1"); modelBuilder.Entity("Harvest.Core.Domain.Account", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("ApprovedById") .HasColumnType("INTEGER"); b.Property<DateTime>("ApprovedOn") .HasColumnType("TEXT"); b.Property<string>("Name") .HasMaxLength(200) .HasColumnType("TEXT"); b.Property<string>("Number") .HasMaxLength(100) .HasColumnType("TEXT"); b.Property<decimal>("Percentage") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("ApprovedById"); b.HasIndex("Name"); b.HasIndex("Number"); b.HasIndex("ProjectId"); b.ToTable("Accounts"); }); modelBuilder.Entity("Harvest.Core.Domain.Document", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Identifier") .IsRequired() .HasMaxLength(200) .HasColumnType("TEXT"); b.Property<string>("Name") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<int>("QuoteId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("Name"); b.HasIndex("QuoteId") .IsUnique(); b.ToTable("Documents"); }); modelBuilder.Entity("Harvest.Core.Domain.Expense", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("CreatedById") .HasColumnType("INTEGER"); b.Property<DateTime>("CreatedOn") .HasColumnType("TEXT"); b.Property<string>("Description") .IsRequired() .HasMaxLength(250) .HasColumnType("TEXT"); b.Property<int?>("InvoiceId") .HasColumnType("INTEGER"); b.Property<decimal>("Price") .HasColumnType("TEXT"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.Property<decimal>("Quantity") .HasColumnType("TEXT"); b.Property<int>("RateId") .HasColumnType("INTEGER"); b.Property<decimal>("Total") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<string>("Type") .IsRequired() .HasMaxLength(15) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("CreatedById"); b.HasIndex("InvoiceId"); b.HasIndex("ProjectId"); b.HasIndex("RateId"); b.ToTable("Expenses"); }); modelBuilder.Entity("Harvest.Core.Domain.Invoice", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime>("CreatedOn") .HasColumnType("TEXT"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.Property<decimal>("Total") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("ProjectId"); b.ToTable("Invoices"); }); modelBuilder.Entity("Harvest.Core.Domain.Notification", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Body") .IsRequired() .HasColumnType("TEXT"); b.Property<string>("Email") .IsRequired() .HasMaxLength(300) .HasColumnType("TEXT"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.Property<bool>("Sent") .HasColumnType("INTEGER"); b.Property<string>("Subject") .IsRequired() .HasMaxLength(300) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("ProjectId"); b.ToTable("Notifications"); }); modelBuilder.Entity("Harvest.Core.Domain.Permission", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int>("RoleId") .HasColumnType("INTEGER"); b.Property<int>("UserId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("Permissions"); }); modelBuilder.Entity("Harvest.Core.Domain.Project", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<decimal>("ChargedTotal") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<int>("CreatedById") .HasColumnType("INTEGER"); b.Property<DateTime>("CreatedOn") .HasColumnType("TEXT"); b.Property<string>("Crop") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<int>("CurrentAccountVersion") .HasColumnType("INTEGER"); b.Property<DateTime>("End") .HasColumnType("TEXT"); b.Property<bool>("IsActive") .HasColumnType("INTEGER"); b.Property<Geometry>("Location") .HasColumnType("GEOMETRY"); b.Property<string>("LocationCode") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("Name") .HasMaxLength(200) .HasColumnType("TEXT"); b.Property<int>("PrincipalInvestigatorId") .HasColumnType("INTEGER"); b.Property<int?>("QuoteId") .HasColumnType("INTEGER"); b.Property<int?>("QuoteId1") .HasColumnType("INTEGER"); b.Property<decimal>("QuoteTotal") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<string>("Requirements") .HasColumnType("TEXT"); b.Property<DateTime>("Start") .HasColumnType("TEXT"); b.Property<string>("Status") .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("CreatedById"); b.HasIndex("Name"); b.HasIndex("PrincipalInvestigatorId"); b.HasIndex("QuoteId"); b.HasIndex("QuoteId1"); b.ToTable("Projects"); }); modelBuilder.Entity("Harvest.Core.Domain.ProjectHistory", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Action") .HasMaxLength(200) .HasColumnType("TEXT"); b.Property<DateTime>("ActionDate") .HasColumnType("TEXT"); b.Property<int>("Actor") .HasMaxLength(20) .HasColumnType("INTEGER"); b.Property<string>("ActorName") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("Description") .HasColumnType("TEXT"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.Property<string>("Type") .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("ProjectId"); b.ToTable("ProjectHistory"); }); modelBuilder.Entity("Harvest.Core.Domain.Quote", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int?>("ApprovedById") .HasColumnType("INTEGER"); b.Property<DateTime?>("ApprovedOn") .HasColumnType("TEXT"); b.Property<DateTime>("CreatedDate") .HasColumnType("TEXT"); b.Property<int?>("CurrentDocumentId") .HasColumnType("INTEGER"); b.Property<int>("InitiatedById") .HasColumnType("INTEGER"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.Property<string>("Status") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("Text") .HasColumnType("TEXT"); b.Property<decimal>("Total") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("ApprovedById"); b.HasIndex("CurrentDocumentId") .IsUnique(); b.HasIndex("InitiatedById"); b.HasIndex("ProjectId"); b.ToTable("Quotes"); }); modelBuilder.Entity("Harvest.Core.Domain.Rate", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Account") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("BillingUnit") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<int>("CreatedById") .HasColumnType("INTEGER"); b.Property<DateTime>("CreatedOn") .HasColumnType("TEXT"); b.Property<string>("Description") .IsRequired() .HasMaxLength(250) .HasColumnType("TEXT"); b.Property<DateTime?>("EffectiveOn") .HasColumnType("TEXT"); b.Property<bool>("IsActive") .HasColumnType("INTEGER"); b.Property<decimal>("Price") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<string>("Type") .IsRequired() .HasMaxLength(15) .HasColumnType("TEXT"); b.Property<string>("Unit") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<int>("UpdatedById") .HasColumnType("INTEGER"); b.Property<DateTime>("UpdatedOn") .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("CreatedById"); b.HasIndex("Description"); b.HasIndex("Type"); b.HasIndex("UpdatedById"); b.ToTable("Rates"); }); modelBuilder.Entity("Harvest.Core.Domain.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("Name") .IsUnique(); b.ToTable("Roles"); }); modelBuilder.Entity("Harvest.Core.Domain.Transfer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<decimal>("Amount") .HasPrecision(18, 2) .HasColumnType("TEXT"); b.Property<string>("Description") .HasMaxLength(40) .HasColumnType("TEXT"); b.Property<int>("FromAccountId") .HasColumnType("INTEGER"); b.Property<int>("ToAccountId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("FromAccountId"); b.HasIndex("ToAccountId"); b.ToTable("Transfers"); }); modelBuilder.Entity("Harvest.Core.Domain.TransferHistory", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Action") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<DateTime>("ActionDateTime") .HasColumnType("TEXT"); b.Property<string>("ActorId") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("ActorName") .HasMaxLength(250) .HasColumnType("TEXT"); b.Property<string>("Notes") .HasColumnType("TEXT"); b.Property<string>("Status") .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<int>("TransferId") .HasColumnType("INTEGER"); b.HasKey("Id"); b.HasIndex("TransferId"); b.ToTable("TransferHistory"); }); modelBuilder.Entity("Harvest.Core.Domain.TransferRequest", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Description") .HasMaxLength(40) .HasColumnType("TEXT"); b.Property<bool>("IsDeleted") .HasColumnType("INTEGER"); b.Property<string>("KfsTrackingNumber") .HasMaxLength(20) .HasColumnType("TEXT"); b.Property<int>("ProjectId") .HasColumnType("INTEGER"); b.Property<int>("RequestedById") .HasColumnType("INTEGER"); b.Property<DateTime>("RequestedOn") .HasColumnType("TEXT"); b.Property<Guid?>("SlothTransactionId") .HasColumnType("TEXT"); b.Property<string>("Status") .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("ProjectId"); b.HasIndex("RequestedById"); b.ToTable("TransferRequests"); }); modelBuilder.Entity("Harvest.Core.Domain.User", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Email") .IsRequired() .HasMaxLength(300) .HasColumnType("TEXT"); b.Property<string>("FirstName") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.Property<string>("Iam") .HasMaxLength(10) .HasColumnType("TEXT"); b.Property<string>("Kerberos") .HasMaxLength(20) .HasColumnType("TEXT"); b.Property<string>("LastName") .IsRequired() .HasMaxLength(50) .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("Email"); b.HasIndex("Iam"); b.HasIndex("Kerberos"); b.ToTable("Users"); }); modelBuilder.Entity("Harvest.Core.Domain.Account", b => { b.HasOne("Harvest.Core.Domain.User", "ApprovedBy") .WithMany() .HasForeignKey("ApprovedById") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany("Accounts") .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("ApprovedBy"); b.Navigation("Project"); }); modelBuilder.Entity("Harvest.Core.Domain.Document", b => { b.HasOne("Harvest.Core.Domain.Quote", null) .WithMany("Documents") .HasForeignKey("QuoteId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Harvest.Core.Domain.Expense", b => { b.HasOne("Harvest.Core.Domain.User", "CreatedBy") .WithMany() .HasForeignKey("CreatedById") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Harvest.Core.Domain.Invoice", "Invoice") .WithMany("Expenses") .HasForeignKey("InvoiceId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany() .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Harvest.Core.Domain.Rate", "Rate") .WithMany() .HasForeignKey("RateId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("CreatedBy"); b.Navigation("Invoice"); b.Navigation("Project"); b.Navigation("Rate"); }); modelBuilder.Entity("Harvest.Core.Domain.Invoice", b => { b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany() .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Project"); }); modelBuilder.Entity("Harvest.Core.Domain.Notification", b => { b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany() .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Project"); }); modelBuilder.Entity("Harvest.Core.Domain.Permission", b => { b.HasOne("Harvest.Core.Domain.Role", "Role") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Harvest.Core.Domain.User", "User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Role"); b.Navigation("User"); }); modelBuilder.Entity("Harvest.Core.Domain.Project", b => { b.HasOne("Harvest.Core.Domain.User", "CreatedBy") .WithMany("CreatedProjects") .HasForeignKey("CreatedById") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Harvest.Core.Domain.User", "PrincipalInvestigator") .WithMany("PrincipalInvestigatorProjects") .HasForeignKey("PrincipalInvestigatorId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Harvest.Core.Domain.Quote", "Quote") .WithMany() .HasForeignKey("QuoteId1"); b.Navigation("CreatedBy"); b.Navigation("PrincipalInvestigator"); b.Navigation("Quote"); }); modelBuilder.Entity("Harvest.Core.Domain.ProjectHistory", b => { b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany() .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Project"); }); modelBuilder.Entity("Harvest.Core.Domain.Quote", b => { b.HasOne("Harvest.Core.Domain.User", "ApprovedBy") .WithMany() .HasForeignKey("ApprovedById"); b.HasOne("Harvest.Core.Domain.Document", "CurrentDocument") .WithOne("Quote") .HasForeignKey("Harvest.Core.Domain.Quote", "CurrentDocumentId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("Harvest.Core.Domain.User", "InitiatedBy") .WithMany() .HasForeignKey("InitiatedById") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany("Quotes") .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("ApprovedBy"); b.Navigation("CurrentDocument"); b.Navigation("InitiatedBy"); b.Navigation("Project"); }); modelBuilder.Entity("Harvest.Core.Domain.Rate", b => { b.HasOne("Harvest.Core.Domain.User", "CreatedBy") .WithMany("CreatedRates") .HasForeignKey("CreatedById") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Harvest.Core.Domain.User", "UpdatedBy") .WithMany("UpdatedRates") .HasForeignKey("UpdatedById") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("CreatedBy"); b.Navigation("UpdatedBy"); }); modelBuilder.Entity("Harvest.Core.Domain.Transfer", b => { b.HasOne("Harvest.Core.Domain.Account", "FromAccount") .WithMany() .HasForeignKey("FromAccountId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("Harvest.Core.Domain.Account", "ToAccount") .WithMany() .HasForeignKey("ToAccountId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("FromAccount"); b.Navigation("ToAccount"); }); modelBuilder.Entity("Harvest.Core.Domain.TransferHistory", b => { b.HasOne("Harvest.Core.Domain.TransferRequest", null) .WithMany("History") .HasForeignKey("TransferId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Harvest.Core.Domain.TransferRequest", b => { b.HasOne("Harvest.Core.Domain.Project", "Project") .WithMany() .HasForeignKey("ProjectId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Harvest.Core.Domain.User", "RequestedBy") .WithMany() .HasForeignKey("RequestedById") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Project"); b.Navigation("RequestedBy"); }); modelBuilder.Entity("Harvest.Core.Domain.Document", b => { b.Navigation("Quote"); }); modelBuilder.Entity("Harvest.Core.Domain.Invoice", b => { b.Navigation("Expenses"); }); modelBuilder.Entity("Harvest.Core.Domain.Project", b => { b.Navigation("Accounts"); b.Navigation("Quotes"); }); modelBuilder.Entity("Harvest.Core.Domain.Quote", b => { b.Navigation("Documents"); }); modelBuilder.Entity("Harvest.Core.Domain.TransferRequest", b => { b.Navigation("History"); }); modelBuilder.Entity("Harvest.Core.Domain.User", b => { b.Navigation("CreatedProjects"); b.Navigation("CreatedRates"); b.Navigation("Permissions"); b.Navigation("PrincipalInvestigatorProjects"); b.Navigation("UpdatedRates"); }); #pragma warning restore 612, 618 } } }
33.717149
88
0.408779
[ "MIT" ]
ucdavis/Harvest
Harvest.Core/Migrations/Sqlite/20210413211913_QuoteInitiatorSpelling.Designer.cs
30,280
C#
using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions.LanguageExt; using SparkPostFun.Sending; using Xunit; namespace SparkPostFun.Tests.TestCase; public class TemplateTest : IClassFixture<TestCaseEmailsFixture> { private readonly TestCaseEmailsFixture fixture; public TemplateTest(TestCaseEmailsFixture fixture) { this.fixture = fixture; } private class Order { public int OrderId { get; set; } public string Desc { get; set; } public int Total { get; set; } } [Fact] public async Task Template_returns_expected_result() { var address = new Address(fixture.ToAddress); var recipients = new List<Recipient> { new(address) { SubstitutionData = new Dictionary<string, object> { ["firstName"] = "Jane" } } }; var returnPath = new SenderAddress(fixture.FromAddress); var content = new StoredTemplateContent("orderSummary") { UseDraftTemplate = true }; var substitutionData = new Dictionary<string, object> { ["title"] = "Dr", ["firstName"] = "Rick", ["lastName"] = "Sanchez", ["orders"] = new List<Order> { new() { OrderId = 101, Desc = "Tomatoes", Total = 5}, new() { OrderId = 271, Desc = "Entropy", Total = 314} } }; var transmission = TransmissionExtensions.CreateTransmission(recipients, content) .WithSubstitutionData(substitutionData) .WithReturnPath(returnPath); var response = await fixture.Client.CreateTransmission(transmission); response.Should().BeRight(); } }
28.313433
89
0.560886
[ "Apache-2.0" ]
jmojiwat/SparkPostFun
src/SparkPostFun.Tests/TestCase/TemplateTest.cs
1,897
C#
using System; using System.Collections.Generic; using System.Text; using Battle.Weapons; using FluentAssertions; using NSubstitute; using Xunit; namespace Battle.Tests { public class ArmyTest { private readonly IHeadquarters _hqMock = Substitute.For<IHeadquarters>(); [Fact] public void Army_CanEnlistSoldiers() { var army = new Army(_hqMock); var soldier = new Soldier("Private Ryan"); army.EnlistSoldier(soldier); army.Soldiers.Should().Contain(soldier); } [Fact] public void Army_HasFrontMan() { var army = new Army(_hqMock); var soldier = new Soldier("Private Ryan"); army.EnlistSoldier(soldier); army.EnlistSoldier(new Soldier("Himmler")); army.FrontMan.Should().Be(soldier); } [Fact] public void Army_CanFightOtherArmyAndWin() { var axe = new Axe(); var ryan = new Soldier("Private Ryan"); var eisenhower = new Soldier("eisenhower") { Weapon = axe }; var alliance = new Army(_hqMock); alliance.EnlistSoldier(ryan); alliance.EnlistSoldier(eisenhower); var sword = new Sword(); var himmler = new Soldier("himmler") { Weapon = sword }; var germans = new Army(_hqMock); germans.EnlistSoldier(himmler); alliance.Engage(germans).Should().BeTrue(); alliance.Soldiers.Should().OnlyContain(s => s == eisenhower); } [Fact] public void Army_CanFightOtherArmyAndLose() { var axe = new Axe(); var ryan = new Soldier("Private Ryan"); var eisenhower = new Soldier("eisenhower") { Weapon = axe }; var alliance = new Army(_hqMock); alliance.EnlistSoldier(ryan); alliance.EnlistSoldier(eisenhower); var sword = new Sword(); var himmler = new Soldier("himmler") { Weapon = sword }; var germans = new Army(_hqMock); germans.EnlistSoldier(himmler); germans.Engage(alliance).Should().BeFalse(); alliance.Soldiers.Should().OnlyContain(s => s == eisenhower); } [Fact] public void Army_CantFightItself() { var army = new Army(_hqMock); Action act = () => army.Engage(army); act.Should().Throw<ArgumentException>(); } } }
28.284211
81
0.527726
[ "MIT" ]
JasDesc/XPTraining-battle
Battle.Tests/ArmyTest.cs
2,689
C#
//----------------------------------------------------------------------- // <copyright file="ClientData.cs" company="Sully"> // Copyright (c) Johnathon Sullinger. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace MudDesigner.Adapters.Server { using MudDesigner.Engine.Game; /// <summary> /// Represents data received or sent from the client. /// </summary> public sealed class ClientData { public ClientData(IPlayer player, IConnection connection, string data) { this.Player = player; this.Connection = connection; this.Data = data; } /// <summary> /// Gets the player that is the owner of the data. /// </summary> public IPlayer Player { get; } /// <summary> /// Gets the connection that the data is associated with. /// </summary> public IConnection Connection { get; } /// <summary> /// Gets the data generated by the player. /// </summary> public string Data { get; } } }
30.783784
78
0.499561
[ "MIT" ]
MudDesigner/MudDesigner
Source/Runtime/MudDesigner.Adapters.Server/ClientData.cs
1,139
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary.EN{ public class enlinped{ // parte privada (propiedades de linea de pedido) private int numPedido; private int linea; private int producto; private float precio; private int cantidad; //******************************************** // constructores // constructor por defecto public enlinped() { } //constructor parametrizado public enlinped(Producto pro, pedido ped) { numPedido = ped.NumPedido; producto = pro.Id; precio = pro.Precio; //cantidad = ped.Cantidad; //linea = } //******************************************** // get set public int NumPedido { get { return numPedido; } set { numPedido = value; } } public int Linea { get { return linea; } set { linea = value; } } public int Producto { get { return producto; } set { producto = value; } } public float Precio { get { return precio; } set { precio = value; } } public int Cantidad { get { return cantidad; } set { cantidad = value; } } //******************************************** // metodos // añade una linea de pedido public void addLinped(Producto pro, pedido ped) { CAD.CADlinped lin = new CAD.CADlinped(); lin.create(this); } // borra una linea de pedido public void deleteLinped(Producto pro, pedido ped) { CAD.CADlinped lin = new CAD.CADlinped(); lin.delete(this); } // modifica una linea de pedido public void updateLinped(Producto pro, pedido ped) { CAD.CADlinped lin = new CAD.CADlinped(); //lin.update(); } // lee, muestra los datos de una linea de pedido public string leerLinped(Producto pro, pedido ped) { string salida = ""; CAD.CADlinped lin = new CAD.CADlinped(); salida = salida + lin.read(this); return salida; } } }
23.873786
58
0.473363
[ "MIT" ]
ajah1/practicahada
BASE DE DATOS/practicahadagrupal/ClassLibrary/EN/enlinped.cs
2,462
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class dissappear : MonoBehaviour, IToggleable { [SerializeField] SpriteRenderer sr; [SerializeField] Collider2D col; [SerializeField] bool is_solid = true; public bool state => is_solid; public void ToggleState() { is_solid = !is_solid; col.enabled = is_solid; sr.color = is_solid ? sr.color.setA(1) : sr.color.setA(.5f); } }
20.083333
68
0.657676
[ "MIT" ]
squagonal/Rocketskates
Assets/dissappear.cs
484
C#
#if !NETSTANDARD13 /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the fsx-2018-03-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; namespace Amazon.FSx.Model { /// <summary> /// Base class for DescribeFileSystemAliases paginators. /// </summary> internal sealed partial class DescribeFileSystemAliasesPaginator : IPaginator<DescribeFileSystemAliasesResponse>, IDescribeFileSystemAliasesPaginator { private readonly IAmazonFSx _client; private readonly DescribeFileSystemAliasesRequest _request; private int _isPaginatorInUse = 0; /// <summary> /// Enumerable containing all full responses for the operation /// </summary> public IPaginatedEnumerable<DescribeFileSystemAliasesResponse> Responses => new PaginatedResponse<DescribeFileSystemAliasesResponse>(this); internal DescribeFileSystemAliasesPaginator(IAmazonFSx client, DescribeFileSystemAliasesRequest request) { this._client = client; this._request = request; } #if BCL IEnumerable<DescribeFileSystemAliasesResponse> IPaginator<DescribeFileSystemAliasesResponse>.Paginate() { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; DescribeFileSystemAliasesResponse response; do { _request.NextToken = nextToken; response = _client.DescribeFileSystemAliases(_request); nextToken = response.NextToken; yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif #if AWS_ASYNC_ENUMERABLES_API async IAsyncEnumerable<DescribeFileSystemAliasesResponse> IPaginator<DescribeFileSystemAliasesResponse>.PaginateAsync(CancellationToken cancellationToken = default) { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } PaginatorUtils.SetUserAgentAdditionOnRequest(_request); var nextToken = _request.NextToken; DescribeFileSystemAliasesResponse response; do { _request.NextToken = nextToken; response = await _client.DescribeFileSystemAliasesAsync(_request, cancellationToken).ConfigureAwait(false); nextToken = response.NextToken; cancellationToken.ThrowIfCancellationRequested(); yield return response; } while (!string.IsNullOrEmpty(nextToken)); } #endif } } #endif
41.247312
172
0.666319
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/FSx/Generated/Model/_bcl45+netstandard/DescribeFileSystemAliasesPaginator.cs
3,836
C#
using System.IO; using System.Linq; using NUnit.Framework; namespace Xamarin.iOS.Tasks { public class ExtensionTestBase : TestBase { public string BundlePath; public string Platform; public ExtensionTestBase () { } public ExtensionTestBase (string platform) { Platform = platform; } public ExtensionTestBase (string bundlePath, string platform) { BundlePath = bundlePath; Platform = platform; } public void BuildExtension (string hostAppName, string extensionName, string platform, int expectedErrorCount = 0) { BuildExtension (hostAppName, extensionName, platform, platform, expectedErrorCount); } public void BuildExtension (string hostAppName, string extensionName, string bundlePath, string platform, int expectedErrorCount = 0) { var mtouchPaths = SetupProjectPaths (hostAppName, "../", true, bundlePath); var proj = SetupProject (Engine, mtouchPaths ["project_csprojpath"]); AppBundlePath = mtouchPaths ["app_bundlepath"]; string extensionPath = Path.Combine(AppBundlePath, "PlugIns", extensionName + ".appex"); Engine.GlobalProperties.SetProperty ("Platform", platform); RunTarget (proj, "Clean"); Assert.IsFalse (Directory.Exists (AppBundlePath), "{1}: App bundle exists after cleanup: {0} ", AppBundlePath, bundlePath); proj = SetupProject (Engine, mtouchPaths.ProjectCSProjPath); RunTarget (proj, "Build", expectedErrorCount); if (expectedErrorCount > 0) return; Assert.IsTrue (Directory.Exists (AppBundlePath), "{1} App Bundle does not exist: {0} ", AppBundlePath, bundlePath); TestPList (AppBundlePath, new string[] {"CFBundleExecutable", "CFBundleVersion"}); Assert.IsTrue (Directory.Exists (extensionPath), "Appex directory does not exist: {0} ", extensionPath); TestPList (extensionPath, new string[] {"CFBundleExecutable", "CFBundleVersion"}); TestFilesExists (AppBundlePath, ExpectedAppFiles); TestFilesDoNotExist (AppBundlePath, UnexpectedAppFiles); var coreFiles = platform == "iPhone" ? CoreAppFiles : CoreAppFiles.Union (new string [] { hostAppName + ".exe", hostAppName }).ToArray (); if (IsTVOS) TestFilesExists (platform == "iPhone" ? Path.Combine (AppBundlePath, ".monotouch-64") : AppBundlePath, coreFiles); else if (IsWatchOS) { coreFiles = platform == "iPhone" ? CoreAppFiles : CoreAppFiles.Union (new string [] { extensionName + ".dll", Path.GetFileNameWithoutExtension (extensionPath) }).ToArray (); TestFilesExists (platform == "iPhone" ? Path.Combine (extensionPath, ".monotouch-32") : extensionPath, coreFiles); } else TestFilesExists (platform == "iPhone" ? Path.Combine (AppBundlePath, ".monotouch-32") : AppBundlePath, coreFiles); } public void SetupPaths (string appName, string platform) { var paths = this.SetupProjectPaths (appName, "../", true, platform); MonoTouchProjectPath = paths ["project_path"]; AppBundlePath = paths ["app_bundlepath"]; } [SetUp] public override void Setup () { SetupEngine (); } } }
36.457831
177
0.721414
[ "BSD-3-Clause" ]
ludovic-henry/xamarin-macios
msbuild/tests/Xamarin.iOS.Tasks.Tests/ProjectsTests/Extensions/ExtensionTestBase.cs
3,028
C#
// =========================================================== // Copyright (C) 2014-2015 Kendar.org // // 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 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.Text; namespace Node.Cs.Lib.Utils { public class EncodingWrapper : Encoding { private readonly Encoding _encoding; public EncodingWrapper(Encoding encoding) { _encoding = encoding; } public override byte[] GetPreamble() { return new byte[0]; } public override int GetByteCount(char[] chars, int index, int count) { return _encoding.GetByteCount(chars, index, count); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { return _encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex); } public override int GetCharCount(byte[] bytes, int index, int count) { return _encoding.GetCharCount(bytes, index, count); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return _encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex); } public override int GetMaxByteCount(int charCount) { return _encoding.GetMaxByteCount(charCount); } public override int GetMaxCharCount(int byteCount) { return _encoding.GetMaxCharCount(byteCount); } public override string BodyName { get { return _encoding.BodyName; } } public override object Clone() { return new EncodingWrapper((Encoding)_encoding.Clone()); } public override int CodePage { get { return _encoding.CodePage; } } public override string EncodingName { get { return _encoding.EncodingName; } } public override Decoder GetDecoder() { return _encoding.GetDecoder(); } public override Encoder GetEncoder() { return _encoding.GetEncoder(); } public override string HeaderName { get { return _encoding.HeaderName; } } public override bool IsAlwaysNormalized(NormalizationForm form) { return _encoding.IsAlwaysNormalized(form); } public override bool IsBrowserDisplay { get { return _encoding.IsBrowserDisplay; } } public override bool IsBrowserSave { get { return _encoding.IsBrowserSave; } } public override bool IsMailNewsDisplay { get { return _encoding.IsMailNewsDisplay; } } public override bool IsMailNewsSave { get { return _encoding.IsMailNewsSave; } } public override bool IsSingleByte { get { return _encoding.IsSingleByte; } } public override string WebName { get { return _encoding.WebName; } } public override int WindowsCodePage { get { return _encoding.WindowsCodePage; } } } }
25.913669
131
0.701555
[ "MIT" ]
endaroza/Node.Cs
Src/Node.Cs.Commons/Utils/EncodingWrapper.cs
3,602
C#
namespace DeclarativeDataDisplayWhidbey { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> 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.components = new System.ComponentModel.Container(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.northwindDataSet = new DeclarativeDataDisplayWhidbey.NorthwindDataSet(); this.CustomersDataConnector = new System.Windows.Forms.DataConnector(this.components); this.customersTableAdapter = new DeclarativeDataDisplayWhidbey.CustomersTableAdapter(); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn7 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn8 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn9 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn10 = new System.Windows.Forms.DataGridViewTextBoxColumn(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.northwindDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CustomersDataConnector)).BeginInit(); this.SuspendLayout(); // // dataGridView1 // this.dataGridView1.AutoGenerateColumns = false; this.dataGridView1.Columns.Add(this.dataGridViewTextBoxColumn1); this.dataGridView1.Columns.Add(this.dataGridViewTextBoxColumn2); this.dataGridView1.Columns.Add(this.dataGridViewTextBoxColumn3); this.dataGridView1.Columns.Add(this.dataGridViewTextBoxColumn4); this.dataGridView1.Columns.Add(this.dataGridViewTextBoxColumn5); this.dataGridView1.Columns.Add(this.dataGridViewTextBoxColumn6); this.dataGridView1.Columns.Add(this.dataGridViewTextBoxColumn7); this.dataGridView1.Columns.Add(this.dataGridViewTextBoxColumn8); this.dataGridView1.Columns.Add(this.dataGridViewTextBoxColumn9); this.dataGridView1.Columns.Add(this.dataGridViewTextBoxColumn10); this.dataGridView1.DataSource = this.CustomersDataConnector; this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView1.Location = new System.Drawing.Point(0, 0); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.Size = new System.Drawing.Size(292, 266); this.dataGridView1.TabIndex = 0; // // northwindDataSet // this.northwindDataSet.DataSetName = "NorthwindDataSet"; this.northwindDataSet.Locale = new System.Globalization.CultureInfo("en-US"); this.northwindDataSet.RemotingFormat = System.Data.SerializationFormat.Xml; // // CustomersDataConnector // this.CustomersDataConnector.DataMember = "Customers"; this.CustomersDataConnector.DataSource = this.northwindDataSet; // // customersTableAdapter // this.customersTableAdapter.ClearBeforeFill = true; // // dataGridViewTextBoxColumn1 // this.dataGridViewTextBoxColumn1.DataPropertyName = "CustomerID"; this.dataGridViewTextBoxColumn1.HeaderText = "CustomerID"; this.dataGridViewTextBoxColumn1.Name = "CustomerID"; this.dataGridViewTextBoxColumn1.ValueType = typeof(string); // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.DataPropertyName = "CompanyName"; this.dataGridViewTextBoxColumn2.HeaderText = "CompanyName"; this.dataGridViewTextBoxColumn2.Name = "CompanyName"; this.dataGridViewTextBoxColumn2.ValueType = typeof(string); // // dataGridViewTextBoxColumn3 // this.dataGridViewTextBoxColumn3.DataPropertyName = "ContactName"; this.dataGridViewTextBoxColumn3.HeaderText = "ContactName"; this.dataGridViewTextBoxColumn3.Name = "ContactName"; this.dataGridViewTextBoxColumn3.ValueType = typeof(string); // // dataGridViewTextBoxColumn4 // this.dataGridViewTextBoxColumn4.DataPropertyName = "ContactTitle"; this.dataGridViewTextBoxColumn4.HeaderText = "ContactTitle"; this.dataGridViewTextBoxColumn4.Name = "ContactTitle"; this.dataGridViewTextBoxColumn4.ValueType = typeof(string); // // dataGridViewTextBoxColumn5 // this.dataGridViewTextBoxColumn5.DataPropertyName = "Address"; this.dataGridViewTextBoxColumn5.HeaderText = "Address"; this.dataGridViewTextBoxColumn5.Name = "Address"; this.dataGridViewTextBoxColumn5.ValueType = typeof(string); // // dataGridViewTextBoxColumn6 // this.dataGridViewTextBoxColumn6.DataPropertyName = "City"; this.dataGridViewTextBoxColumn6.HeaderText = "City"; this.dataGridViewTextBoxColumn6.Name = "City"; this.dataGridViewTextBoxColumn6.ValueType = typeof(string); // // dataGridViewTextBoxColumn7 // this.dataGridViewTextBoxColumn7.DataPropertyName = "PostalCode"; this.dataGridViewTextBoxColumn7.HeaderText = "PostalCode"; this.dataGridViewTextBoxColumn7.Name = "PostalCode"; this.dataGridViewTextBoxColumn7.ValueType = typeof(string); // // dataGridViewTextBoxColumn8 // this.dataGridViewTextBoxColumn8.DataPropertyName = "Country"; this.dataGridViewTextBoxColumn8.HeaderText = "Country"; this.dataGridViewTextBoxColumn8.Name = "Country"; this.dataGridViewTextBoxColumn8.ValueType = typeof(string); // // dataGridViewTextBoxColumn9 // this.dataGridViewTextBoxColumn9.DataPropertyName = "Phone"; this.dataGridViewTextBoxColumn9.HeaderText = "Phone"; this.dataGridViewTextBoxColumn9.Name = "Phone"; this.dataGridViewTextBoxColumn9.ValueType = typeof(string); // // dataGridViewTextBoxColumn10 // this.dataGridViewTextBoxColumn10.DataPropertyName = "Fax"; this.dataGridViewTextBoxColumn10.HeaderText = "Fax"; this.dataGridViewTextBoxColumn10.Name = "Fax"; this.dataGridViewTextBoxColumn10.ValueType = typeof(string); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 266); this.Controls.Add(this.dataGridView1); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.northwindDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CustomersDataConnector)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.DataGridView dataGridView1; private NorthwindDataSet northwindDataSet; private System.Windows.Forms.DataConnector CustomersDataConnector; private CustomersTableAdapter customersTableAdapter; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn6; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn7; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn8; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn9; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn10; } }
44.021164
91
0.794351
[ "MIT" ]
CornerZhang/Learning_CSharp
Programming_C#/ProgCSharp4eSourceR5/Chapter 14/DeclarativeDataDisplayWhidbey/DeclarativeDataDisplayWhidbey/Form1.Designer.cs
8,322
C#
using System.Threading.Tasks; using System; using Newtonsoft.Json; using System.Text; using UnityEngine.Networking; using UnityEngine; namespace Loom.Unity3d { internal class HTTPRPCClient : IRPCClient { private static readonly string LogTag = "Loom.HTTPRPCClient"; private Uri url; /// <summary> /// Logger to be used for logging, defaults to <see cref="NullLogger"/>. /// </summary> public ILogger Logger { get; set; } public Task SubscribeAsync(EventHandler<JsonRpcEventData> handler) { throw new NotImplementedException(); } public Task UnsubscribeAsync(EventHandler<JsonRpcEventData> handler) { throw new NotImplementedException(); } public HTTPRPCClient(string url) { this.url = new Uri(url); this.Logger = NullLogger.Instance; } public bool IsConnected => true; public void Dispose() { } public Task DisconnectAsync() { return Task.CompletedTask; } public async Task<T> SendAsync<T, U>(string method, U args) { string body = JsonConvert.SerializeObject(new JsonRpcRequest<U>(method, args, Guid.NewGuid().ToString())); Logger.Log(LogTag, "[Request Body] " + body); byte[] bodyRaw = new UTF8Encoding().GetBytes(body); using (var r = new UnityWebRequest(this.url.AbsoluteUri, "POST")) { r.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); r.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); r.SetRequestHeader("Content-Type", "application/json"); await r.SendWebRequest(); this.HandleError(r); if (r.downloadHandler != null && !String.IsNullOrEmpty(r.downloadHandler.text)) { Logger.Log(LogTag, "[Response Body] " + r.downloadHandler.text); var respMsg = JsonConvert.DeserializeObject<JsonRpcResponse<T>>(r.downloadHandler.text); if (respMsg.Error != null) { throw new Exception(String.Format( "JSON-RPC Error {0} ({1}): {2}", respMsg.Error.Code, respMsg.Error.Message, respMsg.Error.Data )); } return respMsg.Result; } Logger.Log(LogTag, "[Empty Response Body]"); } return default(T); } private void HandleError(UnityWebRequest r) { if (r.isNetworkError) { throw new Exception(String.Format("HTTP '{0}' request to '{1}' failed", r.method, r.url)); } else if (r.isHttpError) { if (r.downloadHandler != null && !String.IsNullOrEmpty(r.downloadHandler.text)) { // TOOD: extract error message if any } throw new Exception(String.Format("HTTP Error {0}", r.responseCode)); } } } }
34.446809
118
0.534589
[ "MIT" ]
dotrungkien/loom-unity
evm-based/client/Assets/LoomSDK/Internal/HTTPRPCClient.cs
3,240
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Security.Principal; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using HunterPie.Core; using HunterPie.Core.Definitions; using HunterPie.Core.Integrations.DataExporter; using HunterPie.GUIControls; using HunterPie.GUIControls.Custom_Controls; using HunterPie.Plugins; using Debugger = HunterPie.Logger.Debugger; using PluginDisplay = HunterPie.GUIControls.Plugins; using HunterPie.Core.Input; // HunterPie using HunterPie.Memory; using Presence = HunterPie.Core.Integrations.Discord.Presence; using Process = System.Diagnostics.Process; using ProcessStartInfo = System.Diagnostics.ProcessStartInfo; using System.Threading.Tasks; using System.Net.Http; using HunterPie.Core.Craft; using Newtonsoft.Json; using System.Diagnostics; using HunterPie.Core.Events; using System.Xml; using System.Reflection; using HunterPie.Core.Native; using HunterPie.Native; using HunterPie.Native.Connection; using ConfigManager = HunterPie.Core.ConfigManager; using HunterPie.Core.Settings; using Overlay = HunterPie.GUI.Overlay; namespace HunterPie { /// <summary> /// HunterPie main window logic; /// </summary> public partial class Hunterpie : Window { // TODO: Refactor all this messy code // Classes private TrayIcon trayIcon; private readonly Game game = new Game(); private Presence presence; private Overlay overlay; private readonly Exporter dataExporter = new Exporter(); private readonly PluginManager pluginManager = new PluginManager(); private bool offlineMode = false; private bool isUpdating = true; public static Hunterpie Instance; // HunterPie version public const string HUNTERPIE_VERSION = "1.0.5"; public static readonly Version AssemblyVersion = Assembly.GetEntryAssembly().GetName().Version; private readonly List<int> registeredHotkeys = new List<int>(); private Config config => ConfigManager.Settings; #region Properties public bool IsPlayerLoggedOn { get => (bool)GetValue(IsPlayerLoggedOnProperty); set => SetValue(IsPlayerLoggedOnProperty, value); } public static readonly DependencyProperty IsPlayerLoggedOnProperty = DependencyProperty.Register("IsPlayerLoggedOn", typeof(bool), typeof(Hunterpie)); public Visibility AdministratorIconVisibility { get => (Visibility)GetValue(AdministratorIconVisibilityProperty); set => SetValue(AdministratorIconVisibilityProperty, value); } public static readonly DependencyProperty AdministratorIconVisibilityProperty = DependencyProperty.Register("AdministratorIconVisibility", typeof(Visibility), typeof(Hunterpie)); public string Version { get => (string)GetValue(VersionProperty); set => SetValue(VersionProperty, value); } public static readonly DependencyProperty VersionProperty = DependencyProperty.Register("Version", typeof(string), typeof(Hunterpie)); public bool IsDragging { get { return (bool)GetValue(IsDraggingProperty); } set { SetValue(IsDraggingProperty, value); } } public static readonly DependencyProperty IsDraggingProperty = DependencyProperty.Register("IsDragging", typeof(bool), typeof(Hunterpie)); #endregion public Hunterpie() { Instance = this; if (CheckIfItsRunningFromWinrar()) { MessageBox.Show("You must extract HunterPie files before running it, otherwise it will most likely crash due to missing files or not save your settings.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); Close(); return; } CheckIfHunterPieOpen(); AppDomain.CurrentDomain.UnhandledException += ExceptionLogger; IsPlayerLoggedOn = false; SetDPIAwareness(); Buffers.Initialize(1024); Buffers.Add<byte>(64); // Initialize debugger and player config DebuggerControl.InitializeDebugger(); InitializeComponent(); } private bool IsRunningAsAdmin() { var winIdentity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(winIdentity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } private void LoadData() { MonsterData.LoadMonsterData(); AbnormalityData.LoadAbnormalityData(); Recipes.LoadRecipes(); } private void CheckIfHunterPieOpen() { // Block new instances of HunterPie if there's one already running Process instance = Process.GetCurrentProcess(); IEnumerable<Process> processes = Process.GetProcessesByName("HunterPie").Where(p => p.Id != instance.Id); foreach (Process p in processes) p.Kill(); } private void SetDPIAwareness() { if (Environment.OSVersion.Version >= new Version(6, 3, 0)) { if (Environment.OSVersion.Version >= new Version(10, 0, 15063)) { WindowsHelper.SetProcessDpiAwarenessContext((int)WindowsHelper.DPI_AWARENESS_CONTEXT.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); } else { WindowsHelper.SetProcessDpiAwareness(WindowsHelper.PROCESS_DPI_AWARENESS.PROCESS_PER_MONITOR_DPI_AWARE); } } else { WindowsHelper.SetProcessDPIAware(); } } #region AUTO UPDATE private bool StartUpdateProcess() { if (!File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Update.exe"))) return false; Process UpdateProcess = new Process(); UpdateProcess.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Update.exe"); UpdateProcess.StartInfo.Arguments = $"version={HUNTERPIE_VERSION} branch={config.HunterPie.Update.Branch}"; UpdateProcess.Start(); return true; } private async Task<bool> CheckIfUpdateEnableAndStart() { bool serverUp = true; try { using (var httpGet = new HttpClient()) { await httpGet.GetAsync("https://hunterpie.herokuapp.com/ping"); } } catch {serverUp = false; } if (config.HunterPie.Update.Enabled && serverUp) { bool justUpdated = false; bool latestVersion = false; string[] args = Environment.GetCommandLineArgs(); foreach (string argument in args) { if (argument.StartsWith("justUpdated")) { string parsed = ParseArgs(argument); justUpdated = parsed == "True"; } if (argument.StartsWith("latestVersion")) { string parsed = ParseArgs(argument); latestVersion = parsed == "True"; } if (argument.StartsWith("offlineMode")) { offlineMode = ParseArgs(argument) == "True"; } } if (justUpdated) { UnclickButtons(ChangelogBtn.Parent as StackPanel, ChangelogBtn); ConsolePanel.Children.Clear(); ConsolePanel.Children.Add(Changelog.Instance); return true; } if (latestVersion) { return true; } Debugger.Log("Updating updater.exe"); // This will update Update.exe AutoUpdate au = new AutoUpdate(config.HunterPie.Update.Branch); au.Instance.DownloadFileCompleted += OnUpdaterDownloadComplete; offlineMode = au.offlineMode; if (!au.CheckAutoUpdate() && !au.offlineMode) { HandleUpdaterUpdate(); } else { return true; } Hide(); return false; } else { Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_AUTOUPDATE_DISABLED_WARN']")); return true; } } private void OnUpdaterDownloadComplete(object sender, AsyncCompletedEventArgs e) { if (e.Error != null) { Debugger.Error(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_UPDATE_ERROR']")); Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_OFFLINEMODE_WARN']")); offlineMode = true; return; } else { Debugger.Error(e.Error); } HandleUpdaterUpdate(); } private void HandleUpdaterUpdate() { bool StartUpdate = StartUpdateProcess(); if (StartUpdate) { Close(); } else { MessageBox.Show("Update.exe not found! Skipping auto-update...", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } private string ParseArgs(string arg) { try { return arg.Split('=')[1]; } catch { return ""; } } #endregion #region HOT KEYS private void SetHotKeys() { string[] hotkeys = { config.Overlay.ToggleOverlayKeybind, config.Overlay.MonstersComponent.SwitchMonsterBarModeHotkey, config.Overlay.ToggleDesignKeybind }; Action[] callbacks = { ToggleOverlayCallback, SwitchMonsterBarModeCallback, ToggleDesignModeCallback }; for (int i = 0; i < hotkeys.Length; i++) { string hotkey = hotkeys[i]; Action callback = callbacks[i]; if (hotkey == "None" || hotkey is null) { continue; } int id = Hotkey.Register(hotkey, callback); if (id > 0) { registeredHotkeys.Add(id); } else { Debugger.Error("Failed to register hotkey"); } } } private void RemoveHotKeys() { foreach (int id in registeredHotkeys) { Hotkey.Unregister(id); } registeredHotkeys.Clear(); } private async void ToggleOverlayCallback() { if (overlay == null) { return; } config.Overlay.Enabled = !config.Overlay.Enabled; await ConfigManager.TrySaveSettingsAsync(); } private async void SwitchMonsterBarModeCallback() { if (overlay == null) { return; } config.Overlay.MonstersComponent.ShowMonsterBarMode = config.Overlay.MonstersComponent.ShowMonsterBarMode + 1 >= 5 ? (byte)0 : (byte)(config.Overlay.MonstersComponent.ShowMonsterBarMode + 1); await ConfigManager.TrySaveSettingsAsync(); } private void ToggleDesignModeCallback() { overlay?.ToggleDesignMode(); } private void ConvertOldHotkeyToNew(int Key) { if (Key == 0) return; config.Overlay.ToggleDesignKeybind = KeyboardHookHelper.GetKeyboardKeyByID(Key).ToString(); config.Overlay.ToggleDesignModeKey = 0; } #endregion #region TRAY ICON private void InitializeTrayIcon() { // Tray icon itself trayIcon = new TrayIcon( "HunterPie", "HunterPie", Properties.Resources.LOGO_HunterPie, OnTrayIconClick ); // Settings button var settingsItem = trayIcon.AddItem(GStrings.GetLocalizationByXPath("/TrayIcon/String[@ID='TRAYICON_SETTINGS']")); settingsItem.Click += OnTrayIconSettingsClick; // Close button var closeItem = trayIcon.AddItem(GStrings.GetLocalizationByXPath("/TrayIcon/String[@ID='TRAYICON_CLOSE']")); closeItem.Click += OnTrayIconExitClick; } private void OnTrayIconSettingsClick(object sender, EventArgs e) { Show(); WindowState = WindowState.Normal; Focus(); ConsolePanel.Children.Clear(); ConsolePanel.Children.Add(Settings.Instance); UnclickButtons(SettingsBtn.Parent as StackPanel, SettingsBtn); Settings.RefreshSettingsUI(); } private void OnTrayIconExitClick(object sender, EventArgs e) => Close(); private void OnTrayIconClick(object sender, EventArgs e) { Show(); WindowState = WindowState.Normal; Focus(); } #endregion // Why are people running HunterPie before extracting the files?????????????????????? private bool CheckIfItsRunningFromWinrar() { string path = AppDomain.CurrentDomain.BaseDirectory; return path.Contains("AppData\\Local\\Temp\\"); } private void LoadCustomTheme() { if (config.HunterPie.Theme == null || config.HunterPie.Theme == "Default") return; if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Themes"))) { Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Themes")); } if (!File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"Themes/{config.HunterPie.Theme}"))) { Debugger.Error(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_THEME_NOT_FOUND_ERROR']".Replace("{THEME_NAME}", config.HunterPie.Theme))); return; } try { string themePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"Themes/{config.HunterPie.Theme}"); PatchThemeAndValidate(themePath); using (FileStream stream = new FileStream(themePath, FileMode.Open)) { XamlReader reader = new XamlReader(); ResourceDictionary ThemeDictionary = (ResourceDictionary)reader.LoadAsync(stream); Application.Current.Resources.MergedDictionaries.Add(ThemeDictionary); Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_THEME_LOAD_WARN']")); } } catch (Exception err) { Debugger.Error($"{GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_THEME_NOT_LOAD_ERROR']")}\n{err}"); } } private void LoadOverwriteTheme() { try { string overwritePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"HunterPie.Resources/UI/Overwrite.xaml"); PatchThemeAndValidate(overwritePath); using (FileStream stream = new FileStream(overwritePath, FileMode.Open)) { XamlReader reader = new XamlReader(); ResourceDictionary res = (ResourceDictionary)reader.LoadAsync(stream); Application.Current.Resources.MergedDictionaries.Add(res); } } catch (Exception err) { Debugger.Error(err); } } private bool PatchThemeAndValidate(string path) { string theme = File.ReadAllText(path); if (theme.Contains(";assembly=Hunterpie\"")) { try { XmlDocument xml = new XmlDocument(); xml.LoadXml(theme); foreach (XmlAttribute e in xml.DocumentElement.Attributes) { if (!e.Value.Contains(";assembly=HunterPie.UI")) { e.Value = e.Value.Replace(";assembly=Hunterpie", ";assembly=HunterPie.UI"); } } xml.Save(path); Debugger.Warn($"Patched theme"); return true; } catch (Exception err) { Debugger.Error(err); return false; } } else { return true; } } private void ExceptionLogger(object sender, UnhandledExceptionEventArgs e) { File.WriteAllText("crashes.txt", e.ExceptionObject.ToString()); if (config.HunterPie.Debug.SendCrashFileToDev) { const string HunterPieCrashesWebhook = "https://discordapp.com/api/webhooks/756301992930050129/sTbp4PmjYZMlGGT0IYIhYtTiVw9hpaqwjo-n1Aawl2omWfnV-SD3NpH691xm4TleJ2p-"; // Also try to send the crash error to my webhook so I can fix it using (var httpClient = new HttpClient()) { using (var req = new HttpRequestMessage(new HttpMethod("POST"), HunterPieCrashesWebhook)) { using (var content = new MultipartFormDataContent()) { content.Add(new StringContent(""), "username"); content.Add(new StringContent($"```Exception type: {e.ExceptionObject.GetType()}\n-----------------------------------\nBranch: {config.HunterPie.Update.Branch}\nVersion: {FileVersionInfo.GetVersionInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "HunterPie.exe")).FileVersion}\nGAME BUILD VERSION: {Game.Version}\nHunterPie elapsed time: {DateTime.UtcNow - Process.GetCurrentProcess().StartTime.ToUniversalTime()}```"), "content"); content.Add(new StringContent(e.ExceptionObject.ToString()), "file", "crashes.txt"); req.Content = content; httpClient.SendAsync(req).Wait(); } } } } DebuggerControl.WriteStacktrace(); } private void StartEverything() { SetAnimationsFramerate(); HookEvents(); Kernel.StartScanning(); // Scans game memory if (config.HunterPie.StartHunterPieMinimized) { WindowState = WindowState.Minimized; Hide(); } else { Show(); } } private void SetAnimationsFramerate() => Timeline.DesiredFrameRateProperty.OverrideMetadata(typeof(Timeline), new FrameworkPropertyMetadata { DefaultValue = Math.Min(60, Math.Max(1, config.Overlay.DesiredAnimationFrameRate)) }); #region Game & Client Events private void HookEvents() { // Kernel events Kernel.OnGameStart += OnGameStart; Kernel.OnGameClosed += OnGameClose; // Settings ConfigManager.OnSettingsUpdate += SendToOverlay; } private void UnhookEvents() { // Debug AppDomain.CurrentDomain.UnhandledException -= ExceptionLogger; // Kernel events Kernel.OnGameStart -= OnGameStart; Kernel.OnGameClosed -= OnGameClose; // Settings ConfigManager.OnSettingsUpdate -= SendToOverlay; } public void SendToOverlay(object source, EventArgs e) { Debugger.IsDebugEnabled = config.HunterPie.Debug.ShowDebugMessages; overlay?.GlobalSettingsEventHandler(source, e); Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle, new Action(() => { // Only shows notification if HunterPie is visible if (IsVisible) { CNotification notification = new CNotification() { Text = GStrings.GetLocalizationByXPath("/Notifications/String[@ID='STATIC_SETTINGS_LOAD']"), FirstButtonVisibility = Visibility.Collapsed, SecondButtonVisibility = Visibility.Collapsed, NIcon = FindResource("ICON_CHECKED") as ImageSource, ShowTime = 11 }; NotificationsPanel.Children.Add(notification); } Settings.RefreshSettingsUI(); })); } private void HookGameEvents() { // Game events game.Player.OnZoneChange += OnZoneChange; game.Player.OnCharacterLogin += OnLogin; game.Player.OnCharacterLogout += OnLogout; game.Player.OnSessionChange += OnSessionChange; game.Player.OnClassChange += OnClassChange; } private void UnhookGameEvents() { game.Player.OnZoneChange -= OnZoneChange; game.Player.OnCharacterLogin -= OnLogin; game.Player.OnCharacterLogout -= OnLogout; game.Player.OnSessionChange -= OnSessionChange; game.Player.OnClassChange -= OnClassChange; } private void ExportGameData() { if (game.Player.ZoneID != 0) { string sSession = game.Player.SteamID != 0 ? $"steam://joinlobby/582010/{game.Player.SteamSession}/{game.Player.SteamID}" : ""; Data playerData = new Data { Name = game.Player.Name, HR = game.Player.Level, MR = game.Player.MasterRank, BuildURL = Honey.LinkStructureBuilder(game.Player.GetPlayerGear()), Session = game.Player.SessionID, SteamSession = sSession, Playtime = game.Player.PlayTime, WeaponName = game.Player.WeaponName }; dataExporter.ExportData(playerData); } } private void OnSessionChange(object source, EventArgs args) { PlayerEventArgs e = (PlayerEventArgs)args; Debugger.Log($"SESSION: {e.SessionId}"); // Writes the session ID to a Sessions.txt if (!string.IsNullOrEmpty(e.SessionId) && game.Player.IsLoggedOn) { ExportGameData(); // Because some people don't give permissions to write to files zzzzz try { File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Sessions.txt"), e.SessionId); } catch { Debugger.Error("Missing permissions to write to files."); } } } public void OnZoneChange(object source, EventArgs e) { if (game.Player.IsLoggedOn) { Debugger.Debug($"ZoneID: {game.Player.ZoneID}"); ExportGameData(); } } public async void OnLogin(object source, EventArgs e) { Debugger.Log($"Logged on {game.Player.Name}"); await Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => { IsPlayerLoggedOn = true; })); await Chat.SystemMessage("<STYL MOJI_LIGHTBLUE_DEFAULT><ICON SLG_NEWS>HunterPie Native</STYL>\nConnected.", -1, 0, 0); ExportGameData(); } public void OnLogout(object source, EventArgs e) => Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => { IsPlayerLoggedOn = false; })); private void OnClassChange(object source, EventArgs args) => ExportGameData(); private async void OnGameStart(object source, EventArgs e) { // Set HunterPie hotkeys SetHotKeys(); // Create game instances game.CreateInstances(); // Loads memory map if (Address.LoadMemoryMap(Kernel.GameVersion) || Kernel.GameVersion == Address.GAME_VERSION) { Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_MAP_LOAD']").Replace("{HunterPie_Map}", $"'MonsterHunterWorld.{Kernel.GameVersion}.map'")); } else { Debugger.Error(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_GAME_VERSION_UNSUPPORTED']").Replace("{GAME_VERSION}", $"{Kernel.GameVersion}")); return; } Honey.Load(); await Task.Run(() => { GMD.InitializeGMDs(); MusicSkillData.Load(); }); // Hook game events HookGameEvents(); // Set game context and load the modules PluginManager.ctx = game; await pluginManager.LoadPlugins(); await InitializeNative(); // Creates new overlay Dispatcher.Invoke(() => { if (overlay is null) { overlay = new Overlay(game); overlay.HookEvents(); ConfigManager.TriggerSettingsEvent(); } }); // Initializes rich presence if (presence is null) { presence = new Presence(game); if (offlineMode) presence.SetOfflineMode(); presence.StartRPC(); } // Starts scanning game.StartScanning(); } private async Task InitializeNative() { if (Injector.CheckIfAlreadyInjected()) { await Client.Initialize(); } else { if (Injector.InjectNative()) { Debugger.Write("Injected HunterPie.Native.dll succesfully!", "#FFC88DF2"); await Client.Initialize(); } else Debugger.Error("Failed to inject HunterPie.Native.dll"); } await Dispatcher.InvokeAsync(() => { if (!Injector.CheckIfCRCBypassExists()) { CNotification notification = new CNotification() { Text = "Some of HunterPie Native features require CRCBypass", NIcon = FindResource("ICON_WARN") as ImageSource, FirstButtonImage = FindResource("ICON_DOWNLOAD") as ImageSource, FirstButtonText = "Stracker's Loader", FirstButtonVisibility = Visibility.Visible, SecondButtonImage = FindResource("ICON_DOWNLOAD") as ImageSource, SecondButtonText = "CRCBypass", SecondButtonVisibility = Visibility.Visible, Callback1 = new Action(() => { Process.Start("https://www.nexusmods.com/monsterhunterworld/mods/1982"); }), Callback2 = new Action(() => { Process.Start("https://www.nexusmods.com/monsterhunterworld/mods/3473"); }), ShowTime = 20 }; NotificationsPanel.Children.Add(notification); } }); } private async void OnGameClose(object source, EventArgs e) { Client.Instance.Dispose(); // Remove global hotkeys RemoveHotKeys(); UnhookGameEvents(); pluginManager?.UnloadPlugins(); presence?.Dispose(); presence = null; game?.StopScanning(); await Dispatcher.InvokeAsync(async () => { if (overlay is null) return; await overlay.Dispose().ContinueWith(task => game?.DestroyInstances()); overlay = null; }); if (config.HunterPie.Options.CloseWhenGameCloses) { Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() => { Close(); })); } } #endregion #region Animations private void SwitchButtonOn(StackPanel buttonActive) { Border ButtonBorder = (Border)buttonActive.Children[0]; ButtonBorder.SetValue(BorderThicknessProperty, new Thickness(4, 0, 0, 0)); } private void SwitchButtonOff(StackPanel buttonActive) { Border ButtonBorder = (Border)buttonActive.Children[0]; ButtonBorder.SetValue(BorderThicknessProperty, new Thickness(0, 0, 0, 0)); } #endregion #region WINDOW EVENTS private async void OnWindowInitialized(object sender, EventArgs e) { Hide(); await ConfigManager.Initialize(); // Initialize localization GStrings.InitStrings(config.HunterPie.Language, App.Current); // Load custom theme and console colors LoadCustomTheme(); LoadOverwriteTheme(); DebuggerControl.LoadNewColors(); AdministratorIconVisibility = IsRunningAsAdmin() ? Visibility.Visible : Visibility.Collapsed; Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; WindowBlur.SetIsEnabled(this, true); Width = config.HunterPie.Width; Height = config.HunterPie.Height; Top = config.HunterPie.PosY; Left = config.HunterPie.PosX; ConsolePanel.Children.Clear(); ConsolePanel.Children.Add(DebuggerControl.Instance); UnclickButtons(ConsoleBtn.Parent as StackPanel, ConsoleBtn); // Initialize everything under this line if (!await CheckIfUpdateEnableAndStart()) return; // Convert the old HotKey to the new one ConvertOldHotkeyToNew(config.Overlay.ToggleDesignModeKey); isUpdating = false; InitializeTrayIcon(); // Update version text Version = GStrings.GetLocalizationByXPath("/Console/String[@ID='CONSOLE_VERSION']").Replace("{HunterPie_Version}", HUNTERPIE_VERSION).Replace("{HunterPie_Branch}", config.HunterPie.Update.Branch); // Initializes the Hotkey API Hotkey.Load(); // Initializes the rest of HunterPie LoadData(); Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_HUNTERPIE_INITIALIZED']")); await pluginManager.PreloadPlugins(); // Support message :) ShowSupportMessage(); StartEverything(); } private async void OnCloseWindowButtonClick(object sender, MouseButtonEventArgs e) { // X button function; bool exitConfirmation = MessageBox.Show(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_QUIT']"), "HunterPie", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes; config.HunterPie.PosX = Left; config.HunterPie.PosY = Top; await ConfigManager.TrySaveSettingsAsync(); if (exitConfirmation) Close(); } private void OnWindowDrag(object sender, MouseButtonEventArgs e) { if (WindowState == WindowState.Maximized) { Point point = PointToScreen(e.MouseDevice.GetPosition(this)); if (point.X <= RestoreBounds.Width / 2) Left = 0; else if (point.X >= RestoreBounds.Width) Left = point.X - (RestoreBounds.Width - (ActualWidth - point.X)); else { Left = point.X - (RestoreBounds.Width / 2); } Top = point.Y - (((FrameworkElement)sender).ActualWidth / 2); WindowState = WindowState.Normal; } // When top bar is held by LMB DragMove(); } private void OnMinimizeButtonClick(object sender, MouseButtonEventArgs e) { MinimizeWindow(); } private void MinimizeWindow() { if (config.HunterPie.MinimizeToSystemTray) { WindowState = WindowState.Minimized; Hide(); } else { WindowState = WindowState.Minimized; } } private void OnWindowClosing(object sender, CancelEventArgs e) { Hotkey.Unload(); Hide(); Client.Instance.Disconnect(); DebuggerControl.WriteStacktrace(); pluginManager?.UnloadPlugins(); DebuggerControl.DumpLog(); // Dispose tray icon trayIcon?.Dispose(); // Dispose stuff & stop scanning threads overlay?.Dispose(); if (game.IsActive) game?.StopScanning(); presence?.Dispose(); Kernel.StopScanning(); Settings.Instance?.UninstallKeyboardHook(); // Unhook events if (game.Player != null) UnhookGameEvents(); UnhookEvents(); } private void OnLaunchGameButtonClick(object sender, RoutedEventArgs e) => LaunchGame(); private void LaunchGame() { try { ProcessStartInfo GameStartInfo = new ProcessStartInfo { FileName = "steam://run/582010", Arguments = config.HunterPie.Launch.LaunchArgs, UseShellExecute = true }; Process.Start(GameStartInfo); if (config.HunterPie.MinimizeAfterGameStart) { MinimizeWindow(); } } catch (Exception err) { Debugger.Error($"{GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_LAUNCH_ERROR']")}\n{err}"); } } private void OnWindowSizeChange(object sender, SizeChangedEventArgs e) { if (config is null) return; config.HunterPie.Width = (float)e.NewSize.Width; config.HunterPie.Height = (float)e.NewSize.Height; } public void Reload() { // Welp Process.Start(Application.ResourceAssembly.Location, "latestVersion=True"); Application.Current.Shutdown(); } private void OnKeyDown(object sender, KeyEventArgs e) { Key key = (e.Key == Key.System ? e.SystemKey : e.Key); if (key == Key.LeftShift || key == Key.RightShift || key == Key.LeftCtrl || key == Key.RightCtrl || key == Key.LeftAlt || key == Key.RightAlt || key == Key.LWin || key == Key.RWin) { return; } if ((Keyboard.Modifiers & ModifierKeys.Control) != 0 && e.Key == Key.R) { Reload(); } } #endregion #region Helpers public static Version ParseVersion(string version) { return new Version(version); } private void ShowSupportMessage() { CNotification notification = new CNotification() { Text = "Do you like HunterPie and want to support its development? Consider donating!", NIcon = FindResource("LOGO_HunterPie") as ImageSource, FirstButtonImage = FindResource("ICON_PAYPAL") as ImageSource, FirstButtonText = "PayPal", FirstButtonVisibility = Visibility.Visible, SecondButtonImage = FindResource("ICON_PATREON") as ImageSource, SecondButtonText = "Patreon", SecondButtonVisibility = Visibility.Visible, Callback1 = new Action(() => { Process.Start("https://server.hunterpie.me/donate"); }), Callback2 = new Action(() => { Process.Start("https://www.patreon.com/HunterPie"); }), ShowTime = 20 }; NotificationsPanel.Children.Add(notification); } #endregion public async Task<string> InstallPlugin(string moduleContent) { PluginInformation moduleInformation = JsonConvert.DeserializeObject<PluginInformation>(moduleContent); if (moduleInformation is null || string.IsNullOrEmpty(moduleInformation?.Name)) { Debugger.Log("Invalid module.json!"); return null; } string modPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules", moduleInformation.Name); if (!Directory.Exists(modPath)) { Directory.CreateDirectory(modPath); } File.WriteAllText(Path.Combine(modPath, "module.json"), JsonConvert.SerializeObject(moduleInformation, Newtonsoft.Json.Formatting.Indented)); if (PluginUpdate.PluginSupportsUpdate(moduleInformation)) { switch (await PluginUpdate.UpdateAllFiles(moduleInformation, modPath)) { case UpdateResult.Updated: Debugger.Module($"Installed {moduleInformation.Name}! (ver {moduleInformation.Version})"); CNotification notification = new CNotification { Text = GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_PLUGIN_INSTALLED']").Replace("{name}", moduleInformation.Name), NIcon = FindResource("ICON_PLUGIN") as ImageSource, FirstButtonVisibility = Visibility.Visible, Callback1 = Reload, FirstButtonImage = FindResource("ICON_RESTART") as ImageSource, FirstButtonText = GStrings.GetLocalizationByXPath("/Notifications/String[@ID='STATIC_RESTART']"), SecondButtonVisibility = Visibility.Collapsed, ShowTime = 15 }; NotificationsPanel.Children.Add(notification); break; case UpdateResult.Failed: Debugger.Error($"Failed to install {moduleInformation.Name}."); return null; case UpdateResult.UpToDate: string uptodateText = $"Plugin {moduleInformation.Name} is already installed and up-to-date! (ver {moduleInformation.Version})"; Debugger.Module(uptodateText); CNotification uptodateNotification = new CNotification { Text = uptodateText, NIcon = FindResource("ICON_PLUGIN") as ImageSource, FirstButtonVisibility = Visibility.Collapsed, SecondButtonVisibility = Visibility.Collapsed, ShowTime = 5 }; NotificationsPanel.Children.Add(uptodateNotification); return modPath; } } else { Debugger.Error(GStrings.GetLocalizationByXPath("/Console/String[@ID='ERROR_PLUGIN_AUTO_UPDATE']")); return null; } return modPath; } private async void window_Drop(object sender, DragEventArgs e) { IsDragging = false; string modulejson = ((string[])e.Data.GetData("FileName"))?.FirstOrDefault(); string moduleContent; bool isOnline = false; if (modulejson is null) { isOnline = true; modulejson = e.Data.GetData("UnicodeText") as string; } if (!modulejson.ToLower().EndsWith("module.json")) { return; } if (isOnline) { if (!modulejson.StartsWith("http")) { modulejson = $"https://{modulejson}"; } moduleContent = await PluginUpdate.ReadOnlineModuleJson(modulejson); } else { moduleContent = File.ReadAllText(modulejson); } await InstallPlugin(moduleContent); } private void window_DragEnter(object sender, DragEventArgs e) { IsDragging = true; } private void window_DragLeave(object sender, DragEventArgs e) { IsDragging = false; } private void OnDebuggerButtonClick(object sender, MouseButtonEventArgs e) { SideButton snd = (SideButton)sender; StackPanel panel = snd.Parent as StackPanel; UnclickButtons(panel, snd); ConsolePanel.Children.Clear(); ConsolePanel.Children.Add(DebuggerControl.Instance); } private void OnSettingsButtonClick(object sender, MouseButtonEventArgs e) { SideButton snd = (SideButton)sender; StackPanel panel = snd.Parent as StackPanel; UnclickButtons(panel, snd); ConsolePanel.Children.Clear(); ConsolePanel.Children.Add(Settings.Instance); Settings.RefreshSettingsUI(); } private void OnPluginsButtonClick(object sender, MouseButtonEventArgs e) { SideButton snd = (SideButton)sender; StackPanel panel = snd.Parent as StackPanel; UnclickButtons(panel, snd); ConsolePanel.Children.Clear(); ConsolePanel.Children.Add(PluginDisplay.Instance); } private void OnBuildUploadButtonClick(object sender, MouseButtonEventArgs e) { CNotification notification = new CNotification() { Text = GStrings.GetLocalizationByXPath("/Notifications/String[@ID='MESSAGE_BUILD_UPLOADED']"), NIcon = FindResource("ICON_BUILD") as ImageSource, FirstButtonImage = FindResource("ICON_COPY") as ImageSource, FirstButtonText = GStrings.GetLocalizationByXPath("/Settings/String[@ID='STATIC_COPYCLIPBOARD']"), FirstButtonVisibility = Visibility.Visible, SecondButtonImage = FindResource("ICON_LINK") as ImageSource, SecondButtonText = GStrings.GetLocalizationByXPath("/Notifications/String[@ID='STATIC_OPENDEFAULTBROWSER']"), SecondButtonVisibility = Visibility.Visible, Callback1 = new Action(() => { string buildLink = Honey.LinkStructureBuilder(game.Player.GetPlayerGear(), true); Clipboard.SetData(DataFormats.Text, buildLink); }), Callback2 = new Action(() => { string buildLink = Honey.LinkStructureBuilder(game.Player.GetPlayerGear(), true); Process.Start(buildLink); }), ShowTime = 11 }; NotificationsPanel.Children.Add(notification); } private async void OnExportGearButtonClick(object sender, MouseButtonEventArgs e) { await Task.Factory.StartNew(() => { sItem[] decoration = game.Player.GetDecorationsFromStorage(); sGear[] gears = game.Player.GetGearFromStorage(); string exported = Honey.ExportDecorationsToHoney(decoration, gears); if (dataExporter.ExportCustomData("Decorations-HoneyHuntersWorld.txt", exported)) { Debugger.Warn("Exported decorations to ./DataExport/Decorations-HoneyHuntersWorld.txt!"); } else { Debugger.Error("Failed to export decorations. Make sure HunterPie has permission to create/write to files."); } exported = Honey.ExportCharmsToHoney(gears); if (dataExporter.ExportCustomData("Charms-HoneyHuntersWorld.txt", exported)) { Debugger.Warn("Exported charms to ./DataExport/Charms-HoneyHuntersWorld.txt!"); } else { Debugger.Error("Failed to export charms. Make sure HunterPie has permission to create/write to files."); } Dispatcher.Invoke(() => { CNotification notification = new CNotification() { NIcon = FindResource("ICON_DECORATION") as ImageSource, Text = GStrings.GetLocalizationByXPath("/Notifications/String[@ID='MESSAGE_GEAR_EXPORTED']"), FirstButtonImage = FindResource("ICON_LINK") as ImageSource, FirstButtonText = GStrings.GetLocalizationByXPath("/Notifications/String[@ID='STATIC_OPENFOLDER']"), FirstButtonVisibility = Visibility.Visible, SecondButtonVisibility = Visibility.Collapsed, ShowTime = 11, Callback1 = new Action(() => { Process.Start(dataExporter.ExportPath); }) }; NotificationsPanel.Children.Add(notification); }); }); } private void OnChangelogButtonClick(object sender, MouseButtonEventArgs e) { SideButton snd = (SideButton)sender; StackPanel panel = snd.Parent as StackPanel; UnclickButtons(panel, snd); ConsolePanel.Children.Clear(); ConsolePanel.Children.Add(Changelog.Instance); } private void OnDiscordButtonClick(object sender, MouseButtonEventArgs e) { Process.Start("https://discord.gg/5pdDq4Q"); } private void OnGithubButtonClick(object sender, MouseButtonEventArgs e) { Process.Start("https://github.com/Haato3o/HunterPie"); } private static void UnclickButtons(StackPanel parent, SideButton exception = null) { foreach (SideButton btn in parent.Children.Cast<SideButton>()) { btn.IsClicked = btn == exception; } } } }
36.755639
467
0.541659
[ "MIT" ]
ChrisVenus/HunterPie
HunterPie/Hunterpie.xaml.cs
48,887
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.Devices.V20180122.Outputs { [OutputType] public sealed class RoutingPropertiesResponse { /// <summary> /// The properties related to the custom endpoints to which your IoT hub routes messages based on the routing rules. A maximum of 10 custom endpoints are allowed across all endpoint types for paid hubs and only 1 custom endpoint is allowed across all endpoint types for free hubs. /// </summary> public readonly Outputs.RoutingEndpointsResponse? Endpoints; /// <summary> /// The properties of the route that is used as a fall-back route when none of the conditions specified in the 'routes' section are met. This is an optional parameter. When this property is not set, the messages which do not meet any of the conditions specified in the 'routes' section get routed to the built-in eventhub endpoint. /// </summary> public readonly Outputs.FallbackRoutePropertiesResponse? FallbackRoute; /// <summary> /// The list of user-provided routing rules that the IoT hub uses to route messages to built-in and custom endpoints. A maximum of 100 routing rules are allowed for paid hubs and a maximum of 5 routing rules are allowed for free hubs. /// </summary> public readonly ImmutableArray<Outputs.RoutePropertiesResponse> Routes; [OutputConstructor] private RoutingPropertiesResponse( Outputs.RoutingEndpointsResponse? endpoints, Outputs.FallbackRoutePropertiesResponse? fallbackRoute, ImmutableArray<Outputs.RoutePropertiesResponse> routes) { Endpoints = endpoints; FallbackRoute = fallbackRoute; Routes = routes; } } }
48.093023
339
0.710832
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Devices/V20180122/Outputs/RoutingPropertiesResponse.cs
2,068
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.MixedReality.Toolkit.Examples.Demos.EyeTracking.Logging { public static class AsyncHelpers { /// <summary> /// Execute's an async Task method which has a void return value synchronously /// </summary> /// <param name="task">Task method to execute</param> public static void RunSync(Func<Task> task) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); synch.Post(async _ => { try { await task(); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); } /// <summary> /// Execute's an async Task<typeparamref name="T"/> method which has a T return type synchronously /// </summary> /// <typeparam name="T">Return Type</typeparam> /// <param name="task">Task<typeparamref name="T"/> method to execute</param> public static T RunSync<T>(Func<Task<T>> task) { var oldContext = SynchronizationContext.Current; var synch = new ExclusiveSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(synch); T ret = default(T); synch.Post(async _ => { try { ret = await task(); } catch (Exception e) { synch.InnerException = e; throw; } finally { synch.EndMessageLoop(); } }, null); synch.BeginMessageLoop(); SynchronizationContext.SetSynchronizationContext(oldContext); return ret; } private class ExclusiveSynchronizationContext : SynchronizationContext { private bool done; public Exception InnerException { get; set; } readonly AutoResetEvent workItemsWaiting = new AutoResetEvent(false); readonly Queue<Tuple<SendOrPostCallback, object>> items = new Queue<Tuple<SendOrPostCallback, object>>(); public override void Send(SendOrPostCallback d, object state) { throw new NotSupportedException("We cannot send to our same thread"); } public override void Post(SendOrPostCallback d, object state) { lock (items) { items.Enqueue(Tuple.Create(d, state)); } workItemsWaiting.Set(); } public void EndMessageLoop() { Post(_ => done = true, null); } public void BeginMessageLoop() { while (!done) { Tuple<SendOrPostCallback, object> task = null; lock (items) { if (items.Count > 0) { task = items.Dequeue(); } } if (task != null) { task.Item1(task.Item2); if (InnerException != null) // the method threw an exception { throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException); } } else { workItemsWaiting.WaitOne(); } } } public override SynchronizationContext CreateCopy() { return this; } } } }
33.140741
120
0.469826
[ "MIT" ]
AdrianaMusic/MixedRealityToolkit-Unity
Assets/MRTK/Examples/Demos/EyeTracking/DemoVisualizer/Scripts/AsyncHelpers.cs
4,476
C#
#nullable enable using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using BTCPayServer.Abstractions.Constants; using BTCPayServer.Abstractions.Contracts; using BTCPayServer.BIP78.Sender; using BTCPayServer.Client; using BTCPayServer.Client.Models; using BTCPayServer.Data; using BTCPayServer.HostedServices; using BTCPayServer.Models.WalletViewModels; using BTCPayServer.Payments.PayJoin; using BTCPayServer.Payments.PayJoin.Sender; using BTCPayServer.Services; using BTCPayServer.Services.Wallets; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using NBitcoin; using NBitcoin.Payment; using NBXplorer; using NBXplorer.Models; using Newtonsoft.Json.Linq; using StoreData = BTCPayServer.Data.StoreData; namespace BTCPayServer.Controllers.GreenField { [ApiController] [Authorize(AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [EnableCors(CorsPolicies.All)] public class StoreOnChainWalletsController : Controller { private StoreData Store => HttpContext.GetStoreData(); private readonly IAuthorizationService _authorizationService; private readonly BTCPayWalletProvider _btcPayWalletProvider; private readonly BTCPayNetworkProvider _btcPayNetworkProvider; private readonly WalletRepository _walletRepository; private readonly ExplorerClientProvider _explorerClientProvider; private readonly ISettingsRepository _settingsRepository; private readonly NBXplorerDashboard _nbXplorerDashboard; private readonly WalletsController _walletsController; private readonly PayjoinClient _payjoinClient; private readonly DelayedTransactionBroadcaster _delayedTransactionBroadcaster; private readonly EventAggregator _eventAggregator; private readonly WalletReceiveService _walletReceiveService; private readonly IFeeProviderFactory _feeProviderFactory; public StoreOnChainWalletsController( IAuthorizationService authorizationService, BTCPayWalletProvider btcPayWalletProvider, BTCPayNetworkProvider btcPayNetworkProvider, WalletRepository walletRepository, ExplorerClientProvider explorerClientProvider, ISettingsRepository settingsRepository, NBXplorerDashboard nbXplorerDashboard, WalletsController walletsController, PayjoinClient payjoinClient, DelayedTransactionBroadcaster delayedTransactionBroadcaster, EventAggregator eventAggregator, WalletReceiveService walletReceiveService, IFeeProviderFactory feeProviderFactory) { _authorizationService = authorizationService; _btcPayWalletProvider = btcPayWalletProvider; _btcPayNetworkProvider = btcPayNetworkProvider; _walletRepository = walletRepository; _explorerClientProvider = explorerClientProvider; _settingsRepository = settingsRepository; _nbXplorerDashboard = nbXplorerDashboard; _walletsController = walletsController; _payjoinClient = payjoinClient; _delayedTransactionBroadcaster = delayedTransactionBroadcaster; _eventAggregator = eventAggregator; _walletReceiveService = walletReceiveService; _feeProviderFactory = feeProviderFactory; } [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet")] public async Task<IActionResult> ShowOnChainWalletOverview(string storeId, string cryptoCode) { if (IsInvalidWalletRequest(cryptoCode, out var network, out var derivationScheme, out var actionResult)) return actionResult; var wallet = _btcPayWalletProvider.GetWallet(network); var balance = await wallet.GetBalance(derivationScheme.AccountDerivation); return Ok(new OnChainWalletOverviewData() { Label = derivationScheme.ToPrettyString(), Balance = balance.Total.GetValue(network), UnconfirmedBalance= balance.Unconfirmed.GetValue(network), ConfirmedBalance= balance.Confirmed.GetValue(network), }); } [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet/feerate")] public async Task<IActionResult> GetOnChainFeeRate(string storeId, string cryptoCode, int? blockTarget = null) { if (IsInvalidWalletRequest(cryptoCode, out var network, out var derivationScheme, out var actionResult)) return actionResult; var feeRateTarget = blockTarget?? Store.GetStoreBlob().RecommendedFeeBlockTarget; return Ok(new OnChainWalletFeeRateData() { FeeRate = await _feeProviderFactory.CreateFeeProvider(network) .GetFeeRateAsync(feeRateTarget), }); } [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet/address")] public async Task<IActionResult> GetOnChainWalletReceiveAddress(string storeId, string cryptoCode, bool forceGenerate = false) { if (IsInvalidWalletRequest(cryptoCode, out var network, out var derivationScheme, out var actionResult)) return actionResult; var kpi = await _walletReceiveService.GetOrGenerate(new WalletId(storeId, cryptoCode), forceGenerate); if (kpi is null) { return BadRequest(); } var bip21 = network.GenerateBIP21(kpi.Address.ToString(), null); var allowedPayjoin = derivationScheme.IsHotWallet && Store.GetStoreBlob().PayJoinEnabled; if (allowedPayjoin) { bip21 += $"?{PayjoinClient.BIP21EndpointKey}={Request.GetAbsoluteUri(Url.Action(nameof(PayJoinEndpointController.Submit), "PayJoinEndpoint", new {cryptoCode}))}"; } return Ok(new OnChainWalletAddressData() { Address = kpi.Address.ToString(), PaymentLink = bip21, KeyPath = kpi.KeyPath }); } [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpDelete("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet/address")] public async Task<IActionResult> UnReserveOnChainWalletReceiveAddress(string storeId, string cryptoCode) { if (IsInvalidWalletRequest(cryptoCode, out var network, out var derivationScheme, out var actionResult)) return actionResult; var addr = await _walletReceiveService.UnReserveAddress(new WalletId(storeId, cryptoCode)); if (addr is null) { return NotFound(); } return Ok(); } [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet/transactions")] public async Task<IActionResult> ShowOnChainWalletTransactions( string storeId, string cryptoCode, [FromQuery] TransactionStatus[]? statusFilter = null, [FromQuery] int skip = 0, [FromQuery] int limit = int.MaxValue ) { if (IsInvalidWalletRequest(cryptoCode, out var network, out var derivationScheme, out var actionResult)) return actionResult; var wallet = _btcPayWalletProvider.GetWallet(network); var walletId = new WalletId(storeId, cryptoCode); var walletTransactionsInfoAsync = await _walletRepository.GetWalletTransactionsInfo(walletId); var txs = await wallet.FetchTransactions(derivationScheme.AccountDerivation); var filteredFlatList = new List<TransactionInformation>(); if (statusFilter is null || !statusFilter.Any() || statusFilter.Contains(TransactionStatus.Confirmed)) { filteredFlatList.AddRange(txs.ConfirmedTransactions.Transactions); } if (statusFilter is null || !statusFilter.Any() || statusFilter.Contains(TransactionStatus.Unconfirmed)) { filteredFlatList.AddRange(txs.UnconfirmedTransactions.Transactions); } if (statusFilter is null || !statusFilter.Any() ||statusFilter.Contains(TransactionStatus.Replaced)) { filteredFlatList.AddRange(txs.ReplacedTransactions.Transactions); } var result = filteredFlatList.Skip(skip).Take(limit).Select(information => { walletTransactionsInfoAsync.TryGetValue(information.TransactionId.ToString(), out var transactionInfo); return ToModel(transactionInfo, information, wallet); }).ToList(); return Ok(result); } [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet/transactions/{transactionId}")] public async Task<IActionResult> GetOnChainWalletTransaction(string storeId, string cryptoCode, string transactionId) { if (IsInvalidWalletRequest(cryptoCode, out var network, out var derivationScheme, out var actionResult)) return actionResult; var wallet = _btcPayWalletProvider.GetWallet(network); var tx = await wallet.FetchTransaction(derivationScheme.AccountDerivation, uint256.Parse(transactionId)); if (tx is null) { return NotFound(); } var walletId = new WalletId(storeId, cryptoCode); var walletTransactionsInfoAsync = (await _walletRepository.GetWalletTransactionsInfo(walletId, new[] {transactionId})).Values .FirstOrDefault(); return Ok(ToModel(walletTransactionsInfoAsync, tx, wallet)); } [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet/utxos")] public async Task<IActionResult> GetOnChainWalletUTXOs(string storeId, string cryptoCode) { if (IsInvalidWalletRequest(cryptoCode, out var network, out var derivationScheme, out var actionResult)) return actionResult; var wallet = _btcPayWalletProvider.GetWallet(network); var walletId = new WalletId(storeId, cryptoCode); var walletTransactionsInfoAsync = await _walletRepository.GetWalletTransactionsInfo(walletId); var utxos = await wallet.GetUnspentCoins(derivationScheme.AccountDerivation); return Ok(utxos.Select(coin => { walletTransactionsInfoAsync.TryGetValue(coin.OutPoint.Hash.ToString(), out var info); return new OnChainWalletUTXOData() { Outpoint = coin.OutPoint, Amount = coin.Value.GetValue(network), Comment = info?.Comment, Labels = info?.Labels, Link = string.Format(CultureInfo.InvariantCulture, network.BlockExplorerLink, coin.OutPoint.Hash.ToString()), Timestamp = coin.Timestamp, KeyPath = coin.KeyPath, Confirmations = coin.Confirmations, Address = network.NBXplorerNetwork.CreateAddress(derivationScheme.AccountDerivation, coin.KeyPath, coin.ScriptPubKey).ToString() }; }).ToList() ); } [Authorize(Policy = Policies.CanModifyStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpPost("~/api/v1/stores/{storeId}/payment-methods/onchain/{cryptoCode}/wallet/transactions")] public async Task<IActionResult> CreateOnChainTransaction(string storeId, string cryptoCode, [FromBody] CreateOnChainTransactionRequest request) { if (IsInvalidWalletRequest(cryptoCode, out var network, out var derivationScheme, out var actionResult)) return actionResult; if (network.ReadonlyWallet) { return this.CreateAPIError("not-available", $"{cryptoCode} sending services are not currently available"); } //This API is only meant for hot wallet usage for now. We can expand later when we allow PSBT manipulation. if (!(await CanUseHotWallet()).HotWallet) { return Unauthorized(); } var explorerClient = _explorerClientProvider.GetExplorerClient(cryptoCode); var wallet = _btcPayWalletProvider.GetWallet(network); var utxos = await wallet.GetUnspentCoins(derivationScheme.AccountDerivation); if (request.SelectedInputs != null || !utxos.Any()) { utxos = utxos.Where(coin => request.SelectedInputs?.Contains(coin.OutPoint) ?? true) .ToArray(); if (utxos.Any() is false) { //no valid utxos selected request.AddModelError(transactionRequest => transactionRequest.SelectedInputs, "There are no available utxos based on your request", this); } } var balanceAvailable = utxos.Sum(coin => coin.Value.GetValue(network)); var subtractFeesOutputsCount = new List<int>(); var subtractFees = request.Destinations.Any(o => o.SubtractFromAmount); int? payjoinOutputIndex = null; var sum = 0m; var outputs = new List<WalletSendModel.TransactionOutput>(); for (var index = 0; index < request.Destinations.Count; index++) { var destination = request.Destinations[index]; if (destination.SubtractFromAmount) { subtractFeesOutputsCount.Add(index); } BitcoinUrlBuilder? bip21 = null; var amount = destination.Amount; if (amount.GetValueOrDefault(0) <= 0) { amount = null; } var address = string.Empty; try { destination.Destination = destination.Destination.Replace(network.UriScheme+":", "bitcoin:", StringComparison.InvariantCultureIgnoreCase); bip21 = new BitcoinUrlBuilder(destination.Destination, network.NBitcoinNetwork); amount ??= bip21.Amount.GetValue(network); address = bip21.Address.ToString(); if (destination.SubtractFromAmount) { request.AddModelError(transactionRequest => transactionRequest.Destinations[index], "You cannot use a BIP21 destination along with SubtractFromAmount", this); } } catch (FormatException) { try { address = BitcoinAddress.Create(destination.Destination, network.NBitcoinNetwork).ToString(); } catch (Exception) { request.AddModelError(transactionRequest => transactionRequest.Destinations[index], "Destination must be a BIP21 payment link or an address", this); } } if (amount is null || amount <= 0) { request.AddModelError(transactionRequest => transactionRequest.Destinations[index], "Amount must be specified or destination must be a BIP21 payment link, and greater than 0", this); } if (request.ProceedWithPayjoin && bip21?.UnknowParameters?.ContainsKey(PayjoinClient.BIP21EndpointKey) is true) { payjoinOutputIndex = index; } outputs.Add(new WalletSendModel.TransactionOutput() { DestinationAddress = address, Amount = amount, SubtractFeesFromOutput = destination.SubtractFromAmount }); sum += destination.Amount ?? 0; } if (subtractFeesOutputsCount.Count > 1) { foreach (var subtractFeesOutput in subtractFeesOutputsCount) { request.AddModelError(model => model.Destinations[subtractFeesOutput].SubtractFromAmount, "You can only subtract fees from one destination", this); } } if (balanceAvailable < sum) { request.AddModelError(transactionRequest => transactionRequest.Destinations, "You are attempting to send more than is available", this); } else if (balanceAvailable == sum && !subtractFees) { request.AddModelError(transactionRequest => transactionRequest.Destinations, "You are sending your entire balance, you should subtract the fees from a destination", this); } var minRelayFee = _nbXplorerDashboard.Get(network.CryptoCode).Status.BitcoinStatus?.MinRelayTxFee ?? new FeeRate(1.0m); if (request.FeeRate != null && request.FeeRate < minRelayFee) { ModelState.AddModelError(nameof(request.FeeRate), "The fee rate specified is lower than the current minimum relay fee"); } if (!ModelState.IsValid) { return this.CreateValidationError(ModelState); } CreatePSBTResponse psbt; try { psbt = await _walletsController.CreatePSBT(network, derivationScheme, new WalletSendModel() { SelectedInputs = request.SelectedInputs?.Select(point => point.ToString()), Outputs = outputs, AlwaysIncludeNonWitnessUTXO = true, InputSelection = request.SelectedInputs?.Any() is true, AllowFeeBump = !request.RBF.HasValue ? WalletSendModel.ThreeStateBool.Maybe : request.RBF.Value ? WalletSendModel.ThreeStateBool.Yes : WalletSendModel.ThreeStateBool.No, FeeSatoshiPerByte = request.FeeRate?.SatoshiPerByte, NoChange = request.NoChange }, CancellationToken.None); } catch (NBXplorerException ex) { return this.CreateAPIError(ex.Error.Code, ex.Error.Message); } catch (NotSupportedException) { return this.CreateAPIError("not-available", "You need to update your version of NBXplorer"); } derivationScheme.RebaseKeyPaths(psbt.PSBT); var signingContext = new SigningContextModel() { PayJoinBIP21 = payjoinOutputIndex is null ? null : request.Destinations.ElementAt(payjoinOutputIndex.Value).Destination, EnforceLowR = psbt.Suggestions?.ShouldEnforceLowR, ChangeAddress = psbt.ChangeAddress?.ToString() }; var signingKeyStr = await explorerClient .GetMetadataAsync<string>(derivationScheme.AccountDerivation, WellknownMetadataKeys.MasterHDKey); if (!derivationScheme.IsHotWallet || signingKeyStr is null) { return this.CreateAPIError("not-available", $"{cryptoCode} sending services are not currently available"); } var signingKey = ExtKey.Parse(signingKeyStr, network.NBitcoinNetwork); var signingKeySettings = derivationScheme.GetSigningAccountKeySettings(); signingKeySettings.RootFingerprint ??= signingKey.GetPublicKey().GetHDFingerPrint(); RootedKeyPath rootedKeyPath = signingKeySettings.GetRootedKeyPath(); psbt.PSBT.RebaseKeyPaths(signingKeySettings.AccountKey, rootedKeyPath); var accountKey = signingKey.Derive(rootedKeyPath.KeyPath); if (signingContext?.EnforceLowR is bool v) psbt.PSBT.Settings.SigningOptions.EnforceLowR = v; else if (psbt.Suggestions?.ShouldEnforceLowR is bool v2) psbt.PSBT.Settings.SigningOptions.EnforceLowR = v2; var changed = psbt.PSBT.PSBTChanged(() => psbt.PSBT.SignAll(derivationScheme.AccountDerivation, accountKey, rootedKeyPath)); if (!changed) { return this.CreateAPIError("psbt-signing-error", "Impossible to sign the transaction. Probable cause: Incorrect account key path in wallet settings, PSBT already signed."); } psbt.PSBT.Finalize(); var transaction = psbt.PSBT.ExtractTransaction(); var transactionHash = transaction.GetHash(); BroadcastResult broadcastResult; if (!string.IsNullOrEmpty(signingContext?.PayJoinBIP21)) { signingContext.OriginalPSBT = psbt.PSBT.ToBase64(); try { await _delayedTransactionBroadcaster.Schedule(DateTimeOffset.UtcNow + TimeSpan.FromMinutes(2.0), transaction, network); var payjoinPSBT = await _payjoinClient.RequestPayjoin( new BitcoinUrlBuilder(signingContext.PayJoinBIP21, network.NBitcoinNetwork), new PayjoinWallet(derivationScheme), psbt.PSBT, CancellationToken.None); psbt.PSBT.Settings.SigningOptions = new SigningOptions() { EnforceLowR = !(signingContext?.EnforceLowR is false) }; payjoinPSBT = psbt.PSBT.SignAll(derivationScheme.AccountDerivation, accountKey, rootedKeyPath); payjoinPSBT.Finalize(); var payjoinTransaction = payjoinPSBT.ExtractTransaction(); var hash = payjoinTransaction.GetHash(); _eventAggregator.Publish(new UpdateTransactionLabel(new WalletId(Store.Id, cryptoCode), hash, UpdateTransactionLabel.PayjoinLabelTemplate())); broadcastResult = await explorerClient.BroadcastAsync(payjoinTransaction); if (broadcastResult.Success) { return await GetOnChainWalletTransaction(storeId, cryptoCode, hash.ToString()); } } catch (PayjoinException) { //not a critical thing, payjoin is great if possible, fine if not } } if (!request.ProceedWithBroadcast) { return Ok(new JValue(transaction.ToHex())); } broadcastResult = await explorerClient.BroadcastAsync(transaction); if (broadcastResult.Success) { return await GetOnChainWalletTransaction(storeId, cryptoCode, transactionHash.ToString()); } else { return this.CreateAPIError("broadcast-error", broadcastResult.RPCMessage); } } private async Task<(bool HotWallet, bool RPCImport)> CanUseHotWallet() { return await _authorizationService.CanUseHotWallet(await _settingsRepository.GetPolicies(), User); } private bool IsInvalidWalletRequest(string cryptoCode, [MaybeNullWhen(true)] out BTCPayNetwork network, [MaybeNullWhen(true)] out DerivationSchemeSettings derivationScheme, [MaybeNullWhen(false)] out IActionResult actionResult) { derivationScheme = null; network = _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(cryptoCode); if (network is null) { actionResult = NotFound(); return true; } if (!network.WalletSupported || !_btcPayWalletProvider.IsAvailable(network)) { actionResult = this.CreateAPIError("not-available", $"{cryptoCode} services are not currently available"); return true; } derivationScheme = GetDerivationSchemeSettings(cryptoCode); if (derivationScheme?.AccountDerivation is null) { actionResult = NotFound(); return true; } actionResult = null; return false; } private DerivationSchemeSettings GetDerivationSchemeSettings(string cryptoCode) { var paymentMethod = Store .GetSupportedPaymentMethods(_btcPayNetworkProvider) .OfType<DerivationSchemeSettings>() .FirstOrDefault(p => p.PaymentId.PaymentType == Payments.PaymentTypes.BTCLike && p.PaymentId.CryptoCode.Equals(cryptoCode, StringComparison.InvariantCultureIgnoreCase)); return paymentMethod; } private OnChainWalletTransactionData ToModel(WalletTransactionInfo? walletTransactionsInfoAsync, TransactionInformation tx, BTCPayWallet wallet) { return new OnChainWalletTransactionData() { TransactionHash = tx.TransactionId, Comment = walletTransactionsInfoAsync?.Comment ?? string.Empty, Labels = walletTransactionsInfoAsync?.Labels ?? new Dictionary<string, LabelData>(), Amount = tx.BalanceChange.GetValue(wallet.Network), BlockHash = tx.BlockHash, BlockHeight = tx.Height, Confirmations = tx.Confirmations, Timestamp = tx.Timestamp, Status = tx.Confirmations > 0 ? TransactionStatus.Confirmed : tx.ReplacedBy != null ? TransactionStatus.Replaced : TransactionStatus.Unconfirmed }; } } }
47.882353
172
0.614431
[ "MIT" ]
Zaxounette/btcpayserver
BTCPayServer/Controllers/GreenField/StoreOnChainWalletsController.cs
27,676
C#
using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using D2L.CodeStyle.Analyzers.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace D2L.CodeStyle.Analyzers.ApiUsage.Events { [DiagnosticAnalyzer( LanguageNames.CSharp )] internal sealed class EventHandlersDisallowedListAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create( Diagnostics.EventHandlerDisallowed ); public override void Initialize( AnalysisContext context ) { context.EnableConcurrentExecution(); context.RegisterCompilationStartAction( RegisterAnalysis ); } private void RegisterAnalysis( CompilationStartAnalysisContext context ) { Compilation compilation = context.Compilation; IImmutableSet<INamedTypeSymbol> disallowedTypes = GetDisallowedTypes( compilation ); if( disallowedTypes.Count == 0 ) { return; } context.RegisterSyntaxNodeAction( c => AnalyzeSimpleBaseType( c, disallowedTypes ), SyntaxKind.SimpleBaseType ); } private void AnalyzeSimpleBaseType( SyntaxNodeAnalysisContext context, IImmutableSet<INamedTypeSymbol> disallowedTypes ) { SimpleBaseTypeSyntax baseTypeSyntax = (SimpleBaseTypeSyntax)context.Node; SymbolInfo baseTypeSymbol = context.SemanticModel.GetSymbolInfo( baseTypeSyntax.Type ); INamedTypeSymbol baseSymbol = ( baseTypeSymbol.Symbol as INamedTypeSymbol ); if( baseSymbol.IsNullOrErrorType() ) { return; } if( !disallowedTypes.Contains( baseSymbol ) ) { return; } Diagnostic diagnostic = Diagnostic.Create( Diagnostics.EventHandlerDisallowed, baseTypeSyntax.GetLocation(), baseSymbol.ToDisplayString() ); context.ReportDiagnostic( diagnostic ); } private static IImmutableSet<INamedTypeSymbol> GetDisallowedTypes( Compilation compilation ) { IImmutableSet<INamedTypeSymbol> types = EventHandlersDisallowedList.DisallowedTypes .SelectMany( genericType => GetGenericTypes( compilation, genericType.Key, genericType.Value ) ) .ToImmutableHashSet(); return types; } private static IEnumerable<INamedTypeSymbol> GetGenericTypes( Compilation compilation, string genericTypeName, ImmutableArray<ImmutableArray<string>> genericTypeArgumentSets ) { INamedTypeSymbol genericTypeDefinition = compilation.GetTypeByMetadataName( genericTypeName ); if( genericTypeDefinition.IsNullOrErrorType() ) { yield break; } foreach( ImmutableArray<string> genericTypeArguments in genericTypeArgumentSets ) { if( TryGetGenericType( compilation, genericTypeDefinition, genericTypeArguments, out INamedTypeSymbol genericType ) ) { yield return genericType; } } } private static bool TryGetGenericType( Compilation compilation, INamedTypeSymbol genericTypeDefinition, ImmutableArray<string> genericTypeArguments, out INamedTypeSymbol genericType ) { INamedTypeSymbol[] genericTypeArgumentSymbols = new INamedTypeSymbol[ genericTypeArguments.Length ]; for( int i = 0; i < genericTypeArguments.Length; i++ ) { string genericTypeArgumentName = genericTypeArguments[ i ]; INamedTypeSymbol genericTypeArgumentSymbol = compilation.GetTypeByMetadataName( genericTypeArgumentName ); if( genericTypeArgumentSymbol.IsNullOrErrorType() ) { genericType = null; return false; } genericTypeArgumentSymbols[ i ] = genericTypeArgumentSymbol; } genericType = genericTypeDefinition.Construct( genericTypeArgumentSymbols ); if( genericType.IsNullOrErrorType() ) { genericType = null; return false; } return true; } } }
31.261905
124
0.743336
[ "Apache-2.0" ]
JTOne123/D2L.CodeStyle
src/D2L.CodeStyle.Analyzers/ApiUsage/Events/EventHandlersDisallowedListAnalyzer.cs
3,941
C#
// Copyright (c) Niklas Voss. All rights reserved. // Licensed under the Apache2 license. See LICENSE file in the project root for full license information. using System; using CueX.Core; namespace CueX.GridSPS.Config { public class GridConfiguration : Configuration { private double _partitionSize = 0d; public double PartitionHalfDiagonal { get; private set; } = 0d; public double PartitionSize { get => _partitionSize; set { _partitionSize = value; PartitionHalfDiagonal = Math.Sqrt(Math.Pow(_partitionSize * 0.5d, 2d) * 2d); } } public static GridConfiguration Default() { return new GridConfiguration(); } } }
28.071429
105
0.601781
[ "Apache-2.0" ]
trevex/CueX
CueX.GridSPS/Config/GridConfiguration.cs
788
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Axe.Windows.Core.Bases; using Axe.Windows.Core.Misc; using Axe.Windows.Core.Resources; using System; namespace Axe.Windows.Core.Results { /// <summary> /// ScanMetaInfo class /// this class indicate the meta information of Scan results origin /// the meta info would be like below /// - Property Name /// - UI Framework /// - ControlType /// </summary> public class ScanMetaInfo { /// <summary> /// Property is overridable by scan logic via SetProperty() /// </summary> public int PropertyId { get; set; } public string UIFramework { get; set; } public string ControlType { get; set; } /// <summary> /// Populate data based on ScanMetaInfo /// </summary> /// <param name="e"></param> /// <param name="propertyid"></param> public ScanMetaInfo(IA11yElement e, int propertyid):this(e) { this.PropertyId = propertyid; } /// <summary> /// Constructor for the scans which are not using property but to use structure. /// </summary> /// <param name="e"></param> public ScanMetaInfo(IA11yElement e) { if (e == null) throw new ArgumentNullException(nameof(e)); this.UIFramework = e.GetUIFramework(); this.ControlType = Types.ControlType.GetInstance().GetNameById(e.ControlTypeId).Split('(')[0]; this.PropertyId = 0; } /// <summary> /// Get the frameworkID. /// if FrameworkId exists in the element, it returns the value from it. /// otherwise, search it in ancestry. /// </summary> /// <param name="e"></param> /// <returns></returns> /// <summary> /// Constructor for Deserialization. /// </summary> public ScanMetaInfo() { } /// <summary> /// Override Property Id value /// if Property is already set, it will throw an exception. /// </summary> /// <param name="id"></param> public void SetProperty(int id) { if (PropertyId == 0) { this.PropertyId = id; } else { throw new ArgumentException(ErrorMessages.PropertyAlreadySet); } } /// <summary> /// Clone the ScanMetaInfo /// </summary> /// <returns></returns> internal ScanMetaInfo Clone() { var mi = new ScanMetaInfo(); mi.ControlType = this.ControlType; mi.PropertyId = this.PropertyId; mi.UIFramework = this.UIFramework; return mi; } } }
31.765957
107
0.530141
[ "MIT" ]
DaveTryon/axe-windows
src/Core/Results/ScanMetaInfo.cs
2,893
C#
using Microsoft.AspNetCore.Mvc; namespace AddressAnalyzer.Rdap.Api.Controllers { [ControllerName("Heartbeat")] [ApiVersion("1")] [Route("api/v{version:apiVersion}/[controller]")] public class HeartbeatV1Controller : Controller { [HttpGet] public string Get() { return "Address Analyzer Rdap Service Version 1"; } } }
22.764706
61
0.627907
[ "MIT" ]
JacobHeater/address-analyzer
AddressAnalyzer.Rdap.Api/Controllers/HeartbeatV1Controller.cs
389
C#
using System; using System.IO; using System.Reflection; using System.Web.Hosting; using App.Metrics; using App.Metrics.Extensions.Reporting.InfluxDB; using App.Metrics.Extensions.Reporting.InfluxDB.Client; using App.Metrics.Extensions.Reporting.TextFile; using App.Metrics.Reporting.Abstractions; using App.Metrics.Reporting.Interfaces; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Owin; using Owin; using Serilog; using Web.Mvc.Net452; using Web.Mvc.Net452.Infrastructure; [assembly: OwinStartup(typeof(Startup))] namespace Web.Mvc.Net452 { public class Startup { public void Configuration(IAppBuilder app) { var services = new ServiceCollection(); ConfigureServices(services); //DEVNOTE: If already using Autofac for example for DI, you would just build the // servicecollection, resolve IMetrics and register that with your container instead. var provider = services.SetDependencyResolver(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.RollingFile(Path.Combine($@"C:\logs\{Assembly.GetExecutingAssembly().GetName().Name}", "log-{Date}.txt")) .CreateLogger(); app.UseMetrics(provider); var loggerFactory = provider.GetRequiredService<ILoggerFactory>(); loggerFactory.AddSerilog(Log.Logger); HostingEnvironment.QueueBackgroundWorkItem(cancellationToken => { var reportFactory = provider.GetRequiredService<IReportFactory>(); var metrics = provider.GetRequiredService<IMetrics>(); var reporter = reportFactory.CreateReporter(); reporter.RunReports(metrics, cancellationToken); }); } public void ConfigureServices(IServiceCollection services) { services.AddLogging(); services.AddControllersAsServices(); services .AddMetrics(options => { options.DefaultContextLabel = "Mvc.Sample.Net452"; options.ReportingEnabled = true; }, Assembly.GetExecutingAssembly().GetName()) .AddReporting(factory => { factory.AddInfluxDb(new InfluxDBReporterSettings { HttpPolicy = new HttpPolicy { FailuresBeforeBackoff = 3, BackoffPeriod = TimeSpan.FromSeconds(30), Timeout = TimeSpan.FromSeconds(3) }, InfluxDbSettings = new InfluxDBSettings("appmetricsmvcsample452", new Uri("http://127.0.0.1:8086")), ReportInterval = TimeSpan.FromSeconds(5) }); factory.AddTextFile(new TextFileReporterSettings { ReportInterval = TimeSpan.FromSeconds(30), FileName = @"C:\metrics\mvc452sample.txt" }); }) .AddHealthChecks(factory => { factory.RegisterProcessPrivateMemorySizeHealthCheck("Private Memory Size", 200); factory.RegisterProcessVirtualMemorySizeHealthCheck("Virtual Memory Size", 200); factory.RegisterProcessPhysicalMemoryHealthCheck("Working Set", 200); }) .AddJsonSerialization() .AddMetricsMiddleware(options => { }); } } }
38.10101
129
0.573701
[ "Apache-2.0" ]
AppMetrics/AppMetrics.Samples
src/Web.Mvc.Net452/Startup.cs
3,774
C#
namespace TypewiseAlert { class HiActiveCooling : ICoolingType { public int LowerLimit { get { return 0; } } public int UpperLimit { get { return 45; } } } }
20.666667
52
0.607527
[ "MIT" ]
clean-code-craft-tcq-1/add-variety-cs-RaghavendraSR06
TypewiseAlert/HiActiveCooling.cs
186
C#
using UnityEngine; using System.Collections; public class ldaFollowBehaviour : MonoBehaviour { public enum DeactivationEnum { Deactivate, DestroyAfterCollision, DestroyAfterTime, Nothing }; public enum ldaFollowEndModeEnum { OnTimeMustDone=1,//时间必达 OnTime=2,//根据时间触发爆炸 OnDistance=3,//根据追踪距离触发爆炸 OnRangeXZ=4,//根据与发射点XZ平面距离触发爆炸 OnRange=5//根据与发射点直线距离触发爆炸 }; [Tooltip("碰撞半径")] public float ColliderRadius = 0.1f; [Tooltip("碰撞目标偏移(与目标位置点的偏移)")] public Vector3 ColliderOffset = new Vector3(0,1.5f,0); [Tooltip("追踪目标")] public GameObject Target; [Tooltip("移动目标")] public GameObject MoveObject; [Tooltip("爆炸目标")] public GameObject ExplosionObject; public DeactivationEnum DeactivationMode = DeactivationEnum.Nothing; public ldaFollowEndModeEnum FollowEndMode = ldaFollowEndModeEnum.OnTimeMustDone; [Tooltip("追踪速度")] public float MoveSpeed = 2.0f; [Tooltip("追踪时间")] public float MoveTime = 2.0f; [Tooltip("追踪距离")] public float MoveDistance = 2.0f; private float mMovingTime; private float mMovingDistance; private Vector3 mLastPosition; //发射位置 private Vector3 mLaunchPosition; [Tooltip("碰撞物层")] public LayerMask LayerMask = -1; //碰撞检测 private SphereCollider ColliderCheck = null; private Rigidbody ColliderCheckRig = null; [Tooltip("调试碰撞盒")] public bool DebugShowColliderRadius = true; private GameObject DebugColliderRadius = null; public bool DebugShowDebugAttackRange = false; private GameObject DebugAttackRange = null; [Tooltip("运动结束强行爆炸(不管是否发生碰撞)")] public bool ForceExplosion = false; [Tooltip("与目标点最小距离引发碰撞(强行结束)")] public float ManualColliderColliderMinDis = 0.1f; private bool theEnd = false; // Use this for initialization void Start () { } void OnEnable() { Init(); } void OnDisable() { transform.position = Vector3.zero; if (MoveObject != null) MoveObject.SetActive(true); if (ExplosionObject!=null) ExplosionObject.SetActive(false); } // Update is called once per frame void Update () { if (Input.GetKey(KeyCode.N)) { this.gameObject.SetActive(false); this.gameObject.SetActive(true); } if (theEnd) return; //时间必达 if (FollowEndMode == ldaFollowEndModeEnum.OnTimeMustDone) { if (mMovingTime > Time.deltaTime) { //Vector3 targetPos = new Vector3(Target.transform.position.x, Target.transform.position.y, Target.transform.position.z); //transform.position = Vector3.Lerp(transform.position, targetPos, Time.deltaTime / mMovingTime); //mMovingTime -= Time.deltaTime; Vector3 targetPos = new Vector3(Target.transform.position.x, Target.transform.position.y, Target.transform.position.z) + ColliderOffset; Vector3 targetPos22 = Vector3.Lerp(transform.position, targetPos, MoveSpeed * Time.deltaTime / mMovingTime); //transform.position = Vector3.Lerp(transform.position, targetPos, MoveSpeed * mMovingTime / Time.deltaTime); //if (Vector3.Distance(targetPos, transform.position) <= ColliderRadius) //{ // OnTriggerEnter(null); // return; //} transform.LookAt(targetPos22); transform.position = targetPos22; mMovingTime -= MoveSpeed * Time.deltaTime; } else { theEnd = true; ShowMoveObject(false); if (ForceExplosion) ShowExplosionObject(true); } } //根据时间触发爆炸 else if (FollowEndMode == ldaFollowEndModeEnum.OnTime) { if (mMovingTime > 0) { Vector3 targetPos = new Vector3(Target.transform.position.x, Target.transform.position.y, Target.transform.position.z) + ColliderOffset; transform.position = Vector3.Lerp(transform.position, targetPos, MoveSpeed * Time.deltaTime); mMovingTime -= Time.deltaTime; } else { theEnd = true; ShowMoveObject(false); if (ForceExplosion) ShowExplosionObject(true); } } //根据追踪距离触发爆炸 else if (FollowEndMode == ldaFollowEndModeEnum.OnDistance) { if(mMovingDistance>0) { Vector3 targetPos = new Vector3(Target.transform.position.x, Target.transform.position.y, Target.transform.position.z) + ColliderOffset; transform.position = Vector3.Lerp(transform.position, targetPos, MoveSpeed * Time.deltaTime); mMovingDistance -= Vector3.Distance(mLastPosition, transform.position); mLastPosition = transform.position; } else { theEnd = true; ShowMoveObject(false); if (ForceExplosion) ShowExplosionObject(true); } } //根据与发射点XZ平面距离触发爆炸 或 //根据与发射点直线距离触发爆炸 else if (FollowEndMode == ldaFollowEndModeEnum.OnRangeXZ || FollowEndMode == ldaFollowEndModeEnum.OnRange) { Vector3 curPosition = this.transform.position; if(FollowEndMode == ldaFollowEndModeEnum.OnRangeXZ)//根据与发射点XZ平面距离触发爆炸 curPosition.y = mLaunchPosition.y;//根据与发射点XZ平面距离触发爆炸 float dis = Vector3.Distance(curPosition, mLaunchPosition); if (dis < MoveDistance) { Vector3 targetPos = new Vector3(Target.transform.position.x, Target.transform.position.y, Target.transform.position.z) + ColliderOffset; transform.position = Vector3.Lerp(transform.position, targetPos, MoveSpeed * Time.deltaTime); mMovingDistance -= Vector3.Distance(mLastPosition, transform.position); mLastPosition = transform.position; } else { theEnd = true; ShowMoveObject(false); if (ForceExplosion) ShowExplosionObject(true); } } } //爆炸 void ShowExplosionObject(bool show) { if (ExplosionObject!=null) ExplosionObject.SetActive(show); //MoveObject.SetActive(false); } //运动 void ShowMoveObject(bool show) { if (MoveObject != null) MoveObject.SetActive(show); //关碰撞 if(!show) { if (ColliderCheck!=null) ColliderCheck.enabled = show; //ColliderCheckRig. } } public void Init() { if (DebugShowDebugAttackRange) { if (DebugAttackRange == null) { DebugAttackRange = (GameObject)Instantiate(Resources.Load("DebugAttackRange1")); DebugAttackRange.transform.parent = null;//this.transform; DebugAttackRange.transform.localPosition = Vector3.zero; } DebugAttackRange.SetActive(true); DebugAttackRange.transform.localScale = new Vector3(MoveDistance, MoveDistance, MoveDistance); Vector3 tmepPos = this.transform.position; tmepPos.y = -3; DebugAttackRange.transform.position = tmepPos; DebugAttackRange.GetComponent<DebugAttackRange1>().ShowAttackRange("范围" + MoveDistance.ToString(), 1); } if (DebugShowColliderRadius) { if (DebugColliderRadius == null) { DebugColliderRadius = (GameObject)Instantiate(Resources.Load("HitDefinitionSphere")); DebugColliderRadius.transform.parent = this.transform; DebugColliderRadius.transform.localPosition = Vector3.zero; } DebugColliderRadius.SetActive(true); DebugColliderRadius.transform.localScale = new Vector3(ColliderRadius, ColliderRadius, ColliderRadius); } else { if (DebugColliderRadius != null) DestroyImmediate(DebugColliderRadius); } mMovingTime = MoveTime; mLastPosition = transform.position; mMovingDistance = MoveDistance; if (ColliderCheck == null) ColliderCheck = this.gameObject.AddComponent<SphereCollider>(); ColliderCheck.radius = ColliderRadius * 2; ColliderCheck.center = Vector3.zero; ColliderCheck.isTrigger = true; if (ColliderCheckRig == null) ColliderCheckRig = this.gameObject.AddComponent<Rigidbody>(); ColliderCheckRig.useGravity = false; ColliderCheckRig.isKinematic = true; if (MoveObject != null) MoveObject.SetActive(true); if (ExplosionObject != null) ExplosionObject.SetActive(false); //记录下发射点位置 mLaunchPosition = this.transform.position; theEnd = false; } void OnTriggerEnter(Collider other) { Debug.Log("ldaFollowBehaviour OnTriggerEnter"); if (ExplosionObject != null) ExplosionObject.SetActive(true); if (MoveObject != null) MoveObject.SetActive(false); theEnd = true; } void OnTriggerExit(Collider other) { Debug.Log("ldaFollowBehaviour OnTriggerExit"); } }
31.262136
152
0.595238
[ "Apache-2.0" ]
maoa3/meteor_original_ios
Assets/Script/Control/ldaFollowBehaviour.cs
10,150
C#
using System.Threading.Tasks; using Funcky.Extensions; using Funcky.Xunit; using Xunit; using static Funcky.Functional; using static Funcky.Test.Extensions.AsyncEnumerableExtensions.TestData; namespace Funcky.Test.Extensions.AsyncEnumerableExtensions { public sealed class LastOrNoneTest { [Fact] public async Task LastOrNoneReturnsNoneWhenEnumerableIsEmpty() { FunctionalAssert.IsNone(await EmptyEnumerable.LastOrNoneAsync()); } [Fact] public async Task LastOrNoneReturnsItemWhenEnumerableHasOneItem() { FunctionalAssert.IsSome( FirstItem, await EnumerableWithOneItem.LastOrNoneAsync()); } [Fact] public async Task LastOrNoneReturnsNoneWhenEnumerableHasOneItemButItDoesNotMatchPredicate() { FunctionalAssert.IsNone( await EnumerableWithOneItem.LastOrNoneAsync(False)); } [Fact] public async Task LastOrNoneReturnsLastItemWhenEnumerableHasMoreThanOneItem() { FunctionalAssert.IsSome( LastItem, await EnumerableWithMoreThanOneItem.LastOrNoneAsync()); } [Fact] public async Task LastOrNoneReturnsNoneWhenEnumerableHasItemsButNoneMatchesPredicate() { FunctionalAssert.IsNone(await EnumerableWithMoreThanOneItem.LastOrNoneAsync(False)); } } }
30.333333
99
0.67033
[ "Apache-2.0", "MIT" ]
csillikd-messerli/funcky
Funcky.Test/Extensions/AsyncEnumerableExtensions/LastOrNoneTest.cs
1,456
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // </auto-generated> namespace Microsoft.Azure.Management.PrivateDns.Fluent { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; /// <summary> /// The Private DNS Management Client. /// </summary> public partial interface IPrivateDnsManagementClient : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> ServiceClientCredentials Credentials { get; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> string ApiVersion { get; } /// <summary> /// The preferred language for the response. /// </summary> string AcceptLanguage { get; set; } /// <summary> /// The retry timeout in seconds for Long Running Operations. Default /// value is 30. /// </summary> int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// Whether a unique x-ms-client-request-id should be generated. When /// set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IPrivateZonesOperations. /// </summary> IPrivateZonesOperations PrivateZones { get; } /// <summary> /// Gets the IVirtualNetworkLinksOperations. /// </summary> IVirtualNetworkLinksOperations VirtualNetworkLinks { get; } /// <summary> /// Gets the IRecordSetsOperations. /// </summary> IRecordSetsOperations RecordSets { get; } } }
30.629213
78
0.597946
[ "MIT" ]
Azure/azure-libraries-for-net
src/ResourceManagement/PrivateDns/Generated/IPrivateDnsManagementClient.cs
2,726
C#
using Orchard.ContentManagement.Records; using System.ComponentModel.DataAnnotations; namespace Orchard.Autoroute.Models { public class AutoroutePartRecord : ContentPartVersionRecord { public virtual bool UseCustomPattern { get; set; } public virtual bool UseCulturePattern { get; set; } [StringLength(2048)] public virtual string CustomPattern { get; set; } [StringLength(2048)] public virtual string DisplayAlias { get; set; } } }
29.333333
66
0.657197
[ "BSD-3-Clause" ]
Lombiq/Associativy
src/Orchard.Web/Modules/Orchard.Autoroute/Models/AutoroutePartRecord.cs
530
C#
using Com.Danliris.Service.Packing.Inventory.Application.ToBeRefactored.GarmentShipping.GarmentPackingList; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace Com.Danliris.Service.Packing.Inventory.Test.Services.GarmentShipping.GarmentPackingList { public class GarmentPackingListDraftValidationTest { private GarmentPackingListDraftViewModel ViewModel { get { return new GarmentPackingListDraftViewModel { Items = new List<GarmentPackingListItemViewModel>() { new GarmentPackingListItemViewModel() }, Measurements = new List<GarmentPackingListMeasurementViewModel>() { new GarmentPackingListMeasurementViewModel() }, }; } } [Fact] public void Validate_DefaultValue() { GarmentPackingListViewModel viewModel = ViewModel; var result = viewModel.Validate(null); Assert.NotEmpty(result.ToList()); } } }
30.45
108
0.587849
[ "MIT" ]
AndreaZain/com-danliris-service-packing-inventory
src/Com.Danliris.Service.Packing.Inventory.Test/Services/GarmentShipping/GarmentPackingList/GarmentPackingListDraftValidationTest.cs
1,220
C#
namespace GiveCRM.ImportExport { public enum ExcelFileType { XLS, XLSX } }
13.625
31
0.53211
[ "MIT" ]
GiveCampUK/GiveCRM
src/GiveCRM.ImportExport/GiveCRM.ImportExport/ExcelFileType.cs
109
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class CustomConverterTests { private class PocoWithNoBaseClass { } private class DerivedCustomer : Customer { } private class SuccessException : Exception { } private class BadCustomerConverter : JsonConverter<Customer> { public override bool CanConvert(Type typeToConvert) { // Say this converter supports all types even though we specify "Customer". return true; } public override Customer Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { throw new SuccessException(); } public override void Write(Utf8JsonWriter writer, Customer value, JsonSerializerOptions options) { throw new SuccessException(); } } [Fact] public static void ContraVariantConverterFail() { var options = new JsonSerializerOptions(); options.Converters.Add(new BadCustomerConverter()); // Incompatible types. Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<int>("0", options)); Assert.Throws<InvalidOperationException>(() => JsonSerializer.Serialize(0, options)); Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<PocoWithNoBaseClass>("{}", options)); Assert.Throws<InvalidOperationException>(() => JsonSerializer.Serialize(new PocoWithNoBaseClass(), options)); // Contravariant to Customer. Assert.Throws<SuccessException>(() => JsonSerializer.Deserialize<DerivedCustomer>("{}", options)); Assert.Throws<SuccessException>(() => JsonSerializer.Serialize(new DerivedCustomer(), options)); // Covariant to Customer. Assert.Throws<SuccessException>(() => JsonSerializer.Deserialize<Customer>("{}", options)); Assert.Throws<SuccessException>(() => JsonSerializer.Serialize(new Customer(), options)); Assert.Throws<SuccessException>(() => JsonSerializer.Serialize<Customer>(new DerivedCustomer(), options)); Assert.Throws<SuccessException>(() => JsonSerializer.Deserialize<Person>("{}", options)); Assert.Throws<SuccessException>(() => JsonSerializer.Serialize<Person>(new Customer(), options)); Assert.Throws<SuccessException>(() => JsonSerializer.Serialize<Person>(new DerivedCustomer(), options)); } private class InvalidConverterAttribute : JsonConverterAttribute { // converterType is not valid since typeof(int) is not a type that derives from JsonConverter. public InvalidConverterAttribute() : base(converterType: typeof(int)) { } } private class PocoWithInvalidConverter { [InvalidConverter] public int MyInt { get; set; } } [Fact] public static void AttributeCreateConverterFail() { InvalidOperationException ex; ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Serialize(new PocoWithInvalidConverter())); // Message should be in the form "The converter specified on 'System.Text.Json.Serialization.Tests.CustomConverterTests+PocoWithInvalidConverter.MyInt' does not derive from JsonConverter or have a public parameterless constructor." Assert.Contains("'System.Text.Json.Serialization.Tests.CustomConverterTests+PocoWithInvalidConverter.MyInt'", ex.Message); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<PocoWithInvalidConverter>("{}")); Assert.Contains("'System.Text.Json.Serialization.Tests.CustomConverterTests+PocoWithInvalidConverter.MyInt'", ex.Message); } private class InvalidTypeConverterClass { [JsonConverter(typeof(JsonStringEnumConverter))] public ICollection<InvalidTypeConverterEnum> MyEnumValues { get; set; } } private enum InvalidTypeConverterEnum { Value1, Value2, } [Fact] public static void AttributeOnPropertyFail() { InvalidOperationException ex; ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Serialize(new InvalidTypeConverterClass())); // Message should be in the form "The converter specified on 'System.Text.Json.Serialization.Tests.CustomConverterTests+InvalidTypeConverterClass.MyEnumValues' is not compatible with the type 'System.Collections.Generic.ICollection`1[System.Text.Json.Serialization.Tests.CustomConverterTests+InvalidTypeConverterEnum]'." Assert.Contains("'System.Text.Json.Serialization.Tests.CustomConverterTests+InvalidTypeConverterClass.MyEnumValues'", ex.Message); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<InvalidTypeConverterClass>("{}")); Assert.Contains("'System.Text.Json.Serialization.Tests.CustomConverterTests+InvalidTypeConverterClass.MyEnumValues'", ex.Message); Assert.Contains("'System.Collections.Generic.ICollection`1[System.Text.Json.Serialization.Tests.CustomConverterTests+InvalidTypeConverterEnum]'", ex.Message); } [JsonConverter(typeof(JsonStringEnumConverter))] private class InvalidTypeConverterClassWithAttribute { } [Fact] public static void AttributeOnClassFail() { const string expectedSubStr = "'System.Text.Json.Serialization.Tests.CustomConverterTests+InvalidTypeConverterClassWithAttribute'"; InvalidOperationException ex; ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Serialize(new InvalidTypeConverterClassWithAttribute())); // Message should be in the form "The converter specified on 'System.Text.Json.Serialization.Tests.CustomConverterTests+InvalidTypeConverterClassWithAttribute' is not compatible with the type 'System.Text.Json.Serialization.Tests.CustomConverterTests+InvalidTypeConverterClassWithAttribute'." int pos = ex.Message.IndexOf(expectedSubStr); Assert.True(pos > 0); Assert.Contains(expectedSubStr, ex.Message.Substring(pos + expectedSubStr.Length)); // The same string is repeated again. ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<InvalidTypeConverterClassWithAttribute>("{}")); pos = ex.Message.IndexOf(expectedSubStr); Assert.True(pos > 0); Assert.Contains(expectedSubStr, ex.Message.Substring(pos + expectedSubStr.Length)); } private class ConverterThatReturnsNull : JsonConverterFactory { public override bool CanConvert(Type typeToConvert) { return true; } public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { return null; } } [Fact] public static void ConverterThatReturnsNullFail() { var options = new JsonSerializerOptions(); options.Converters.Add(new ConverterThatReturnsNull()); Assert.Throws<ArgumentNullException>(() => JsonSerializer.Serialize(0, options)); Assert.Throws<ArgumentNullException>(() => JsonSerializer.Deserialize<int>("0", options)); } private class Level1 { public Level1() { Level2 = new Level2(); Level2.Level3s = new Level3[] { new Level3() }; } public Level2 Level2 { get; set; } } private class Level2 { public Level3[] Level3s {get; set; } } private class Level3 { // If true, read\write too much instead of too little. public bool ReadWriteTooMuch { get; set; } } private class Level3ConverterThatsBad: JsonConverter<Level3> { public override Level3 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { Assert.Equal(JsonTokenType.StartObject, reader.TokenType); reader.Read(); Assert.Equal(JsonTokenType.PropertyName, reader.TokenType); reader.Read(); Assert.True(reader.TokenType == JsonTokenType.True || reader.TokenType == JsonTokenType.False); // Determine if we should read too much. if (reader.TokenType == JsonTokenType.True) { // Do the correct read. reader.Read(); Assert.Equal(JsonTokenType.EndObject, reader.TokenType); // Do an extra read. reader.Read(); Assert.Equal(JsonTokenType.EndArray, reader.TokenType); // End on EndObject token so it looks good, but wrong depth. reader.Read(); Assert.Equal(JsonTokenType.EndObject, reader.TokenType); } return new Level3(); } public override void Write(Utf8JsonWriter writer, Level3 value, JsonSerializerOptions options) { if (value.ReadWriteTooMuch) { writer.WriteStartObject(); } } } [Fact] public static void ConverterReadTooLittle() { const string json = @"{""Level2"":{""Level3s"":[{""ReadWriteTooMuch"":false}]}}"; var options = new JsonSerializerOptions(); options.Converters.Add(new Level3ConverterThatsBad()); try { JsonSerializer.Deserialize<Level1>(json, options); Assert.True(false, "Expected exception"); } catch (JsonException ex) { Assert.Contains("$.Level2.Level3s[1]", ex.ToString()); Assert.Equal("$.Level2.Level3s[1]", ex.Path); } } [Fact] public static void ConverterReadTooMuch() { const string json = @"{""Level2"":{""Level3s"":[{""ReadWriteTooMuch"":true}]}}"; var options = new JsonSerializerOptions(); options.Converters.Add(new Level3ConverterThatsBad ()); try { JsonSerializer.Deserialize<Level1>(json, options); Assert.True(false, "Expected exception"); } catch (JsonException ex) { Assert.Contains("$.Level2.Level3s[1]", ex.ToString()); Assert.Equal("$.Level2.Level3s[1]", ex.Path); } } [Fact] public static void ConverterWroteNothing() { var options = new JsonSerializerOptions(); options.Converters.Add(new Level3ConverterThatsBad()); // Not writing is allowed. string str = JsonSerializer.Serialize(new Level1(), options); Assert.False(string.IsNullOrEmpty(str)); } [Fact] public static void ConverterWroteTooMuch() { var options = new JsonSerializerOptions(); options.Converters.Add(new Level3ConverterThatsBad()); try { var l1 = new Level1(); l1.Level2.Level3s[0].ReadWriteTooMuch = true; JsonSerializer.Serialize(l1, options); Assert.True(false, "Expected exception"); } catch (JsonException ex) { Assert.Contains("$.Level2.Level3s", ex.ToString()); Assert.Equal("$.Level2.Level3s", ex.Path); } } private class PocoWithTwoConvertersOnProperty { [InvalidConverter] [PointConverter] public int MyInt { get; set; } } [Fact] public static void PropertyHasMoreThanOneConverter() { InvalidOperationException ex; ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Serialize(new PocoWithTwoConvertersOnProperty())); // Message should be in the form "The attribute 'System.Text.Json.Serialization.JsonConverterAttribute' cannot exist more than once on 'System.Text.Json.Serialization.Tests.CustomConverterTests+PocoWithTwoConvertersOnProperty.MyInt'." Assert.Contains("'System.Text.Json.Serialization.JsonConverterAttribute'", ex.Message); Assert.Contains("'System.Text.Json.Serialization.Tests.CustomConverterTests+PocoWithTwoConvertersOnProperty.MyInt'", ex.Message); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<PocoWithTwoConvertersOnProperty>("{}")); Assert.Contains("'System.Text.Json.Serialization.JsonConverterAttribute'", ex.Message); Assert.Contains("'System.Text.Json.Serialization.Tests.CustomConverterTests+PocoWithTwoConvertersOnProperty.MyInt'", ex.Message); } [InvalidConverter] [PointConverter] private class PocoWithTwoConverters { public int MyInt { get; set; } } [Fact] public static void TypeHasMoreThanOneConverter() { InvalidOperationException ex; ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Serialize(new PocoWithTwoConverters())); // Message should be in the form "The attribute 'System.Text.Json.Serialization.JsonConverterAttribute' cannot exist more than once on 'System.Text.Json.Serialization.Tests.CustomConverterTests+PocoWithTwoConverters'." Assert.Contains("'System.Text.Json.Serialization.JsonConverterAttribute'", ex.Message); Assert.Contains("'System.Text.Json.Serialization.Tests.CustomConverterTests+PocoWithTwoConverters'", ex.Message); ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<PocoWithTwoConverters>("{}")); Assert.Contains("'System.Text.Json.Serialization.JsonConverterAttribute'", ex.Message); Assert.Contains("'System.Text.Json.Serialization.Tests.CustomConverterTests+PocoWithTwoConverters'", ex.Message); } [Fact] public static void ConverterWithoutDefaultCtor() { string json = @"{""MyType"":""ABC""}"; InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => JsonSerializer.Deserialize<ClassWithConverterWithoutPublicEmptyCtor>(json)); Assert.Contains("'System.Text.Json.Serialization.Tests.CustomConverterTests+ClassWithConverterWithoutPublicEmptyCtor'", ex.Message); } [JsonConverter(typeof(ConverterWithoutPublicEmptyCtor))] public class ClassWithConverterWithoutPublicEmptyCtor { public string MyType { get; set; } } internal class ConverterWithoutPublicEmptyCtor : JsonConverter<ClassWithConverterWithoutPublicEmptyCtor> { public ConverterWithoutPublicEmptyCtor(int x) { } public override ClassWithConverterWithoutPublicEmptyCtor Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { throw new NotImplementedException(); } public override void Write(Utf8JsonWriter writer, ClassWithConverterWithoutPublicEmptyCtor value, JsonSerializerOptions options) { throw new NotImplementedException(); } } } }
43.794038
332
0.632426
[ "MIT" ]
AArnott/runtime
src/libraries/System.Text.Json/tests/Serialization/CustomConverterTests.BadConverters.cs
16,162
C#
using System; using System.Collections.Generic; using System.Text; using Substrate.Nbt; namespace Substrate.Entities { public class EntityAnimal : EntityMob { public static readonly SchemaNodeCompound AnimalSchema = MobSchema.MergeInto(new SchemaNodeCompound("") { new SchemaNodeScaler("Age", TagType.TAG_INT, SchemaOptions.CREATE_ON_MISSING), new SchemaNodeScaler("InLove", TagType.TAG_INT, SchemaOptions.CREATE_ON_MISSING), }); private int _age; private int _inLove; public int Age { get { return _age; } set { _age = value; } } public int InLove { get { return _inLove; } set { _inLove = value; } } protected EntityAnimal (string id) : base(id) { } public EntityAnimal () : this(TypeId) { } public EntityAnimal (TypedEntity e) : base(e) { EntityAnimal e2 = e as EntityAnimal; if (e2 != null) { _age = e2._age; _inLove = e2._inLove; } } #region INBTObject<Entity> Members public override TypedEntity LoadTree (TagNode tree) { TagNodeCompound ctree = tree as TagNodeCompound; if (ctree == null || base.LoadTree(tree) == null) { return null; } _age = ctree["Age"].ToTagInt(); _inLove = ctree["InLove"].ToTagInt(); return this; } public override TagNode BuildTree () { TagNodeCompound tree = base.BuildTree() as TagNodeCompound; tree["Age"] = new TagNodeInt(_age); tree["InLove"] = new TagNodeInt(_inLove); return tree; } public override bool ValidateTree (TagNode tree) { return new NbtVerifier(tree, AnimalSchema).Verify(); } #endregion #region ICopyable<Entity> Members public override TypedEntity Copy () { return new EntityAnimal(this); } #endregion } }
23.56383
111
0.526411
[ "MIT" ]
Cable89/Substrate
SubstrateCS/Source/Entities/EntityAnimal.cs
2,217
C#
// Copyright (c) Josef Pihrt. 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.Linq; using System.Collections.Generic; namespace Roslynator.CSharp.Refactorings.Test { internal static class CallExtensionMethodAsInstanceMethodRefactoring { public static void ExtensionMethod(this string parameter1, string parameter2) { ExtensionMethod(parameter1, parameter2); CallExtensionMethodAsInstanceMethodRefactoring.ExtensionMethod(parameter1, parameter2); Roslynator.CSharp.Refactorings.Test.CallExtensionMethodAsInstanceMethodRefactoring.ExtensionMethod(parameter1, parameter2); parameter1.ExtensionMethod(parameter2); var items = Enumerable.Select(Enumerable.Range(0, 1), f => f); } private static IEnumerable<TResult> Select<TResult, TSource>(this IEnumerable<TSource> items, Func<TSource, TResult> selector) { foreach (var item in items) yield return selector(item); } } }
40.321429
160
0.715678
[ "Apache-2.0" ]
TechnoridersForks/Roslynator
source/Test/RefactoringsTest/CallExtensionMethodAsInstanceMethodRefactoring.cs
1,131
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xamarin.Forms.Controls.GalleryPages; using Xamarin.Forms.Controls.GalleryPages.CollectionViewGalleries; using Xamarin.Forms.CustomAttributes; using Xamarin.Forms.Internals; using Xamarin.Forms.PlatformConfiguration; using Xamarin.Forms.PlatformConfiguration.AndroidSpecific; using Xamarin.Forms.PlatformConfiguration.iOSSpecific; using Xamarin.Forms.Controls.GalleryPages.VisualStateManagerGalleries; namespace Xamarin.Forms.Controls { [Preserve(AllMembers = true)] public static class Messages { public const string ChangeRoot = "com.xamarin.ChangeRoot"; } [Preserve(AllMembers = true)] internal class CoreCarouselPage : CarouselPage { public CoreCarouselPage() { AutomationId = "CarouselPageRoot"; Children.Add(new CoreRootPage(this, NavigationBehavior.PushModalAsync) { Title = "Page 1" }); Children.Add(new CoreRootPage(this, NavigationBehavior.PushModalAsync) { Title = "Page 2" }); } } [Preserve(AllMembers = true)] internal class CoreContentPage : ContentPage { public CoreContentPage() { On<iOS>().SetUseSafeArea(true); AutomationId = "ContentPageRoot"; Content = new StackLayout { Children = { new CoreRootView(), new CorePageView(this, NavigationBehavior.PushModalAsync) } }; } } [Preserve(AllMembers = true)] internal class CoreMasterDetailPage : MasterDetailPage { public CoreMasterDetailPage() { AutomationId = "MasterDetailPageRoot"; var toCrashButton = new Button { Text = "Crash Me" }; var masterPage = new ContentPage { Title = "Menu", Icon = "bank.png", Content = toCrashButton }; var detailPage = new CoreRootPage(this, NavigationBehavior.PushModalAsync) { Title = "DetailPage" }; bool toggle = false; toCrashButton.Clicked += (sender, args) => { if (toggle) Detail = new ContentPage { BackgroundColor = Color.Green, }; else Detail = detailPage; toggle = !toggle; }; Master = masterPage; Detail = detailPage; } } [Preserve(AllMembers = true)] internal class CoreNavigationPage : NavigationPage { public CoreNavigationPage() { AutomationId = "NavigationPageRoot"; BarBackgroundColor = Color.Maroon; BarTextColor = Color.Yellow; Device.StartTimer(TimeSpan.FromSeconds(2), () => { BarBackgroundColor = Color.Default; BarTextColor = Color.Default; return false; }); On<iOS>().SetPrefersLargeTitles(true); Navigation.PushAsync(new CoreRootPage(this)); } } [Preserve(AllMembers = true)] public class CoreTabbedPageAsBottomNavigation : CoreTabbedPageBase { protected override void Init() { On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom); base.Init(); } } [Preserve(AllMembers = true)] [Issue(IssueTracker.Github, 2456, "StackOverflow after reordering tabs in a TabbedPageView", PlatformAffected.All)] public class CoreTabbedPage : CoreTabbedPageBase { } [Preserve(AllMembers = true)] public class CoreTabbedPageBase : TestTabbedPage { protected override void Init() { } #if APP public CoreTabbedPageBase() { AutomationId = "TabbedPageRoot"; Device.StartTimer(TimeSpan.FromSeconds(6), () => { BarBackgroundColor = Color.Maroon; BarTextColor = Color.Yellow; Device.StartTimer(TimeSpan.FromSeconds(6), () => { BarBackgroundColor = Color.Default; BarTextColor = Color.Default; return false; }); return false; }); Children.Add(new CoreRootPage(this, NavigationBehavior.PushModalAsync) { Title = "Tab 1" }); Children.Add(new CoreRootPage(this, NavigationBehavior.PushModalAsync) { Title = "Tab 2" }); Children.Add(new NavigationPage(new Page()) { Title = "Rubriques", Icon = "coffee.png", BarBackgroundColor = Color.Blue, BarTextColor = Color.Aqua }); Children.Add(new NavigationPage(new Page()) { Title = "Le Club" }); Children.Add(new NavigationPage(new Page { Title = "Bookmarks" }) { Title = "Bookmarks", }); if (On<Android>().GetMaxItemCount() > 5) { Children.Add(new NavigationPage(new Page { Title = "Alertes" }) { Title = "Notifications", }); Children.Add(new NavigationPage(new Page { Title = "My account" }) { Title = "My account", }); Children.Add(new NavigationPage(new Page { Title = "About" }) { Title = "About", }); } } #endif #if UITest [Test] [Issue (IssueTracker.Github, 2456, "StackOverflow after reordering tabs in a TabbedPageView", PlatformAffected.iOS)] public void TestReorderTabs () { App.Tap (c => c.Marked("More")); App.Tap (c => c.Marked("Edit")); var bookmarks = App.Query (c => c.Marked ("Bookmarks"))[0]; var notifications = App.Query (c => c.Marked ("Notifications"))[0]; var tab2 = App.Query (c => c.Marked ("Tab 2"))[2]; var rubriques = App.Query (c => c.Marked ("Rubriques"))[2]; App.DragCoordinates (bookmarks.Rect.CenterX, bookmarks.Rect.CenterY, rubriques.Rect.CenterX, rubriques.Rect.CenterY); App.DragCoordinates (notifications.Rect.CenterX, notifications.Rect.CenterY, tab2.Rect.CenterX, tab2.Rect.CenterY); App.Tap (c => c.Marked("Done")); App.Tap (c => c.Marked("Tab 1")); App.Tap (c => c.Marked("Le Club")); App.Tap (c => c.Marked("Bookmarks")); App.Tap (c => c.Marked("Notifications")); } #endif } [Preserve(AllMembers = true)] internal class CoreViewContainer { public string Name { get; private set; } public Type PageType { get; private set; } public CoreViewContainer(string name, Type pageType) { Name = name; PageType = pageType; } } [Preserve(AllMembers = true)] public class CoreRootView : ListView { public CoreRootView() { var roots = new[] { new CoreViewContainer ("SwapRoot - CarouselPage", typeof(CoreCarouselPage)), new CoreViewContainer ("SwapRoot - ContentPage", typeof(CoreContentPage)), new CoreViewContainer ("SwapRoot - MasterDetailPage", typeof(CoreMasterDetailPage)), new CoreViewContainer ("SwapRoot - NavigationPage", typeof(CoreNavigationPage)), new CoreViewContainer ("SwapRoot - TabbedPage", typeof(CoreTabbedPage)), new CoreViewContainer ("SwapRoot - BottomNavigation TabbedPage", typeof(CoreTabbedPageAsBottomNavigation)), new CoreViewContainer ("SwapRoot - Store Shell", typeof(XamStore.StoreShell)), }; var template = new DataTemplate(typeof(TextCell)); template.SetBinding(TextCell.TextProperty, "Name"); ItemTemplate = template; ItemsSource = roots; #if PRE_APPLICATION_CLASS ItemSelected += (sender, args) => MessagingCenter.Send (this, Messages.ChangeRoot, ((CoreViewContainer)args.SelectedItem).PageType); #else ItemSelected += (sender, args) => { var app = Application.Current as App; if (app != null) { var page = (Page)Activator.CreateInstance(((CoreViewContainer)args.SelectedItem).PageType); app.SetMainPage(page); } }; #endif SetValue(AutomationProperties.NameProperty, "SwapRoot"); } } [Preserve(AllMembers = true)] internal class CorePageView : ListView { [Preserve(AllMembers = true)] internal class GalleryPageFactory { public GalleryPageFactory(Func<Page> create, string title) { Realize = () => { var p = create(); p.Title = title; return p; }; Title = title; TitleAutomationId = $"{Title}AutomationId"; } public Func<Page> Realize { get; set; } public string Title { get; set; } public string TitleAutomationId { get; set; } public override string ToString() { // a11y: let Narrator read a friendly string instead of the default ToString() return Title; } } List<GalleryPageFactory> _pages = new List<GalleryPageFactory> { new GalleryPageFactory(() => new Issues.A11yTabIndex(), "Accessibility TabIndex"), new GalleryPageFactory(() => new FontImageSourceGallery(), "Font ImageSource"), new GalleryPageFactory(() => new CollectionViewGallery(), "CollectionView Gallery"), new GalleryPageFactory(() => new CollectionViewCoreGalleryPage(), "CollectionView Core Gallery"), new GalleryPageFactory(() => new Issues.PerformanceGallery(), "Performance"), new GalleryPageFactory(() => new EntryReturnTypeGalleryPage(), "Entry ReturnType "), new GalleryPageFactory(() => new VisualStateManagerGallery(), "VisualStateManager Gallery"), new GalleryPageFactory(() => new FlowDirectionGalleryLandingPage(), "FlowDirection"), new GalleryPageFactory(() => new AutomationPropertiesGallery(), "Accessibility"), new GalleryPageFactory(() => new PlatformSpecificsGallery(), "Platform Specifics"), new GalleryPageFactory(() => new NativeBindingGalleryPage(), "Native Binding Controls Gallery"), new GalleryPageFactory(() => new XamlNativeViews(), "Xaml Native Views Gallery"), new GalleryPageFactory(() => new AppLinkPageGallery(), "App Link Page Gallery"), new GalleryPageFactory(() => new NestedNativeControlGalleryPage(), "Nested Native Controls Gallery"), new GalleryPageFactory(() => new CellForceUpdateSizeGalleryPage(), "Cell Force Update Size Gallery"), new GalleryPageFactory(() => new AppearingGalleryPage(), "Appearing Gallery"), new GalleryPageFactory(() => new EntryCoreGalleryPage(), "Entry Gallery"), new GalleryPageFactory(() => new MaterialEntryGalleryPage(), "Entry Material Demos"), new GalleryPageFactory(() => new NavBarTitleTestPage(), "Titles And Navbar Windows"), new GalleryPageFactory(() => new PanGestureGalleryPage(), "Pan gesture Gallery"), new GalleryPageFactory(() => new SwipeGestureGalleryPage(), "Swipe gesture Gallery"), new GalleryPageFactory(() => new PinchGestureTestPage(), "Pinch gesture Gallery"), new GalleryPageFactory(() => new ClickGestureGalleryPage(), "Click gesture Gallery"), new GalleryPageFactory(() => new AutomationIdGallery(), "AutomationID Gallery"), new GalleryPageFactory(() => new LayoutPerformanceGallery(), "Layout Perf Gallery"), new GalleryPageFactory(() => new ListViewSelectionColor(), "ListView SelectionColor Gallery"), new GalleryPageFactory(() => new AlertGallery(), "DisplayAlert Gallery"), new GalleryPageFactory(() => new ToolbarItems(), "ToolbarItems Gallery"), new GalleryPageFactory(() => new ActionSheetGallery(), "ActionSheet Gallery"), new GalleryPageFactory(() => new ActivityIndicatorCoreGalleryPage(), "ActivityIndicator Gallery"), new GalleryPageFactory(() => new BehaviorsAndTriggers(), "BehaviorsTriggers Gallery"), new GalleryPageFactory(() => new ContextActionsGallery(), "ContextActions List Gallery"), new GalleryPageFactory(() => new ContextActionsGallery (tableView: true), "ContextActions Table Gallery"), new GalleryPageFactory(() => new CoreBoxViewGalleryPage(), "BoxView Gallery"), new GalleryPageFactory(() => new ButtonCoreGalleryPage(), "Button Gallery"), new GalleryPageFactory(() => new ButtonLayoutGalleryPage(), "Button Layout Gallery"), new GalleryPageFactory(() => new ButtonLayoutGalleryPage(VisualMarker.Material), "Button Layout Gallery (Material)"), new GalleryPageFactory(() => new ButtonBorderBackgroundGalleryPage(), "Button Border & Background Gallery"), new GalleryPageFactory(() => new ButtonBorderBackgroundGalleryPage(VisualMarker.Material), "Button Border & Background Gallery (Material)"), new GalleryPageFactory(() => new DatePickerCoreGalleryPage(), "DatePicker Gallery"), new GalleryPageFactory(() => new EditorCoreGalleryPage(), "Editor Gallery"), new GalleryPageFactory(() => new FrameCoreGalleryPage(), "Frame Gallery"), new GalleryPageFactory(() => new ImageCoreGalleryPage(), "Image Gallery"), new GalleryPageFactory(() => new ImageButtonCoreGalleryPage(), "Image Button Gallery"), new GalleryPageFactory(() => new KeyboardCoreGallery(), "Keyboard Gallery"), new GalleryPageFactory(() => new LabelCoreGalleryPage(), "Label Gallery"), new GalleryPageFactory(() => new ListViewCoreGalleryPage(), "ListView Gallery"), new GalleryPageFactory(() => new OpenGLViewCoreGalleryPage(), "OpenGLView Gallery"), new GalleryPageFactory(() => new PickerCoreGalleryPage(), "Picker Gallery"), new GalleryPageFactory(() => new ProgressBarCoreGalleryPage(), "ProgressBar Gallery"), new GalleryPageFactory(() => new MaterialProgressBarGallery(), "ProgressBar & Slider Gallery (Material)"), new GalleryPageFactory(() => new MaterialActivityIndicatorGallery(), "ActivityIndicator Gallery (Material)"), new GalleryPageFactory(() => new ScrollGallery(), "ScrollView Gallery"), new GalleryPageFactory(() => new ScrollGallery(ScrollOrientation.Horizontal), "ScrollView Gallery Horizontal"), new GalleryPageFactory(() => new ScrollGallery(ScrollOrientation.Both), "ScrollView Gallery 2D"), new GalleryPageFactory(() => new SearchBarCoreGalleryPage(), "SearchBar Gallery"), new GalleryPageFactory(() => new SliderCoreGalleryPage(), "Slider Gallery"), new GalleryPageFactory(() => new StepperCoreGalleryPage(), "Stepper Gallery"), new GalleryPageFactory(() => new SwitchCoreGalleryPage(), "Switch Gallery"), new GalleryPageFactory(() => new TableViewCoreGalleryPage(), "TableView Gallery"), new GalleryPageFactory(() => new TimePickerCoreGalleryPage(), "TimePicker Gallery"), new GalleryPageFactory(() => new VisualGallery(), "Visual Gallery"), new GalleryPageFactory(() => new WebViewCoreGalleryPage(), "WebView Gallery"), new GalleryPageFactory(() => new WkWebViewCoreGalleryPage(), "WkWebView Gallery"), new GalleryPageFactory(() => new DynamicViewGallery(), "Dynamic ViewGallery"), //pages new GalleryPageFactory(() => new RootContentPage ("Content"), "RootPages Gallery"), new GalleryPageFactory(() => new MasterDetailPageTabletPage(), "MasterDetailPage Tablet Page"), // legacy galleries new GalleryPageFactory(() => new AbsoluteLayoutGallery(), "AbsoluteLayout Gallery - Legacy"), new GalleryPageFactory(() => new BoundContentPage(), "BoundPage Gallery - Legacy"), new GalleryPageFactory(() => new BackgroundImageGallery(), "BackgroundImage gallery"), new GalleryPageFactory(() => new ButtonGallery(), "Button Gallery - Legacy"), new GalleryPageFactory(() => new CarouselPageGallery(), "CarouselPage Gallery - Legacy"), new GalleryPageFactory(() => new CellTypesListPage(), "Cells Gallery - Legacy"), new GalleryPageFactory(() => new ClipToBoundsGallery(), "ClipToBounds Gallery - Legacy"), new GalleryPageFactory(() => new ControlTemplatePage(), "ControlTemplated Gallery - Legacy"), new GalleryPageFactory(() => new ControlTemplateXamlPage(), "ControlTemplated XAML Gallery - Legacy"), new GalleryPageFactory(() => new DisposeGallery(), "Dispose Gallery - Legacy"), new GalleryPageFactory(() => new EditorGallery(), "Editor Gallery - Legacy"), new GalleryPageFactory(() => new EntryGallery(), "Entry Gallery - Legacy"), new GalleryPageFactory(() => new FrameGallery (), "Frame Gallery - Legacy"), new GalleryPageFactory(() => new GridGallery(), "Grid Gallery - Legacy"), new GalleryPageFactory(() => new GroupedListActionsGallery(), "GroupedListActions Gallery - Legacy"), new GalleryPageFactory(() => new GroupedListContactsGallery(), "GroupedList Gallery - Legacy"), new GalleryPageFactory(() => new ImageGallery (), "Image Gallery - Legacy"), new GalleryPageFactory(() => new ImageLoadingGallery (), "ImageLoading Gallery - Legacy"), new GalleryPageFactory(() => new InputIntentGallery(), "InputIntent Gallery - Legacy"), new GalleryPageFactory(() => new LabelGallery(), "Label Gallery - Legacy"), new GalleryPageFactory(() => new LayoutAddPerformance(), "Layout Add Performance - Legacy"), new GalleryPageFactory(() => new LayoutOptionsGallery(), "LayoutOptions Gallery - Legacy"), new GalleryPageFactory(() => new LineBreakModeGallery(), "LineBreakMode Gallery - Legacy"), new GalleryPageFactory(() => new ListPage(), "ListView Gallery - Legacy"), new GalleryPageFactory(() => new ListScrollTo(), "ListView.ScrollTo"), new GalleryPageFactory(() => new ListRefresh(), "ListView.PullToRefresh"), new GalleryPageFactory(() => new ListViewDemoPage(), "ListView Demo Gallery - Legacy"), new GalleryPageFactory(() => new MapGallery(), "Map Gallery - Legacy"), new GalleryPageFactory(() => new MapWithItemsSourceGallery(), "Map With ItemsSource Gallery - Legacy"), new GalleryPageFactory(() => new MinimumSizeGallery(), "MinimumSize Gallery - Legacy"), new GalleryPageFactory(() => new MultiGallery(), "Multi Gallery - Legacy"), new GalleryPageFactory(() => new NavigationPropertiesGallery(), "Navigation Properties"), #if HAVE_OPENTK new GalleryPageFactory(() => new BasicOpenGLGallery(), "Basic OpenGL Gallery - Legacy"), new GalleryPageFactory(() => new AdvancedOpenGLGallery(), "Advanced OpenGL Gallery - Legacy"), #endif new GalleryPageFactory(() => new PickerGallery(), "Picker Gallery - Legacy"), new GalleryPageFactory(() => new ProgressBarGallery(), "ProgressBar Gallery - Legacy"), new GalleryPageFactory(() => new RelativeLayoutGallery(), "RelativeLayout Gallery - Legacy"), new GalleryPageFactory(() => new ScaleRotate(), "Scale Rotate Gallery - Legacy"), new GalleryPageFactory(() => new SearchBarGallery(), "SearchBar Gallery - Legacy"), new GalleryPageFactory(() => new SettingsPage(), "Settings Page - Legacy"), new GalleryPageFactory(() => new SliderGallery(), "Slider Gallery - Legacy"), new GalleryPageFactory(() => new StackLayoutGallery(), "StackLayout Gallery - Legacy"), new GalleryPageFactory(() => new StepperGallery(), "Stepper Gallery - Legacy"), new GalleryPageFactory(() => new StyleGallery(), "Style Gallery"), new GalleryPageFactory(() => new StyleXamlGallery(), "Style Gallery in Xaml"), new GalleryPageFactory(() => new SwitchGallery(), "Switch Gallery - Legacy"), new GalleryPageFactory(() => new TableViewGallery(), "TableView Gallery - Legacy"), new GalleryPageFactory(() => new TemplatedCarouselGallery(), "TemplatedCarouselPage Gallery - Legacy"), new GalleryPageFactory(() => new TemplatedTabbedGallery(), "TemplatedTabbedPage Gallery - Legacy"), new GalleryPageFactory(() => new UnevenViewCellGallery(), "UnevenViewCell Gallery - Legacy"), new GalleryPageFactory(() => new UnevenListGallery(), "UnevenList Gallery - Legacy"), new GalleryPageFactory(() => new ViewCellGallery(), "ViewCell Gallery - Legacy"), new GalleryPageFactory(() => new WebViewGallery(), "WebView Gallery - Legacy"), new GalleryPageFactory(() => new BindableLayoutGalleryPage(), "BindableLayout Gallery - Legacy"), }; public CorePageView(Page rootPage, NavigationBehavior navigationBehavior = NavigationBehavior.PushAsync) { var galleryFactory = DependencyService.Get<IPlatformSpecificCoreGalleryFactory>(); var platformPages = galleryFactory?.GetPages(); if (platformPages != null) _pages.AddRange(platformPages.Select(p => new GalleryPageFactory(p.Create, p.Title + " (Platform Specifc)"))); _titleToPage = _pages.ToDictionary(o => o.Title); // avoid NRE for root pages without NavigationBar if (navigationBehavior == NavigationBehavior.PushAsync && rootPage.GetType () == typeof (CoreNavigationPage)) { _pages.Insert (0, new GalleryPageFactory(() => new NavigationBarGallery((NavigationPage)rootPage), "NavigationBar Gallery - Legacy")); _pages.Insert(1, new GalleryPageFactory(() => new TitleView(true), "TitleView")); } _pages.Sort((x, y) => string.Compare(x.Title, y.Title, true)); var template = new DataTemplate(() => { var cell = new TextCell(); cell.ContextActions.Add(new MenuItem { Text = "Select Visual", Command = new Command(async () => { var buttons = typeof(VisualMarker).GetProperties().Select(p => p.Name); var selection = await rootPage.DisplayActionSheet("Select Visual", "Cancel", null, buttons.ToArray()); if (cell.BindingContext is GalleryPageFactory pageFactory) { var page = pageFactory.Realize(); if (typeof(VisualMarker).GetProperty(selection)?.GetValue(null) is IVisual visual) page.Visual = visual; await PushPage(page); } }) }); return cell; }); template.SetBinding(TextCell.TextProperty, "Title"); template.SetBinding(TextCell.AutomationIdProperty, "TitleAutomationId"); BindingContext = _pages; ItemTemplate = template; ItemsSource = _pages; ItemSelected += async (sender, args) => { if (SelectedItem == null) return; var item = args.SelectedItem; var page = item as GalleryPageFactory; if (page != null) await PushPage(page.Realize()); SelectedItem = null; }; SetValue(AutomationProperties.NameProperty, "Core Pages"); } NavigationBehavior navigationBehavior; async Task PushPage(Page contentPage) { if (navigationBehavior == NavigationBehavior.PushModalAsync) { await Navigation.PushModalAsync(contentPage); } else { await Navigation.PushAsync(contentPage); } } readonly Dictionary<string, GalleryPageFactory> _titleToPage; public async Task PushPage(string pageTitle) { GalleryPageFactory pageFactory = null; if (!_titleToPage.TryGetValue(pageTitle, out pageFactory)) return; var page = pageFactory.Realize(); await PushPage(page); } public void FilterPages(string filter) { if (string.IsNullOrWhiteSpace(filter)) ItemsSource = _pages; else ItemsSource = _pages.Where(p => p.Title.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) != -1); } } [Preserve(AllMembers = true)] internal class CoreRootPage : ContentPage { public CoreRootPage(Page rootPage, NavigationBehavior navigationBehavior = NavigationBehavior.PushAsync) { ValidateRegistrar(); var galleryFactory = DependencyService.Get<IPlatformSpecificCoreGalleryFactory>(); Title = galleryFactory?.Title ?? "Core Gallery"; var corePageView = new CorePageView(rootPage, navigationBehavior); var searchBar = new SearchBar() { AutomationId = "SearchBar" }; searchBar.TextChanged += (sender, e) => { corePageView.FilterPages(e.NewTextValue); }; var testCasesButton = new Button { Text = "Go to Test Cases", AutomationId = "GoToTestButton", TabIndex = -2, Command = new Command(async () => { if (!string.IsNullOrEmpty(searchBar.Text)) await corePageView.PushPage(searchBar.Text); else await Navigation.PushModalAsync(TestCases.GetTestCases()); }) }; var stackLayout = new StackLayout() { Children = { testCasesButton, searchBar, new Button { Text = "Click to Force GC", TabIndex = -2, Command = new Command(() => { GC.Collect (); GC.WaitForPendingFinalizers (); GC.Collect (); }) } } }; this.SetAutomationPropertiesName("Gallery"); this.SetAutomationPropertiesHelpText("Lists all gallery pages"); Content = new AbsoluteLayout { Children = { { new CoreRootView (), new Rectangle(0, 0.0, 1, 0.35), AbsoluteLayoutFlags.All }, { stackLayout, new Rectangle(0, 0.5, 1, 0.30), AbsoluteLayoutFlags.All }, { corePageView, new Rectangle(0, 1.0, 1.0, 0.35), AbsoluteLayoutFlags.All }, } }; } void ValidateRegistrar() { foreach (var view in Issues.Helpers.ViewHelper.GetAllViews()) { if (!DependencyService.Get<IRegistrarValidationService>().Validate(view, out string message)) throw new InvalidOperationException(message); } foreach (var page in Issues.Helpers.ViewHelper.GetAllPages()) { page.Visual = VisualMarker.Default; if (!DependencyService.Get<IRegistrarValidationService>().Validate(page, out string message)) throw new InvalidOperationException(message); } } } [Preserve(AllMembers = true)] public interface IPlatformSpecificCoreGalleryFactory { string Title { get; } IEnumerable<(Func<Page> Create, string Title)> GetPages(); } [Preserve(AllMembers = true)] public static class CoreGallery { public static Page GetMainPage() { return new CoreNavigationPage(); } } }
39.829787
144
0.704265
[ "MIT" ]
PawKanarek/Xamarin.Forms
Xamarin.Forms.Controls/CoreGallery.cs
24,338
C#
using System.Collections.Generic; using System.Xml.Serialization; namespace Sekhmet.Serialization.XmlSerializerSupport.Test.Dummies { public class FooWithNonNestedListAndProperty { [XmlElement("Bar")] public List<SimpleBar> Bars { get; set; } [XmlElement("Bar2")] public SimpleBar Bar { get; set; } } }
24.857143
65
0.683908
[ "MIT" ]
kimbirkelund/SekhmetSerialization
trunk/src/Sekhmet.Serialization.XmlSerializerSupport.Test/Dummies/FooWithNonNestedListAndProperty.cs
348
C#
using System.Linq; using Application.Storage.Interfaces.ReadModels; using Common; using Domain.Interfaces.Entities; using QueryAny; namespace Storage.ReadModels { public sealed class ReadModelCheckpointStore : IReadModelCheckpointStore { public const long StartingCheckpointPosition = 1; private readonly IDomainFactory domainFactory; private readonly IIdentifierFactory idFactory; private readonly IRecorder recorder; private readonly IRepository repository; public ReadModelCheckpointStore(IRecorder recorder, IIdentifierFactory idFactory, IDomainFactory domainFactory, IRepository repository) { recorder.GuardAgainstNull(nameof(recorder)); idFactory.GuardAgainstNull(nameof(idFactory)); repository.GuardAgainstNull(nameof(repository)); domainFactory.GuardAgainstNull(nameof(domainFactory)); this.recorder = recorder; this.idFactory = idFactory; this.repository = repository; this.domainFactory = domainFactory; } private static string ContainerName => typeof(Checkpoint).GetEntityNameSafe(); public long LoadCheckpoint(string streamName) { var checkpoint = GetCheckpoint(streamName); return checkpoint == null ? StartingCheckpointPosition : checkpoint.Position; } public void SaveCheckpoint(string streamName, long position) { var checkpoint = GetCheckpoint(streamName); if (checkpoint == null) { checkpoint = new Checkpoint { Position = position, StreamName = streamName }; checkpoint.Id = this.idFactory.Create(checkpoint); this.repository.Add(ContainerName, CommandEntity.FromType(checkpoint)); } else { checkpoint.Position = position; this.repository.Replace(ContainerName, checkpoint.Id, CommandEntity.FromType(checkpoint)); } this.recorder.TraceDebug("Saved checkpoint {StreamName} to position: {Position}", streamName, position); } private Checkpoint GetCheckpoint(string streamName) { var checkpoint = this.repository .Query(ContainerName, Query.From<Checkpoint>().Where(cp => cp.StreamName, ConditionOperator.EqualTo, streamName), RepositoryEntityMetadata.FromType<Checkpoint>()) .FirstOrDefault(); return checkpoint?.ToEntity<Checkpoint>(this.domainFactory); } } }
37.876712
111
0.61953
[ "Apache-2.0" ]
jezzsantos/queryany
samples/ri/Storage.ReadModels/ReadModelCheckpointStore.cs
2,767
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.470) // Version 5.470.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Drawing; using System.Drawing.Text; using System.Windows.Forms; using System.Diagnostics; using System.Windows.Forms.VisualStyles; using System.Runtime.InteropServices; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Provide accurate text measuring and drawing capability. /// </summary> public class AccurateText : GlobalId { #region Static Fields private const int GLOW_EXTRA_WIDTH = 14; private const int GLOW_EXTRA_HEIGHT = 3; #endregion #region Public Static Methods /// <summary> /// Pixel accurate measure of the specified string when drawn with the specified Font object. /// </summary> /// <param name="g">Graphics instance used to measure text.</param> /// <param name="rtl">Right to left setting for control.</param> /// <param name="text">String to measure.</param> /// <param name="font">Font object that defines the text format of the string.</param> /// <param name="trim">How to trim excess text.</param> /// <param name="align">How to align multi-line text.</param> /// <param name="prefix">How to process prefix characters.</param> /// <param name="hint">Rendering hint.</param> /// <param name="composition">Should draw on a composition element.</param> /// <param name="glowing">When on composition draw with glowing.</param> /// <param name="disposeFont">Dispose of font when finished with it.</param> /// <exception cref="ArgumentNullException"></exception> /// <returns>A memento used to draw the text.</returns> public static AccurateTextMemento MeasureString(Graphics g, RightToLeft rtl, string text, Font font, PaletteTextTrim trim, PaletteRelativeAlign align, PaletteTextHotkeyPrefix prefix, TextRenderingHint hint, bool composition, bool glowing, bool disposeFont) { Debug.Assert(g != null); Debug.Assert(text != null); Debug.Assert(font != null); if (g == null) { throw new ArgumentNullException(nameof(g)); } if (text == null) { throw new ArgumentNullException(nameof(text)); } if (font == null) { throw new ArgumentNullException(nameof(font)); } // An empty string cannot be drawn, so uses the empty memento if (text.Length == 0) { return AccurateTextMemento.Empty; } // Create the format object used when measuring and drawing StringFormat format = new StringFormat { FormatFlags = StringFormatFlags.NoClip }; // Ensure that text reflects reversed RTL setting if (rtl == RightToLeft.Yes) { format.FormatFlags |= StringFormatFlags.DirectionRightToLeft; } // How do we position text horizontally? switch (align) { case PaletteRelativeAlign.Near: format.Alignment = (rtl == RightToLeft.Yes) ? StringAlignment.Far : StringAlignment.Near; break; case PaletteRelativeAlign.Center: format.Alignment = StringAlignment.Center; break; case PaletteRelativeAlign.Far: format.Alignment = (rtl == RightToLeft.Yes) ? StringAlignment.Near : StringAlignment.Far; break; default: // Should never happen! Debug.Assert(false); break; } // Do we need to trim text that is too big? switch (trim) { case PaletteTextTrim.Character: format.Trimming = StringTrimming.Character; break; case PaletteTextTrim.EllipsisCharacter: format.Trimming = StringTrimming.EllipsisCharacter; break; case PaletteTextTrim.EllipsisPath: format.Trimming = StringTrimming.EllipsisPath; break; case PaletteTextTrim.EllipsisWord: format.Trimming = StringTrimming.EllipsisWord; break; case PaletteTextTrim.Word: format.Trimming = StringTrimming.Word; break; case PaletteTextTrim.Hide: format.Trimming = StringTrimming.None; break; default: // Should never happen! Debug.Assert(false); break; } // Setup the correct prefix processing switch (prefix) { case PaletteTextHotkeyPrefix.None: format.HotkeyPrefix = HotkeyPrefix.None; break; case PaletteTextHotkeyPrefix.Hide: format.HotkeyPrefix = HotkeyPrefix.Hide; break; case PaletteTextHotkeyPrefix.Show: format.HotkeyPrefix = HotkeyPrefix.Show; break; default: // Should never happen! Debug.Assert(false); break; } // Replace tab characters with a fixed four spaces text = text.Replace("\t", " "); // Perform actual measure of the text using (GraphicsTextHint graphicsHint = new GraphicsTextHint(g, hint)) { SizeF textSize = Size.Empty; try { textSize = g.MeasureString(text, font, int.MaxValue, format); if (composition && glowing) //Seb { textSize.Width += GLOW_EXTRA_WIDTH; } } catch { // ignored } // Return a memento with drawing details return new AccurateTextMemento(text, font, textSize, format, hint, disposeFont); } } /// <summary> /// Pixel accurate drawing of the requested text memento information. /// </summary> /// <param name="g">Graphics object used for drawing.</param> /// <param name="brush">Brush for drawing text with.</param> /// <param name="rect">Rectangle to draw text inside.</param> /// <param name="rtl">Right to left setting for control.</param> /// <param name="orientation">Orientation for drawing text.</param> /// <param name="memento">Memento containing text context.</param> /// <param name="state">State of the source element.</param> /// <param name="composition">Should draw on a composition element.</param> /// <param name="glowing">When on composition draw with glowing.</param> /// <exception cref="ArgumentNullException"></exception> /// <returns>True if draw succeeded; False is draw produced an error.</returns> public static bool DrawString(Graphics g, Brush brush, Rectangle rect, RightToLeft rtl, VisualOrientation orientation, bool composition, bool glowing, PaletteState state, AccurateTextMemento memento) { Debug.Assert(g != null); Debug.Assert(memento != null); // Cannot draw with a null graphics instance if (g == null) { throw new ArgumentNullException(nameof(g)); } // Cannot draw with a null memento instance if (memento == null) { throw new ArgumentNullException(nameof(memento)); } bool ret = true; // Is there a valid place to be drawn into if ((rect.Width > 0) && (rect.Height > 0)) { // Does the memento contain something to draw? if (!memento.IsEmpty) { int translateX = 0; int translateY = 0; float rotation = 0f; // Perform any transformations needed for orientation switch (orientation) { case VisualOrientation.Bottom: // Translate to opposite side of origin, so the rotate can // then bring it back to original position but mirror image translateX = (rect.X * 2) + rect.Width; translateY = (rect.Y * 2) + rect.Height; rotation = 180f; break; case VisualOrientation.Left: // Invert the dimensions of the rectangle for drawing upwards rect = new Rectangle(rect.X, rect.Y, rect.Height, rect.Width); // Translate back from a quarter left turn to the original place translateX = rect.X - rect.Y - 1; translateY = rect.X + rect.Y + rect.Width; rotation = 270; break; case VisualOrientation.Right: // Invert the dimensions of the rectangle for drawing upwards rect = new Rectangle(rect.X, rect.Y, rect.Height, rect.Width); // Translate back from a quarter right turn to the original place translateX = rect.X + rect.Y + rect.Height + 1; translateY = -(rect.X - rect.Y); rotation = 90f; break; } // Apply the transforms if we have any to apply if ((translateX != 0) || (translateY != 0)) { g.TranslateTransform(translateX, translateY); } if (rotation != 0f) { g.RotateTransform(rotation); } try { if (Application.RenderWithVisualStyles && composition && glowing) { //DrawCompositionGlowingText(g, memento.Text, memento.Font, rect, state, // SystemColors.ActiveCaptionText, true); if (Environment.OSVersion.Version.Major >= 10 && Environment.OSVersion.Version.Build >= 10586) { DrawCompositionGlowingText(g, memento.Text, memento.Font, rect, state, (state == PaletteState.Disabled) ? Color.FromArgb(170, 170, 170) : ContrastColor(AccentColorService.GetColorByTypeName("ImmersiveSystemAccent")), true); } else { DrawCompositionGlowingText(g, memento.Text, memento.Font, rect, state, SystemColors.ActiveCaptionText, true); } } else if (Application.RenderWithVisualStyles && composition) { //Check if correct in all cases SolidBrush tmpBrush = brush as SolidBrush; Color tmpColor = tmpBrush?.Color ?? SystemColors.ActiveCaptionText; DrawCompositionText(g, memento.Text, memento.Font, rect, state, tmpColor, true, memento.Format); } else { g.DrawString(memento.Text, memento.Font, brush, rect, memento.Format); } } catch { // Ignore any error from the DrawString, usually because the display settings // have changed causing Fonts to be invalid. Our controls will notice the change // and refresh the fonts but sometimes the draw happens before the fonts are // regenerated. Just ignore message and everything will sort itself out. Trust me! ret = false; } finally { // Remove the applied transforms if (rotation != 0f) { g.RotateTransform(-rotation); } if ((translateX != 0) || (translateY != 0)) { g.TranslateTransform(-translateX, -translateY); } } } } return ret; } private static Color ContrastColor(Color color) { // Counting the perceptive luminance - human eye favours green colour... double a = (1 - (((0.299 * color.R) + ((0.587 * color.G) + (0.114 * color.B))) / 255)); int d = a < 0.5 ? 0 : 255; // dark colours - white font return Color.FromArgb(d, d, d); } #endregion #region Implementation /// <summary> /// Draw text with a glowing background, for use on a composition element. /// </summary> /// <param name="g">Graphics reference.</param> /// <param name="text">Text to be drawn.</param> /// <param name="font">Font to use for text.</param> /// <param name="bounds">Bounding area for the text.</param> /// <param name="state">State of the source element.</param> /// <param name="color"><see cref="Color"/> of the text.</param> /// <param name="copyBackground">Should existing background be copied into the bitmap.</param> public static void DrawCompositionGlowingText(Graphics g, string text, Font font, Rectangle bounds, PaletteState state, Color color, bool copyBackground) { // Get the hDC for the graphics instance and create a memory DC IntPtr gDC = g.GetHdc(); try { IntPtr mDC = PI.CreateCompatibleDC(gDC); PI.BITMAPINFO bmi = new PI.BITMAPINFO { biWidth = bounds.Width, biHeight = -(bounds.Height + (GLOW_EXTRA_HEIGHT * 2)), biCompression = 0, biBitCount = 32, biPlanes = 1 }; bmi.biSize = (uint) Marshal.SizeOf(bmi); // Create a device independent bitmap and select into the memory DC IntPtr hDIB = PI.CreateDIBSection(gDC, ref bmi, 0, out _, IntPtr.Zero, 0); PI.SelectObject(mDC, hDIB); if (copyBackground) { // Copy existing background into the bitmap PI.BitBlt(mDC, 0, 0, bounds.Width, bounds.Height + (GLOW_EXTRA_HEIGHT * 2), gDC, bounds.X, bounds.Y - GLOW_EXTRA_HEIGHT, 0x00CC0020); } // Select the font for use when drawing IntPtr hFont = font.ToHfont(); PI.SelectObject(mDC, hFont); // Get renderer for the correct state VisualStyleRenderer renderer = new VisualStyleRenderer(state == PaletteState.Normal ? VisualStyleElement.Window.Caption.Active : VisualStyleElement.Window.Caption.Inactive); // Create structures needed for theme drawing call PI.RECT textBounds = new PI.RECT { left = 0, top = 0, right = (bounds.Right - bounds.Left), bottom = (bounds.Bottom - bounds.Top) + (GLOW_EXTRA_HEIGHT * 2) }; PI.DTTOPTS dttOpts = new PI.DTTOPTS { dwSize = Marshal.SizeOf(typeof(PI.DTTOPTS)), dwFlags = PI.DTT_COMPOSITED | PI.DTT_GLOWSIZE | PI.DTT_TEXTCOLOR, crText = ColorTranslator.ToWin32(color), iGlowSize = 11 }; // Always draw text centered const TextFormatFlags TEXT_FORMAT = TextFormatFlags.SingleLine | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis; // Perform actual drawing PI.DrawThemeTextEx(renderer.Handle, mDC, 0, 0, text, -1, (int)TEXT_FORMAT, ref textBounds, ref dttOpts); // Copy to foreground PI.BitBlt(gDC, bounds.Left, bounds.Top - GLOW_EXTRA_HEIGHT, bounds.Width, bounds.Height + (GLOW_EXTRA_HEIGHT * 2), mDC, 0, 0, 0x00CC0020); // Dispose of allocated objects PI.DeleteObject(hFont); PI.DeleteObject(hDIB); PI.DeleteDC(mDC); } catch { // ignored } finally { // Must remember to release the hDC g.ReleaseHdc(gDC); } } /// <summary> /// Draw text without a glowing background, for use on a composition element. /// </summary> /// <param name="g">Graphics reference.</param> /// <param name="text">Text to be drawn.</param> /// <param name="font">Font to use for text.</param> /// <param name="bounds">Bounding area for the text.</param> /// <param name="state">State of the source element.</param> /// <param name="color"><see cref="Color"/> of the text.</param> /// <param name="copyBackground">Should existing background be copied into the bitmap.</param> /// <param name="sf">StringFormat of the memento.</param> public static void DrawCompositionText(Graphics g, string text, Font font, Rectangle bounds, PaletteState state, Color color, bool copyBackground, StringFormat sf) { // Get the hDC for the graphics instance and create a memory DC IntPtr gDC = g.GetHdc(); try { IntPtr mDC = PI.CreateCompatibleDC(gDC); PI.BITMAPINFO bmi = new PI.BITMAPINFO { biWidth = bounds.Width, biHeight = -(bounds.Height), biCompression = 0, biBitCount = 32, biPlanes = 1 }; bmi.biSize = (uint)Marshal.SizeOf(bmi); // Create a device independent bitmap and select into the memory DC IntPtr hDIB = PI.CreateDIBSection(gDC, ref bmi, 0, out _, IntPtr.Zero, 0); PI.SelectObject(mDC, hDIB); if (copyBackground) { // Copy existing background into the bitmap PI.BitBlt(mDC, 0, 0, bounds.Width, bounds.Height, gDC, bounds.X, bounds.Y, 0x00CC0020); } // Select the font for use when drawing IntPtr hFont = font.ToHfont(); PI.SelectObject(mDC, hFont); // Get renderer for the correct state VisualStyleRenderer renderer = new VisualStyleRenderer(state == PaletteState.Normal ? VisualStyleElement.Window.Caption.Active : VisualStyleElement.Window.Caption.Inactive); // Create structures needed for theme drawing call PI.RECT textBounds = new PI.RECT { left = 0, top = 0, right = (bounds.Right - bounds.Left), bottom = (bounds.Bottom - bounds.Top) }; PI.DTTOPTS dttOpts = new PI.DTTOPTS { dwSize = Marshal.SizeOf(typeof(PI.DTTOPTS)), dwFlags = PI.DTT_COMPOSITED | PI.DTT_TEXTCOLOR, crText = ColorTranslator.ToWin32(color) }; // Always draw text centered TextFormatFlags textFormat = TextFormatFlags.SingleLine | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter; ////Seb | TextFormatFlags.EndEllipsis; // Perform actual drawing //PI.DrawThemeTextEx(renderer.Handle, // mDC, 0, 0, // text, -1, (int)StringFormatToFlags(sf), // ref textBounds, ref dttOpts); PI.DrawThemeTextEx(renderer.Handle, mDC, 0, 0, text, -1, (int)textFormat, ref textBounds, ref dttOpts); // Copy to foreground PI.BitBlt(gDC, bounds.Left, bounds.Top, bounds.Width, bounds.Height, mDC, 0, 0, 0x00CC0020); // Dispose of allocated objects PI.DeleteObject(hFont); PI.DeleteObject(hDIB); PI.DeleteDC(mDC); } catch { // ignored } finally { // Must remember to release the hDC g.ReleaseHdc(gDC); } } private static StringFormat FlagsToStringFormat(TextFormatFlags flags) { StringFormat sf = new StringFormat(); // Translation table: http://msdn.microsoft.com/msdnmag/issues/06/03/TextRendering/default.aspx?fig=true#fig4 // Horizontal Alignment if ((flags & TextFormatFlags.HorizontalCenter) == TextFormatFlags.HorizontalCenter) { sf.Alignment = StringAlignment.Center; } else if ((flags & TextFormatFlags.Right) == TextFormatFlags.Right) { sf.Alignment = StringAlignment.Far; } else { sf.Alignment = StringAlignment.Near; } // Vertical Alignment if ((flags & TextFormatFlags.Bottom) == TextFormatFlags.Bottom) { sf.LineAlignment = StringAlignment.Far; } else if ((flags & TextFormatFlags.VerticalCenter) == TextFormatFlags.VerticalCenter) { sf.LineAlignment = StringAlignment.Center; } else { sf.LineAlignment = StringAlignment.Near; } // Ellipsis if ((flags & TextFormatFlags.EndEllipsis) == TextFormatFlags.EndEllipsis) { sf.Trimming = StringTrimming.EllipsisCharacter; } else if ((flags & TextFormatFlags.PathEllipsis) == TextFormatFlags.PathEllipsis) { sf.Trimming = StringTrimming.EllipsisPath; } else if ((flags & TextFormatFlags.WordEllipsis) == TextFormatFlags.WordEllipsis) { sf.Trimming = StringTrimming.EllipsisWord; } else { sf.Trimming = StringTrimming.Character; } // Hotkey Prefix if ((flags & TextFormatFlags.NoPrefix) == TextFormatFlags.NoPrefix) { sf.HotkeyPrefix = HotkeyPrefix.None; } else if ((flags & TextFormatFlags.HidePrefix) == TextFormatFlags.HidePrefix) { sf.HotkeyPrefix = HotkeyPrefix.Hide; } else { sf.HotkeyPrefix = HotkeyPrefix.Show; } // Text Padding if ((flags & TextFormatFlags.NoPadding) == TextFormatFlags.NoPadding) { sf.FormatFlags |= StringFormatFlags.FitBlackBox; } // Text Wrapping if ((flags & TextFormatFlags.SingleLine) == TextFormatFlags.SingleLine) { sf.FormatFlags |= StringFormatFlags.NoWrap; } else if ((flags & TextFormatFlags.TextBoxControl) == TextFormatFlags.TextBoxControl) { sf.FormatFlags |= StringFormatFlags.LineLimit; } // Other Flags //if ((flags & TextFormatFlags.RightToLeft) == TextFormatFlags.RightToLeft) // sf.FormatFlags |= StringFormatFlags.DirectionRightToLeft; if ((flags & TextFormatFlags.NoClipping) == TextFormatFlags.NoClipping) { sf.FormatFlags |= StringFormatFlags.NoClip; } return sf; } private static TextFormatFlags StringFormatToFlags(StringFormat sf) { TextFormatFlags flags = new TextFormatFlags(); // Translation table: http://msdn.microsoft.com/msdnmag/issues/06/03/TextRendering/default.aspx?fig=true#fig4 switch (sf.Alignment) { // Horizontal Alignment case StringAlignment.Center: flags = flags & TextFormatFlags.HorizontalCenter; break; case StringAlignment.Far: flags = flags & TextFormatFlags.Right; break; default: flags = flags & TextFormatFlags.Left; break; } switch (sf.LineAlignment) { // Vertical Alignment case StringAlignment.Far: flags = flags & TextFormatFlags.Bottom; break; case StringAlignment.Center: flags = flags & TextFormatFlags.VerticalCenter; break; default: flags = flags & TextFormatFlags.Top; break; } switch (sf.Trimming) { // Ellipsis case StringTrimming.EllipsisCharacter: flags = flags & TextFormatFlags.EndEllipsis; break; case StringTrimming.EllipsisPath: flags = flags & TextFormatFlags.PathEllipsis; break; case StringTrimming.EllipsisWord: flags = flags & TextFormatFlags.WordEllipsis; break; } // Hotkey Prefix if (sf.HotkeyPrefix == HotkeyPrefix.None) { flags = flags & TextFormatFlags.NoPrefix; } else if (sf.HotkeyPrefix == HotkeyPrefix.Hide) { flags = flags & TextFormatFlags.HidePrefix; } // Text Padding if (sf.FormatFlags == StringFormatFlags.FitBlackBox) { flags = flags & TextFormatFlags.NoPadding; } // Text Wrapping if (sf.FormatFlags == StringFormatFlags.NoWrap) { flags = flags & TextFormatFlags.SingleLine; } else if (sf.FormatFlags == StringFormatFlags.LineLimit) { flags = flags & TextFormatFlags.TextBoxControl; } // Other Flags if (sf.FormatFlags == StringFormatFlags.DirectionRightToLeft) { flags = flags & TextFormatFlags.RightToLeft; } if (sf.FormatFlags == StringFormatFlags.NoClip) { flags = flags & TextFormatFlags.NoClipping; } return flags; } #endregion } }
41.808201
157
0.462809
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-NET-5.470
Source/Krypton Components/ComponentFactory.Krypton.Toolkit/AccurateText/AccurateText.cs
31,610
C#
#pragma warning disable 1587 /** * Copyright 2019-2020 Wingify Software Pvt. Ltd. * * 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. */ #pragma warning restore 1587 namespace VWOSdk { //Common ErrorMessages among different SDKs. internal static class LogDebugMessage { public static void LogLevelSet(string file, LogLevel level) { Log.Debug($"({file}): Log level set to {level.ToString()}"); } //public static void SetColoredLog(string file, string value) //{ // Log.Debug($"({file}): Colored log set to {value}"); //} public static void SetDevelopmentMode(string file) { Log.Debug($"({file}): DEVELOPMENT mode is ON"); } public static void ValidConfiguration(string file) { Log.Debug($"({file}): SDK configuration and account settings are valid."); } public static void CustomLoggerUsed(string file) { Log.Debug($"({file}): Custom logger used"); } public static void SdkInitialized(string file) { Log.Debug($"({file}): SDK properly initialzed"); } public static void SettingsFileProcessed(string file) { Log.Debug($"({file}): Settings file processed"); } public static void NoStoredVariation(string file, string userId, string campaignKey) { Log.Debug($"({file}): No stored variation for UserId:{userId} for Campaign:{campaignKey} found in UserStorageService"); } public static void NoUserStorageServiceGet(string file) { Log.Debug($"({file}): No UserStorageService to look for stored data"); } public static void NoUserStorageServiceSet(string file) { Log.Debug($"({file}): No UserStorageService to set data"); } public static void CheckUserEligibilityForCampaign(string file, string campaignKey, double trafficAllocation, string userId) { Log.Debug($"({file}): campaign:{campaignKey} having traffic allocation:{trafficAllocation} assigned value:{trafficAllocation} to userId:{userId}"); } public static void UserHashBucketValue(string file, string userId, double hashValue, double bucketValue) { Log.Debug($"({file}): userId:{userId} having hash:{hashValue} got bucketValue:{bucketValue}"); } public static void VariationHashBucketValue(string file, string userId, string campaignKey, double percentTraffic, double hashValue, double bucketValue) { Log.Debug($"({file}): userId:{userId} for campaign:{campaignKey} having percent traffic:{percentTraffic} got hash-value:{hashValue} and bucket value:{bucketValue}"); } public static void GotVariationForUser(string file, string userId, string campaignKey, string variationName, string method) { Log.Debug($"({file}): userId:{userId} for campaign:{campaignKey} got variationName:{variationName} inside method:{method}"); } public static void UserNotPartOfCampaign(string file, string userId, string campaignKey, string method) { Log.Debug($"({file}): userId:{userId} for campaign:{campaignKey} did not become part of campaign, method:{method}"); } public static void UuidForUser(string file, string userId, long accountId, string desiredUuid) { Log.Debug($"({file}): Uuid generated for userId:{userId} and accountId:{accountId} is {desiredUuid}"); } public static void ImpressionForTrackUser(string file, string properties) { Log.Debug($"({file}): impression built for track-user - {properties}"); } public static void ImpressionForTrackGoal(string file, string properties) { Log.Debug($"({file}): impression built for track-goal - {properties}"); } public static void ImpressionForPushTag(string file, string properties) { Log.Debug($"({file}): impression built for push-tags - {properties}"); } public static void SkippingSegmentation(string file , string userId, string campaignKey, string apiName, string variationName) { Log.Debug($"({file}): In API: {apiName}, Skipping segmentation for UserId:{userId} in campaing:{campaignKey} for variation: {variationName} as no valid segment is found"); } public static void SegmentationStatus(string file , string userId, string campaignKey, string apiName, string variationName, string status) { Log.Debug($"({file}): In API: {apiName}, Whitelisting for UserId:{userId} in campaing:{campaignKey} for variation: {variationName} is: {status}"); } } }
50.523364
184
0.640215
[ "Apache-2.0" ]
decabits/vwo-dotnet-sdk
VWOSdk/Logger/Messages/LogDebugMessage.cs
5,408
C#
using Castle.DynamicProxy; namespace Coldairarrow.Util { /// <summary> /// 过滤器 /// </summary> public interface IFilter { /// <summary> /// 执行前 /// </summary> /// <param name="invocation">执行信息</param> void OnActionExecuting(IInvocation invocation); /// <summary> /// 执行后 /// </summary> /// <param name="invocation">执行信息</param> void OnActionExecuted(IInvocation invocation); } }
21.086957
55
0.536082
[ "MIT" ]
2644783865/Colder.Admin.AntdVue
src/Coldairarrow.Util/DI/IFilter.cs
521
C#
namespace Roslin.Msg.view_controller_msgs { [MsgInfo("view_controller_msgs/CameraPlacement", "38be6efe15caa86e2c835dd05ab88393", @"# The interpolation mode to use during this step uint8 interpolation_mode uint8 LINEAR = 0 # Positions will be linearly interpolated uint8 SPHERICAL = 1 # Position and orientation will be interpolated in a spherical sense. # Sets this as the camera attached (fixed) frame before movement. # An empty string will leave the attached frame unchanged. string target_frame # When should this pose be reached? # A negative value will disable the pose command altogether. duration time_from_start # The frame-relative point for the camera. geometry_msgs/PointStamped eye # The frame-relative point for the focus (or pivot for an Orbit controller). geometry_msgs/PointStamped focus # The frame-relative vector that maps to ""up"" in the view plane. # The zero-vector will default to +Z in the view controller's ""Target Frame"". geometry_msgs/Vector3Stamped up # ------------------------------------------------ # Some paramters for interaction control # ------------------------------------------------ # The interaction style that should be activated when movement is done. uint8 mouse_interaction_mode uint8 NO_CHANGE = 0 # Leaves the control style unchanged uint8 ORBIT = 1 # Activates the Orbit-style controller uint8 FPS = 2 # Activates the FPS-style controller # A flag to enable or disable user interaction # (defaults to false so that interaction is enabled) bool interaction_disabled # A flag indicating if the camera yaw axis is fixed to +Z of the camera attached_frame bool allow_free_yaw_axis ")] public partial class CameraPlacement : RosMsg { public System.Byte LINEAR => 0; public System.Byte SPHERICAL => 1; public System.Byte NO_CHANGE => 0; public System.Byte ORBIT => 1; public System.Byte FPS => 2; public System.Byte interpolation_mode { get; set; } public System.String target_frame { get; set; } public System.TimeSpan time_from_start { get; set; } public geometry_msgs.PointStamped eye { get; set; } public geometry_msgs.PointStamped focus { get; set; } public geometry_msgs.Vector3Stamped up { get; set; } public System.Byte mouse_interaction_mode { get; set; } public System.Boolean interaction_disabled { get; set; } public System.Boolean allow_free_yaw_axis { get; set; } public CameraPlacement(): base() { } public CameraPlacement(System.IO.BinaryReader binaryReader): base(binaryReader) { } public override void Serilize(System.IO.BinaryWriter binaryWriter) { binaryWriter.Write(interpolation_mode); binaryWriter.Write(target_frame.Length); binaryWriter . Write ( System . Text . Encoding . UTF8 . GetBytes ( target_frame ) ) ; binaryWriter.Write(time_from_start); eye.Serilize(binaryWriter); focus.Serilize(binaryWriter); up.Serilize(binaryWriter); binaryWriter.Write(mouse_interaction_mode); binaryWriter.Write(interaction_disabled); binaryWriter.Write(allow_free_yaw_axis); } public override void Deserilize(System.IO.BinaryReader binaryReader) { interpolation_mode = binaryReader.ReadByte(); target_frame = System.Text.Encoding.UTF8.GetString(binaryReader.ReadBytes(binaryReader.ReadInt32())); time_from_start = binaryReader.ReadTimeSpan(); eye = new geometry_msgs.PointStamped(binaryReader); focus = new geometry_msgs.PointStamped(binaryReader); up = new geometry_msgs.Vector3Stamped(binaryReader); mouse_interaction_mode = binaryReader.ReadByte(); interaction_disabled = binaryReader.ReadBoolean(); allow_free_yaw_axis = binaryReader.ReadBoolean(); } } }
31.693431
140
0.630355
[ "MIT" ]
MoeLang/Roslin
Msg/GenMsgs/view_controller_msgs/CameraPlacement.cs
4,342
C#
using System; using System.ComponentModel.DataAnnotations; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Singulink.Enums.Tests { [TestClass] public class EnumParsingTests { [TestMethod] public new void ToString() { var parser = EnumParser<NormalEnum>.Default; Assert.AreEqual("None", parser.ToString(NormalEnum.None)); Assert.AreEqual("B", parser.ToString(NormalEnum.B)); Assert.AreEqual("D", parser.ToString(NormalEnum.D)); } [TestMethod] public void UndefinedValueToString() { var parser = EnumParser<NormalEnum>.Default; Assert.AreEqual("3", parser.ToString((NormalEnum)3)); Assert.AreEqual("12", parser.ToString((NormalEnum)12)); } [TestMethod] public void ToCustomNameString() { var parser = new EnumParser<NormalEnum>(m => m.Field.GetCustomAttribute<DisplayAttribute>()!.GetName()!); Assert.AreEqual("None (Display)", parser.ToString(NormalEnum.None)); Assert.AreEqual("C (Display)", parser.ToString(NormalEnum.C)); } [TestMethod] public void ParseWhitespace() { var parser = EnumParser<NormalEnum>.Default; Assert.ThrowsException<FormatException>(() => parser.Parse(string.Empty)); Assert.ThrowsException<FormatException>(() => parser.Parse(" ")); Assert.ThrowsException<FormatException>(() => parser.Parse(" ")); } [TestMethod] public void Parse() { var parser = EnumParser<NormalEnum>.Default; Assert.AreEqual(NormalEnum.A, parser.Parse("A")); Assert.AreEqual(NormalEnum.C, parser.Parse("C")); } [TestMethod] public void ParseUndefined() { var parser = EnumParser<NormalEnum>.Default; Assert.AreEqual((NormalEnum)32, parser.Parse("32")); Assert.AreEqual((NormalEnum)3, parser.Parse("3")); } [TestMethod] public void ParseMissing() { var parser = EnumParser<NormalEnum>.Default; Assert.ThrowsException<FormatException>(() => parser.Parse("X")); } private enum NormalEnum : byte { [Display(Name = "None (Display)")] None = 0, [Display(Name = "A (Display)")] A = 1, [Display(Name = "B (Display)")] B = 2, [Display(Name = "C (Display)")] C = 4, [Display(Name = "D (Display)")] D = 8, } } }
31.033333
118
0.540279
[ "MIT" ]
Singulink/Singulink.Enums
Source/Singulink.Enums.Tests/EnumParsingTests.cs
2,795
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Knowdes { public class ContentSpecificButton : MonoBehaviour { [SerializeField] private Transform _base; public Transform Base => _base; } }
20.538462
54
0.700375
[ "MIT" ]
BlackLambert/knowdes
Knowdes Project/Assets/Scripts/Entry/ContentSpecificButton.cs
269
C#
using UnityEngine; ///////////////////////////////////////////////////////////////////////////////////////// // // Name: AudioManager // Author: David Floyd // Date: 23-10-2016 // // Brief: Manages Sound effects individually , offers balancing of volume // ///////////////////////////////////////////////////////////////////////////////////////// public class AudioManager : MonoBehaviour { public static AudioManager instance; [Space] // level begin public AudioClip levelIntroSound; [Range(0.0f, 1.0f)] public float levelIntroVol; // level begin public AudioClip levelEndSound; [Range(0.0f, 1.0f)] public float levelEndVol; //player vacuum sound public AudioClip playerVacuumSound; [Range(0.0f, 1.0f)] public float playerVacuumVol; // item hit player public AudioClip itemHitSound; [Range(0.0f, 1.0f)] public float playerAttackVol; //itemPositive public AudioClip itemPositiveSound; [Range(0.0f, 1.0f)] public float itemPositiveVol; //itemNegative public AudioClip itemNegativeSound; [Range(0.0f, 1.0f)] public float itemNegativeVol; // scorePositive public AudioClip scorePositiveSound; [Range(0.0f, 1.0f)] public float scorePositiveVol; //playerCollision public AudioClip playerCollisionSound; [Range(0.0f, 1.0f)] public float playerCollisionVol; // menu select public AudioClip menuSelectSound; [Range(0.0f, 1.0f)] public float menuSelectVol; // menu scroll public AudioClip menuScrollSound; [Range(0.0f, 1.0f)] public float menuScrollVol; // hovering public AudioClip hoveringSound; [Range(0.0f, 1.0f)] public float hoveringVol; void Awake() { if (instance != null) // Check if singelton has already been instantiated { Debug.LogError("More than one AudioManager"); return; } instance = this; } void Update() { } public void playLevelIntroSound() { GetComponent<AudioSource>().PlayOneShot(levelIntroSound, levelIntroVol); } public void playLevelEndSound() { GetComponent<AudioSource>().PlayOneShot(levelEndSound, levelEndVol); } public void playPlayerVacuumSound() { GetComponent<AudioSource>().PlayOneShot(playerVacuumSound, playerVacuumVol); } public void playItemHitSound() { GetComponent<AudioSource>().PlayOneShot(itemHitSound, playerAttackVol); } public void playItemPositiveSound() { GetComponent<AudioSource>().PlayOneShot(itemPositiveSound, itemPositiveVol); } public void playItemNegativeSound() { GetComponent<AudioSource>().PlayOneShot(itemNegativeSound, itemNegativeVol); } public void playScorePositiveSound() { GetComponent<AudioSource>().PlayOneShot(scorePositiveSound, scorePositiveVol); } public void playPlayerCollisionSound() { GetComponent<AudioSource>().PlayOneShot(playerCollisionSound, playerCollisionVol); } public void playMenuSelectSound() { GetComponent<AudioSource>().PlayOneShot(menuSelectSound, menuSelectVol); } public void playMenuScrollSound() { GetComponent<AudioSource>().PlayOneShot(menuScrollSound, menuScrollVol); } public void playHoveringSound() { GetComponent<AudioSource>().PlayOneShot(hoveringSound, hoveringVol); } }
23.581081
90
0.633811
[ "MIT" ]
Darker1300/GameJam_May_2017
src/GameJam/Assets/AudioManager.cs
3,492
C#
using System; using System.Collections.Generic; namespace Sample.CountingBits{ public class countingBits{ public static int naive(int n){ return n; } } }
17.363636
39
0.633508
[ "MIT" ]
zcemycl/algoTest
cs/sample/Sample/CountingBits/CountingBits.cs
191
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Linq; using NUnit.Framework; using QuestPDF.Drawing; using QuestPDF.Examples.Engine; using QuestPDF.Fluent; using QuestPDF.Helpers; using QuestPDF.Infrastructure; using IContainer = QuestPDF.Infrastructure.IContainer; namespace QuestPDF.Examples { public class TableExamples { [Test] public void BasicPlacement() { RenderingTest .Create() .ProduceImages() .PageSize(220, 220) .ShowResults() .Render(container => { container .Padding(10) .MinimalBox() .Border(1) .Table(table => { table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); }); // by using custom 'Element' method, we can reuse visual configuration table.Cell().Row(1).Column(4).Element(Block).Text("A"); table.Cell().Row(2).Column(2).Element(Block).Text("B"); table.Cell().Row(3).Column(3).Element(Block).Text("C"); table.Cell().Row(4).Column(1).Element(Block).Text("D"); }); }); } [Test] public void PagingSupport() { RenderingTest .Create() .ProducePdf() .PageSize(420, 220) .ShowResults() .Render(container => { container .Padding(10) .MinimalBox() .Border(1) .Table(table => { table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); }); // by using custom 'Element' method, we can reuse visual configuration table.Cell().Element(Block).Text(Placeholders.Label()); table.Cell().Element(Block).Text(Placeholders.Label()); table.Cell().Element(Block).Text(Placeholders.Paragraph()); table.Cell().Element(Block).Text(Placeholders.Label()); }); }); } [Test] public void DefaultCellStyle() { RenderingTest .Create() .ProduceImages() .PageSize(220, 120) .ShowResults() .Render(container => { container .Padding(10) .MinimalBox() .Border(1) .DefaultTextStyle(TextStyle.Default.Size(16)) .Table(table => { table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); }); table.Cell().Row(1).Column(1).Element(Block).Text("A"); table.Cell().Row(2).Column(2).Element(Block).Text("B"); table.Cell().Row(1).Column(3).Element(Block).Text("C"); table.Cell().Row(2).Column(4).Element(Block).Text("D"); }); }); } [Test] public void ColumnsDefinition() { RenderingTest .Create() .ProduceImages() .PageSize(320, 80) .ShowResults() .Render(container => { container .Padding(10) .Table(table => { table.ColumnsDefinition(columns => { columns.ConstantColumn(50); columns.ConstantColumn(100); columns.RelativeColumn(2); columns.RelativeColumn(3); }); table.Cell().ColumnSpan(4).LabelCell("Total width: 300px"); table.Cell().ValueCell("50px"); table.Cell().ValueCell("100px"); table.Cell().ValueCell("100px"); table.Cell().ValueCell("150px"); }); }); } [Test] public void PartialAutoPlacement() { RenderingTest .Create() .ProduceImages() .PageSize(220, 220) .ShowResults() .Render(container => { container .Padding(10) .MinimalBox() .Border(1) .Table(table => { table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); }); table.Cell().Element(Block).Text("A"); table.Cell().Row(2).Column(2).Element(Block).Text("B"); table.Cell().Element(Block).Text("C"); table.Cell().Row(3).Column(3).Element(Block).Text("D"); table.Cell().ColumnSpan(2).Element(Block).Text("E"); }); }); } [Test] public void ExtendLastCellsToTableBottom() { RenderingTest .Create() .ProduceImages() .PageSize(220, 170) .ShowResults() .Render(container => { container .Padding(10) .MinimalBox() .Border(1) .Table(table => { table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); }); table.ExtendLastCellsToTableBottom(); table.Cell().Row(1).Column(1).Element(Block).Text("A"); table.Cell().Row(3).Column(1).Element(Block).Text("B"); table.Cell().Row(2).Column(2).Element(Block).Text("C"); table.Cell().Row(3).Column(3).Element(Block).Text("D"); table.Cell().Row(2).RowSpan(2).Column(4).Element(Block).Text("E"); }); }); } [Test] public void Overlapping() { RenderingTest .Create() .ProduceImages() .PageSize(170, 170) .ShowResults() .Render(container => { container .Padding(10) .MinimalBox() .Border(1) .Table(table => { table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); }); table.Cell().Row(1).RowSpan(3).Column(1).ColumnSpan(3).Background(Colors.Grey.Lighten3).MinHeight(150); table.Cell().Row(1).RowSpan(2).Column(1).ColumnSpan(2).Background(Colors.Grey.Lighten1).MinHeight(100); table.Cell().Row(3).Column(3).Background(Colors.Grey.Darken1).MinHeight(50); }); }); } [Test] public void Spans() { RenderingTest .Create() .ProduceImages() .PageSize(220, 170) .ShowResults() .Render(container => { container .Padding(10) .Table(table => { table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); }); table.Cell().RowSpan(2).ColumnSpan(2).Element(Block).Text("1"); table.Cell().ColumnSpan(2).Element(Block).Text("2"); table.Cell().Element(Block).Text("3"); table.Cell().Element(Block).Text("4"); table.Cell().RowSpan(2).Element(Block).Text("5"); table.Cell().ColumnSpan(2).Element(Block).Text("6"); table.Cell().RowSpan(2).Element(Block).Text("7"); table.Cell().Element(Block).Text("8"); table.Cell().Element(Block).Text("9"); }); }); } [Test] public void Stability() { RenderingTest .Create() .ProduceImages() .PageSize(300, 300) .ShowResults() .Render(container => { container .Padding(10) .Table(table => { table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); columns.RelativeColumn(); }); table.Cell().RowSpan(4).Element(Block).Text("1"); table.Cell().RowSpan(2).Element(Block).Text("2"); table.Cell().RowSpan(1).Element(Block).Text("3"); table.Cell().RowSpan(1).Element(Block).Text("4"); table.Cell().RowSpan(2).Element(Block).Text("5"); table.Cell().RowSpan(1).Element(Block).Text("6"); table.Cell().RowSpan(1).Element(Block).Text("7"); }); }); } [Test] public void TableHeader() { RenderingTest .Create() .ProduceImages() .PageSize(500, 200) .ShowResults() .EnableDebugging() .Render(container => { var pageSizes = new List<(string name, double width, double height)>() { ("Letter (ANSI A)", 8.5f, 11), ("Legal", 8.5f, 14), ("Ledger (ANSI B)", 11, 17), ("Tabloid (ANSI B)", 17, 11), ("ANSI C", 22, 17), ("ANSI D", 34, 22), ("ANSI E", 44, 34) }; const int inchesToPoints = 72; container .Padding(10) .MinimalBox() .Border(1) .Table(table => { IContainer DefaultCellStyle(IContainer container, string backgroundColor) { return container .Border(1) .BorderColor(Colors.Grey.Lighten1) .Background(backgroundColor) .PaddingVertical(5) .PaddingHorizontal(10) .AlignCenter() .AlignMiddle(); } table.ColumnsDefinition(columns => { columns.RelativeColumn(); columns.ConstantColumn(75); columns.ConstantColumn(75); columns.ConstantColumn(75); columns.ConstantColumn(75); }); table.Header(header => { header.Cell().RowSpan(2).Element(CellStyle).ExtendHorizontal().AlignLeft().Text("Document type"); header.Cell().ColumnSpan(2).Element(CellStyle).Text("Inches"); header.Cell().ColumnSpan(2).Element(CellStyle).Text("Points"); header.Cell().Element(CellStyle).Text("Width"); header.Cell().Element(CellStyle).Text("Height"); header.Cell().Element(CellStyle).Text("Width"); header.Cell().Element(CellStyle).Text("Height"); // you can extend already existing styles by creating additional methods IContainer CellStyle(IContainer container) => DefaultCellStyle(container, Colors.Grey.Lighten3); }); foreach (var page in pageSizes) { table.Cell().Element(CellStyle).ExtendHorizontal().AlignLeft().Text(page.name); // inches table.Cell().Element(CellStyle).Text(page.width); table.Cell().Element(CellStyle).Text(page.height); // points table.Cell().Element(CellStyle).Text(page.width * inchesToPoints); table.Cell().Element(CellStyle).Text(page.height * inchesToPoints); IContainer CellStyle(IContainer container) => DefaultCellStyle(container, Colors.White); } }); }); } [Test] public void PerformanceText_TemperatureReport() { RenderingTest .Create() .ProducePdf() .PageSize(PageSizes.A4) .MaxPages(10_000) .EnableCaching() .EnableDebugging(false) .ShowResults() .Render(container => GeneratePerformanceStructure(container, 250)); } public static void GeneratePerformanceStructure(IContainer container, int repeats) { container .Padding(25) //.Background(Colors.Blue.Lighten2) .MinimalBox() .Border(1) //.Background(Colors.Red.Lighten2) .Table(table => { table.ColumnsDefinition(columns => { columns.ConstantColumn(100); columns.RelativeColumn(); columns.ConstantColumn(100); columns.RelativeColumn(); }); table.ExtendLastCellsToTableBottom(); foreach (var i in Enumerable.Range(0, repeats)) { table.Cell().RowSpan(3).LabelCell("Project"); table.Cell().RowSpan(3).ShowEntire().ValueCell(Placeholders.Sentence()); table.Cell().LabelCell("Report number"); table.Cell().ValueCell(i.ToString()); table.Cell().LabelCell("Date"); table.Cell().ValueCell(Placeholders.ShortDate()); table.Cell().LabelCell("Inspector"); table.Cell().ValueCell("Marcin Ziąbek"); table.Cell().ColumnSpan(2).LabelCell("Morning weather"); table.Cell().ColumnSpan(2).LabelCell("Evening weather"); table.Cell().ValueCell("Time"); table.Cell().ValueCell("7:13"); table.Cell().ValueCell("Time"); table.Cell().ValueCell("18:25"); table.Cell().ValueCell("Description"); table.Cell().ValueCell("Sunny"); table.Cell().ValueCell("Description"); table.Cell().ValueCell("Windy"); table.Cell().ValueCell("Wind"); table.Cell().ValueCell("Mild"); table.Cell().ValueCell("Wind"); table.Cell().ValueCell("Strong"); table.Cell().ValueCell("Temperature"); table.Cell().ValueCell("17°C"); table.Cell().ValueCell("Temperature"); table.Cell().ValueCell("32°C"); table.Cell().LabelCell("Remarks"); table.Cell().ColumnSpan(3).ValueCell(Placeholders.Paragraph()); } }); } // this method uses a higher order function to define a custom and dynamic style static IContainer Block(IContainer container) { return container .Border(1) .Background(Colors.Grey.Lighten3) .ShowOnce() .MinWidth(50) .MinHeight(50) .Padding(10) .AlignCenter() .AlignMiddle(); } } }
41.062
131
0.368418
[ "MIT" ]
B-wareBS/QuestPDF
QuestPDF.Examples/TableExamples.cs
20,536
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 using Elastic.Xunit.XunitPlumbing; using Nest; using System.ComponentModel; namespace Examples.Search.Suggesters { public class MiscPage : ExampleBase { [U(Skip = "Example not implemented")] [Description("search/suggesters/misc.asciidoc:10")] public void Line10() { // tag::e194e9cbe3eb2305f4f7cdda0cf529bd[] var response0 = new SearchResponse<object>(); // end::e194e9cbe3eb2305f4f7cdda0cf529bd[] response0.MatchesExample(@"POST _search?typed_keys { ""suggest"": { ""text"" : ""some test mssage"", ""my-first-suggester"" : { ""term"" : { ""field"" : ""message"" } }, ""my-second-suggester"" : { ""phrase"" : { ""field"" : ""message"" } } } }"); } } }
25.461538
76
0.6143
[ "Apache-2.0" ]
magaum/elasticsearch-net
tests/Examples/Search/Suggesters/MiscPage.cs
993
C#
using System; using Cli.Exceptions; using Microsoft.Extensions.Logging; using Reservation.Domain.Exceptions; namespace Cli.Applications { public abstract class BaseApplication : IApplication { protected readonly ILogger<IApplication> Logger; protected BaseApplication(ILogger<IApplication> logger) { Logger = logger; } /// <summary> /// エントリポイント /// </summary> public void Run(string[] args) { try { Before(); Main(args); } catch (UI入出力がおかしいぞException e) { Logger.LogError("UIなんかおかしい", e); } catch (ドメインエラーException e) { Logger.LogError("ドメインなんかおかしい", e); } catch (Exception e) { // TODO: システム例外/アプリケーション例外/ドメイン例外をどうする? Logger.LogError("予期せぬエラーです", e); } finally { After(); } } /// <summary> /// 事前処理 /// </summary> protected virtual void Before() { Logger.LogInformation("処理開始"); } /// <summary> /// メイン処理 /// </summary> protected abstract void Main(string[] args); /// <summary> /// 事後処理 /// </summary> protected virtual void After() { Logger.LogInformation("処理完了"); } } }
22.5
63
0.454902
[ "MIT" ]
shibatea/ModelingKai-Reservation
Presentations/Cli/Applications/BaseApplication.cs
1,732
C#
using System.Linq; using Xunit; namespace Kiota.Builder.Tests { public static class AssertExtensions { public static void CurlyBracesAreClosed(string generatedCode) { if(!string.IsNullOrEmpty(generatedCode)) Assert.Equal(generatedCode.Count(x => x == '}'), generatedCode.Count(x => x == '{')); } } }
29.416667
101
0.634561
[ "MIT" ]
PureKrome/kiota
tests/Kiota.Builder.Tests/AssertExtensions.cs
353
C#
using ShellScript.Core.Language.Library; using ShellScript.Core.Language.Library.Core.Math; namespace ShellScript.Unix.Bash.Api.ClassLibrary.Core.Math { public partial class BashMath : ApiMath { public override IApiFunc[] Functions { get; } = { new BashAbs(), //new ShellScriptResourceFunction(ClassAccessName, "Truncate", "ApiMath_Truncate.shellscript", null, // DataTypes.Numeric, false, true, new [] { NumberParameter } //), }; } }
32.625
112
0.637931
[ "MIT" ]
amkherad/ShellScript
ShellScript/Unix/Bash/Api/ClassLibrary/Core/Math/BashMath.cs
522
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Reactive; namespace Octokit.Reactive { public interface IObservableRepositoriesClient { /// <summary> /// Creates a new repository for the current user. /// </summary> /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param> /// <returns>An <see cref="IObservable{Repository}"/> instance for the created repository</returns> IObservable<Repository> Create(NewRepository newRepository); /// <summary> /// Creates a new repository in the specified organization. /// </summary> /// <param name="organizationLogin">The login of the organization in which to create the repostiory</param> /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param> /// <returns>An <see cref="IObservable{Repository}"/> instance for the created repository</returns> IObservable<Repository> Create(string organizationLogin, NewRepository newRepository); /// <summary> /// Deletes a repository for the specified owner and name. /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <remarks>Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required.</remarks> /// <returns>An <see cref="IObservable{Unit}"/> for the operation</returns> IObservable<Unit> Delete(string owner, string name); /// <summary> /// Retrieves the <see cref="Repository"/> for the specified owner and name. /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>A <see cref="Repository"/></returns> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] IObservable<Repository> Get(string owner, string name); /// <summary> /// Retrieves every public <see cref="Repository"/>. /// </summary> /// <remarks> /// The default page size on GitHub.com is 30. /// </remarks> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] IObservable<Repository> GetAllPublic(); /// <summary> /// Retrieves every public <see cref="Repository"/> since the last repository seen. /// </summary> /// <remarks> /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="request">Search parameters of the last repository seen</param> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] IObservable<Repository> GetAllPublic(PublicRepositoryRequest request); /// <summary> /// Retrieves every <see cref="Repository"/> that belongs to the current user. /// </summary> /// <remarks> /// The default page size on GitHub.com is 30. /// </remarks> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] IObservable<Repository> GetAllForCurrent(); /// <summary> /// Retrieves every <see cref="Repository"/> that belongs to the current user. /// </summary> /// <remarks> /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="request">Search parameters to filter results on</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] IObservable<Repository> GetAllForCurrent(RepositoryRequest request); /// <summary> /// Retrieves every <see cref="Repository"/> that belongs to the specified user. /// </summary> /// <remarks> /// The default page size on GitHub.com is 30. /// </remarks> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] IObservable<Repository> GetAllForUser(string login); /// <summary> /// Retrieves every <see cref="Repository"/> that belongs to the specified organization. /// </summary> /// <remarks> /// The default page size on GitHub.com is 30. /// </remarks> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] IObservable<Repository> GetAllForOrg(string organization); /// <summary> /// A client for GitHub's Commit Status API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statuses/">Commit Status API documentation</a> for more /// details. Also check out the <a href="https://github.com/blog/1227-commit-status-api">blog post</a> /// that announced this feature. /// </remarks> [Obsolete("Use Status instead")] IObservableCommitStatusClient CommitStatus { get; } /// <summary> /// A client for GitHub's Commit Status API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statuses/">Commit Status API documentation</a> for more /// details. Also check out the <a href="https://github.com/blog/1227-commit-status-api">blog post</a> /// that announced this feature. /// </remarks> IObservableCommitStatusClient Status { get; } /// <summary> /// Client for GitHub's Repository Deployments API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/deployment/">Collaborators API documentation</a> for more details /// </remarks> IObservableDeploymentsClient Deployment { get; } /// <summary> /// Client for GitHub's Repository Statistics API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statistics/">Statistics API documentation</a> for more details ///</remarks> IObservableStatisticsClient Statistics { get; } /// <summary> /// Client for GitHub's Repository Comments API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/comments/">Repository Comments API documentation</a> for more information. /// </remarks> [Obsolete("Comment information is now available under the Comment property. This will be removed in a future update.")] IObservableRepositoryCommentsClient RepositoryComments { get; } /// <summary> /// Client for GitHub's Repository Comments API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/comments/">Repository Comments API documentation</a> for more information. /// </remarks> IObservableRepositoryCommentsClient Comment { get; } /// <summary> /// A client for GitHub's Repository Hooks API. /// </summary> /// <remarks>See <a href="http://developer.github.com/v3/repos/hooks/">Hooks API documentation</a> for more information.</remarks> IObservableRepositoryHooksClient Hooks { get; } /// <summary> /// A client for GitHub's Repository Forks API. /// </summary> /// <remarks>See <a href="http://developer.github.com/v3/repos/forks/">Forks API documentation</a> for more information.</remarks> IObservableRepositoryForksClient Forks { get; } /// <summary> /// Client for GitHub's Repository Contents API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/contents/">Repository Contents API documentation</a> for more information. /// </remarks> IObservableRepositoryContentsClient Content { get; } /// <summary> /// Client for GitHub's Repository Merging API /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/merging/">Merging API documentation</a> for more details ///</remarks> IObservableMergingClient Merging { get; } /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> IObservable<Branch> GetAllBranches(string owner, string name); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All contributors of the repository.</returns> IObservable<RepositoryContributor> GetAllContributors(string owner, string name); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <returns>All contributors of the repository.</returns> IObservable<RepositoryContributor> GetAllContributors(string owner, string name, bool includeAnonymous); /// <summary> /// Gets all languages for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All languages used in the repository and the number of bytes of each language.</returns> IObservable<RepositoryLanguage> GetAllLanguages(string owner, string name); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> IObservable<Team> GetAllTeams(string owner, string name); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All of the repositorys tags.</returns> IObservable<RepositoryTag> GetAllTags(string owner, string name); /// <summary> /// Gets the specified branch. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get-branch">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="repositoryName">The name of the repository</param> /// <param name="branchName">The name of the branch</param> /// <returns>The specified <see cref="T:Octokit.Branch"/></returns> IObservable<Branch> GetBranch(string owner, string repositoryName, string branchName); /// <summary> /// Updates the specified repository with the values given in <paramref name="update"/> /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="update">New values to update the repository with</param> /// <returns>The updated <see cref="T:Octokit.Repository"/></returns> IObservable<Repository> Edit(string owner, string name, RepositoryUpdate update); /// <summary> /// Edit the specified branch with the values given in <paramref name="update"/> /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="branch">The name of the branch</param> /// <param name="update">New values to update the branch with</param> /// <returns>The updated <see cref="T:Octokit.Branch"/></returns> IObservable<Branch> EditBranch(string owner, string name, string branch, BranchUpdate update); /// <summary> /// A client for GitHub's Repo Collaborators. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details /// </remarks> [Obsolete("Collaborator information is now available under the Collaborator property. This will be removed in a future update.")] IObservableRepoCollaboratorsClient RepoCollaborators { get; } /// <summary> /// A client for GitHub's Repo Collaborators. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details /// </remarks> IObservableRepoCollaboratorsClient Collaborator { get; } /// <summary> /// Client for GitHub's Repository Commits API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/commits/">Commits API documentation</a> for more details ///</remarks> [System.Obsolete("Commit information is now available under the Commit property. This will be removed in a future update.")] IObservableRepositoryCommitsClient Commits { get; } /// <summary> /// Client for GitHub's Repository Commits API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/commits/">Commits API documentation</a> for more details ///</remarks> IObservableRepositoryCommitsClient Commit { get; } /// <summary> /// Access GitHub's Releases API. /// </summary> /// <remarks> /// Refer to the API docmentation for more information: https://developer.github.com/v3/repos/releases/ /// </remarks> IObservableReleasesClient Release { get; } /// <summary> /// Client for managing pull requests. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/pulls/">Pull Requests API documentation</a> for more details /// </remarks> IObservablePullRequestsClient PullRequest { get; } /// <summary> /// Client for managing deploy keys /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/keys/">Repository Deploy Keys API documentation</a> for more information. /// </remarks> IObservableRepositoryDeployKeysClient DeployKeys { get; } /// <summary> /// A client for GitHub's Repository Pages API. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/pages/">Repository Pages API documentation</a> for more information. /// </remarks> IObservableRepositoryPagesClient Page { get; } } }
50.189415
146
0.622489
[ "MIT" ]
hahmed/octokit.net
Octokit.Reactive/Clients/IObservableRepositoriesClient.cs
18,020
C#
using Flamingo.Attributes.Filters.Messages; using Flamingo.Fishes.Advanced.InComingHandlers; using Flamingo.Fishes.Awaitables.FillFormHelper; using Flamingo.Fishes.Awaitables.FillFormHelper.FromDataChecks; using Flamingo.Helpers.Types.Enums; using System; using System.Text.RegularExpressions; using System.Threading.Tasks; using Telegram.Bot.Types; namespace FlamingoProduction.InComings.Messages { public enum Gender { None = 0, Male = 1, Female = 2, } public class UserDataForm { [FlamingoFormProperty] [StringLength(10, FailureMessage = "10 char at most")] [StringRegex(@"^[a-zA-Z]+$", FailureMessage = "only letters")] public string FirstName { get; set; } [FlamingoFormProperty] [StringLength(10)] [StringRegex(@"^[a-zA-Z]+$", FailureMessage = "only letters")] public string LastName { get; set; } [FlamingoFormProperty] public int Code { get; set; } [FlamingoFormProperty(Required = false)] public Gender Gender { get; set; } = Gender.None; public string FullName => $"{FirstName} {LastName} ({Code}) ({Gender})"; } [CommandFilter("form")] [ChatTypeFilter(FlamingoChatType.Private)] public class MyAdvMessageInComing : AdvInComingMessage { protected override async Task GetEatenWrapper(Message inComing) { // Creates a form filler instance for `UserDataForm` class // 'StatusChanged' is a callback function that is called when // status changed in asking process (eg new answer, validation failure, ...) // this functions provides enough information about filler and can cancel // processing there is you suppose to using 'filler.Terminate()' var filler = Flamingo.CreateFormFiller<UserDataForm>(StatusChanged); // Asks user for marked properties of `UserDataForm` // And allows user to fail for 1 time ( Type check failure or value checks ) await filler.Ask( Cdmt.SenderId, triesOnFailure: 1, timeOut: 10, cancellInputPattern: new Regex("^/cancel")); if (filler.Succeeded) // filler.Instance is an instance of `UserDataForm` which is filled! await ReplyText(filler.Instance.FullName); else if (filler.Canceled) await ReplyText("See you."); else if (filler.TimedOut) await ReplyText("Answer faster next time."); else if (filler.Terminated) await ReplyText("Operation terminated."); else await ReplyText("Something wrong try again."); } // if this function returns false then no message will send to user. private bool StatusChanged( FillFormRequest<UserDataForm> form, FlamingoFormStatus status, IFlamingoFormData data) { if (status == FlamingoFormStatus.TimedOut) { // This means: don't send any further message for this question return false; } else if (status == FlamingoFormStatus.RecoverableTimedOut) { form.Flamingo.BotClient.SendTextMessageAsync( form.UserId, $"You missed {data.Name}. but no worries it's optional!"); return false; } else if (status == FlamingoFormStatus.ValidatingFailed) { form.Flamingo.BotClient.SendTextMessageAsync( form.UserId, $"No mistakes allowed!"); form.Terminate(); return false; } return true; } } }
35.425926
91
0.595661
[ "Apache-2.0" ]
immmdreza/FlamingoFramework
FlamingoProduction/InComings/Messages/MyAdvMessageInComing.cs
3,828
C#
using MovingCastles.GameSystems.Spells; using System.Collections.Generic; namespace MovingCastles.Components { public interface ISpellCastingComponent { List<SpellTemplate> Spells { get; } } }
21.4
43
0.742991
[ "MIT" ]
AnotherEpigone/moving-castles
MovingCastles/Components/ISpellCastingComponent.cs
216
C#
using UnityEngine; using System.Collections; public class PreciseTurnOnSpot : MonoBehaviour { protected Animator animator; float targetTurn = 90; bool doTurn = false; Quaternion targetRotation; void Start() { animator = GetComponent<Animator>(); } void OnGUI() { GUILayout.Label("Simple example to get precise turn on spot while keeping animation as intact as possible"); GUILayout.Label("Uses a 'Turn On Spot' BlendTree (in Turn state) in conjunction with Mecanim's MatchTarget call"); GUILayout.Label("Details in PreciseTurnOnSpot.cs"); GUILayout.BeginHorizontal(); targetTurn = GUILayout.HorizontalSlider(targetTurn, -180, 180); GUILayout.Label(targetTurn.ToString()); if(GUILayout.Button("Do Turn")) { doTurn = true; } GUILayout.EndHorizontal(); } void Update() { animator.SetBool("Turn", doTurn); animator.SetFloat("Direction", targetTurn); if (animator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Idle")) { if (doTurn) // just triggered { targetRotation = transform.rotation * Quaternion.AngleAxis(targetTurn, Vector3.up); // Compute target rotation when doTurn is triggered doTurn = false; } } else if (animator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Turn")) { // calls MatchTarget when in Turn state, subsequent calls are ignored until targetTime (0.9f) is reached . animator.MatchTarget(Vector3.one, targetRotation, AvatarTarget.Root, new MatchTargetWeightMask(Vector3.zero, 1), animator.GetCurrentAnimatorStateInfo(0).normalizedTime, 0.9f); } } }
26.416667
181
0.724921
[ "MIT" ]
Altoid76/Unity3DTraining
MacanimSystem/Macanim_Training/Assets/Scripts/PreciseTurnOnSpot.cs
1,585
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace OrderService { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddDapr(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCloudEvents(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapSubscribeHandler(); endpoints.MapControllers(); }); } } }
27.836364
106
0.636185
[ "MIT" ]
PacktPublishing/Software-Architecture-for-Busy-Developers
Chapter07/microservices/OrderService/Startup.cs
1,531
C#
using FastSQL.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FastSQL.Magento2.Integration.Mappers { public class ParentCategoryMapperOptionManager : BaseOptionManager { public override IEnumerable<OptionItem> GetOptionsTemplate() { return new List<OptionItem>(); } } }
23.388889
71
0.688836
[ "MIT" ]
st2forget/fastSQL
src/api/Vendors/Magento2/FastSQL.Magento2.Integration/Mappers/ParentCategoryMapperOptionManager.cs
423
C#
using System.Collections.Generic; using System.Linq; namespace CoPeg { public abstract class Input<T> : IInput<T> { private readonly List<T> elements; public Input(IEnumerable<T> elements) { this.elements = elements.ToList(); } public ISequence<T> First => new Sequencer(this, 0); private class Sequencer : ISequence<T> { private readonly Input<T> input; private readonly int index; public Sequencer(Input<T> input, int index) { this.input = input; this.index = index; } public T Current => this.input.elements[this.index]; public ISequence<T> Next() { return new Sequencer(this.input, this.index+1); } } } }
23.27027
64
0.524971
[ "MIT" ]
knutjelitto/CoTy
CoPeg/Input.cs
863
C#
using Terraria; using Terraria.ID; using Terraria.Localization; using Terraria.ModLoader; namespace MagicStorageExtra.Items { public class UpgradeHallowed : StorageItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Hallowed Storage Upgrade"); DisplayName.AddTranslation(GameCulture.Russian, "Святое Улучшение Ячейки Хранилища"); DisplayName.AddTranslation(GameCulture.Polish, "Ulepszenie jednostki magazynującej (Święcone)"); DisplayName.AddTranslation(GameCulture.French, "Amélioration d'Unité de stockage (Sacré)"); DisplayName.AddTranslation(GameCulture.Spanish, "Actualización de Unidad de Almacenamiento (Sagrado)"); Tooltip.SetDefault("Upgrades Storage Unit to 160 capacity" + "\n<right> a Hellstone Storage Unit to use"); Tooltip.AddTranslation(GameCulture.Russian, "Увеличивает количество слотов в Ячейке Хранилища до 160" + "\n<right> на Адской Ячейке Хранилища для улучшения"); Tooltip.AddTranslation(GameCulture.Polish, "Ulepsza jednostkę magazynującą do 160 miejsc" + "\n<right> na Jednostkę magazynującą (Piekielny kamień), aby użyć"); Tooltip.AddTranslation(GameCulture.French, "améliore la capacité de unité de stockage à 160" + "\n<right> l'unité de stockage (Infernale) pour utiliser"); Tooltip.AddTranslation(GameCulture.Spanish, "Capacidad de unidad de almacenamiento mejorada a 160" + "\n<right> en la unidad de almacenamiento (Piedra Infernal) para utilizar"); Tooltip.AddTranslation(GameCulture.Chinese, "将存储单元升级至160容量" + "\n<right>一个存储单元(神圣)可镶嵌"); } public override void SetDefaults() { item.width = 12; item.height = 12; item.maxStack = 99; item.rare = ItemRarityID.LightRed; item.value = Item.sellPrice(0, 0, 40); } public override void AddRecipe(ModItem result) { var recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.HallowedBar, 10); recipe.AddIngredient(ItemID.SoulofFright); recipe.AddIngredient(ItemID.SoulofMight); recipe.AddIngredient(ItemID.SoulofSight); if (MagicStorageExtra.legendMod is null) recipe.AddIngredient(ItemID.Sapphire); else recipe.AddRecipeGroup("MagicStorageExtra:AnySapphire"); recipe.AddTile(TileID.MythrilAnvil); recipe.SetResult(result); recipe.AddRecipe(); } } }
43.480769
180
0.762052
[ "MIT" ]
ExterminatorX99/MagicStorage
Items/UpgradeHallowed.cs
2,436
C#
// Copyright (c) 2022 AccelByte Inc. All Rights Reserved. // This is licensed software from AccelByte Inc, for limitations // and restrictions contact your company contract manager. // This code is generated by tool. DO NOT EDIT. using AccelByte.Sdk.Api.Legal.Model; using AccelByte.Sdk.Api.Legal.Operation; using AccelByte.Sdk.Api.Legal.Wrapper; using AccelByte.Sdk.Core; namespace AccelByte.Sdk.Api { public static class LegalAnonymization_OpExts { public static void Execute( this AnonymizeUserAgreement.AnonymizeUserAgreementBuilder builder, string userId ) { AnonymizeUserAgreement op = builder.Build( userId ); ((Legal.Wrapper.Anonymization)builder.WrapperObject!).AnonymizeUserAgreement(op); } } }
29.571429
93
0.68599
[ "MIT" ]
AccelByte/accelbyte-csharp-sdk
AccelByte.Sdk/Api/Legal/Wrapper/Anonymization_OpExts.cs
828
C#
using DinoCat; using DinoCat.Elements; using DinoCat.Wpf; using System; using static DinoCat.Elements.Factories; using static DinoCat.Wpf.System.Windows.Controls.Factories; using static Interop.Wpf.Factories; namespace Interop.Wpf { [ToWpfType("Interop.Wpf.DinoControlWrapper")] class DinoControl : DinoCat.Elements.Control<int> { public DinoControl(string incomming) => Incomming = incomming; public string Incomming { get; } public override Element Build(Context context, int state, Action<int> setState) => Column( TextBlock().Text(Incomming), MyUserControlWrapper().MyValue(state), Button() .Content("Increment 🐱‍🐉") .OnClick(args => setState(state + 1)) .Margin(2) .Center(), Row(VerticalAlignment.Baseline, Text("HELLO", fontSize: 32), Button("world", () => { }), Text(" trailing text")), MyUserControlWrapper().MyValue(-state)); } }
32.823529
90
0.569892
[ "MIT" ]
maxbrister/DinoCat
examples/Interop.Wpf/DinoControl.cs
1,126
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.Dingtalkservice_group_1_0.Models { public class TransferTicketResponse : TeaModel { [NameInMap("headers")] [Validation(Required=true)] public Dictionary<string, string> Headers { get; set; } } }
20.526316
63
0.705128
[ "Apache-2.0" ]
aliyun/dingtalk-sdk
dingtalk/csharp/core/service_group_1_0/Models/TransferTicketResponse.cs
390
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using WebApi.Data; namespace WebApi.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20200731162537_AddTableArticles")] partial class AddTableArticles { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.4-rtm-31024") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("WebApi.Data.Models.ApplicationRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<DateTime>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("ModifiedOn"); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("WebApi.Data.Models.ApplicationUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<DateTime>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("IsDeleted"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<DateTime?>("ModifiedOn"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("WebApi.Data.Models.Article", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AuthorId"); b.Property<DateTime>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("ModifiedOn"); b.Property<string>("Title"); b.HasKey("Id"); b.HasIndex("AuthorId"); b.HasIndex("IsDeleted"); b.ToTable("Articles"); }); modelBuilder.Entity("WebApi.Data.Models.TodoItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AuthorId") .IsRequired(); b.Property<DateTime>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsDone"); b.Property<DateTime?>("ModifiedOn"); b.Property<string>("Title") .IsRequired(); b.HasKey("Id"); b.HasIndex("AuthorId"); b.HasIndex("IsDeleted"); b.ToTable("TodoItems"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("WebApi.Data.Models.ApplicationRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("WebApi.Data.Models.ApplicationUser") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("WebApi.Data.Models.ApplicationUser") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("WebApi.Data.Models.ApplicationRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("WebApi.Data.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("WebApi.Data.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("WebApi.Data.Models.Article", b => { b.HasOne("WebApi.Data.Models.ApplicationUser", "Author") .WithMany("Articles") .HasForeignKey("AuthorId"); }); modelBuilder.Entity("WebApi.Data.Models.TodoItem", b => { b.HasOne("WebApi.Data.Models.ApplicationUser", "Author") .WithMany() .HasForeignKey("AuthorId") .OnDelete(DeleteBehavior.Restrict); }); #pragma warning restore 612, 618 } } }
33.748466
125
0.475368
[ "MIT" ]
pirocorp/ASP.NET-Core
Workshops/WebApi/Data/WebApi.Data/Migrations/20200731162537_AddTableArticles.Designer.cs
11,004
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Linq; namespace Azure.Analytics.Synapse.Artifacts.Models { /// <summary> This activity is used for iterating over a collection and execute given activities. </summary> public partial class ForEachActivity : Activity { /// <summary> Initializes a new instance of ForEachActivity. </summary> /// <param name="name"> Activity name. </param> /// <param name="items"> Collection to iterate. </param> /// <param name="activities"> List of activities to execute . </param> public ForEachActivity(string name, Expression items, IEnumerable<Activity> activities) : base(name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (items == null) { throw new ArgumentNullException(nameof(items)); } if (activities == null) { throw new ArgumentNullException(nameof(activities)); } Items = items; Activities = activities.ToArray(); Type = "ForEach"; } /// <summary> Initializes a new instance of ForEachActivity. </summary> /// <param name="name"> Activity name. </param> /// <param name="type"> Type of activity. </param> /// <param name="description"> Activity description. </param> /// <param name="dependsOn"> Activity depends on condition. </param> /// <param name="userProperties"> Activity user properties. </param> /// <param name="additionalProperties"> . </param> /// <param name="isSequential"> Should the loop be executed in sequence or in parallel (max 50). </param> /// <param name="batchCount"> Batch count to be used for controlling the number of parallel execution (when isSequential is set to false). </param> /// <param name="items"> Collection to iterate. </param> /// <param name="activities"> List of activities to execute . </param> internal ForEachActivity(string name, string type, string description, IList<ActivityDependency> dependsOn, IList<UserProperty> userProperties, IDictionary<string, object> additionalProperties, bool? isSequential, int? batchCount, Expression items, IList<Activity> activities) : base(name, type, description, dependsOn, userProperties, additionalProperties) { IsSequential = isSequential; BatchCount = batchCount; Items = items; Activities = activities ?? new List<Activity>(); Type = type ?? "ForEach"; } /// <summary> Should the loop be executed in sequence or in parallel (max 50). </summary> public bool? IsSequential { get; set; } /// <summary> Batch count to be used for controlling the number of parallel execution (when isSequential is set to false). </summary> public int? BatchCount { get; set; } /// <summary> Collection to iterate. </summary> public Expression Items { get; set; } /// <summary> List of activities to execute . </summary> public IList<Activity> Activities { get; } } }
47.380282
365
0.627229
[ "MIT" ]
AzureDataBox/azure-sdk-for-net
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/ForEachActivity.cs
3,364
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20190701.Inputs { /// <summary> /// VPN client root certificate of P2SVpnServerConfiguration. /// </summary> public sealed class P2SVpnServerConfigVpnClientRootCertificateArgs : Pulumi.ResourceArgs { /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Input("etag")] public Input<string>? Etag { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// The name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The certificate public data. /// </summary> [Input("publicCertData", required: true)] public Input<string> PublicCertData { get; set; } = null!; public P2SVpnServerConfigVpnClientRootCertificateArgs() { } } }
30.638298
122
0.614583
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20190701/Inputs/P2SVpnServerConfigVpnClientRootCertificateArgs.cs
1,440
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace AppMvc.Net.Migrations { public partial class AddProduct : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Product", columns: table => new { ProductId = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), ProductName = table.Column<string>(type: "nvarchar(160)", maxLength: 160, nullable: false), SupplierId = table.Column<int>(type: "int", nullable: false), ProductTypeId = table.Column<int>(type: "int", nullable: false), Unit = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Product", x => x.ProductId); table.ForeignKey( name: "FK_Product_ProductType_ProductTypeId", column: x => x.ProductTypeId, principalTable: "ProductType", principalColumn: "ProductTypeId", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Product_Supplier_SupplierId", column: x => x.SupplierId, principalTable: "Supplier", principalColumn: "SupplierId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Product_ProductTypeId", table: "Product", column: "ProductTypeId"); migrationBuilder.CreateIndex( name: "IX_Product_SupplierId", table: "Product", column: "SupplierId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Product"); } } }
40.327273
111
0.506763
[ "MIT" ]
LucasTran-tq/Business-Management-AspNet
Migrations/20211203100732_AddProduct.cs
2,220
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; using Top.Api; namespace DingTalk.Api.Response { /// <summary> /// OapiSnsVerifyMobileResponse. /// </summary> public class OapiSnsVerifyMobileResponse : DingTalkResponse { /// <summary> /// errcode /// </summary> [XmlElement("errcode")] public long Errcode { get; set; } /// <summary> /// errmsg /// </summary> [XmlElement("errmsg")] public string Errmsg { get; set; } /// <summary> /// 1 /// </summary> [XmlElement("result")] public bool Result { get; set; } } }
21
63
0.541126
[ "MIT" ]
lee890720/YiShaAdmin
YiSha.Util/YsSha.Dingtalk/DingTalk/Response/OapiSnsVerifyMobileResponse.cs
693
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GeneratorScript : MonoBehaviour { public GameObject[] salas; public List<GameObject> salasAtuais; private float screenWidthInPoints; public GameObject[] availableObjects; public List<GameObject> objects; public float objectsMinDistance = 5.0f; public float objectsMaxDistance = 10.0f; public float objectsMinY = -1.4f; public float objectsMaxY = 1.4f; public float objectsMinRotation = -45.0f; public float objectsMaxRotation = 45.0f; // Use this for initialization void Start () { float height = 2.0f * Camera.main.orthographicSize; screenWidthInPoints = height * Camera.main.aspect; } // Update is called once per frame void Update () { } void FixedUpdate () { GenerateRoomIfRequired (); GenerateObjectsIfRequired (); } void AddSala (float farhtestRoomEndX) { int randomRoomIndex = Random.Range(0, salas.Length); GameObject room = (GameObject)Instantiate(salas[randomRoomIndex]); float roomWidth = room.transform.Find("PISO").localScale.x; float roomCenter = farhtestRoomEndX + roomWidth * 0.5f; room.transform.position = new Vector3(roomCenter, 0, 0); salasAtuais.Add(room); } void GenerateRoomIfRequired () { List<GameObject> salasRemover = new List<GameObject>(); bool addSalas = true; float playerX = transform.position.x; float removeSalaX = playerX - screenWidthInPoints; float addSalaX = playerX + screenWidthInPoints; float farthestRoomEndX = 0; foreach(var sala in salasAtuais){ float salaWidth = sala.transform.Find("PISO").localScale.x; float salaStartX = sala.transform.position.x - (salaWidth * 0.5f); float salaEndX = salaStartX + salaWidth; if (salaStartX > addSalaX) { addSalas = false; } if (salaEndX < removeSalaX) { salasRemover.Add (sala); } farthestRoomEndX = Mathf.Max(farthestRoomEndX, salaEndX); } foreach(var sala in salasRemover){ salasAtuais.Remove(sala); Destroy(sala); } if (addSalas) { AddSala (farthestRoomEndX); } } void AddObject(float lastObjectX){ int randomIndex = Random.Range(0, availableObjects.Length); GameObject obj = (GameObject)Instantiate(availableObjects[randomIndex]); float objectPositionX = lastObjectX + Random.Range(objectsMinDistance, objectsMaxDistance); float randomY = Random.Range(objectsMinY, objectsMaxY); obj.transform.position = new Vector3(objectPositionX,randomY,0); float rotation = Random.Range(objectsMinRotation, objectsMaxRotation); obj.transform.rotation = Quaternion.Euler(Vector3.forward * rotation); objects.Add(obj); } void GenerateObjectsIfRequired(){ float playerX = transform.position.x; float removeObjectsX = playerX - screenWidthInPoints; float addObjectX = playerX + screenWidthInPoints; float farthestObjectX = 0; List<GameObject> objectsToRemove = new List<GameObject>(); foreach (var obj in objects){ float objX = obj.transform.position.x; farthestObjectX = Mathf.Max(farthestObjectX, objX); if (objX < removeObjectsX) objectsToRemove.Add(obj); } foreach (var obj in objectsToRemove) { objects.Remove(obj); Destroy(obj); } if (farthestObjectX < addObjectX) AddObject(farthestObjectX); } }
28.378151
93
0.711578
[ "MIT" ]
rlMaica/santa-jetpack
Assets/Scripts/GeneratorScript.cs
3,379
C#
using ServiceStack.Common.Net30; using ServiceStack.Redis; using Snake.Core.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Snake.Core.Redis { public class CacheFactory { //private const int REDIS_DB1 = 1; private static CacheFactory _cacheFactory; private static System.Collections.Concurrent.ConcurrentDictionary<string, PooledRedisClientManager > _pcms = new System.Collections.Concurrent.ConcurrentDictionary<string, PooledRedisClientManager>(); private static ConcurrentQueue<RedisProvider> RedisList = new ConcurrentQueue<RedisProvider>(); private static object _lock = new object(); public static CacheFactory Instance { get { if (_cacheFactory == null) { lock (_lock) { if (_cacheFactory == null) { _cacheFactory = new CacheFactory(); } } } return _cacheFactory; } } private static string[] SplitString(string strSource, string split) { return strSource.Split(split.ToArray()); } private IRedisClient GetRedisClient(string sectionName = "RedisConfig") { PooledRedisClientManager pcm; if (!_pcms.TryGetValue(sectionName, out pcm)) { var redisConfigInfo = RedisConfigInfo.GetConfig(sectionName); string[] writeServerList = SplitString(redisConfigInfo.WriteServerList, ","); string[] readServerList = SplitString(redisConfigInfo.ReadServerList, ","); pcm = new PooledRedisClientManager(readServerList, writeServerList, new RedisClientManagerConfig { MaxWritePoolSize = redisConfigInfo.MaxWritePoolSize, MaxReadPoolSize = redisConfigInfo.MaxReadPoolSize, AutoStart = redisConfigInfo.AutoStart, DefaultDb = redisConfigInfo.DefaultDb, }); pcm.ConnectTimeout = 2 * 60 * 1000; _pcms[sectionName] = pcm; } if (pcm == null) { throw new InvalidOperationException("Redis尚未初始化或失败,无法打开客户端!"); } IRedisClient client = null; try { client = pcm.GetClient();//获取连接; } catch (TimeoutException) { client = pcm.GetClient(); } catch (Exception ex) { return null; } return client;//获取连接; } public ICacheProvider GetClient(CacheTargetType cacheTargetType = CacheTargetType.Redis, string sectionName = "RedisConfig") { switch (cacheTargetType) { case CacheTargetType.Redis: { var redisClient = GetRedisClient(sectionName); if (redisClient == null) return null; return new RedisProvider(redisClient); } default: { var redisClient = GetRedisClient(sectionName); if (redisClient == null) return null; return new RedisProvider(redisClient); } } } } }
35.37963
208
0.500131
[ "Apache-2.0" ]
yepeng2002/Snake
src/Snake.Core/Redis/CacheFactory.cs
3,873
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Eqstra.BusinessLogic.Enums { public enum VehicleTypeEnum { Commercial, Passenger, Trailer } }
16.125
36
0.693798
[ "MIT" ]
pithline/FMS
Pithline.FMS.BusinessLogic/Enums/VehicleTypeEnum.cs
260
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("04.FixEmails")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("04.FixEmails")] [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("f18b82fb-79b8-4ebe-a740-77bc1c8196d5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.621622
84
0.746408
[ "MIT" ]
rdineva/Programming-Fundamentals
DictionariesLambdaAndLINQ-Exercises/04.FixEmails/Properties/AssemblyInfo.cs
1,395
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Nucleus.Gaming.Interop { public class Win32API { [DllImport("ntdll.dll")] public static extern int NtQueryObject(IntPtr ObjectHandle, int ObjectInformationClass, IntPtr ObjectInformation, int ObjectInformationLength, ref int returnLength); [DllImport("kernel32.dll", SetLastError = true)] public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax); [DllImport("ntdll.dll")] public static extern uint NtQuerySystemInformation(int SystemInformationClass, IntPtr SystemInformation, int SystemInformationLength, ref int returnLength); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr OpenMutex(UInt32 desiredAccess, bool inheritHandle, string name); [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll")] public static extern int CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, IntPtr hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions); //public static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, // ushort hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle, // uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions); [DllImport("kernel32.dll")] public static extern IntPtr GetCurrentProcess(); public enum ObjectInformationClass : int { ObjectBasicInformation = 0, ObjectNameInformation = 1, ObjectTypeInformation = 2, ObjectAllTypesInformation = 3, ObjectHandleInformation = 4 } [Flags] public enum ProcessAccessFlags : uint { All = 0x001F0FFF, Terminate = 0x00000001, CreateThread = 0x00000002, VMOperation = 0x00000008, VMRead = 0x00000010, VMWrite = 0x00000020, DupHandle = 0x00000040, SetInformation = 0x00000200, QueryInformation = 0x00000400, Synchronize = 0x00100000 } [StructLayout(LayoutKind.Sequential)] public struct OBJECT_BASIC_INFORMATION { // Information Class 0 public int Attributes; public int GrantedAccess; public int HandleCount; public int PointerCount; public int PagedPoolUsage; public int NonPagedPoolUsage; public int Reserved1; public int Reserved2; public int Reserved3; public int NameInformationLength; public int TypeInformationLength; public int SecurityDescriptorLength; public System.Runtime.InteropServices.ComTypes.FILETIME CreateTime; } [StructLayout(LayoutKind.Sequential)] public struct OBJECT_TYPE_INFORMATION { // Information Class 2 public UNICODE_STRING Name; public int ObjectCount; public int HandleCount; public int Reserved1; public int Reserved2; public int Reserved3; public int Reserved4; public int PeakObjectCount; public int PeakHandleCount; public int Reserved5; public int Reserved6; public int Reserved7; public int Reserved8; public int InvalidAttributes; public GENERIC_MAPPING GenericMapping; public int ValidAccess; public byte Unknown; public byte MaintainHandleDatabase; public int PoolType; public int PagedPoolUsage; public int NonPagedPoolUsage; } [StructLayout(LayoutKind.Sequential)] public struct OBJECT_NAME_INFORMATION { // Information Class 1 public UNICODE_STRING Name; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct UNICODE_STRING { public ushort Length; public ushort MaximumLength; public IntPtr Buffer; } [StructLayout(LayoutKind.Sequential)] public struct GENERIC_MAPPING { public int GenericRead; public int GenericWrite; public int GenericExecute; public int GenericAll; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct SYSTEM_HANDLE_INFORMATION { // Information Class 16 public int ProcessID; public byte ObjectTypeNumber; public byte Flags; // 0x01 = PROTECT_FROM_CLOSE, 0x02 = INHERIT public ushort Handle; public int Object_Pointer; public UInt32 GrantedAccess; } public const int MAX_PATH = 260; public const uint STATUS_INFO_LENGTH_MISMATCH = 0xC0000004; public const int DUPLICATE_SAME_ACCESS = 0x2; public const int DUPLICATE_CLOSE_SOURCE = 0x1; } public class Win32Processes { const int CNST_SYSTEM_HANDLE_INFORMATION = 16; const uint STATUS_INFO_LENGTH_MISMATCH = 0xc0000004; public static string getObjectTypeName(Win32API.SYSTEM_HANDLE_INFORMATION shHandle, Process process) { IntPtr m_ipProcessHwnd = Win32API.OpenProcess(Win32API.ProcessAccessFlags.All, false, process.Id); IntPtr ipHandle = IntPtr.Zero; var objBasic = new Win32API.OBJECT_BASIC_INFORMATION(); IntPtr ipBasic = IntPtr.Zero; var objObjectType = new Win32API.OBJECT_TYPE_INFORMATION(); IntPtr ipObjectType = IntPtr.Zero; IntPtr ipObjectName = IntPtr.Zero; string strObjectTypeName = ""; int nLength = 0; int nReturn = 0; IntPtr ipTemp = IntPtr.Zero; if (!Win32API.DuplicateHandle(m_ipProcessHwnd, (IntPtr)shHandle.Handle, Win32API.GetCurrentProcess(), out ipHandle, 0, false, Win32API.DUPLICATE_SAME_ACCESS)) return null; ipBasic = Marshal.AllocHGlobal(Marshal.SizeOf(objBasic)); Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectBasicInformation, ipBasic, Marshal.SizeOf(objBasic), ref nLength); objBasic = (Win32API.OBJECT_BASIC_INFORMATION)Marshal.PtrToStructure(ipBasic, objBasic.GetType()); Marshal.FreeHGlobal(ipBasic); ipObjectType = Marshal.AllocHGlobal(objBasic.TypeInformationLength); nLength = objBasic.TypeInformationLength; while ((uint)(nReturn = Win32API.NtQueryObject( ipHandle, (int)Win32API.ObjectInformationClass.ObjectTypeInformation, ipObjectType, nLength, ref nLength)) == Win32API.STATUS_INFO_LENGTH_MISMATCH) { Marshal.FreeHGlobal(ipObjectType); ipObjectType = Marshal.AllocHGlobal(nLength); } objObjectType = (Win32API.OBJECT_TYPE_INFORMATION)Marshal.PtrToStructure(ipObjectType, objObjectType.GetType()); if (Is64Bits()) { ipTemp = new IntPtr(Convert.ToInt64(objObjectType.Name.Buffer.ToString(), 10) >> 32); } else { ipTemp = objObjectType.Name.Buffer; } strObjectTypeName = Marshal.PtrToStringUni(ipTemp, objObjectType.Name.Length >> 1); Marshal.FreeHGlobal(ipObjectType); return strObjectTypeName; } public static string getObjectName(Win32API.SYSTEM_HANDLE_INFORMATION shHandle, Process process) { IntPtr m_ipProcessHwnd = Win32API.OpenProcess(Win32API.ProcessAccessFlags.All, false, process.Id); IntPtr ipHandle = IntPtr.Zero; var objBasic = new Win32API.OBJECT_BASIC_INFORMATION(); IntPtr ipBasic = IntPtr.Zero; IntPtr ipObjectType = IntPtr.Zero; var objObjectName = new Win32API.OBJECT_NAME_INFORMATION(); IntPtr ipObjectName = IntPtr.Zero; string strObjectName = ""; int nLength = 0; int nReturn = 0; IntPtr ipTemp = IntPtr.Zero; if (!Win32API.DuplicateHandle(m_ipProcessHwnd, (IntPtr)shHandle.Handle, Win32API.GetCurrentProcess(), out ipHandle, 0, false, Win32API.DUPLICATE_SAME_ACCESS)) return null; ipBasic = Marshal.AllocHGlobal(Marshal.SizeOf(objBasic)); Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectBasicInformation, ipBasic, Marshal.SizeOf(objBasic), ref nLength); objBasic = (Win32API.OBJECT_BASIC_INFORMATION)Marshal.PtrToStructure(ipBasic, objBasic.GetType()); Marshal.FreeHGlobal(ipBasic); nLength = objBasic.NameInformationLength; ipObjectName = Marshal.AllocHGlobal(nLength); while ((uint)(nReturn = Win32API.NtQueryObject( ipHandle, (int)Win32API.ObjectInformationClass.ObjectNameInformation, ipObjectName, nLength, ref nLength)) == Win32API.STATUS_INFO_LENGTH_MISMATCH) { Marshal.FreeHGlobal(ipObjectName); ipObjectName = Marshal.AllocHGlobal(nLength); } objObjectName = (Win32API.OBJECT_NAME_INFORMATION)Marshal.PtrToStructure(ipObjectName, objObjectName.GetType()); if (Is64Bits()) { ipTemp = new IntPtr(Convert.ToInt64(objObjectName.Name.Buffer.ToString(), 10) >> 32); } else { ipTemp = objObjectName.Name.Buffer; } if (ipTemp != IntPtr.Zero) { byte[] baTemp2 = new byte[nLength]; try { Marshal.Copy(ipTemp, baTemp2, 0, nLength); strObjectName = Marshal.PtrToStringUni(Is64Bits() ? new IntPtr(ipTemp.ToInt64()) : new IntPtr(ipTemp.ToInt32())); return strObjectName; } catch (AccessViolationException) { return null; } finally { Marshal.FreeHGlobal(ipObjectName); Win32API.CloseHandle(ipHandle); } } return null; } public static List<Win32API.SYSTEM_HANDLE_INFORMATION> GetHandles(Process process, string IN_strObjectTypeName, string IN_strObjectName, string inclusiveName) { uint nStatus; int nHandleInfoSize = 0x10000; IntPtr ipHandlePointer = Marshal.AllocHGlobal(nHandleInfoSize); int nLength = 0; IntPtr ipHandle = IntPtr.Zero; while ((nStatus = Win32API.NtQuerySystemInformation(CNST_SYSTEM_HANDLE_INFORMATION, ipHandlePointer, nHandleInfoSize, ref nLength)) == STATUS_INFO_LENGTH_MISMATCH) { nHandleInfoSize = nLength; Marshal.FreeHGlobal(ipHandlePointer); ipHandlePointer = Marshal.AllocHGlobal(nLength); } byte[] baTemp = new byte[nLength]; Marshal.Copy(ipHandlePointer, baTemp, 0, nLength); long lHandleCount = 0; if (Is64Bits()) { lHandleCount = Marshal.ReadInt64(ipHandlePointer); ipHandle = new IntPtr(ipHandlePointer.ToInt64() + 8); } else { lHandleCount = Marshal.ReadInt32(ipHandlePointer); ipHandle = new IntPtr(ipHandlePointer.ToInt32() + 4); } Win32API.SYSTEM_HANDLE_INFORMATION shHandle; List<Win32API.SYSTEM_HANDLE_INFORMATION> lstHandles = new List<Win32API.SYSTEM_HANDLE_INFORMATION>(); for (long lIndex = 0; lIndex < lHandleCount; lIndex++) { shHandle = new Win32API.SYSTEM_HANDLE_INFORMATION(); if (Is64Bits()) { shHandle = (Win32API.SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(ipHandle, shHandle.GetType()); ipHandle = new IntPtr(ipHandle.ToInt64() + Marshal.SizeOf(shHandle) + 8); } else { ipHandle = new IntPtr(ipHandle.ToInt64() + Marshal.SizeOf(shHandle)); shHandle = (Win32API.SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(ipHandle, shHandle.GetType()); } if (process != null) { if (shHandle.ProcessID != process.Id) { continue; } } string strObjectTypeName = ""; if (IN_strObjectTypeName != null) { strObjectTypeName = getObjectTypeName(shHandle, Process.GetProcessById(shHandle.ProcessID)); if (strObjectTypeName != IN_strObjectTypeName) continue; } string strObjectName = ""; if (IN_strObjectName != null) { strObjectName = getObjectName(shHandle, Process.GetProcessById(shHandle.ProcessID)); //if (strObjectName != IN_strObjectName) continue; if (strObjectName != null && strObjectName.Contains(IN_strObjectName)) { } else { continue; } } Process proc = Process.GetProcessById(shHandle.ProcessID); string strObjectTypeName2 = getObjectTypeName(shHandle, proc); string strObjectName2 = getObjectName(shHandle, proc); //Console.WriteLine("Win32Api: {0} {1} {2}", shHandle.ProcessID, strObjectTypeName2, strObjectName2); if (strObjectName2.Contains(inclusiveName)) { lstHandles.Add(shHandle); } } return lstHandles; } public static bool Is64Bits() { return Environment.Is64BitProcess; int size = Marshal.SizeOf(typeof(IntPtr)); return size == 8 ? true : false; } } class Program { static void Main(string[] args) { } } }
43.298851
154
0.600544
[ "MIT" ]
jackxriot/nucleuscoop
Master/Nucleus.Gaming/Platform/Windows/Interop/Win32Api.cs
15,070
C#
namespace Binance.Spot.SubAccountExamples { using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Binance.Common; using Binance.Spot; using Binance.Spot.Models; using Microsoft.Extensions.Logging; public class QuerySubaccountSpotAssetsSummary_Example { public static async Task Main(string[] args) { using var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); }); ILogger logger = loggerFactory.CreateLogger<QuerySubaccountSpotAssetsSummary_Example>(); HttpMessageHandler loggingHandler = new BinanceLoggingHandler(logger: logger); HttpClient httpClient = new HttpClient(handler: loggingHandler); string apiKey = "api-key"; string apiSecret = "api-secret"; var subAccount = new SubAccount(httpClient, apiKey, apiSecret); var result = await subAccount.QuerySubaccountSpotAssetsSummary(); } } }
32.121212
100
0.65283
[ "MIT" ]
binance/binance-connector-dotnet
Examples/CSharp/SubAccount/QuerySubaccountSpotAssetsSummary_Example.cs
1,060
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.ParseURL")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("12.ParseURL")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e7c3dfb2-5f77-4e47-809e-54c42c09ce59")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.702703
84
0.743369
[ "MIT" ]
ztodorova/Telerik-Academy
C#-part2/StringsAndTextProcessing/12.ParseURL/Properties/AssemblyInfo.cs
1,398
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using MLIDS.lib.DAL; using System; using System.IO; using System.Threading.Tasks; namespace MLIDS.UnitTests.lib.ML { [TestClass] public class Trainer { [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task Trainer_NullTest() { await new MLIDS.lib.ML.Trainer().GenerateModel(null, null); } [TestMethod] [ExpectedException(typeof(FileNotFoundException))] public async Task Trainer_ModelNotFoundTest() { await new MLIDS.lib.ML.Trainer().GenerateModel(new MongoDAL(new MLIDS.lib.Containers.SettingsItem()), "test"); } } }
25.785714
122
0.660665
[ "MIT" ]
jcapellman/jcIDS
src/MLIDS.UnitTests/lib/ML/Trainer.cs
724
C#
#region BSD License /* * * Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) * © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved. * * New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE) * Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2022. All rights reserved. * */ #endregion namespace Krypton.Ribbon { /// <summary> /// Draws a ribbon group cluster button. /// </summary> internal class ViewDrawRibbonGroupClusterButton : ViewComposite, IRibbonViewGroupItemView { #region Instance Fields private readonly Padding _smallImagePadding; // = new(3); private readonly KryptonRibbon _ribbon; private readonly NeedPaintHandler _needPaint; private PaletteBackInheritForced _backForced; private PaletteBorderInheritForced _borderForced; private ViewDrawRibbonGroupButtonBackBorder _viewMediumSmall; private ViewLayoutRibbonRowCenter _viewMediumSmallCenter; private ViewDrawRibbonGroupClusterButtonImage _viewMediumSmallImage; private ViewDrawRibbonGroupClusterButtonText _viewMediumSmallText1; private ViewDrawRibbonDropArrow _viewMediumSmallDropArrow; private ViewLayoutRibbonSeparator _viewMediumSmallText2Sep1; private ViewLayoutRibbonSeparator _viewMediumSmallText2Sep2; private GroupItemSize _currentSize; #endregion #region Identity /// <summary> /// Initialize a new instance of the ViewDrawRibbonGroupClusterButton class. /// </summary> /// <param name="ribbon">Reference to owning ribbon control.</param> /// <param name="ribbonButton">Reference to source button definition.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public ViewDrawRibbonGroupClusterButton(KryptonRibbon ribbon, KryptonRibbonGroupClusterButton ribbonButton, NeedPaintHandler needPaint) { Debug.Assert(ribbon != null); Debug.Assert(ribbonButton != null); Debug.Assert(needPaint != null); // Remember incoming references _ribbon = ribbon; GroupClusterButton = ribbonButton; _needPaint = needPaint; _currentSize = GroupClusterButton.ItemSizeCurrent; // Associate this view with the source component (required for design time selection) Component = GroupClusterButton; // Create the small button view CreateView(); // Update view reflect current button state UpdateEnabledState(); UpdateCheckedState(); UpdateDropDownState(); UpdateItemSizeState(); // Hook into changes in the ribbon button definition GroupClusterButton.PropertyChanged += OnButtonPropertyChanged; _smallImagePadding = new Padding((int)(3 * FactorDpiX), (int)(3 * FactorDpiY), (int)(3 * FactorDpiX), (int)(3 * FactorDpiY)); } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>User readable name of the instance.</returns> public override string ToString() => // Return the class name and instance identifier @"ViewDrawRibbonGroupClusterButton:" + Id; /// <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) { if (GroupClusterButton != null) { // Must unhook to prevent memory leaks GroupClusterButton.PropertyChanged -= OnButtonPropertyChanged; // Remove association with definition GroupClusterButton.ClusterButtonView = null; GroupClusterButton = null; } } base.Dispose(disposing); } #endregion #region GroupClusterButton /// <summary> /// Gets access to the connected button definition. /// </summary> public KryptonRibbonGroupClusterButton GroupClusterButton { get; private set; } #endregion #region MaxBorderEdges /// <summary> /// Gets and sets the maximum edges allowed. /// </summary> public PaletteDrawBorders MaxBorderEdges { get => _borderForced.MaxBorderEdges; set => _borderForced.MaxBorderEdges = value; } #endregion #region BorderIgnoreNormal /// <summary> /// ets and sets the ignoring of normal borders. /// </summary> public bool BorderIgnoreNormal { get => _borderForced.BorderIgnoreNormal; set { _backForced.BorderIgnoreNormal = value; _borderForced.BorderIgnoreNormal = value; } } #endregion #region ConstantBorder /// <summary> /// Gets and sets the drawing of a constant border. /// </summary> public bool ConstantBorder { get => _viewMediumSmall.ConstantBorder; set => _viewMediumSmall.ConstantBorder = value; } #endregion #region DrawNonTrackingAreas /// <summary> /// Gets and sets if the non tracking areas are drawn. /// </summary> public bool DrawNonTrackingAreas { get => _viewMediumSmall.DrawNonTrackingAreas; set => _viewMediumSmall.DrawNonTrackingAreas = value; } #endregion #region GetFirstFocusItem /// <summary> /// Gets the first focus item from the container. /// </summary> /// <returns>ViewBase of item; otherwise false.</returns> public ViewBase GetFirstFocusItem() { // Only take focus if we are visible and enabled if (GroupClusterButton.Visible && GroupClusterButton.Enabled) { return _viewMediumSmall; } else { return null; } } #endregion #region GetLastFocusItem /// <summary> /// Gets the last focus item from the item. /// </summary> /// <returns>ViewBase of item; otherwise false.</returns> public ViewBase GetLastFocusItem() { // Only take focus if we are visible and enabled if (GroupClusterButton.Visible && GroupClusterButton.Enabled) { return _viewMediumSmall; } else { return null; } } #endregion #region GetNextFocusItem /// <summary> /// Gets the next focus item based on the current item as provided. /// </summary> /// <param name="current">The view that is currently focused.</param> /// <param name="matched">Has the current focus item been matched yet.</param> /// <returns>ViewBase of item; otherwise false.</returns> public ViewBase GetNextFocusItem(ViewBase current, ref bool matched) { // Do we match the current item? matched = current == _viewMediumSmall; return null; } #endregion #region GetPreviousFocusItem /// <summary> /// Gets the previous focus item based on the current item as provided. /// </summary> /// <param name="current">The view that is currently focused.</param> /// <param name="matched">Has the current focus item been matched yet.</param> /// <returns>ViewBase of item; otherwise false.</returns> public ViewBase GetPreviousFocusItem(ViewBase current, ref bool matched) { // Do we match the current item? matched = current == _viewMediumSmall; return null; } #endregion #region GetGroupKeyTips /// <summary> /// Gets the array of group level key tips. /// </summary> /// <param name="keyTipList">List to add new entries into.</param> /// <param name="lineHint">Provide hint to item about its location.</param> public void GetGroupKeyTips(KeyTipInfoList keyTipList, int lineHint) { // Only provide a key tip if we are visible if (Visible) { // Get the screen location of the button Rectangle viewRect = _ribbon.KeyTipToScreen(this[0]); // Determine the screen position of the key tip dependant on item location Point screenPt = _ribbon.CalculatedValues.KeyTipRectToPoint(viewRect, lineHint); keyTipList.Add(new KeyTipInfo(GroupClusterButton.Enabled, GroupClusterButton.KeyTip, screenPt, this[0].ClientRectangle, _viewMediumSmall.Controller)); } } #endregion #region Layout /// <summary> /// Override the group item size if possible. /// </summary> /// <param name="size">New size to use.</param> public void SetGroupItemSize(GroupItemSize size) { UpdateItemSizeState(size); } /// <summary> /// Reset the group item size to the item definition. /// </summary> public void ResetGroupItemSize() { UpdateItemSizeState(); } /// <summary> /// Discover the preferred size of the element. /// </summary> /// <param name="context">Layout context.</param> public override Size GetPreferredSize(ViewLayoutContext context) { // Get the preferred size of button view Size preferredSize = base.GetPreferredSize(context); preferredSize.Height = _ribbon.CalculatedValues.GroupLineHeight; return preferredSize; } /// <summary> /// Perform a layout of the elements. /// </summary> /// <param name="context">Layout context.</param> public override void Layout(ViewLayoutContext context) { Debug.Assert(context != null); // Update our enabled and checked state UpdateEnabledState(); UpdateCheckedState(); UpdateDropDownState(); // We take on all the available display area ClientRectangle = context.DisplayRectangle; // Let child elements layout in given space base.Layout(context); // For split buttons we need to calculate the split button areas if (GroupClusterButton.ButtonType == GroupButtonType.Split) { // Find the position of the split area var smallSplitRight = _viewMediumSmallText2Sep1.ClientLocation.X; _viewMediumSmall.SplitRectangle = new Rectangle(smallSplitRight, ClientLocation.Y, ClientRectangle.Right - smallSplitRight, ClientHeight); } else { _viewMediumSmall.SplitRectangle = Rectangle.Empty; } } #endregion #region Protected /// <summary> /// Raises the NeedPaint event. /// </summary> /// <param name="needLayout">Does the palette change require a layout.</param> protected virtual void OnNeedPaint(bool needLayout) { OnNeedPaint(needLayout, Rectangle.Empty); } /// <summary> /// Raises the NeedPaint event. /// </summary> /// <param name="needLayout">Does the palette change require a layout.</param> /// <param name="invalidRect">Rectangle to invalidate.</param> protected virtual void OnNeedPaint(bool needLayout, Rectangle invalidRect) { if (_needPaint != null) { _needPaint(this, new NeedLayoutEventArgs(needLayout)); if (needLayout) { _ribbon.PerformLayout(); } } } #endregion #region Implementation private void CreateView() { // Override the palette provided values _backForced = new PaletteBackInheritForced(_ribbon.StateCommon.RibbonGroupClusterButton.PaletteBack); _borderForced = new PaletteBorderInheritForced(_ribbon.StateCommon.RibbonGroupClusterButton.PaletteBorder); // Create the background and border view _viewMediumSmall = new ViewDrawRibbonGroupButtonBackBorder(_ribbon, GroupClusterButton, _backForced, _borderForced, true, _needPaint) { SplitVertical = false }; _viewMediumSmall.Click += OnSmallButtonClick; _viewMediumSmall.DropDown += OnSmallButtonDropDown; if (_ribbon.InDesignMode) { _viewMediumSmall.ContextClick += OnContextClick; } // Create the layout docker for the contents of the button ViewLayoutDocker contentLayout = new(); // Create the image and drop down content _viewMediumSmallImage = new ViewDrawRibbonGroupClusterButtonImage(_ribbon, GroupClusterButton); _viewMediumSmallText1 = new ViewDrawRibbonGroupClusterButtonText(_ribbon, GroupClusterButton) { Visible = _currentSize != GroupItemSize.Small }; _viewMediumSmallDropArrow = new ViewDrawRibbonDropArrow(_ribbon); _viewMediumSmallText2Sep1 = new ViewLayoutRibbonSeparator(3, false); _viewMediumSmallText2Sep2 = new ViewLayoutRibbonSeparator(3, false); ViewLayoutRibbonCenterPadding imagePadding = new(_smallImagePadding) { _viewMediumSmallImage }; // Layout the content in the center of a row _viewMediumSmallCenter = new ViewLayoutRibbonRowCenter { imagePadding, _viewMediumSmallText1, _viewMediumSmallText2Sep1, _viewMediumSmallDropArrow, _viewMediumSmallText2Sep2 }; // Use content as only fill item contentLayout.Add(_viewMediumSmallCenter, ViewDockStyle.Fill); // Add the content into the background and border _viewMediumSmall.Add(contentLayout); // Create controller for intercepting events to determine tool tip handling _viewMediumSmall.MouseController = new ToolTipController(_ribbon.TabsArea.ButtonSpecManager.ToolTipManager, _viewMediumSmall, _viewMediumSmall.MouseController); // Provide back reference to the button definition GroupClusterButton.ClusterButtonView = _viewMediumSmall; // Define the actual view Add(_viewMediumSmall); } private void UpdateItemSizeState() { UpdateItemSizeState(GroupClusterButton.ItemSizeCurrent); } private void UpdateItemSizeState(GroupItemSize size) { _currentSize = size; _viewMediumSmallCenter.CurrentSize = size; _viewMediumSmallText1.Visible = size != GroupItemSize.Small; } private void UpdateEnabledState() { // Get the correct enabled state from the button definition var buttonEnabled = GroupClusterButton.Enabled; if (GroupClusterButton.KryptonCommand != null) { buttonEnabled = GroupClusterButton.KryptonCommand.Enabled; } // Take into account the ribbon state and mode var enabled = _ribbon.InDesignHelperMode || (buttonEnabled && _ribbon.Enabled); _viewMediumSmall.Enabled = enabled; _viewMediumSmallText1.Enabled = enabled; _viewMediumSmallImage.Enabled = enabled; _viewMediumSmallDropArrow.Enabled = enabled; } private void UpdateCheckedState() { var checkedState = false; // Only show as checked if also a check type button if (GroupClusterButton.ButtonType == GroupButtonType.Check) { checkedState = GroupClusterButton.KryptonCommand?.Checked ?? GroupClusterButton.Checked; } _viewMediumSmall.Checked = checkedState; } private void UpdateDropDownState() { var dropDown = (GroupClusterButton.ButtonType == GroupButtonType.DropDown) || (GroupClusterButton.ButtonType == GroupButtonType.Split); var splitDown = GroupClusterButton.ButtonType == GroupButtonType.Split; _viewMediumSmallText2Sep1.Visible = splitDown; _viewMediumSmallDropArrow.Visible = dropDown; _viewMediumSmallText2Sep2.Visible = dropDown; // Update the view with the type of button being used _viewMediumSmall.ButtonType = GroupClusterButton.ButtonType; } private void OnSmallButtonClick(object sender, EventArgs e) { GroupClusterButton.PerformClick(_viewMediumSmall.FinishDelegate); } private void OnSmallButtonDropDown(object sender, EventArgs e) { GroupClusterButton.PerformDropDown(_viewMediumSmall.FinishDelegate); } private void OnContextClick(object sender, MouseEventArgs e) { GroupClusterButton.OnDesignTimeContextMenu(e); } private void OnButtonPropertyChanged(object sender, PropertyChangedEventArgs e) { var updateLayout = false; var updatePaint = false; switch (e.PropertyName) { case "Visible": updateLayout = true; break; case "TextLine": _viewMediumSmallText1.MakeDirty(); updateLayout = true; break; case "ButtonType": UpdateDropDownState(); updateLayout = true; break; case "Checked": UpdateCheckedState(); updatePaint = true; break; case "Enabled": UpdateEnabledState(); updatePaint = true; break; case "ImageSmall": updatePaint = true; break; case "ItemSizeMinimum": case "ItemSizeMaximum": case "ItemSizeCurrent": UpdateItemSizeState(); updateLayout = true; break; case "KryptonCommand": _viewMediumSmallText1.MakeDirty(); UpdateEnabledState(); UpdateCheckedState(); updateLayout = true; break; } if (updateLayout) { // If we are on the currently selected tab then... if ((GroupClusterButton.RibbonTab != null) && (_ribbon.SelectedTab == GroupClusterButton.RibbonTab)) { // ...layout so the visible change is made OnNeedPaint(true); } } if (updatePaint) { // If this button is actually defined as visible... if (GroupClusterButton.Visible || _ribbon.InDesignMode) { // ...and on the currently selected tab then... if ((GroupClusterButton.RibbonTab != null) && (_ribbon.SelectedTab == GroupClusterButton.RibbonTab)) { // ...repaint it right now OnNeedPaint(false, ClientRectangle); } } } } #endregion } }
37.357914
154
0.573588
[ "BSD-3-Clause" ]
Krypton-Suite/standard-toolkit
Source/Krypton Components/Krypton.Ribbon/View Draw/ViewDrawRibbonGroupClusterButton.cs
20,774
C#
using Microsoft.Owin; using KnowledgeCenter.Web.AppStart; [assembly: OwinStartup(typeof(Startup))] namespace KnowledgeCenter.Web.AppStart { using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; using Owin; /// <summary> /// Owin Startup /// </summary> public partial class Startup { /// <summary> /// Configurations the specified application. /// </summary> /// <param name="app">The application.</param> public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); AreaRegistration.RegisterAllAreas(); SetupBundles(); SetupGlobalMvcFilters(GlobalFilters.Filters); SetupMvcRoutes(RouteTable.Routes); SetupWebApiRoutes(config); SetupWebApiFormatters(config.Formatters); SetupIoC(app, config); InitializeSystem(); app.UseWebApi(config); } } }
22.886364
57
0.600794
[ "MIT" ]
Socres/KnowledgeCenter
src/Presentation/KnowledgeCenter.Web/AppStart/Startup.cs
1,009
C#
using Microsoft.Azure.Commands.WebApps.Models; using Microsoft.Azure.Commands.WebApps.Utilities; using Microsoft.Azure.Management.WebSites.Models; using System.Management.Automation; namespace Microsoft.Azure.Commands.WebApps { // For some cmdlets, the slot is optional, but will be used if specified. public class WebAppOptionalSlotBaseCmdlet : WebAppBaseClientCmdLet { protected const string ParameterSet1Name = "FromResourceName"; protected const string ParameterSet2Name = "FromWebApp"; [Parameter(ParameterSetName = ParameterSet1Name, Position = 0, Mandatory = true, HelpMessage = "The name of the resource group.", ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter(ParameterSetName = ParameterSet1Name, Position = 1, Mandatory = true, HelpMessage = "The name of the web app.", ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(ParameterSetName = ParameterSet1Name, Position = 2, Mandatory = false, HelpMessage = "The name of the web app slot.", ValueFromPipelineByPropertyName = true)] public string Slot { get; set; } [Parameter(ParameterSetName = ParameterSet2Name, Position = 0, Mandatory = true, HelpMessage = "The web app object", ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public Site WebApp { get; set; } public override void ExecuteCmdlet() { switch (ParameterSetName) { case ParameterSet1Name: string webAppName, slotName; if (CmdletHelpers.TryParseAppAndSlotNames(Name, out webAppName, out slotName)) { Name = webAppName; // We have to choose between the slot name embedded in the name parameter or the slot parameter. // The choice for now is to prefer the embeeded slot name over the slot parameter. Slot = slotName; } break; case ParameterSet2Name: string rg, name, slot; CmdletHelpers.TryParseWebAppMetadataFromResourceId(WebApp.Id, out rg, out name, out slot); ResourceGroupName = rg; Name = name; Slot = slot; break; } } } }
44.627119
122
0.597417
[ "MIT" ]
FosterMichelle/azure-powershell
src/ResourceManager/Websites/Commands.Websites/Models.WebApp/WebAppOptionalSlotBaseCmdlet.cs
2,577
C#
/************************************************************************************* Extended WPF Toolkit Copyright (C) 2007-2013 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license For more features, controls, and fast professional support, pick up the Plus Edition at http://xceed.com/wpf_toolkit Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids ***********************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Windows; namespace Xceed.Wpf.DataGrid { internal class VisibilityChangedEventManager : WeakEventManager { private VisibilityChangedEventManager() { } public static void AddListener( ColumnCollection source, IWeakEventListener listener ) { CurrentManager.ProtectedAddListener( source, listener ); } public static void RemoveListener( ColumnCollection source, IWeakEventListener listener ) { CurrentManager.ProtectedRemoveListener( source, listener ); } protected override void StartListening( object source ) { var columnCollection = ( ColumnCollection )source; columnCollection.ColumnVisibilityChanged += new EventHandler( this.OnColumnVisibilityChanged ); } protected override void StopListening( object source ) { var columnCollection = ( ColumnCollection )source; columnCollection.ColumnVisibilityChanged -= new EventHandler( this.OnColumnVisibilityChanged ); } private static VisibilityChangedEventManager CurrentManager { get { Type managerType = typeof( VisibilityChangedEventManager ); VisibilityChangedEventManager currentManager = ( VisibilityChangedEventManager )WeakEventManager.GetCurrentManager( managerType ); if( currentManager == null ) { currentManager = new VisibilityChangedEventManager(); WeakEventManager.SetCurrentManager( managerType, currentManager ); } return currentManager; } } private void OnColumnVisibilityChanged( object sender, EventArgs args ) { this.DeliverEvent( sender, args ); } } }
32.146667
139
0.649938
[ "MIT" ]
BenInCOSprings/WpfDockingWindowsApplicationTemplate
wpftoolkit-110921/Main/Source/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.DataGrid/(Generator)/VisibilityChangedEventManager.cs
2,413
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Shopping.Aggregator.Models { public class BasketModel { public string UserName { get; set; } public List<BasketItemExtendedModel> Items { get; set; } = new List<BasketItemExtendedModel>(); } }
22.066667
103
0.70997
[ "MIT" ]
Azilen/gRPC-API-Performance-Improvement
src/ApiGateways/Shopping.Aggregator/Models/BasketModel.cs
333
C#
using System; using System.Collections.Generic; using System.Linq; public class BombNumbers { public static void Main() { List<int> numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToList(); List<int> bombAndPower = Console.ReadLine().Split(' ').Select(int.Parse).ToList(); int bomb = bombAndPower[0]; int power = bombAndPower[1]; for (int i = 0; i < numbers.Count; i++) { if (numbers[i] == bomb) { int startIndex = i - power; int endIndex = i + power; if (startIndex < 0) { startIndex = 0; } if (endIndex > numbers.Count - 1) { endIndex = numbers.Count - 1; } int count = endIndex + 1 - startIndex; numbers.RemoveRange(startIndex, count); i = -1; } } int sum = 0; for (int i = 0; i < numbers.Count; i++) { sum += numbers[i]; } Console.WriteLine(sum); } }
24.723404
90
0.44062
[ "MIT" ]
yani-valeva/Programming-Fundamentals
Lists/BombNumbers/BombNumbers.cs
1,164
C#
using UnityEngine; [CreateAssetMenu(fileName = "Inventory Item", menuName = "Fire Over the Horizon/Inventory Item")] public class InventoryItem : ScriptableObject { public Sprite sprite; }
32.166667
97
0.772021
[ "MIT" ]
alexismorin/rooms
Assets/Scripts/Player/InventoryItem.cs
193
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AGame.Src.OGL { class GLObject { public int ID; public virtual void Delete() { throw new NotImplementedException(); } public virtual void Bind() { throw new NotImplementedException(); } public virtual void Use(Action A) { Bind(); A(); Unbind(); } public virtual void Unbind() { throw new NotImplementedException(); } } }
16.896552
39
0.687755
[ "MIT" ]
cartman300/AGame
AGame/Src/OGL/GLObject.cs
492
C#
using System.Collections.Generic; using Xunit; using Plivo.Http; using Plivo.Resource; using Plivo.Resource.Recording; using Plivo.Utilities; namespace Plivo.NetCore.Test.Resources { public class TestRecording : BaseTestCase { [Fact] public void TestRecordingList() { var data = new Dictionary<string, object>() { {"limit", 10}, {"is_voice_request", true} }; var request = new PlivoRequest( "GET", "Account/MAXXXXXXXXXXXXXXXXXX/Recording/", "", data); var response = System.IO.File.ReadAllText( SOURCE_DIR + @"../Mocks/recordingListResponse.json" ); Setup<ListResponse<Recording>>( 200, response ); Assert.Empty( ComparisonUtilities.Compare( response, Api.Recording.List(limit: 10))); AssertRequest(request); } [Fact] public void TestRecordingGet() { var id = "abcabcabc"; var data = new Dictionary<string, object>() { {"is_voice_request", true} }; var request = new PlivoRequest( "GET", "Account/MAXXXXXXXXXXXXXXXXXX/Recording/" + id + "/", "", data); var response = System.IO.File.ReadAllText( SOURCE_DIR + @"../Mocks/recordingGetResponse.json" ); Setup<Recording>( 200, response ); Assert.Empty( ComparisonUtilities.Compare( response, Api.Recording.Get(id))); AssertRequest(request); } [Fact] public void TestRecordingDelete() { var id = "abcabcabc"; var data = new Dictionary<string, object>() { {"is_voice_request", true} }; var request = new PlivoRequest( "DELETE", "Account/MAXXXXXXXXXXXXXXXXXX/Recording/" + id + "/", "", data); var response = ""; Setup<UpdateResponse<Recording>>( 204, response ); Api.Recording.Delete(id); AssertRequest(request); } } }
27.44898
73
0.428253
[ "MIT" ]
huzaif-plivo/plivo-dotnet
tests_netcore/Plivo.NetCore.Test/Resources/TestRecording.cs
2,690
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nix.Store.Client.Sections { public enum LoaderType { Manual, XmlFile, RemoteWeb } }
15.466667
36
0.616379
[ "MIT" ]
NixCody/Nix.Storage
Nix.Store.Client/Sections/LoaderType.cs
234
C#
using System; using System.Collections.Generic; using System.Text; namespace Collections.Classes { public class Card { //card properties public Suit CardSuit { get; set; } public CardValue Value { get; set; } public Suit suit { get; set; } //card constructor public Card(CardValue value, Suit suit) { Value = value; CardSuit = suit; } public Card() { } //enums act as a class within the card class public enum Suit { Hearts, Spades, Diamonds, Clubs } public enum CardValue { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } } }
18.307692
52
0.42437
[ "MIT" ]
dezteague/LAB07-COLLECTIONS
Collections/Collections/Classes/Card.cs
954
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>Functions for matching file names with patterns.</summary> //----------------------------------------------------------------------- using System; using System.IO; using System.Text; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Globalization; using System.Collections.Generic; namespace Microsoft.Build.Shared { /// <summary> /// Functions for matching file names with patterns. /// </summary> internal static class FileMatcher { private const string recursiveDirectoryMatch = "**"; private const string dotdot = ".."; private static readonly string s_directorySeparator = new string(Path.DirectorySeparatorChar, 1); private static readonly string s_thisDirectory = "." + s_directorySeparator; private static readonly char[] s_wildcardCharacters = { '*', '?' }; private static readonly char[] s_wildcardAndSemicolonCharacters = { '*', '?', ';' }; // on OSX both System.IO.Path separators are '/', so we have to use the literals internal static readonly char[] directorySeparatorCharacters = { '/', '\\' }; internal static readonly string[] directorySeparatorStrings = directorySeparatorCharacters.Select(c => c.ToString()).ToArray(); internal static readonly GetFileSystemEntries s_defaultGetFileSystemEntries = new GetFileSystemEntries(GetAccessibleFileSystemEntries); private static readonly DirectoryExists s_defaultDirectoryExists = new DirectoryExists(Directory.Exists); /// <summary> /// Cache of the list of invalid path characters, because this method returns a clone (for security reasons) /// which can cause significant transient allocations /// </summary> private static readonly char[] s_invalidPathChars = Path.GetInvalidPathChars(); /// <summary> /// The type of entity that GetFileSystemEntries should return. /// </summary> internal enum FileSystemEntity { Files, Directories, FilesAndDirectories }; /// <summary> /// Delegate defines the GetFileSystemEntries signature that GetLongPathName uses /// to enumerate directories on the file system. /// </summary> /// <param name="entityType">Files, Directories, or Files and Directories</param> /// <param name="path">The path to search.</param> /// <param name="pattern">The file pattern.</param> /// <param name="projectDirectory"></param> /// <param name="stripProjectDirectory"></param> /// <returns>The array of filesystem entries.</returns> internal delegate string[] GetFileSystemEntries(FileSystemEntity entityType, string path, string pattern, string projectDirectory, bool stripProjectDirectory); /// <summary> /// Determines whether the given path has any wild card characters. /// </summary> /// <param name="filespec"></param> /// <returns></returns> internal static bool HasWildcards(string filespec) { return -1 != filespec.IndexOfAny(s_wildcardCharacters); } /// <summary> /// Determines whether the given path has any wild card characters or any semicolons. /// </summary> internal static bool HasWildcardsSemicolonItemOrPropertyReferences(string filespec) { return ( (-1 != filespec.IndexOfAny(s_wildcardAndSemicolonCharacters)) || filespec.Contains("$(") || filespec.Contains("@(") ); } /// <summary> /// Get the files and\or folders specified by the given path and pattern. /// </summary> /// <param name="entityType">Whether Files, Directories or both.</param> /// <param name="path">The path to search.</param> /// <param name="pattern">The pattern to search.</param> /// <param name="projectDirectory">The directory for the project within which the call is made</param> /// <param name="stripProjectDirectory">If true the project directory should be stripped</param> /// <returns></returns> private static string[] GetAccessibleFileSystemEntries(FileSystemEntity entityType, string path, string pattern, string projectDirectory, bool stripProjectDirectory) { path = FileUtilities.FixFilePath(path); string[] files = null; switch (entityType) { case FileSystemEntity.Files: files = GetAccessibleFiles(path, pattern, projectDirectory, stripProjectDirectory); break; case FileSystemEntity.Directories: files = GetAccessibleDirectories(path, pattern); break; case FileSystemEntity.FilesAndDirectories: files = GetAccessibleFilesAndDirectories(path, pattern); break; default: ErrorUtilities.VerifyThrow(false, "Unexpected filesystem entity type."); break; } return files; } /// <summary> /// Returns an array of file system entries matching the specified search criteria. Inaccessible or non-existent file /// system entries are skipped. /// </summary> /// <param name="path"></param> /// <param name="pattern"></param> /// <returns>Array of matching file system entries (can be empty).</returns> private static string[] GetAccessibleFilesAndDirectories(string path, string pattern) { string[] entries = null; if (Directory.Exists(path)) { try { entries = Directory.GetFileSystemEntries(path, pattern); } // for OS security catch (UnauthorizedAccessException) { // do nothing } // for code access security catch (System.Security.SecurityException) { // do nothing } } if (entries == null) { entries = new string[0]; } return entries; } /// <summary> /// Same as Directory.GetFiles(...) except that files that /// aren't accessible are skipped instead of throwing an exception. /// /// Other exceptions are passed through. /// </summary> /// <param name="path">The path.</param> /// <param name="filespec">The pattern.</param> /// <param name="projectDirectory">The project directory</param> /// <param name="stripProjectDirectory"></param> /// <returns>Files that can be accessed.</returns> private static string[] GetAccessibleFiles ( string path, string filespec, // can be null string projectDirectory, bool stripProjectDirectory ) { try { // look in current directory if no path specified string dir = ((path.Length == 0) ? s_thisDirectory : path); // get all files in specified directory, unless a file-spec has been provided string[] files = (filespec == null) ? Directory.GetFiles(dir) : Directory.GetFiles(dir, filespec); // If the Item is based on a relative path we need to strip // the current directory from the front if (stripProjectDirectory) { RemoveProjectDirectory(files, projectDirectory); } // Files in the current directory are coming back with a ".\" // prepended to them. We need to remove this; it breaks the // IDE, which expects just the filename if it is in the current // directory. But only do this if the original path requested // didn't itself contain a ".\". else if (!path.StartsWith(s_thisDirectory, StringComparison.Ordinal)) { RemoveInitialDotSlash(files); } return files; } catch (System.Security.SecurityException) { // For code access security. return new string[0]; } catch (System.UnauthorizedAccessException) { // For OS security. return new string[0]; } } /// <summary> /// Same as Directory.GetDirectories(...) except that files that /// aren't accessible are skipped instead of throwing an exception. /// /// Other exceptions are passed through. /// </summary> /// <param name="path">The path.</param> /// <param name="pattern">Pattern to match</param> /// <returns>Accessible directories.</returns> private static string[] GetAccessibleDirectories ( string path, string pattern ) { try { string[] directories = null; if (pattern == null) { directories = Directory.GetDirectories((path.Length == 0) ? s_thisDirectory : path); } else { directories = Directory.GetDirectories((path.Length == 0) ? s_thisDirectory : path, pattern); } // Subdirectories in the current directory are coming back with a ".\" // prepended to them. We need to remove this; it breaks the // IDE, which expects just the filename if it is in the current // directory. But only do this if the original path requested // didn't itself contain a ".\". if (!path.StartsWith(s_thisDirectory, StringComparison.Ordinal)) { RemoveInitialDotSlash(directories); } return directories; } catch (System.Security.SecurityException) { // For code access security. return new string[0]; } catch (System.UnauthorizedAccessException) { // For OS security. return new string[0]; } } /// <summary> /// Given a path name, get its long version. /// </summary> /// <param name="path">The short path.</param> /// <returns>The long path.</returns> internal static string GetLongPathName ( string path ) { return GetLongPathName(path, s_defaultGetFileSystemEntries); } /// <summary> /// Given a path name, get its long version. /// </summary> /// <param name="path">The short path.</param> /// <param name="getFileSystemEntries">Delegate.</param> /// <returns>The long path.</returns> internal static string GetLongPathName ( string path, GetFileSystemEntries getFileSystemEntries ) { if (path.IndexOf("~", StringComparison.Ordinal) == -1) { // A path with no '~' must not be a short name. return path; } ErrorUtilities.VerifyThrow(!HasWildcards(path), "GetLongPathName does not handle wildcards and was passed '{0}'.", path); string[] parts = path.Split(directorySeparatorCharacters); string pathRoot; int startingElement = 0; bool isUnc = path.StartsWith(s_directorySeparator + s_directorySeparator, StringComparison.Ordinal); if (isUnc) { pathRoot = s_directorySeparator + s_directorySeparator; pathRoot += parts[2]; pathRoot += s_directorySeparator; pathRoot += parts[3]; pathRoot += s_directorySeparator; startingElement = 4; } else { // Is it relative? if (path.Length > 2 && path[1] == ':') { // Not relative pathRoot = parts[0] + s_directorySeparator; startingElement = 1; } else { // Relative pathRoot = String.Empty; startingElement = 0; } } // Build up an array of parts. These elements may be "" if there are // extra slashes. string[] longParts = new string[parts.Length - startingElement]; string longPath = pathRoot; for (int i = startingElement; i < parts.Length; ++i) { // If there is a zero-length part, then that means there was an extra slash. if (parts[i].Length == 0) { longParts[i - startingElement] = String.Empty; } else { if (parts[i].IndexOf("~", StringComparison.Ordinal) == -1) { // If there's no ~, don't hit the disk. longParts[i - startingElement] = parts[i]; longPath = Path.Combine(longPath, parts[i]); } else { // getFileSystemEntries(...) returns an empty array if longPath doesn't exist. string[] entries = getFileSystemEntries(FileSystemEntity.FilesAndDirectories, longPath, parts[i], null, false); if (0 == entries.Length) { // The next part doesn't exist. Therefore, no more of the path will exist. // Just return the rest. for (int j = i; j < parts.Length; ++j) { longParts[j - startingElement] = parts[j]; } break; } // Since we know there are no wild cards, this should be length one. ErrorUtilities.VerifyThrow(entries.Length == 1, "Unexpected number of entries ({3}) found when enumerating '{0}' under '{1}'. Original path was '{2}'", parts[i], longPath, path, entries.Length); // Entries[0] contains the full path. longPath = entries[0]; // We just want the trailing node. longParts[i - startingElement] = Path.GetFileName(longPath); } } } return pathRoot + String.Join(s_directorySeparator, longParts); } /// <summary> /// Given a filespec, split it into left-most 'fixed' dir part, middle 'wildcard' dir part, and filename part. /// The filename part may have wildcard characters in it. /// </summary> /// <param name="filespec">The filespec to be decomposed.</param> /// <param name="fixedDirectoryPart">Receives the fixed directory part.</param> /// <param name="wildcardDirectoryPart">The wildcard directory part.</param> /// <param name="filenamePart">The filename part.</param> /// <param name="getFileSystemEntries">Delegate.</param> internal static void SplitFileSpec ( string filespec, out string fixedDirectoryPart, out string wildcardDirectoryPart, out string filenamePart, GetFileSystemEntries getFileSystemEntries ) { PreprocessFileSpecForSplitting ( filespec, out fixedDirectoryPart, out wildcardDirectoryPart, out filenamePart ); /* * Handle the special case in which filenamePart is '**'. * In this case, filenamePart becomes '*.*' and the '**' is appended * to the end of the wildcardDirectory part. * This is so that later regular expression matching can accurately * pull out the different parts (fixed, wildcard, filename) of given * file specs. */ if (recursiveDirectoryMatch == filenamePart) { wildcardDirectoryPart += recursiveDirectoryMatch; wildcardDirectoryPart += s_directorySeparator; filenamePart = "*.*"; } fixedDirectoryPart = FileMatcher.GetLongPathName(fixedDirectoryPart, getFileSystemEntries); } /// <summary> /// Do most of the grunt work of splitting the filespec into parts. /// Does not handle post-processing common to the different matching /// paths. /// </summary> /// <param name="filespec">The filespec to be decomposed.</param> /// <param name="fixedDirectoryPart">Receives the fixed directory part.</param> /// <param name="wildcardDirectoryPart">The wildcard directory part.</param> /// <param name="filenamePart">The filename part.</param> private static void PreprocessFileSpecForSplitting ( string filespec, out string fixedDirectoryPart, out string wildcardDirectoryPart, out string filenamePart ) { filespec = FileUtilities.FixFilePath(filespec); int indexOfLastDirectorySeparator = filespec.LastIndexOfAny(directorySeparatorCharacters); if (-1 == indexOfLastDirectorySeparator) { /* * No dir separator found. This is either this form, * * Source.cs * *.cs * * or this form, * * ** */ fixedDirectoryPart = String.Empty; wildcardDirectoryPart = String.Empty; filenamePart = filespec; return; } int indexOfFirstWildcard = filespec.IndexOfAny(s_wildcardCharacters); if ( -1 == indexOfFirstWildcard || indexOfFirstWildcard > indexOfLastDirectorySeparator ) { /* * There is at least one dir separator, but either there is no wild card or the * wildcard is after the dir separator. * * The form is one of these: * * dir1\Source.cs * dir1\*.cs * * Where the trailing spec is meant to be a filename. Or, * * dir1\** * * Where the trailing spec is meant to be any file recursively. */ // We know the fixed director part now. fixedDirectoryPart = filespec.Substring(0, indexOfLastDirectorySeparator + 1); wildcardDirectoryPart = String.Empty; filenamePart = filespec.Substring(indexOfLastDirectorySeparator + 1); return; } /* * Find the separator right before the first wildcard. */ string filespecLeftOfWildcard = filespec.Substring(0, indexOfFirstWildcard); int indexOfSeparatorBeforeWildCard = filespecLeftOfWildcard.LastIndexOfAny(directorySeparatorCharacters); if (-1 == indexOfSeparatorBeforeWildCard) { /* * There is no separator before the wildcard, so the form is like this: * * dir?\Source.cs * * or this, * * dir?\** */ fixedDirectoryPart = String.Empty; wildcardDirectoryPart = filespec.Substring(0, indexOfLastDirectorySeparator + 1); filenamePart = filespec.Substring(indexOfLastDirectorySeparator + 1); return; } /* * There is at least one wildcard and one dir separator, split parts out. */ fixedDirectoryPart = filespec.Substring(0, indexOfSeparatorBeforeWildCard + 1); wildcardDirectoryPart = filespec.Substring(indexOfSeparatorBeforeWildCard + 1, indexOfLastDirectorySeparator - indexOfSeparatorBeforeWildCard); filenamePart = filespec.Substring(indexOfLastDirectorySeparator + 1); } /// <summary> /// Removes the leading ".\" from all of the paths in the array. /// </summary> /// <param name="paths">Paths to remove .\ from.</param> private static void RemoveInitialDotSlash ( string[] paths ) { for (int i = 0; i < paths.Length; i++) { if (paths[i].StartsWith(s_thisDirectory, StringComparison.Ordinal)) { paths[i] = paths[i].Substring(2); } } } /// <summary> /// Checks if the char is a DirectorySeparatorChar or a AltDirectorySeparatorChar /// </summary> /// <param name="c"></param> /// <returns></returns> internal static bool IsDirectorySeparator(char c) { return (c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar); } /// <summary> /// Removes the current directory converting the file back to relative path /// </summary> /// <param name="paths">Paths to remove current directory from.</param> /// <param name="projectDirectory"></param> internal static void RemoveProjectDirectory ( string[] paths, string projectDirectory ) { bool directoryLastCharIsSeparator = IsDirectorySeparator(projectDirectory[projectDirectory.Length - 1]); for (int i = 0; i < paths.Length; i++) { if (paths[i].StartsWith(projectDirectory, StringComparison.Ordinal)) { // If the project directory did not end in a slash we need to check to see if the next char in the path is a slash if (!directoryLastCharIsSeparator) { //If the next char after the project directory is not a slash, skip this path if (paths[i].Length <= projectDirectory.Length || !IsDirectorySeparator(paths[i][projectDirectory.Length])) { continue; } paths[i] = paths[i].Substring(projectDirectory.Length + 1); } else { paths[i] = paths[i].Substring(projectDirectory.Length); } } } } struct RecursiveStepResult { public string[] Files; public string[] Subdirs; public string RemainingWildcardDirectory; } class FilesSearchData { public FilesSearchData( string filespec, // can be null int extensionLengthToEnforce, // only relevant when filespec is not null Regex regexFileMatch, // can be null bool needsRecursion ) { Filespec = filespec; ExtensionLengthToEnforce = extensionLengthToEnforce; RegexFileMatch = regexFileMatch; NeedsRecursion = needsRecursion; } /// <summary> /// The filespec. /// </summary> public string Filespec { get; } public int ExtensionLengthToEnforce { get; } /// <summary> /// Wild-card matching. /// </summary> public Regex RegexFileMatch { get; } /// <summary> /// If true, then recursion is required. /// </summary> public bool NeedsRecursion { get; } } struct RecursionState { /// <summary> /// The directory to search in /// </summary> public string BaseDirectory; /// <summary> /// The remaining, wildcard part of the directory. /// </summary> public string RemainingWildcardDirectory; /// <summary> /// Data about a search that does not change as the search recursively traverses directories /// </summary> public FilesSearchData SearchData; } /// <summary> /// Get all files that match either the file-spec or the regular expression. /// </summary> /// <param name="listOfFiles">List of files that gets populated.</param> /// <param name="recursionState">Information about the search</param> /// <param name="projectDirectory"></param> /// <param name="stripProjectDirectory"></param> /// <param name="getFileSystemEntries">Delegate.</param> /// <param name="searchesToExclude">Patterns to exclude from the results</param> /// <param name="searchesToExcludeInSubdirs">exclude patterns that might activate farther down the directory tree. Keys assume paths are normalized with forward slashes and no trailing slashes</param> private static void GetFilesRecursive ( IList<string> listOfFiles, RecursionState recursionState, string projectDirectory, bool stripProjectDirectory, GetFileSystemEntries getFileSystemEntries, IList<RecursionState> searchesToExclude, Dictionary<string, List<RecursionState>> searchesToExcludeInSubdirs ) { ErrorUtilities.VerifyThrow((recursionState.SearchData.Filespec== null) || (recursionState.SearchData.RegexFileMatch == null), "File-spec overrides the regular expression -- pass null for file-spec if you want to use the regular expression."); ErrorUtilities.VerifyThrow((recursionState.SearchData.Filespec != null) || (recursionState.SearchData.RegexFileMatch != null), "Need either a file-spec or a regular expression to match files."); ErrorUtilities.VerifyThrow(recursionState.RemainingWildcardDirectory != null, "Expected non-null remaning wildcard directory."); // Determine if any of searchesToExclude is necessarily a superset of the results that will be returned. // This means all results will be excluded and we should bail out now. if (searchesToExclude != null) { foreach (var searchToExclude in searchesToExclude) { // The BaseDirectory of all the exclude searches should be the same as the include one Debug.Assert(FileUtilities.PathsEqual(searchToExclude.BaseDirectory, recursionState.BaseDirectory), "Expected exclude search base directory to match include search base directory"); // We can exclude all results in this folder if: if ( // We are matching files based on a filespec and not a regular expression searchToExclude.SearchData.Filespec != null && // The wildcard path portion of the excluded search matches the include search FileUtilities.PathsEqual(searchToExclude.RemainingWildcardDirectory, recursionState.RemainingWildcardDirectory) && // The exclude search will match ALL filenames OR (searchToExclude.SearchData.Filespec == "*" || searchToExclude.SearchData.Filespec == "*.*" || // The exclude search filename pattern matches the include search's pattern (searchToExclude.SearchData.Filespec == recursionState.SearchData.Filespec && searchToExclude.SearchData.ExtensionLengthToEnforce == recursionState.SearchData.ExtensionLengthToEnforce))) { // We won't get any results from this search that we would end up keeping return; } } } RecursiveStepResult nextStep = GetFilesRecursiveStep( recursionState, projectDirectory, stripProjectDirectory, getFileSystemEntries); RecursiveStepResult[] excludeNextSteps = null; if (searchesToExclude != null) { excludeNextSteps = new RecursiveStepResult[searchesToExclude.Count]; for (int i = 0; i < searchesToExclude.Count; i++) { excludeNextSteps[i] = GetFilesRecursiveStep( searchesToExclude[i], projectDirectory, stripProjectDirectory, getFileSystemEntries); } } if (nextStep.Files != null) { HashSet<string> filesToExclude = null; if (excludeNextSteps != null) { filesToExclude = new HashSet<string>(); foreach (var excludeStep in excludeNextSteps) { if (excludeStep.Files != null) { foreach (var file in excludeStep.Files) { filesToExclude.Add(file); } } } } foreach (var file in nextStep.Files) { if (filesToExclude == null || !filesToExclude.Contains(file)) { listOfFiles.Add(file); } } } if (nextStep.Subdirs != null) { foreach (string subdir in nextStep.Subdirs) { // RecursionState is a struct so this copies it var newRecursionState = recursionState; newRecursionState.BaseDirectory = subdir; newRecursionState.RemainingWildcardDirectory = nextStep.RemainingWildcardDirectory; List<RecursionState> newSearchesToExclude = null; if (excludeNextSteps != null) { newSearchesToExclude = new List<RecursionState>(); for (int i = 0; i < excludeNextSteps.Length; i++) { if (excludeNextSteps[i].Subdirs != null && excludeNextSteps[i].Subdirs.Any(excludedDir => FileUtilities.PathsEqual(excludedDir, subdir))) { RecursionState thisExcludeStep = searchesToExclude[i]; thisExcludeStep.BaseDirectory = subdir; thisExcludeStep.RemainingWildcardDirectory = excludeNextSteps[i].RemainingWildcardDirectory; newSearchesToExclude.Add(thisExcludeStep); } } } if (searchesToExcludeInSubdirs != null) { List<RecursionState> searchesForSubdir; // The normalization fixes https://github.com/Microsoft/msbuild/issues/917 // and is a partial fix for https://github.com/Microsoft/msbuild/issues/724 if (searchesToExcludeInSubdirs.TryGetValue(subdir.NormalizeForPathComparison(), out searchesForSubdir)) { // We've found the base directory that these exclusions apply to. So now add them as normal searches if (newSearchesToExclude == null) { newSearchesToExclude = new List<RecursionState>(); } newSearchesToExclude.AddRange(searchesForSubdir); } } // We never want to strip the project directory from the leaves, because the current // process directory maybe different GetFilesRecursive( listOfFiles, newRecursionState, projectDirectory, stripProjectDirectory, getFileSystemEntries, newSearchesToExclude, searchesToExcludeInSubdirs); } } } private static RecursiveStepResult GetFilesRecursiveStep ( RecursionState recursionState, string projectDirectory, bool stripProjectDirectory, GetFileSystemEntries getFileSystemEntries ) { RecursiveStepResult ret = new RecursiveStepResult(); /* * Get the matching files. */ bool considerFiles = false; // Only consider files if... if (recursionState.RemainingWildcardDirectory.Length == 0) { // We've reached the end of the wildcard directory elements. considerFiles = true; } else if (recursionState.RemainingWildcardDirectory.IndexOf(recursiveDirectoryMatch, StringComparison.Ordinal) == 0) { // or, we've reached a "**" so everything else is matched recursively. considerFiles = true; } if (considerFiles) { string[] files = getFileSystemEntries(FileSystemEntity.Files, recursionState.BaseDirectory, recursionState.SearchData.Filespec, projectDirectory, stripProjectDirectory); bool needToProcessEachFile = recursionState.SearchData.Filespec == null || recursionState.SearchData.ExtensionLengthToEnforce != 0; if (needToProcessEachFile) { List<string> listOfFiles = new List<string>(); foreach (string file in files) { if ((recursionState.SearchData.Filespec != null) || // if no file-spec provided, match the file to the regular expression // PERF NOTE: Regex.IsMatch() is an expensive operation, so we avoid it whenever possible recursionState.SearchData.RegexFileMatch.IsMatch(file)) { if ((recursionState.SearchData.Filespec == null) || // if we used a file-spec with a "loosely" defined extension (recursionState.SearchData.ExtensionLengthToEnforce == 0) || // discard all files that do not have extensions of the desired length (Path.GetExtension(file).Length == recursionState.SearchData.ExtensionLengthToEnforce)) { listOfFiles.Add(file); } } } ret.Files = listOfFiles.ToArray(); } else { ret.Files = files; } } /* * Recurse into subdirectories. */ if (recursionState.SearchData.NeedsRecursion && recursionState.RemainingWildcardDirectory.Length > 0) { // Find the next directory piece. string pattern = null; if (!IsRecursiveDirectoryMatch(recursionState.RemainingWildcardDirectory)) { int indexOfNextSlash = recursionState.RemainingWildcardDirectory.IndexOfAny(directorySeparatorCharacters); ErrorUtilities.VerifyThrow(indexOfNextSlash != -1, "Slash should be guaranteed."); pattern = recursionState.RemainingWildcardDirectory.Substring(0, indexOfNextSlash); if (pattern == recursiveDirectoryMatch) { // If pattern turned into **, then there's no choice but to enumerate everything. pattern = null; recursionState.RemainingWildcardDirectory = recursiveDirectoryMatch; } else { // Peel off the leftmost directory piece. So for example, if remainingWildcardDirectory // contains: // // ?emp\foo\**\bar // // then put '?emp' into pattern. Then put the remaining part, // // foo\**\bar // // back into remainingWildcardDirectory. // This is a performance optimization. We don't want to enumerate everything if we // don't have to. recursionState.RemainingWildcardDirectory = recursionState.RemainingWildcardDirectory.Substring(indexOfNextSlash + 1); } } ret.RemainingWildcardDirectory = recursionState.RemainingWildcardDirectory; ret.Subdirs = getFileSystemEntries(FileSystemEntity.Directories, recursionState.BaseDirectory, pattern, null, false); } return ret; } /// <summary> /// Given a file spec, create a regular expression that will match that /// file spec. /// /// PERF WARNING: this method is called in performance-critical /// scenarios, so keep it fast and cheap /// </summary> /// <param name="fixedDirectoryPart">The fixed directory part.</param> /// <param name="wildcardDirectoryPart">The wildcard directory part.</param> /// <param name="filenamePart">The filename part.</param> /// <param name="isLegalFileSpec">Receives whether this pattern is legal or not.</param> /// <returns>The regular expression string.</returns> private static string RegularExpressionFromFileSpec ( string fixedDirectoryPart, string wildcardDirectoryPart, string filenamePart, out bool isLegalFileSpec ) { isLegalFileSpec = true; /* * The code below uses tags in the form <:tag:> to encode special information * while building the regular expression. * * This format was chosen because it's not a legal form for filespecs. If the * filespec comes in with either "<:" or ":>", return isLegalFileSpec=false to * prevent intrusion into the special processing. */ if ((fixedDirectoryPart.IndexOf("<:", StringComparison.Ordinal) != -1) || (fixedDirectoryPart.IndexOf(":>", StringComparison.Ordinal) != -1) || (wildcardDirectoryPart.IndexOf("<:", StringComparison.Ordinal) != -1) || (wildcardDirectoryPart.IndexOf(":>", StringComparison.Ordinal) != -1) || (filenamePart.IndexOf("<:", StringComparison.Ordinal) != -1) || (filenamePart.IndexOf(":>", StringComparison.Ordinal) != -1)) { isLegalFileSpec = false; return String.Empty; } /* * Its not legal for there to be a ".." after a wildcard. */ if (wildcardDirectoryPart.Contains(dotdot)) { isLegalFileSpec = false; return String.Empty; } /* * Trailing dots in file names have to be treated specially. * We want: * * *. to match foo * * but 'foo' doesn't have a trailing '.' so we need to handle this while still being careful * not to match 'foo.txt' */ if (filenamePart.EndsWith(".", StringComparison.Ordinal)) { filenamePart = filenamePart.Replace("*", "<:anythingbutdot:>"); filenamePart = filenamePart.Replace("?", "<:anysinglecharacterbutdot:>"); filenamePart = filenamePart.Substring(0, filenamePart.Length - 1); } /* * Now, build up the starting filespec but put tags in to identify where the fixedDirectory, * wildcardDirectory and filenamePart are. Also tag the beginning of the line and the end of * the line, so that we can identify patterns by whether they're on one end or the other. */ StringBuilder matchFileExpression = new StringBuilder(); matchFileExpression.Append("<:bol:>"); matchFileExpression.Append("<:fixeddir:>").Append(fixedDirectoryPart).Append("<:endfixeddir:>"); matchFileExpression.Append("<:wildcarddir:>").Append(wildcardDirectoryPart).Append("<:endwildcarddir:>"); matchFileExpression.Append("<:filename:>").Append(filenamePart).Append("<:endfilename:>"); matchFileExpression.Append("<:eol:>"); /* * Call out our special matching characters. */ foreach (var separator in directorySeparatorStrings) { matchFileExpression.Replace(separator, "<:dirseparator:>"); } /* * Capture the leading \\ in UNC paths, so that the doubled slash isn't * reduced in a later step. */ matchFileExpression.Replace("<:fixeddir:><:dirseparator:><:dirseparator:>", "<:fixeddir:><:uncslashslash:>"); /* * Iteratively reduce four cases involving directory separators * * (1) <:dirseparator:>.<:dirseparator:> -> <:dirseparator:> * This is an identity, so for example, these two are equivalent, * * dir1\.\dir2 == dir1\dir2 * * (2) <:dirseparator:><:dirseparator:> -> <:dirseparator:> * Double directory separators are treated as a single directory separator, * so, for example, this is an identity: * * f:\dir1\\dir2 == f:\dir1\dir2 * * The single exemption is for UNC path names, like this: * * \\server\share != \server\share * * This case is handled by the <:uncslashslash:> which was substituted in * a prior step. * * (3) <:fixeddir:>.<:dirseparator:>.<:dirseparator:> -> <:fixeddir:>.<:dirseparator:> * A ".\" at the beginning of a line is equivalent to nothing, so: * * .\.\dir1\file.txt == .\dir1\file.txt * * (4) <:dirseparator:>.<:eol:> -> <:eol:> * A "\." at the end of a line is equivalent to nothing, so: * * dir1\dir2\. == dir1\dir2 * */ int sizeBefore; do { sizeBefore = matchFileExpression.Length; // NOTE: all these replacements will necessarily reduce the expression length i.e. length will either reduce or // stay the same through this loop matchFileExpression.Replace("<:dirseparator:>.<:dirseparator:>", "<:dirseparator:>"); matchFileExpression.Replace("<:dirseparator:><:dirseparator:>", "<:dirseparator:>"); matchFileExpression.Replace("<:fixeddir:>.<:dirseparator:>.<:dirseparator:>", "<:fixeddir:>.<:dirseparator:>"); matchFileExpression.Replace("<:dirseparator:>.<:endfilename:>", "<:endfilename:>"); matchFileExpression.Replace("<:filename:>.<:endfilename:>", "<:filename:><:endfilename:>"); ErrorUtilities.VerifyThrow(matchFileExpression.Length <= sizeBefore, "Expression reductions cannot increase the length of the expression."); } while (matchFileExpression.Length < sizeBefore); /* * Collapse **\** into **. */ do { sizeBefore = matchFileExpression.Length; matchFileExpression.Replace(recursiveDirectoryMatch + "<:dirseparator:>" + recursiveDirectoryMatch, recursiveDirectoryMatch); ErrorUtilities.VerifyThrow(matchFileExpression.Length <= sizeBefore, "Expression reductions cannot increase the length of the expression."); } while (matchFileExpression.Length < sizeBefore); /* * Call out legal recursion operators: * * fixed-directory + **\ * \**\ * **\** * */ do { sizeBefore = matchFileExpression.Length; matchFileExpression.Replace("<:dirseparator:>" + recursiveDirectoryMatch + "<:dirseparator:>", "<:middledirs:>"); matchFileExpression.Replace("<:wildcarddir:>" + recursiveDirectoryMatch + "<:dirseparator:>", "<:wildcarddir:><:leftdirs:>"); ErrorUtilities.VerifyThrow(matchFileExpression.Length <= sizeBefore, "Expression reductions cannot increase the length of the expression."); } while (matchFileExpression.Length < sizeBefore); /* * By definition, "**" must appear alone between directory slashes. If there is any remaining "**" then this is not * a valid filespec. */ // NOTE: this condition is evaluated left-to-right -- this is important because we want the length BEFORE stripping // any "**"s remaining in the expression if (matchFileExpression.Length > matchFileExpression.Replace(recursiveDirectoryMatch, null).Length) { isLegalFileSpec = false; return String.Empty; } /* * Remaining call-outs not involving "**" */ matchFileExpression.Replace("*.*", "<:anynonseparator:>"); matchFileExpression.Replace("*", "<:anynonseparator:>"); matchFileExpression.Replace("?", "<:singlecharacter:>"); /* * Escape all special characters defined for regular expresssions. */ matchFileExpression.Replace("\\", "\\\\"); // Must be first. matchFileExpression.Replace("$", "\\$"); matchFileExpression.Replace("(", "\\("); matchFileExpression.Replace(")", "\\)"); matchFileExpression.Replace("*", "\\*"); matchFileExpression.Replace("+", "\\+"); matchFileExpression.Replace(".", "\\."); matchFileExpression.Replace("[", "\\["); matchFileExpression.Replace("?", "\\?"); matchFileExpression.Replace("^", "\\^"); matchFileExpression.Replace("{", "\\{"); matchFileExpression.Replace("|", "\\|"); /* * Now, replace call-outs with their regex equivalents. */ matchFileExpression.Replace("<:middledirs:>", "((/)|(\\\\)|(/.*/)|(/.*\\\\)|(\\\\.*\\\\)|(\\\\.*/))"); matchFileExpression.Replace("<:leftdirs:>", "((.*/)|(.*\\\\)|())"); matchFileExpression.Replace("<:rightdirs:>", ".*"); matchFileExpression.Replace("<:anything:>", ".*"); matchFileExpression.Replace("<:anythingbutdot:>", "[^\\.]*"); matchFileExpression.Replace("<:anysinglecharacterbutdot:>", "[^\\.]."); matchFileExpression.Replace("<:anynonseparator:>", "[^/\\\\]*"); matchFileExpression.Replace("<:singlecharacter:>", "."); matchFileExpression.Replace("<:dirseparator:>", "[/\\\\]+"); matchFileExpression.Replace("<:uncslashslash:>", @"\\\\"); matchFileExpression.Replace("<:bol:>", "^"); matchFileExpression.Replace("<:eol:>", "$"); matchFileExpression.Replace("<:fixeddir:>", "(?<FIXEDDIR>"); matchFileExpression.Replace("<:endfixeddir:>", ")"); matchFileExpression.Replace("<:wildcarddir:>", "(?<WILDCARDDIR>"); matchFileExpression.Replace("<:endwildcarddir:>", ")"); matchFileExpression.Replace("<:filename:>", "(?<FILENAME>"); matchFileExpression.Replace("<:endfilename:>", ")"); return matchFileExpression.ToString(); } /// <summary> /// Given a filespec, get the information needed for file matching. /// </summary> /// <param name="filespec">The filespec.</param> /// <param name="regexFileMatch">Receives the regular expression.</param> /// <param name="needsRecursion">Receives the flag that is true if recursion is required.</param> /// <param name="isLegalFileSpec">Receives the flag that is true if the filespec is legal.</param> /// <param name="getFileSystemEntries">Delegate.</param> internal static void GetFileSpecInfo ( string filespec, out Regex regexFileMatch, out bool needsRecursion, out bool isLegalFileSpec, GetFileSystemEntries getFileSystemEntries ) { string fixedDirectoryPart; string wildcardDirectoryPart; string filenamePart; string matchFileExpression; GetFileSpecInfo(filespec, out fixedDirectoryPart, out wildcardDirectoryPart, out filenamePart, out matchFileExpression, out needsRecursion, out isLegalFileSpec, getFileSystemEntries); if (isLegalFileSpec) { regexFileMatch = new Regex(matchFileExpression, RegexOptions.IgnoreCase); } else { regexFileMatch = null; } } /// <summary> /// Given a filespec, get the information needed for file matching. /// </summary> /// <param name="filespec">The filespec.</param> /// <param name="fixedDirectoryPart">Receives the fixed directory part.</param> /// <param name="wildcardDirectoryPart">Receives the wildcard directory part.</param> /// <param name="filenamePart">Receives the filename part.</param> /// <param name="matchFileExpression">Receives the regular expression.</param> /// <param name="needsRecursion">Receives the flag that is true if recursion is required.</param> /// <param name="isLegalFileSpec">Receives the flag that is true if the filespec is legal.</param> /// <param name="getFileSystemEntries">Delegate.</param> private static void GetFileSpecInfo ( string filespec, out string fixedDirectoryPart, out string wildcardDirectoryPart, out string filenamePart, out string matchFileExpression, out bool needsRecursion, out bool isLegalFileSpec, GetFileSystemEntries getFileSystemEntries ) { isLegalFileSpec = true; needsRecursion = false; fixedDirectoryPart = String.Empty; wildcardDirectoryPart = String.Empty; filenamePart = String.Empty; matchFileExpression = null; // bail out if filespec contains illegal characters if (-1 != filespec.IndexOfAny(s_invalidPathChars)) { isLegalFileSpec = false; return; } /* * Check for patterns in the filespec that are explicitly illegal. * * Any path with "..." in it is illegal. */ if (-1 != filespec.IndexOf("...", StringComparison.Ordinal)) { isLegalFileSpec = false; return; } /* * If there is a ':' anywhere but the second character, this is an illegal pattern. * Catches this case among others, * * http://www.website.com * */ int rightmostColon = filespec.LastIndexOf(":", StringComparison.Ordinal); if ( -1 != rightmostColon && 1 != rightmostColon ) { isLegalFileSpec = false; return; } /* * Now break up the filespec into constituent parts--fixed, wildcard and filename. */ SplitFileSpec(filespec, out fixedDirectoryPart, out wildcardDirectoryPart, out filenamePart, getFileSystemEntries); /* * Get a regular expression for matching files that will be found. */ matchFileExpression = RegularExpressionFromFileSpec(fixedDirectoryPart, wildcardDirectoryPart, filenamePart, out isLegalFileSpec); /* * Was the filespec valid? If not, then just return now. */ if (!isLegalFileSpec) { return; } /* * Determine whether recursion will be required. */ needsRecursion = (wildcardDirectoryPart.Length != 0); } /// <summary> /// The results of a match between a filespec and a file name. /// </summary> internal sealed class Result { /// <summary> /// Default constructor. /// </summary> internal Result() { // do nothing } internal bool isLegalFileSpec; // initially false internal bool isMatch; // initially false internal bool isFileSpecRecursive; // initially false internal string fixedDirectoryPart = String.Empty; internal string wildcardDirectoryPart = String.Empty; internal string filenamePart = String.Empty; } /// <summary> /// Given a pattern (filespec) and a candidate filename (fileToMatch) /// return matching information. /// </summary> /// <param name="filespec">The filespec.</param> /// <param name="fileToMatch">The candidate to match against.</param> /// <returns>The result class.</returns> internal static Result FileMatch ( string filespec, string fileToMatch ) { Result matchResult = new Result(); fileToMatch = GetLongPathName(fileToMatch, s_defaultGetFileSystemEntries); Regex regexFileMatch; GetFileSpecInfo ( filespec, out regexFileMatch, out matchResult.isFileSpecRecursive, out matchResult.isLegalFileSpec, s_defaultGetFileSystemEntries ); if (matchResult.isLegalFileSpec) { Match match = regexFileMatch.Match(fileToMatch); matchResult.isMatch = match.Success; if (matchResult.isMatch) { matchResult.fixedDirectoryPart = match.Groups["FIXEDDIR"].Value; matchResult.wildcardDirectoryPart = match.Groups["WILDCARDDIR"].Value; matchResult.filenamePart = match.Groups["FILENAME"].Value; } } return matchResult; } /// <summary> /// Given a filespec, find the files that match. /// Will never throw IO exceptions: if there is no match, returns the input verbatim. /// </summary> /// <param name="projectDirectoryUnescaped">The project directory.</param> /// <param name="filespecUnescaped">Get files that match the given file spec.</param> /// <param name="excludeSpecsUnescaped">Exclude files that match this file spec.</param> /// <returns>The array of files.</returns> internal static string[] GetFiles ( string projectDirectoryUnescaped, string filespecUnescaped, IEnumerable<string> excludeSpecsUnescaped = null ) { string[] files = GetFiles(projectDirectoryUnescaped, filespecUnescaped, excludeSpecsUnescaped, s_defaultGetFileSystemEntries, s_defaultDirectoryExists); return files; } enum SearchAction { RunSearch, ReturnFileSpec, ReturnEmptyList, } static SearchAction GetFileSearchData(string projectDirectoryUnescaped, string filespecUnescaped, GetFileSystemEntries getFileSystemEntries, DirectoryExists directoryExists, out bool stripProjectDirectory, out RecursionState result) { stripProjectDirectory = false; result = new RecursionState(); string fixedDirectoryPart; string wildcardDirectoryPart; string filenamePart; string matchFileExpression; bool needsRecursion; bool isLegalFileSpec; GetFileSpecInfo ( filespecUnescaped, out fixedDirectoryPart, out wildcardDirectoryPart, out filenamePart, out matchFileExpression, out needsRecursion, out isLegalFileSpec, getFileSystemEntries ); /* * If the filespec is invalid, then just return now. */ if (!isLegalFileSpec) { return SearchAction.ReturnFileSpec; } // The projectDirectory is not null only if we are running the evaluation from // inside the engine (i.e. not from a task) if (projectDirectoryUnescaped != null) { if (fixedDirectoryPart != null) { string oldFixedDirectoryPart = fixedDirectoryPart; try { fixedDirectoryPart = Path.Combine(projectDirectoryUnescaped, fixedDirectoryPart); } catch (ArgumentException) { return SearchAction.ReturnEmptyList; } stripProjectDirectory = !String.Equals(fixedDirectoryPart, oldFixedDirectoryPart, StringComparison.OrdinalIgnoreCase); } else { fixedDirectoryPart = projectDirectoryUnescaped; stripProjectDirectory = true; } } /* * If the fixed directory part doesn't exist, then this means no files should be * returned. */ if (fixedDirectoryPart.Length > 0 && !directoryExists(fixedDirectoryPart)) { return SearchAction.ReturnEmptyList; } // determine if we need to use the regular expression to match the files // PERF NOTE: Constructing a Regex object is expensive, so we avoid it whenever possible bool matchWithRegex = // if we have a directory specification that uses wildcards, and (wildcardDirectoryPart.Length > 0) && // the specification is not a simple "**" !IsRecursiveDirectoryMatch(wildcardDirectoryPart); // then we need to use the regular expression // if we're not using the regular expression, get the file pattern extension string extensionPart = matchWithRegex ? null : Path.GetExtension(filenamePart); // check if the file pattern would cause Windows to match more loosely on the extension // NOTE: Windows matches loosely in two cases (in the absence of the * wildcard in the extension): // 1) if the extension ends with the ? wildcard, it matches files with shorter extensions also e.g. "file.tx?" would // match both "file.txt" and "file.tx" // 2) if the extension is three characters, and the filename contains the * wildcard, it matches files with longer // extensions that start with the same three characters e.g. "*.htm" would match both "file.htm" and "file.html" bool needToEnforceExtensionLength = (extensionPart != null) && (extensionPart.IndexOf('*') == -1) && (extensionPart.EndsWith("?", StringComparison.Ordinal) || ((extensionPart.Length == (3 + 1 /* +1 for the period */)) && (filenamePart.IndexOf('*') != -1))); var searchData = new FilesSearchData( // if using the regular expression, ignore the file pattern (matchWithRegex ? null : filenamePart), (needToEnforceExtensionLength ? extensionPart.Length : 0), // if using the file pattern, ignore the regular expression (matchWithRegex ? new Regex(matchFileExpression, RegexOptions.IgnoreCase) : null), needsRecursion); result.SearchData = searchData; result.BaseDirectory = fixedDirectoryPart; result.RemainingWildcardDirectory = wildcardDirectoryPart; return SearchAction.RunSearch; } static string[] CreateArrayWithSingleItemIfNotExcluded(string filespecUnescaped, IEnumerable<string> excludeSpecsUnescaped) { if (excludeSpecsUnescaped != null) { foreach (string excludeSpec in excludeSpecsUnescaped) { // The FileMatch method always creates a Regex to check if the file matches the pattern // Creating a Regex is relatively expensive, so we may want to avoid doing so if possible Result match = FileMatch(excludeSpec, filespecUnescaped); if (match.isLegalFileSpec && match.isMatch) { // This file is excluded return new string[0]; } } } return new string[] { filespecUnescaped }; } /// <summary> /// Given a filespec, find the files that match. /// Will never throw IO exceptions: if there is no match, returns the input verbatim. /// </summary> /// <param name="projectDirectoryUnescaped">The project directory.</param> /// <param name="filespecUnescaped">Get files that match the given file spec.</param> /// <param name="excludeSpecsUnescaped">Exclude files that match this file spec.</param> /// <param name="getFileSystemEntries">Get files that match the given file spec.</param> /// <param name="directoryExists">Determine whether a directory exists.</param> /// <returns>The array of files.</returns> internal static string[] GetFiles ( string projectDirectoryUnescaped, string filespecUnescaped, IEnumerable<string> excludeSpecsUnescaped, GetFileSystemEntries getFileSystemEntries, DirectoryExists directoryExists ) { // For performance. Short-circuit iff there is no wildcard. // Perf Note: Doing a [Last]IndexOfAny(...) is much faster than compiling a // regular expression that does the same thing, regardless of whether // filespec contains one of the characters. // Choose LastIndexOfAny instead of IndexOfAny because it seems more likely // that wildcards will tend to be towards the right side. if (!HasWildcards(filespecUnescaped)) { return CreateArrayWithSingleItemIfNotExcluded(filespecUnescaped, excludeSpecsUnescaped); } // UNDONE (perf): Short circuit the complex processing when we only have a path and a wildcarded filename /* * Analyze the file spec and get the information we need to do the matching. */ bool stripProjectDirectory; RecursionState state; var action = GetFileSearchData(projectDirectoryUnescaped, filespecUnescaped, getFileSystemEntries, directoryExists, out stripProjectDirectory, out state); if (action == SearchAction.ReturnEmptyList) { return new string[0]; } else if (action == SearchAction.ReturnFileSpec) { return CreateArrayWithSingleItemIfNotExcluded(filespecUnescaped, excludeSpecsUnescaped); } else if (action != SearchAction.RunSearch) { // This means the enum value wasn't valid (or a new one was added without updating code correctly) throw new NotSupportedException(action.ToString()); } List<RecursionState> searchesToExclude = null; // Exclude searches which will become active when the recursive search reaches their BaseDirectory. // The BaseDirectory of the exclude search is the key for this dictionary. Dictionary<string, List<RecursionState>> searchesToExcludeInSubdirs = null; HashSet<string> resultsToExclude = null; if (excludeSpecsUnescaped != null) { searchesToExclude = new List<RecursionState>(); foreach (string excludeSpec in excludeSpecsUnescaped) { // This is ignored, we always use the include pattern's value for stripProjectDirectory bool excludeStripProjectDirectory; RecursionState excludeState; var excludeAction = GetFileSearchData(projectDirectoryUnescaped, excludeSpec, getFileSystemEntries, directoryExists, out excludeStripProjectDirectory, out excludeState); if (excludeAction == SearchAction.ReturnFileSpec) { if (resultsToExclude == null) { resultsToExclude = new HashSet<string>(); } resultsToExclude.Add(excludeSpec); } else if (excludeAction == SearchAction.ReturnEmptyList) { // Nothing to do continue; } else if (excludeAction != SearchAction.RunSearch) { // This means the enum value wasn't valid (or a new one was added without updating code correctly) throw new NotSupportedException(excludeAction.ToString()); } var excludeBaseDirectoryNormalized = excludeState.BaseDirectory.NormalizeForPathComparison(); var includeBaseDirectoryNormalized = state.BaseDirectory.NormalizeForPathComparison(); if (excludeBaseDirectoryNormalized != includeBaseDirectoryNormalized) { // What to do if the BaseDirectory for the exclude search doesn't match the one for inclusion? // - If paths don't match (one isn't a prefix of the other), then ignore the exclude search. Examples: // - c:\Foo\ - c:\Bar\ // - c:\Foo\Bar\ - C:\Foo\Baz\ // - c:\Foo\ - c:\Foo2\ if (excludeBaseDirectoryNormalized.Length == includeBaseDirectoryNormalized.Length) { // Same length, but different paths. Ignore this exclude search continue; } else if (excludeBaseDirectoryNormalized.Length > includeBaseDirectoryNormalized.Length) { if (!excludeBaseDirectoryNormalized.StartsWith(includeBaseDirectoryNormalized)) { // Exclude path is longer, but doesn't start with include path. So ignore it. continue; } // - The exclude BaseDirectory is somewhere under the include BaseDirectory. So // keep the exclude search, but don't do any processing on it while recursing until the baseDirectory // in the recursion matches the exclude BaseDirectory. Examples: // - Include - Exclude // - C:\git\msbuild\ - c:\git\msbuild\obj\ // - C:\git\msbuild\ - c:\git\msbuild\src\Common\ if (searchesToExcludeInSubdirs == null) { searchesToExcludeInSubdirs = new Dictionary<string, List<RecursionState>>(); } List<RecursionState> listForSubdir; if (!searchesToExcludeInSubdirs.TryGetValue(excludeBaseDirectoryNormalized, out listForSubdir)) { listForSubdir = new List<RecursionState>(); // The normalization fixes https://github.com/Microsoft/msbuild/issues/917 // and is a partial fix for https://github.com/Microsoft/msbuild/issues/724 searchesToExcludeInSubdirs[excludeBaseDirectoryNormalized] = listForSubdir; } listForSubdir.Add(excludeState); } else { // Exclude base directory length is less than include base directory length. if (!state.BaseDirectory.StartsWith(excludeState.BaseDirectory)) { // Include path is longer, but doesn't start with the exclude path. So ignore exclude path // (since it won't match anything under the include path) continue; } // Now check the wildcard part if (excludeState.RemainingWildcardDirectory.Length == 0) { // The wildcard part is empty, so ignore the exclude search, as it's looking for files non-recursively // in a folder higher up than the include baseDirectory. // Example: include="c:\git\msbuild\src\Framework\**\*.cs" exclude="c:\git\msbuild\*.cs" continue; } else if (IsRecursiveDirectoryMatch(excludeState.RemainingWildcardDirectory)) { // The wildcard part is exactly "**\", so the exclude pattern will apply to everything in the include // pattern, so simply update the exclude's BaseDirectory to be the same as the include baseDirectory // Example: include="c:\git\msbuild\src\Framework\**\*.*" exclude="c:\git\msbuild\**\*.bak" excludeState.BaseDirectory = state.BaseDirectory; searchesToExclude.Add(excludeState); } else { // The wildcard part is non-empty and not "**\", so we will need to match it with a Regex. Fortunately // these conditions mean that it needs to be matched with a Regex anyway, so here we will update the // BaseDirectory to be the same as the exclude BaseDirectory, and change the wildcard part to be "**\" // because we don't know where the different parts of the exclude wildcard part would be matched. // Example: include="c:\git\msbuild\src\Framework\**\*.*" exclude="c:\git\msbuild\**\bin\**\*.*" Debug.Assert(excludeState.SearchData.RegexFileMatch != null, "Expected Regex to be used for exclude file matching"); excludeState.BaseDirectory = state.BaseDirectory; excludeState.RemainingWildcardDirectory = recursiveDirectoryMatch + s_directorySeparator; searchesToExclude.Add(excludeState); } } } else { searchesToExclude.Add(excludeState); } } } if (searchesToExclude != null && searchesToExclude.Count == 0) { searchesToExclude = null; } /* * Even though we return a string[] we work internally with an IList. * This is because it's cheaper to add items to an IList and this code * might potentially do a lot of that. */ var listOfFiles = new List<string>(); /* * Now get the files that match, starting at the lowest fixed directory. */ try { GetFilesRecursive( listOfFiles, state, projectDirectoryUnescaped, stripProjectDirectory, getFileSystemEntries, searchesToExclude, searchesToExcludeInSubdirs); } catch (Exception ex) when (ExceptionHandling.IsIoRelatedException(ex)) { // Assume it's not meant to be a path return CreateArrayWithSingleItemIfNotExcluded(filespecUnescaped, excludeSpecsUnescaped); } /* * Build the return array. */ var files = resultsToExclude != null ? listOfFiles.Where(f => !resultsToExclude.Contains(f)).ToArray() : listOfFiles.ToArray(); return files; } private static bool IsRecursiveDirectoryMatch(string path) => path.TrimTrailingSlashes() == recursiveDirectoryMatch; } }
44.880814
208
0.53177
[ "MIT" ]
azurechamp/msbuild
src/Shared/FileMatcher.cs
77,197
C#
using Pathfinding.RVO; using UnityEditor; namespace Pathfinding { [CustomEditor(typeof(RVOSquareObstacle))] [CanEditMultipleObjects] public class RVOSquareObstacleEditor : Editor { public override void OnInspectorGUI() { DrawDefaultInspector(); } } }
19.25
49
0.662338
[ "MIT" ]
baidenx7/Elebris-Adventures
Assets/AstarPathfindingProject/Editor/RVOSquareObstacleEditor.cs
308
C#
using Cosmos.Logging.Events; namespace Cosmos.Logging.Sinks.NLog.Internals { internal static class LogLevelSwitcher { public static global::NLog.LogLevel Switch(LogEventLevel level) { switch (level) { case LogEventLevel.Verbose: return global::NLog.LogLevel.Trace; case LogEventLevel.Debug: return global::NLog.LogLevel.Debug; case LogEventLevel.Information: return global::NLog.LogLevel.Info; case LogEventLevel.Warning: return global::NLog.LogLevel.Warn; case LogEventLevel.Error: return global::NLog.LogLevel.Error; case LogEventLevel.Fatal: return global::NLog.LogLevel.Fatal; case LogEventLevel.Off: return global::NLog.LogLevel.Off; default: return global::NLog.LogLevel.Info; } } } }
39.538462
73
0.544747
[ "Apache-2.0" ]
CosmosLoops/Cosmos
src/Cosmos.Logging.Sinks.NLog/Cosmos/Logging/Sinks/NLog/Internals/LogLevelSwitcher.cs
1,030
C#
using Sce.Atf; namespace Razix { public static class RZCEResources { /* Razix logo 32x32 icon */ [ImageResource("RazixCodeEditorLogo.ico")] public static readonly string RazixCodeEditorLogo; [ImageResource("RazixAtf.ico")] public static readonly string RazixAtf; private const string ResourcePath = "Razix.Resources."; static RZCEResources() { ResourceUtil.Register(typeof(Resources), ResourcePath); } } }
23
67
0.634387
[ "Apache-2.0" ]
Pikachuxxxx/RazixCodeEditor
src/RZCEResources.cs
506
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; namespace Microsoft.Diagnostics.Runtime { /// <summary> /// Represents an instance of a type which inherits from <see cref="ValueType"/>. /// </summary> public readonly struct ClrValueType : IAddressableTypedEntity { private IDataReader DataReader => GetTypeOrThrow().ClrObjectHelpers.DataReader; private readonly bool _interior; /// <summary> /// Gets the address of the object. /// </summary> public ulong Address { get; } /// <summary> /// Gets the type of the object. /// </summary> public ClrType? Type { get; } /// <summary> /// Returns whether this ClrValueType has a valid Type. In most normal operations of ClrMD, we will have a /// non-null type. However if we are missing metadata, or in some generic cases we might not be able to /// determine the type of this value type. In those cases, Type? will be null and IsValid will return false. /// </summary> public bool IsValid => Type != null; internal ClrValueType(ulong address, ClrType? type, bool interior) { Address = address; Type = type; _interior = interior; DebugOnly.Assert(type != null && type.IsValueType); } /// <summary> /// Gets the given object reference field from this ClrObject. /// </summary> /// <param name="fieldName">The name of the field to retrieve.</param> /// <returns>A ClrObject of the given field.</returns> /// <exception cref="ArgumentException"> /// The given field does not exist in the object. /// -or- /// The given field was not an object reference. /// </exception> public ClrObject ReadObjectField(string fieldName) { ClrType type = GetTypeOrThrow(); ClrInstanceField? field = type.GetFieldByName(fieldName); if (field is null) throw new ArgumentException($"Type '{type.Name}' does not contain a field named '{fieldName}'"); if (!field.IsObjectReference) throw new ArgumentException($"Field '{type.Name}.{fieldName}' is not an object reference."); ClrHeap heap = type.Heap; ulong addr = field.GetAddress(Address, _interior); if (!DataReader.ReadPointer(addr, out ulong obj)) return default; return heap.GetObject(obj); } /// <summary> /// Gets the value of a primitive field. This will throw an InvalidCastException if the type parameter /// does not match the field's type. /// </summary> /// <typeparam name="T">The type of the field itself.</typeparam> /// <param name="fieldName">The name of the field.</param> /// <returns>The value of this field.</returns> public T ReadField<T>(string fieldName) where T : unmanaged { ClrType type = GetTypeOrThrow(); ClrInstanceField? field = type.GetFieldByName(fieldName); if (field is null) throw new ArgumentException($"Type '{type.Name}' does not contain a field named '{fieldName}'"); object value = field.Read<T>(Address, _interior); return (T)value; } /// <summary> /// </summary> /// <param name="fieldName"></param> /// <returns></returns> public ClrValueType ReadValueTypeField(string fieldName) { ClrType type = GetTypeOrThrow(); ClrInstanceField? field = type.GetFieldByName(fieldName); if (field is null) throw new ArgumentException($"Type '{type.Name}' does not contain a field named '{fieldName}'"); if (!field.IsValueType) throw new ArgumentException($"Field '{type.Name}.{fieldName}' is not a ValueClass."); if (field.Type is null) throw new InvalidOperationException("Field does not have an associated class."); ulong addr = field.GetAddress(Address, _interior); return new ClrValueType(addr, field.Type, true); } /// <summary> /// Gets a string field from the object. Note that the type must match exactly, as this method /// will not do type coercion. /// </summary> /// <param name="fieldName">The name of the field to get the value for.</param> /// <param name="maxLength">The maximum length of the string returned. Warning: If the DataTarget /// being inspected has corrupted or an inconsistent heap state, the length of a string may be /// incorrect, leading to OutOfMemory and other failures.</param> /// <returns>The value of the given field.</returns> /// <exception cref="ArgumentException">No field matches the given name.</exception> /// <exception cref="InvalidOperationException">The field is not a string.</exception> public string? ReadStringField(string fieldName, int maxLength = 4096) { ulong address = GetFieldAddress(fieldName, ClrElementType.String, "string"); if (!DataReader.ReadPointer(address, out ulong str)) return null; if (str == 0) return null; ClrObject obj = new ClrObject(str, GetTypeOrThrow().Heap.StringType); return obj.AsString(maxLength); } private ulong GetFieldAddress(string fieldName, ClrElementType element, string typeName) { ClrType type = GetTypeOrThrow(); ClrInstanceField? field = type.GetFieldByName(fieldName); if (field is null) throw new ArgumentException($"Type '{type.Name}' does not contain a field named '{fieldName}'"); if (field.ElementType != element) throw new InvalidOperationException($"Field '{type.Name}.{fieldName}' is not of type '{typeName}'."); ulong address = field.GetAddress(Address, _interior); return address; } public bool Equals(IAddressableTypedEntity? other) => other != null && Address == other.Address && Type == other.Type; private ClrType GetTypeOrThrow() { if (Type is null) throw new InvalidOperationException($"Unknown type of value at {Address:x}."); return Type; } } }
41.670807
117
0.600388
[ "MIT" ]
Bhaskers-Blu-Org2/clrmd
src/Microsoft.Diagnostics.Runtime/src/Common/ClrValueType.cs
6,711
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WarGameUpdate { public partial class Default { /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// PlayButton control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button PlayButton; /// <summary> /// resultLabel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label resultLabel; } }
33.44186
85
0.486092
[ "MIT" ]
ademilua/WarCardGame
Default.aspx.designer.cs
1,440
C#
using Javeriana.Pica.ApplicationCore.Entities; namespace Javeriana.Pica.UnitTests.Builders { public class AddressBuilder { private Address _address; public string TestStreet => "123 Main St."; public string TestCity => "Kent"; public string TestState => "OH"; public string TestCountry => "USA"; public string TestZipCode => "44240"; public AddressBuilder() { _address = WithDefaultValues(); } public Address Build() { return _address; } public Address WithDefaultValues() { _address = new Address(TestStreet, TestCity, TestState, TestCountry, TestZipCode); return _address; } } }
26.344828
94
0.585079
[ "MIT" ]
andresalarconfranco/talleres
tests/UnitTests/Builders/AddressBuilder.cs
766
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/SyncMgr.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="SyncMgrFolder" /> struct.</summary> public static unsafe partial class SyncMgrFolderTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="SyncMgrFolder" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(SyncMgrFolder).GUID, Is.EqualTo(IID_SyncMgrFolder)); } /// <summary>Validates that the <see cref="SyncMgrFolder" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<SyncMgrFolder>(), Is.EqualTo(sizeof(SyncMgrFolder))); } /// <summary>Validates that the <see cref="SyncMgrFolder" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(SyncMgrFolder).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="SyncMgrFolder" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(SyncMgrFolder), Is.EqualTo(1)); } }
36.25
145
0.705329
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/Windows/um/SyncMgr/SyncMgrFolderTests.cs
1,597
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the eks-2017-11-01.normal.json service model. */ using System; using Amazon.Runtime; namespace Amazon.EKS { /// <summary> /// Constants used for properties of type AddonIssueCode. /// </summary> public class AddonIssueCode : ConstantClass { /// <summary> /// Constant AccessDenied for AddonIssueCode /// </summary> public static readonly AddonIssueCode AccessDenied = new AddonIssueCode("AccessDenied"); /// <summary> /// Constant AdmissionRequestDenied for AddonIssueCode /// </summary> public static readonly AddonIssueCode AdmissionRequestDenied = new AddonIssueCode("AdmissionRequestDenied"); /// <summary> /// Constant ClusterUnreachable for AddonIssueCode /// </summary> public static readonly AddonIssueCode ClusterUnreachable = new AddonIssueCode("ClusterUnreachable"); /// <summary> /// Constant ConfigurationConflict for AddonIssueCode /// </summary> public static readonly AddonIssueCode ConfigurationConflict = new AddonIssueCode("ConfigurationConflict"); /// <summary> /// Constant InsufficientNumberOfReplicas for AddonIssueCode /// </summary> public static readonly AddonIssueCode InsufficientNumberOfReplicas = new AddonIssueCode("InsufficientNumberOfReplicas"); /// <summary> /// Constant InternalFailure for AddonIssueCode /// </summary> public static readonly AddonIssueCode InternalFailure = new AddonIssueCode("InternalFailure"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public AddonIssueCode(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static AddonIssueCode FindValue(string value) { return FindValue<AddonIssueCode>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator AddonIssueCode(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type AddonStatus. /// </summary> public class AddonStatus : ConstantClass { /// <summary> /// Constant ACTIVE for AddonStatus /// </summary> public static readonly AddonStatus ACTIVE = new AddonStatus("ACTIVE"); /// <summary> /// Constant CREATE_FAILED for AddonStatus /// </summary> public static readonly AddonStatus CREATE_FAILED = new AddonStatus("CREATE_FAILED"); /// <summary> /// Constant CREATING for AddonStatus /// </summary> public static readonly AddonStatus CREATING = new AddonStatus("CREATING"); /// <summary> /// Constant DEGRADED for AddonStatus /// </summary> public static readonly AddonStatus DEGRADED = new AddonStatus("DEGRADED"); /// <summary> /// Constant DELETE_FAILED for AddonStatus /// </summary> public static readonly AddonStatus DELETE_FAILED = new AddonStatus("DELETE_FAILED"); /// <summary> /// Constant DELETING for AddonStatus /// </summary> public static readonly AddonStatus DELETING = new AddonStatus("DELETING"); /// <summary> /// Constant UPDATING for AddonStatus /// </summary> public static readonly AddonStatus UPDATING = new AddonStatus("UPDATING"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public AddonStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static AddonStatus FindValue(string value) { return FindValue<AddonStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator AddonStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type AMITypes. /// </summary> public class AMITypes : ConstantClass { /// <summary> /// Constant AL2_ARM_64 for AMITypes /// </summary> public static readonly AMITypes AL2_ARM_64 = new AMITypes("AL2_ARM_64"); /// <summary> /// Constant AL2_x86_64 for AMITypes /// </summary> public static readonly AMITypes AL2_x86_64 = new AMITypes("AL2_x86_64"); /// <summary> /// Constant AL2_x86_64_GPU for AMITypes /// </summary> public static readonly AMITypes AL2_x86_64_GPU = new AMITypes("AL2_x86_64_GPU"); /// <summary> /// Constant CUSTOM for AMITypes /// </summary> public static readonly AMITypes CUSTOM = new AMITypes("CUSTOM"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public AMITypes(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static AMITypes FindValue(string value) { return FindValue<AMITypes>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator AMITypes(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type CapacityTypes. /// </summary> public class CapacityTypes : ConstantClass { /// <summary> /// Constant ON_DEMAND for CapacityTypes /// </summary> public static readonly CapacityTypes ON_DEMAND = new CapacityTypes("ON_DEMAND"); /// <summary> /// Constant SPOT for CapacityTypes /// </summary> public static readonly CapacityTypes SPOT = new CapacityTypes("SPOT"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public CapacityTypes(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static CapacityTypes FindValue(string value) { return FindValue<CapacityTypes>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator CapacityTypes(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ClusterStatus. /// </summary> public class ClusterStatus : ConstantClass { /// <summary> /// Constant ACTIVE for ClusterStatus /// </summary> public static readonly ClusterStatus ACTIVE = new ClusterStatus("ACTIVE"); /// <summary> /// Constant CREATING for ClusterStatus /// </summary> public static readonly ClusterStatus CREATING = new ClusterStatus("CREATING"); /// <summary> /// Constant DELETING for ClusterStatus /// </summary> public static readonly ClusterStatus DELETING = new ClusterStatus("DELETING"); /// <summary> /// Constant FAILED for ClusterStatus /// </summary> public static readonly ClusterStatus FAILED = new ClusterStatus("FAILED"); /// <summary> /// Constant UPDATING for ClusterStatus /// </summary> public static readonly ClusterStatus UPDATING = new ClusterStatus("UPDATING"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ClusterStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ClusterStatus FindValue(string value) { return FindValue<ClusterStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ClusterStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ConfigStatus. /// </summary> public class ConfigStatus : ConstantClass { /// <summary> /// Constant ACTIVE for ConfigStatus /// </summary> public static readonly ConfigStatus ACTIVE = new ConfigStatus("ACTIVE"); /// <summary> /// Constant CREATING for ConfigStatus /// </summary> public static readonly ConfigStatus CREATING = new ConfigStatus("CREATING"); /// <summary> /// Constant DELETING for ConfigStatus /// </summary> public static readonly ConfigStatus DELETING = new ConfigStatus("DELETING"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ConfigStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ConfigStatus FindValue(string value) { return FindValue<ConfigStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ConfigStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ErrorCode. /// </summary> public class ErrorCode : ConstantClass { /// <summary> /// Constant AccessDenied for ErrorCode /// </summary> public static readonly ErrorCode AccessDenied = new ErrorCode("AccessDenied"); /// <summary> /// Constant AdmissionRequestDenied for ErrorCode /// </summary> public static readonly ErrorCode AdmissionRequestDenied = new ErrorCode("AdmissionRequestDenied"); /// <summary> /// Constant ClusterUnreachable for ErrorCode /// </summary> public static readonly ErrorCode ClusterUnreachable = new ErrorCode("ClusterUnreachable"); /// <summary> /// Constant ConfigurationConflict for ErrorCode /// </summary> public static readonly ErrorCode ConfigurationConflict = new ErrorCode("ConfigurationConflict"); /// <summary> /// Constant EniLimitReached for ErrorCode /// </summary> public static readonly ErrorCode EniLimitReached = new ErrorCode("EniLimitReached"); /// <summary> /// Constant InsufficientFreeAddresses for ErrorCode /// </summary> public static readonly ErrorCode InsufficientFreeAddresses = new ErrorCode("InsufficientFreeAddresses"); /// <summary> /// Constant InsufficientNumberOfReplicas for ErrorCode /// </summary> public static readonly ErrorCode InsufficientNumberOfReplicas = new ErrorCode("InsufficientNumberOfReplicas"); /// <summary> /// Constant IpNotAvailable for ErrorCode /// </summary> public static readonly ErrorCode IpNotAvailable = new ErrorCode("IpNotAvailable"); /// <summary> /// Constant NodeCreationFailure for ErrorCode /// </summary> public static readonly ErrorCode NodeCreationFailure = new ErrorCode("NodeCreationFailure"); /// <summary> /// Constant OperationNotPermitted for ErrorCode /// </summary> public static readonly ErrorCode OperationNotPermitted = new ErrorCode("OperationNotPermitted"); /// <summary> /// Constant PodEvictionFailure for ErrorCode /// </summary> public static readonly ErrorCode PodEvictionFailure = new ErrorCode("PodEvictionFailure"); /// <summary> /// Constant SecurityGroupNotFound for ErrorCode /// </summary> public static readonly ErrorCode SecurityGroupNotFound = new ErrorCode("SecurityGroupNotFound"); /// <summary> /// Constant SubnetNotFound for ErrorCode /// </summary> public static readonly ErrorCode SubnetNotFound = new ErrorCode("SubnetNotFound"); /// <summary> /// Constant Unknown for ErrorCode /// </summary> public static readonly ErrorCode Unknown = new ErrorCode("Unknown"); /// <summary> /// Constant VpcIdNotFound for ErrorCode /// </summary> public static readonly ErrorCode VpcIdNotFound = new ErrorCode("VpcIdNotFound"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ErrorCode(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ErrorCode FindValue(string value) { return FindValue<ErrorCode>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ErrorCode(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type FargateProfileStatus. /// </summary> public class FargateProfileStatus : ConstantClass { /// <summary> /// Constant ACTIVE for FargateProfileStatus /// </summary> public static readonly FargateProfileStatus ACTIVE = new FargateProfileStatus("ACTIVE"); /// <summary> /// Constant CREATE_FAILED for FargateProfileStatus /// </summary> public static readonly FargateProfileStatus CREATE_FAILED = new FargateProfileStatus("CREATE_FAILED"); /// <summary> /// Constant CREATING for FargateProfileStatus /// </summary> public static readonly FargateProfileStatus CREATING = new FargateProfileStatus("CREATING"); /// <summary> /// Constant DELETE_FAILED for FargateProfileStatus /// </summary> public static readonly FargateProfileStatus DELETE_FAILED = new FargateProfileStatus("DELETE_FAILED"); /// <summary> /// Constant DELETING for FargateProfileStatus /// </summary> public static readonly FargateProfileStatus DELETING = new FargateProfileStatus("DELETING"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public FargateProfileStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static FargateProfileStatus FindValue(string value) { return FindValue<FargateProfileStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator FargateProfileStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type LogType. /// </summary> public class LogType : ConstantClass { /// <summary> /// Constant Api for LogType /// </summary> public static readonly LogType Api = new LogType("api"); /// <summary> /// Constant Audit for LogType /// </summary> public static readonly LogType Audit = new LogType("audit"); /// <summary> /// Constant Authenticator for LogType /// </summary> public static readonly LogType Authenticator = new LogType("authenticator"); /// <summary> /// Constant ControllerManager for LogType /// </summary> public static readonly LogType ControllerManager = new LogType("controllerManager"); /// <summary> /// Constant Scheduler for LogType /// </summary> public static readonly LogType Scheduler = new LogType("scheduler"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public LogType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static LogType FindValue(string value) { return FindValue<LogType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator LogType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type NodegroupIssueCode. /// </summary> public class NodegroupIssueCode : ConstantClass { /// <summary> /// Constant AccessDenied for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode AccessDenied = new NodegroupIssueCode("AccessDenied"); /// <summary> /// Constant AsgInstanceLaunchFailures for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode AsgInstanceLaunchFailures = new NodegroupIssueCode("AsgInstanceLaunchFailures"); /// <summary> /// Constant AutoScalingGroupInvalidConfiguration for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode AutoScalingGroupInvalidConfiguration = new NodegroupIssueCode("AutoScalingGroupInvalidConfiguration"); /// <summary> /// Constant AutoScalingGroupNotFound for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode AutoScalingGroupNotFound = new NodegroupIssueCode("AutoScalingGroupNotFound"); /// <summary> /// Constant ClusterUnreachable for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode ClusterUnreachable = new NodegroupIssueCode("ClusterUnreachable"); /// <summary> /// Constant Ec2LaunchTemplateNotFound for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode Ec2LaunchTemplateNotFound = new NodegroupIssueCode("Ec2LaunchTemplateNotFound"); /// <summary> /// Constant Ec2LaunchTemplateVersionMismatch for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode Ec2LaunchTemplateVersionMismatch = new NodegroupIssueCode("Ec2LaunchTemplateVersionMismatch"); /// <summary> /// Constant Ec2SecurityGroupDeletionFailure for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode Ec2SecurityGroupDeletionFailure = new NodegroupIssueCode("Ec2SecurityGroupDeletionFailure"); /// <summary> /// Constant Ec2SecurityGroupNotFound for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode Ec2SecurityGroupNotFound = new NodegroupIssueCode("Ec2SecurityGroupNotFound"); /// <summary> /// Constant Ec2SubnetInvalidConfiguration for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode Ec2SubnetInvalidConfiguration = new NodegroupIssueCode("Ec2SubnetInvalidConfiguration"); /// <summary> /// Constant Ec2SubnetNotFound for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode Ec2SubnetNotFound = new NodegroupIssueCode("Ec2SubnetNotFound"); /// <summary> /// Constant IamInstanceProfileNotFound for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode IamInstanceProfileNotFound = new NodegroupIssueCode("IamInstanceProfileNotFound"); /// <summary> /// Constant IamLimitExceeded for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode IamLimitExceeded = new NodegroupIssueCode("IamLimitExceeded"); /// <summary> /// Constant IamNodeRoleNotFound for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode IamNodeRoleNotFound = new NodegroupIssueCode("IamNodeRoleNotFound"); /// <summary> /// Constant InstanceLimitExceeded for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode InstanceLimitExceeded = new NodegroupIssueCode("InstanceLimitExceeded"); /// <summary> /// Constant InsufficientFreeAddresses for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode InsufficientFreeAddresses = new NodegroupIssueCode("InsufficientFreeAddresses"); /// <summary> /// Constant InternalFailure for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode InternalFailure = new NodegroupIssueCode("InternalFailure"); /// <summary> /// Constant NodeCreationFailure for NodegroupIssueCode /// </summary> public static readonly NodegroupIssueCode NodeCreationFailure = new NodegroupIssueCode("NodeCreationFailure"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public NodegroupIssueCode(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static NodegroupIssueCode FindValue(string value) { return FindValue<NodegroupIssueCode>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator NodegroupIssueCode(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type NodegroupStatus. /// </summary> public class NodegroupStatus : ConstantClass { /// <summary> /// Constant ACTIVE for NodegroupStatus /// </summary> public static readonly NodegroupStatus ACTIVE = new NodegroupStatus("ACTIVE"); /// <summary> /// Constant CREATE_FAILED for NodegroupStatus /// </summary> public static readonly NodegroupStatus CREATE_FAILED = new NodegroupStatus("CREATE_FAILED"); /// <summary> /// Constant CREATING for NodegroupStatus /// </summary> public static readonly NodegroupStatus CREATING = new NodegroupStatus("CREATING"); /// <summary> /// Constant DEGRADED for NodegroupStatus /// </summary> public static readonly NodegroupStatus DEGRADED = new NodegroupStatus("DEGRADED"); /// <summary> /// Constant DELETE_FAILED for NodegroupStatus /// </summary> public static readonly NodegroupStatus DELETE_FAILED = new NodegroupStatus("DELETE_FAILED"); /// <summary> /// Constant DELETING for NodegroupStatus /// </summary> public static readonly NodegroupStatus DELETING = new NodegroupStatus("DELETING"); /// <summary> /// Constant UPDATING for NodegroupStatus /// </summary> public static readonly NodegroupStatus UPDATING = new NodegroupStatus("UPDATING"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public NodegroupStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static NodegroupStatus FindValue(string value) { return FindValue<NodegroupStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator NodegroupStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ResolveConflicts. /// </summary> public class ResolveConflicts : ConstantClass { /// <summary> /// Constant NONE for ResolveConflicts /// </summary> public static readonly ResolveConflicts NONE = new ResolveConflicts("NONE"); /// <summary> /// Constant OVERWRITE for ResolveConflicts /// </summary> public static readonly ResolveConflicts OVERWRITE = new ResolveConflicts("OVERWRITE"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ResolveConflicts(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ResolveConflicts FindValue(string value) { return FindValue<ResolveConflicts>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ResolveConflicts(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type UpdateParamType. /// </summary> public class UpdateParamType : ConstantClass { /// <summary> /// Constant AddonVersion for UpdateParamType /// </summary> public static readonly UpdateParamType AddonVersion = new UpdateParamType("AddonVersion"); /// <summary> /// Constant ClusterLogging for UpdateParamType /// </summary> public static readonly UpdateParamType ClusterLogging = new UpdateParamType("ClusterLogging"); /// <summary> /// Constant DesiredSize for UpdateParamType /// </summary> public static readonly UpdateParamType DesiredSize = new UpdateParamType("DesiredSize"); /// <summary> /// Constant EncryptionConfig for UpdateParamType /// </summary> public static readonly UpdateParamType EncryptionConfig = new UpdateParamType("EncryptionConfig"); /// <summary> /// Constant EndpointPrivateAccess for UpdateParamType /// </summary> public static readonly UpdateParamType EndpointPrivateAccess = new UpdateParamType("EndpointPrivateAccess"); /// <summary> /// Constant EndpointPublicAccess for UpdateParamType /// </summary> public static readonly UpdateParamType EndpointPublicAccess = new UpdateParamType("EndpointPublicAccess"); /// <summary> /// Constant IdentityProviderConfig for UpdateParamType /// </summary> public static readonly UpdateParamType IdentityProviderConfig = new UpdateParamType("IdentityProviderConfig"); /// <summary> /// Constant LabelsToAdd for UpdateParamType /// </summary> public static readonly UpdateParamType LabelsToAdd = new UpdateParamType("LabelsToAdd"); /// <summary> /// Constant LabelsToRemove for UpdateParamType /// </summary> public static readonly UpdateParamType LabelsToRemove = new UpdateParamType("LabelsToRemove"); /// <summary> /// Constant LaunchTemplateName for UpdateParamType /// </summary> public static readonly UpdateParamType LaunchTemplateName = new UpdateParamType("LaunchTemplateName"); /// <summary> /// Constant LaunchTemplateVersion for UpdateParamType /// </summary> public static readonly UpdateParamType LaunchTemplateVersion = new UpdateParamType("LaunchTemplateVersion"); /// <summary> /// Constant MaxSize for UpdateParamType /// </summary> public static readonly UpdateParamType MaxSize = new UpdateParamType("MaxSize"); /// <summary> /// Constant MinSize for UpdateParamType /// </summary> public static readonly UpdateParamType MinSize = new UpdateParamType("MinSize"); /// <summary> /// Constant PlatformVersion for UpdateParamType /// </summary> public static readonly UpdateParamType PlatformVersion = new UpdateParamType("PlatformVersion"); /// <summary> /// Constant PublicAccessCidrs for UpdateParamType /// </summary> public static readonly UpdateParamType PublicAccessCidrs = new UpdateParamType("PublicAccessCidrs"); /// <summary> /// Constant ReleaseVersion for UpdateParamType /// </summary> public static readonly UpdateParamType ReleaseVersion = new UpdateParamType("ReleaseVersion"); /// <summary> /// Constant ResolveConflicts for UpdateParamType /// </summary> public static readonly UpdateParamType ResolveConflicts = new UpdateParamType("ResolveConflicts"); /// <summary> /// Constant ServiceAccountRoleArn for UpdateParamType /// </summary> public static readonly UpdateParamType ServiceAccountRoleArn = new UpdateParamType("ServiceAccountRoleArn"); /// <summary> /// Constant Version for UpdateParamType /// </summary> public static readonly UpdateParamType Version = new UpdateParamType("Version"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public UpdateParamType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static UpdateParamType FindValue(string value) { return FindValue<UpdateParamType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator UpdateParamType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type UpdateStatus. /// </summary> public class UpdateStatus : ConstantClass { /// <summary> /// Constant Cancelled for UpdateStatus /// </summary> public static readonly UpdateStatus Cancelled = new UpdateStatus("Cancelled"); /// <summary> /// Constant Failed for UpdateStatus /// </summary> public static readonly UpdateStatus Failed = new UpdateStatus("Failed"); /// <summary> /// Constant InProgress for UpdateStatus /// </summary> public static readonly UpdateStatus InProgress = new UpdateStatus("InProgress"); /// <summary> /// Constant Successful for UpdateStatus /// </summary> public static readonly UpdateStatus Successful = new UpdateStatus("Successful"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public UpdateStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static UpdateStatus FindValue(string value) { return FindValue<UpdateStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator UpdateStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type UpdateType. /// </summary> public class UpdateType : ConstantClass { /// <summary> /// Constant AddonUpdate for UpdateType /// </summary> public static readonly UpdateType AddonUpdate = new UpdateType("AddonUpdate"); /// <summary> /// Constant AssociateEncryptionConfig for UpdateType /// </summary> public static readonly UpdateType AssociateEncryptionConfig = new UpdateType("AssociateEncryptionConfig"); /// <summary> /// Constant AssociateIdentityProviderConfig for UpdateType /// </summary> public static readonly UpdateType AssociateIdentityProviderConfig = new UpdateType("AssociateIdentityProviderConfig"); /// <summary> /// Constant ConfigUpdate for UpdateType /// </summary> public static readonly UpdateType ConfigUpdate = new UpdateType("ConfigUpdate"); /// <summary> /// Constant DisassociateIdentityProviderConfig for UpdateType /// </summary> public static readonly UpdateType DisassociateIdentityProviderConfig = new UpdateType("DisassociateIdentityProviderConfig"); /// <summary> /// Constant EndpointAccessUpdate for UpdateType /// </summary> public static readonly UpdateType EndpointAccessUpdate = new UpdateType("EndpointAccessUpdate"); /// <summary> /// Constant LoggingUpdate for UpdateType /// </summary> public static readonly UpdateType LoggingUpdate = new UpdateType("LoggingUpdate"); /// <summary> /// Constant VersionUpdate for UpdateType /// </summary> public static readonly UpdateType VersionUpdate = new UpdateType("VersionUpdate"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public UpdateType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static UpdateType FindValue(string value) { return FindValue<UpdateType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator UpdateType(string value) { return FindValue(value); } } }
40.492701
152
0.62393
[ "Apache-2.0" ]
KenHundley/aws-sdk-net
sdk/src/Services/EKS/Generated/ServiceEnumerations.cs
44,380
C#
namespace SkbKontur.EdiApi.Client.Types.Connectors { /// <summary>Информация о доступных пользователю ящиках коннекторов</summary> public class ConnectorBoxesInfo { /// <summary>Список доступных ящиков коннекторов</summary> public ConnectorBoxInfo[] ConnectorBoxes { get; set; } } }
35
81
0.714286
[ "MIT" ]
skbkontur/edi-api
EdiApi.Client/Types/Connectors/ConnectorBoxesInfo.cs
398
C#