content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Text.Json.Serialization; namespace Essensoft.Paylink.Alipay.Response { /// <summary> /// AlipayUserElectronicidMerchantbarcodeCreateResponse. /// </summary> public class AlipayUserElectronicidMerchantbarcodeCreateResponse : AlipayResponse { /// <summary> /// 二维码码串 /// </summary> [JsonPropertyName("barcode")] public string Barcode { get; set; } /// <summary> /// 二维码图片链接 /// </summary> [JsonPropertyName("image_url")] public string ImageUrl { get; set; } } }
25.217391
85
0.605172
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Response/AlipayUserElectronicidMerchantbarcodeCreateResponse.cs
606
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Eventures.Data.Entities; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using System.Linq; namespace Eventures.Areas.Identity.Pages.Account { [AllowAnonymous] public class RegisterModel : PageModel { private readonly SignInManager<EventuresUser> _signInManager; private readonly UserManager<EventuresUser> _userManager; private readonly ILogger<RegisterModel> _logger; private readonly IEmailSender _emailSender; public RegisterModel( UserManager<EventuresUser> userManager, SignInManager<EventuresUser> signInManager, ILogger<RegisterModel> logger, IEmailSender emailSender) { _userManager = userManager; _signInManager = signInManager; _logger = logger; _emailSender = emailSender; } [BindProperty] public InputModel Input { get; set; } public string ReturnUrl { get; set; } public class InputModel { [Required] [RegularExpression(@"[a-zA-Z0-9\\~\\_\\-\\*\\ ]*", ErrorMessage = "The {0} must contain only alphanumeric characters, dashes, underscores, dots, asterisks and tildes.")] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 3)] [Display(Name = "Username")] public string Username { get; set; } [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 5)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Required] [Display(Name = "FirstName")] public string FirstName { get; set; } [Required] [Display(Name = "LastName")] public string LastName { get; set; } [Required] [RegularExpression(@"\d+", ErrorMessage = "Must contain digits only.")] [StringLength(10, ErrorMessage = "Must be exactly 10 digits.", MinimumLength = 10)] [Display(Name = "UCN")] public string UCN { get; set; } } public void OnGet(string returnUrl = null) { ReturnUrl = returnUrl; } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var user = new EventuresUser { UserName = Input.Username, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName, UCN = Input.UCN }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); /*var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");*/ if (_userManager.Users.Count() == 1) { await _userManager.AddToRoleAsync(user, "Admin"); } else { await _userManager.AddToRoleAsync(user, "User"); } await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(returnUrl); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return Page(); } } }
37.737226
181
0.55648
[ "MIT" ]
SimeonVSimeonov/ASP.NET-Core
Eventures/Eventures/Areas/Identity/Pages/Account/Register.cshtml.cs
5,172
C#
using JetBrains.Application.Settings; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.FeaturesTestFramework.Intentions; using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.PerformanceCriticalCodeAnalysis.Highlightings; using JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.QuickFixes.MoveQuickFixes; using JetBrains.ReSharper.Psi; using NUnit.Framework; namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Intentions.QuickFixes { [TestUnity] public class MoveCostlyMethodQuickFixAvailabilityTests : QuickFixAvailabilityTestBase { protected override string RelativeTestDataPath=> @"CSharp\Intentions\QuickFixes\MoveCostlyMethod\Availability"; [Test][Ignore("AvailabilityTestBase does not support global analysis")] public void EveryThingAvailable() { DoNamedTest(); } [Test][Ignore("AvailabilityTestBase does not support global analysis")] public void NotAvailableDueToLocalDependencies1() { DoNamedTest(); } [Test][Ignore("AvailabilityTestBase does not support global analysis")] public void NotAvailableDueToLocalDependencies2() { DoNamedTest(); } protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile psiSourceFile, IContextBoundSettingsStore boundSettingsStore) { return (!(highlighting is IHighlightingTestBehaviour highlightingTestBehaviour) || !highlightingTestBehaviour.IsSuppressed) && highlighting is PerformanceHighlightingBase && !(highlighting is PerformanceHighlighting); } } [TestUnity] public class MoveCostlyMethodQuickFixTests : CSharpQuickFixAfterSwaTestBase<MoveCostlyInvocationQuickFix> { protected override string RelativeTestDataPath=> @"CSharp\Intentions\QuickFixes\MoveCostlyMethod"; [Test] public void MoveToStart() { DoNamedTest(); } [Test] public void MoveToAwake() { DoNamedTest(); } [Test] public void MoveOutsideTheLoop() { DoNamedTest(); } [Test] public void MoveOutsideTheLoop2() { DoNamedTest(); } [Test] public void MoveOutsideTheLoop3() { DoNamedTest(); } [Test] public void MoveOutsideTheLoop4() { DoNamedTest(); } [Test] public void FieldGenerationWithRespectToCodeStyleTest() {DoNamedTest(); } [Test] public void MultiReplace() { DoNamedTest();} [Test] public void MoveCostlyVoid() {DoNamedTest();} } }
54.844444
149
0.745543
[ "Apache-2.0" ]
akarpov89/resharper-unity
resharper/resharper-unity/test/src/CSharp/Intentions/QuickFixes/MoveCostlyMethodQuickFixTests.cs
2,468
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Textures; using osu.Framework.Platform; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Database; using osu.Game.Graphics; using osu.Game.Input; using osu.Game.Input.Bindings; using osu.Game.IO; using osu.Game.Online.API; using osu.Game.Online.Chat; using osu.Game.Overlays; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Scoring; using osu.Game.Screens.Menu; using osu.Game.Skinning; using osu.Game.Utils; using osuTK.Graphics; namespace osu.Game.Tests.Visual { [TestFixture] public class TestSceneOsuGame : OsuTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(OsuLogo), }; private IReadOnlyList<Type> requiredGameDependencies => new[] { typeof(OsuGame), typeof(SentryLogger), typeof(OsuLogo), typeof(IdleTracker), typeof(OnScreenDisplay), typeof(NotificationOverlay), typeof(DirectOverlay), typeof(SocialOverlay), typeof(ChannelManager), typeof(ChatOverlay), typeof(SettingsOverlay), typeof(UserProfileOverlay), typeof(BeatmapSetOverlay), typeof(LoginOverlay), typeof(MusicController), typeof(AccountCreationOverlay), typeof(DialogOverlay), typeof(ScreenshotManager) }; private IReadOnlyList<Type> requiredGameBaseDependencies => new[] { typeof(OsuGameBase), typeof(DatabaseContextFactory), typeof(Bindable<RulesetInfo>), typeof(IBindable<RulesetInfo>), typeof(Bindable<IReadOnlyList<Mod>>), typeof(IBindable<IReadOnlyList<Mod>>), typeof(LargeTextureStore), typeof(OsuConfigManager), typeof(SkinManager), typeof(ISkinSource), typeof(IAPIProvider), typeof(RulesetStore), typeof(FileStore), typeof(ScoreManager), typeof(BeatmapManager), typeof(KeyBindingStore), typeof(SettingsStore), typeof(RulesetConfigCache), typeof(OsuColour), typeof(IBindable<WorkingBeatmap>), typeof(Bindable<WorkingBeatmap>), typeof(GlobalActionContainer), typeof(PreviewTrackManager), }; [BackgroundDependencyLoader] private void load(GameHost host, OsuGameBase gameBase) { OsuGame game = new OsuGame(); game.SetHost(host); Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black, }, game }; AddUntilStep("wait for load", () => game.IsLoaded); AddAssert("check OsuGame DI members", () => { foreach (var type in requiredGameDependencies) { if (game.Dependencies.Get(type) == null) throw new InvalidOperationException($"{type} has not been cached"); } return true; }); AddAssert("check OsuGameBase DI members", () => { foreach (var type in requiredGameBaseDependencies) { if (gameBase.Dependencies.Get(type) == null) throw new InvalidOperationException($"{type} has not been cached"); } return true; }); } } }
32
92
0.559422
[ "MIT" ]
Altenhh/osu
osu.Game.Tests/Visual/TestSceneOsuGame.cs
4,095
C#
namespace DataFlow.EdFi.Models.Types { public class AssessmentItemResultType { /// <summary> /// The unique identifier of the resource. /// </summary> public string id { get; set; } /// <summary> /// Key for AssessmentItemResult /// </summary> public int? assessmentItemResultTypeId { get; set; } /// <summary> /// Code for AssessmentItemResult type. /// </summary> public string codeValue { get; set; } /// <summary> /// The description of the descriptor. /// </summary> public string description { get; set; } /// <summary> /// A shortened description for the assessment item result type. /// </summary> public string shortDescription { get; set; } /// <summary> /// A unique system-generated value that identifies the version of the resource. /// </summary> public string _etag { get; set; } } }
26.736842
88
0.549213
[ "Apache-2.0" ]
schoolstacks/dataflow
DataFlow.EdFi/Models/Types/AssessmentItemResultType.cs
1,016
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using PureCloudPlatform.Client.V2.Client; namespace PureCloudPlatform.Client.V2.Model { /// <summary> /// InboundRouteEntityListing /// </summary> [DataContract] public partial class InboundRouteEntityListing : IEquatable<InboundRouteEntityListing>, IPagedResource<InboundRoute> { /// <summary> /// Initializes a new instance of the <see cref="InboundRouteEntityListing" /> class. /// </summary> /// <param name="Entities">Entities.</param> /// <param name="PageSize">PageSize.</param> /// <param name="PageNumber">PageNumber.</param> /// <param name="Total">Total.</param> /// <param name="FirstUri">FirstUri.</param> /// <param name="SelfUri">SelfUri.</param> /// <param name="NextUri">NextUri.</param> /// <param name="PreviousUri">PreviousUri.</param> /// <param name="LastUri">LastUri.</param> /// <param name="PageCount">PageCount.</param> public InboundRouteEntityListing(List<InboundRoute> Entities = null, int? PageSize = null, int? PageNumber = null, long? Total = null, string FirstUri = null, string SelfUri = null, string NextUri = null, string PreviousUri = null, string LastUri = null, int? PageCount = null) { this.Entities = Entities; this.PageSize = PageSize; this.PageNumber = PageNumber; this.Total = Total; this.FirstUri = FirstUri; this.SelfUri = SelfUri; this.NextUri = NextUri; this.PreviousUri = PreviousUri; this.LastUri = LastUri; this.PageCount = PageCount; } /// <summary> /// Gets or Sets Entities /// </summary> [DataMember(Name="entities", EmitDefaultValue=false)] public List<InboundRoute> Entities { get; set; } /// <summary> /// Gets or Sets PageSize /// </summary> [DataMember(Name="pageSize", EmitDefaultValue=false)] public int? PageSize { get; set; } /// <summary> /// Gets or Sets PageNumber /// </summary> [DataMember(Name="pageNumber", EmitDefaultValue=false)] public int? PageNumber { get; set; } /// <summary> /// Gets or Sets Total /// </summary> [DataMember(Name="total", EmitDefaultValue=false)] public long? Total { get; set; } /// <summary> /// Gets or Sets FirstUri /// </summary> [DataMember(Name="firstUri", EmitDefaultValue=false)] public string FirstUri { get; set; } /// <summary> /// Gets or Sets SelfUri /// </summary> [DataMember(Name="selfUri", EmitDefaultValue=false)] public string SelfUri { get; set; } /// <summary> /// Gets or Sets NextUri /// </summary> [DataMember(Name="nextUri", EmitDefaultValue=false)] public string NextUri { get; set; } /// <summary> /// Gets or Sets PreviousUri /// </summary> [DataMember(Name="previousUri", EmitDefaultValue=false)] public string PreviousUri { get; set; } /// <summary> /// Gets or Sets LastUri /// </summary> [DataMember(Name="lastUri", EmitDefaultValue=false)] public string LastUri { get; set; } /// <summary> /// Gets or Sets PageCount /// </summary> [DataMember(Name="pageCount", EmitDefaultValue=false)] public int? PageCount { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class InboundRouteEntityListing {\n"); sb.Append(" Entities: ").Append(Entities).Append("\n"); sb.Append(" PageSize: ").Append(PageSize).Append("\n"); sb.Append(" PageNumber: ").Append(PageNumber).Append("\n"); sb.Append(" Total: ").Append(Total).Append("\n"); sb.Append(" FirstUri: ").Append(FirstUri).Append("\n"); sb.Append(" SelfUri: ").Append(SelfUri).Append("\n"); sb.Append(" NextUri: ").Append(NextUri).Append("\n"); sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n"); sb.Append(" LastUri: ").Append(LastUri).Append("\n"); sb.Append(" PageCount: ").Append(PageCount).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as InboundRouteEntityListing); } /// <summary> /// Returns true if InboundRouteEntityListing instances are equal /// </summary> /// <param name="other">Instance of InboundRouteEntityListing to be compared</param> /// <returns>Boolean</returns> public bool Equals(InboundRouteEntityListing other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return true && ( this.Entities == other.Entities || this.Entities != null && this.Entities.SequenceEqual(other.Entities) ) && ( this.PageSize == other.PageSize || this.PageSize != null && this.PageSize.Equals(other.PageSize) ) && ( this.PageNumber == other.PageNumber || this.PageNumber != null && this.PageNumber.Equals(other.PageNumber) ) && ( this.Total == other.Total || this.Total != null && this.Total.Equals(other.Total) ) && ( this.FirstUri == other.FirstUri || this.FirstUri != null && this.FirstUri.Equals(other.FirstUri) ) && ( this.SelfUri == other.SelfUri || this.SelfUri != null && this.SelfUri.Equals(other.SelfUri) ) && ( this.NextUri == other.NextUri || this.NextUri != null && this.NextUri.Equals(other.NextUri) ) && ( this.PreviousUri == other.PreviousUri || this.PreviousUri != null && this.PreviousUri.Equals(other.PreviousUri) ) && ( this.LastUri == other.LastUri || this.LastUri != null && this.LastUri.Equals(other.LastUri) ) && ( this.PageCount == other.PageCount || this.PageCount != null && this.PageCount.Equals(other.PageCount) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Entities != null) hash = hash * 59 + this.Entities.GetHashCode(); if (this.PageSize != null) hash = hash * 59 + this.PageSize.GetHashCode(); if (this.PageNumber != null) hash = hash * 59 + this.PageNumber.GetHashCode(); if (this.Total != null) hash = hash * 59 + this.Total.GetHashCode(); if (this.FirstUri != null) hash = hash * 59 + this.FirstUri.GetHashCode(); if (this.SelfUri != null) hash = hash * 59 + this.SelfUri.GetHashCode(); if (this.NextUri != null) hash = hash * 59 + this.NextUri.GetHashCode(); if (this.PreviousUri != null) hash = hash * 59 + this.PreviousUri.GetHashCode(); if (this.LastUri != null) hash = hash * 59 + this.LastUri.GetHashCode(); if (this.PageCount != null) hash = hash * 59 + this.PageCount.GetHashCode(); return hash; } } } }
31.254438
285
0.466679
[ "MIT" ]
seowleng/platform-client-sdk-dotnet
build/src/PureCloudPlatform.Client.V2/Model/InboundRouteEntityListing.cs
10,564
C#
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System.Collections; using System.Collections.Generic; namespace DotSpatial.Data { /// <summary> /// VertexRange /// </summary> public class VertexRange : IEnumerable<Vertex> { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="VertexRange"/> class that can have the vertices and number of vertices assigned later. /// </summary> public VertexRange() { } /// <summary> /// Initializes a new instance of the <see cref="VertexRange"/> class. /// </summary> /// <param name="allVertices">An array of all the vertex locations</param> /// <param name="shapeOffset">The shape offset.</param> /// <param name="partOffset">The part offset.</param> public VertexRange(double[] allVertices, int shapeOffset, int partOffset) { ShapeOffset = shapeOffset; PartOffset = partOffset; Vertices = allVertices; } #endregion #region Properties /// <summary> /// Gets the integer index of the last vertex included in this range. /// </summary> public int EndIndex => StartIndex + NumVertices - 1; /// <summary> /// Gets or sets the number of vertices. This will also set the EndIndex relative to the start position. /// </summary> public int NumVertices { get; set; } /// <summary> /// Gets or sets the part offset. For parts, controlling the part offset is perhaps more useful that controlling the shape offset. /// </summary> public int PartOffset { get; set; } /// <summary> /// Gets or sets the shape offset. The StartIndex is the sum of the shape offset and the part offset. Controlling them separately /// allows the entire shape offset to be adjusted independently after the part is created. /// </summary> public int ShapeOffset { get; set; } /// <summary> /// Gets the index of the first vertex included in this range. This is overridden /// in the case of part ranges to also take into account the shape start index. /// </summary> public int StartIndex => ShapeOffset + PartOffset; /// <summary> /// Gets or sets the vertices /// </summary> public double[] Vertices { get; set; } #endregion #region Methods /// <summary> /// Gets an enumerator. This exists to make it easier to cycle values, /// but in truth should not be used because it re-adds the property accessor /// which slows down the data access, which is the whole point of putting /// all the vertices into a jagged array of doubles in the first place. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<Vertex> GetEnumerator() { return new VertexRangeEnumerator(Vertices, StartIndex, EndIndex); } /// <summary> /// Gets an enumerator. This exists to make it easier to cycle values, /// but in truth should not be used because it re-adds the property accessor /// which slows down the data access, which is the whole point of putting /// all the vertices into a jagged array of doubles in the first place. /// </summary> /// <returns>The enumerator.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region Classes /// <summary> /// The enumerator is here to provide an easy method for cycling vertex values /// in each range. This sort of defeats the point because it adds /// two method calls for advancing each step (one to MoveNext and one to /// access the property. The whole point of loading everything /// into a single array of vertices in the first place is to avoid /// property accessors slowing down the process. However, it's here /// if someone wants it. /// </summary> private class VertexRangeEnumerator : IEnumerator<Vertex> { #region Fields private readonly int _end; private readonly int _start; private readonly double[] _vertices; private int _index; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="VertexRangeEnumerator"/> class. /// </summary> /// <param name="vertices">The vertices to create</param> /// <param name="start">The integer index of the first included vertex </param> /// <param name="end">The integer index of the last included vertex</param> public VertexRangeEnumerator(double[] vertices, int start, int end) { _start = start; _end = end; _index = start - 1; _vertices = vertices; } #endregion #region Properties /// <summary> /// Gets the current value. /// </summary> public Vertex Current { get; private set; } object IEnumerator.Current => Current; #endregion #region Methods /// <summary> /// This does nothing /// </summary> public void Dispose() { } /// <summary> /// Advances the enumerator to the next position. /// </summary> /// <returns>True if it was moved.</returns> public bool MoveNext() { _index++; if (_index > _end) return false; Current = new Vertex(_vertices[_index * 2], _vertices[(_index * 2) + 1]); return true; } /// <summary> /// Resets this enumerator to the beginning of the range of vertices /// </summary> public void Reset() { _index = _start - 1; } #endregion } #endregion // Internally keep track of the vertices array. } }
35.294737
144
0.549359
[ "MIT" ]
AlexanderSemenyak/DotSpatial
Source/DotSpatial.Data/VertexRange.cs
6,706
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.AzureNextGen.Management.V20180301Preview { public static class GetManagementGroup { public static Task<GetManagementGroupResult> InvokeAsync(GetManagementGroupArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetManagementGroupResult>("azure-nextgen:management/v20180301preview:getManagementGroup", args ?? new GetManagementGroupArgs(), options.WithVersion()); } public sealed class GetManagementGroupArgs : Pulumi.InvokeArgs { /// <summary> /// The $expand=children query string parameter allows clients to request inclusion of children in the response payload. /// </summary> [Input("expand")] public string? Expand { get; set; } /// <summary> /// A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription') /// </summary> [Input("filter")] public string? Filter { get; set; } /// <summary> /// Management Group ID. /// </summary> [Input("groupId", required: true)] public string GroupId { get; set; } = null!; /// <summary> /// The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. /// </summary> [Input("recurse")] public bool? Recurse { get; set; } public GetManagementGroupArgs() { } } [OutputType] public sealed class GetManagementGroupResult { /// <summary> /// The list of children. /// </summary> public readonly ImmutableArray<Outputs.ManagementGroupChildInfoResponse> Children; /// <summary> /// The details of a management group. /// </summary> public readonly Outputs.ManagementGroupDetailsResponse? Details; /// <summary> /// The friendly name of the management group. /// </summary> public readonly string? DisplayName; /// <summary> /// The name of the management group. For example, 00000000-0000-0000-0000-000000000000 /// </summary> public readonly string Name; /// <summary> /// The role definitions associated with the management group. /// </summary> public readonly ImmutableArray<string> Roles; /// <summary> /// The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000 /// </summary> public readonly string? TenantId; /// <summary> /// The type of the resource. For example, /providers/Microsoft.Management/managementGroups /// </summary> public readonly string Type; [OutputConstructor] private GetManagementGroupResult( ImmutableArray<Outputs.ManagementGroupChildInfoResponse> children, Outputs.ManagementGroupDetailsResponse? details, string? displayName, string name, ImmutableArray<string> roles, string? tenantId, string type) { Children = children; Details = details; DisplayName = displayName; Name = name; Roles = roles; TenantId = tenantId; Type = type; } } }
34.669725
207
0.622651
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Management/V20180301Preview/GetManagementGroup.cs
3,779
C#
using System; using System.Collections.Generic; using System.Text; namespace MYH.ABP.Member.Dto { public class CreateMemberOutput { public string OpenIdMp { get; set; } } }
16.25
44
0.687179
[ "MIT" ]
moyuanhui/MYH.ABP
aspnet-core/src/MYH.ABP.Application/Member/Dto/CreateMemberOutput.cs
197
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Entity.Spatial; namespace RoadSegmentMapping { class WayInfo { public long id; public DbGeography line; public double Dist; } }
17.647059
33
0.703333
[ "Apache-2.0" ]
OSADP/Road-Weather-Performance-Management-
Cloud/RWPMHostedSystem/RoadSegmentMappingLib/WayInfo.cs
302
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.TestPlatform.AcceptanceTests { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class FrameworkTests : AcceptanceTestBase { [TestMethod] [NetFullTargetFrameworkDataSource] [NetCoreTargetFrameworkDataSource] public void FrameworkArgumentShouldWork(RunnerInfo runnerInfo) { AcceptanceTestBase.SetTestEnvironment(this.testEnvironment, runnerInfo); var resultsDir = GetResultsDirectory(); var arguments = PrepareArguments(GetSampleTestAssembly(), string.Empty, string.Empty, string.Empty, resultsDirectory: resultsDir); arguments = string.Concat(arguments, " ", $"/Framework:{this.FrameworkArgValue}"); this.InvokeVsTest(arguments); this.ValidateSummaryStatus(1, 1, 1); TryRemoveDirectory(resultsDir); } [TestMethod] [NetFullTargetFrameworkDataSource] [NetCoreTargetFrameworkDataSource] public void FrameworkShortNameArgumentShouldWork(RunnerInfo runnerInfo) { AcceptanceTestBase.SetTestEnvironment(this.testEnvironment, runnerInfo); var resultsDir = GetResultsDirectory(); var arguments = PrepareArguments(GetSampleTestAssembly(), string.Empty, string.Empty, string.Empty, resultsDirectory: resultsDir); arguments = string.Concat(arguments, " ", $"/Framework:{this.testEnvironment.TargetFramework}"); this.InvokeVsTest(arguments); this.ValidateSummaryStatus(1, 1, 1); TryRemoveDirectory(resultsDir); } [TestMethod] // framework runner not available on Linux [TestCategory("Windows-Review")] [NetFullTargetFrameworkDataSource(useCoreRunner: false)] //[NetCoreTargetFrameworkDataSource] public void OnWrongFrameworkPassedTestRunShouldNotRun(RunnerInfo runnerInfo) { AcceptanceTestBase.SetTestEnvironment(this.testEnvironment, runnerInfo); var resultsDir = GetResultsDirectory(); var arguments = PrepareArguments(GetSampleTestAssembly(), string.Empty, string.Empty, string.Empty, resultsDirectory: resultsDir); if (runnerInfo.TargetFramework.Contains("netcore")) { arguments = string.Concat(arguments, " ", "/Framework:Framework45"); } else { arguments = string.Concat(arguments, " ", "/Framework:FrameworkCore10"); } this.InvokeVsTest(arguments); if (runnerInfo.TargetFramework.Contains("netcore")) { this.StdOutputContains("No test is available"); } else { // This test indirectly tests that we abort when incorrect framework is forced on a DLL, the failure message with the new fallback // is uglier than then one before that suggests (incorrectly) to install Microsoft.NET.Test.Sdk into the project, which would work, // but would not solve the problem. In either cases we should improve the message later. this.StdErrorContains("Test Run Failed."); } TryRemoveDirectory(resultsDir); } [TestMethod] [NetFullTargetFrameworkDataSource] [NetCoreTargetFrameworkDataSource] public void RunSpecificTestsShouldWorkWithFrameworkInCompatibleWarning(RunnerInfo runnerInfo) { AcceptanceTestBase.SetTestEnvironment(this.testEnvironment, runnerInfo); var resultsDir = GetResultsDirectory(); var arguments = PrepareArguments(GetSampleTestAssembly(), string.Empty, string.Empty, string.Empty, resultsDirectory: resultsDir); arguments = string.Concat(arguments, " ", "/tests:PassingTest"); arguments = string.Concat(arguments, " ", "/Framework:Framework40"); this.InvokeVsTest(arguments); if (runnerInfo.TargetFramework.Contains("netcore")) { this.StdOutputContains("No test is available"); } else { this.StdOutputContains("Following DLL(s) do not match current settings, which are .NETFramework,Version=v4.0 framework and X86 platform."); this.ValidateSummaryStatus(1, 0, 0); } TryRemoveDirectory(resultsDir); } } }
43.345794
155
0.649418
[ "MIT" ]
HeroMaxPower/vstest
test/Microsoft.TestPlatform.AcceptanceTests/FrameworkTests.cs
4,640
C#
// Copyright (c) 2016 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows; using System.Windows.Automation.Provider; using System.Windows.Automation.Text; using System.Windows.Documents; using UyghurEditPP.Document; using UyghurEditPP.Rendering; namespace UyghurEditPP.Editing { class TextRangeProvider : ITextRangeProvider { readonly TextArea textArea; readonly TextDocument doc; ISegment segment; public TextRangeProvider(TextArea textArea, TextDocument doc, ISegment segment) { this.textArea = textArea; this.doc = doc; this.segment = segment; } public TextRangeProvider(TextArea textArea, TextDocument doc, int offset, int length) { this.textArea = textArea; this.doc = doc; this.segment = new AnchorSegment(doc, offset, length); } string ID { get { return string.Format("({0}: {1})", GetHashCode().ToString("x8"), segment); } } [Conditional("DEBUG")] static void Log(string format, params object[] args) { Debug.WriteLine(string.Format(format, args)); } public void AddToSelection() { Log("{0}.AddToSelection()", ID); } public ITextRangeProvider Clone() { var result = new TextRangeProvider(textArea, doc, segment); Log("{0}.Clone() = {1}", ID, result.ID); return result; } public bool Compare(ITextRangeProvider range) { TextRangeProvider other = (TextRangeProvider)range; bool result = doc == other.doc && segment.Offset == other.segment.Offset && segment.EndOffset == other.segment.EndOffset; Log("{0}.Compare({1}) = {2}", ID, other.ID, result); return result; } int GetEndpoint(TextPatternRangeEndpoint endpoint) { switch (endpoint) { case TextPatternRangeEndpoint.Start: return segment.Offset; case TextPatternRangeEndpoint.End: return segment.EndOffset; default: throw new ArgumentOutOfRangeException("endpoint"); } } public int CompareEndpoints(TextPatternRangeEndpoint endpoint, ITextRangeProvider targetRange, TextPatternRangeEndpoint targetEndpoint) { TextRangeProvider other = (TextRangeProvider)targetRange; int result = GetEndpoint(endpoint).CompareTo(other.GetEndpoint(targetEndpoint)); Log("{0}.CompareEndpoints({1}, {2}, {3}) = {4}", ID, endpoint, other.ID, targetEndpoint, result); return result; } public void ExpandToEnclosingUnit(TextUnit unit) { Log("{0}.ExpandToEnclosingUnit({1})", ID, unit); switch (unit) { case TextUnit.Character: ExpandToEnclosingUnit(CaretPositioningMode.Normal); break; case TextUnit.Format: case TextUnit.Word: ExpandToEnclosingUnit(CaretPositioningMode.WordStartOrSymbol); break; case TextUnit.Line: case TextUnit.Paragraph: segment = doc.GetLineByOffset(segment.Offset); break; case TextUnit.Document: segment = new AnchorSegment(doc, 0, doc.TextLength); break; } } private void ExpandToEnclosingUnit(CaretPositioningMode mode) { int start = TextUtilities.GetNextCaretPosition(doc, segment.Offset + 1, LogicalDirection.Backward, mode); if (start < 0) return; int end = TextUtilities.GetNextCaretPosition(doc, start, LogicalDirection.Forward, mode); if (end < 0) return; segment = new AnchorSegment(doc, start, end - start); } public ITextRangeProvider FindAttribute(int attribute, object value, bool backward) { Log("{0}.FindAttribute({1}, {2}, {3})", ID, attribute, value, backward); return null; } public ITextRangeProvider FindText(string text, bool backward, bool ignoreCase) { Log("{0}.FindText({1}, {2}, {3})", ID, text, backward, ignoreCase); string segmentText = doc.GetText(segment); var comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; int pos = backward ? segmentText.LastIndexOf(text, comparison) : segmentText.IndexOf(text, comparison); if (pos >= 0) { return new TextRangeProvider(textArea, doc, segment.Offset + pos, text.Length); } return null; } public object GetAttributeValue(int attribute) { Log("{0}.GetAttributeValue({1})", ID, attribute); return null; } public double[] GetBoundingRectangles() { Log("{0}.GetBoundingRectangles()", ID); var textView = textArea.TextView; var source = PresentationSource.FromVisual(this.textArea); var result = new List<double>(); foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, segment)) { var tl = textView.PointToScreen(rect.TopLeft); var br = textView.PointToScreen(rect.BottomRight); result.Add(tl.X); result.Add(tl.Y); result.Add(br.X - tl.X); result.Add(br.Y - tl.Y); } return result.ToArray(); } public IRawElementProviderSimple[] GetChildren() { Log("{0}.GetChildren()", ID); return new IRawElementProviderSimple[0]; } public IRawElementProviderSimple GetEnclosingElement() { Log("{0}.GetEnclosingElement()", ID); var peer = TextAreaAutomationPeer.FromElement(textArea) as TextAreaAutomationPeer; if (peer == null) throw new NotSupportedException(); return peer.Provider; } public string GetText(int maxLength) { Log("{0}.GetText({1})", ID, maxLength); if (maxLength < 0) return doc.GetText(segment); else return doc.GetText(segment.Offset, Math.Min(segment.Length, maxLength)); } public int Move(TextUnit unit, int count) { Log("{0}.Move({1}, {2})", ID, unit, count); int movedCount = MoveEndpointByUnit(TextPatternRangeEndpoint.Start, unit, count); segment = new SimpleSegment(segment.Offset, 0); // Collapse to empty range ExpandToEnclosingUnit(unit); return movedCount; } public void MoveEndpointByRange(TextPatternRangeEndpoint endpoint, ITextRangeProvider targetRange, TextPatternRangeEndpoint targetEndpoint) { TextRangeProvider other = (TextRangeProvider)targetRange; Log("{0}.MoveEndpointByRange({1}, {2}, {3})", ID, endpoint, other.ID, targetEndpoint); SetEndpoint(endpoint, other.GetEndpoint(targetEndpoint)); } void SetEndpoint(TextPatternRangeEndpoint endpoint, int targetOffset) { if (endpoint == TextPatternRangeEndpoint.Start) { // set start of this range to targetOffset segment = new AnchorSegment(doc, targetOffset, Math.Max(0, segment.EndOffset - targetOffset)); } else { // set end of this range to targetOffset int newStart = Math.Min(segment.Offset, targetOffset); segment = new AnchorSegment(doc, newStart, targetOffset - newStart); } } public int MoveEndpointByUnit(TextPatternRangeEndpoint endpoint, TextUnit unit, int count) { Log("{0}.MoveEndpointByUnit({1}, {2}, {3})", ID, endpoint, unit, count); int offset = GetEndpoint(endpoint); switch (unit) { case TextUnit.Character: offset = MoveOffset(offset, CaretPositioningMode.Normal, count); break; case TextUnit.Format: case TextUnit.Word: offset = MoveOffset(offset, CaretPositioningMode.WordStart, count); break; case TextUnit.Line: case TextUnit.Paragraph: int line = doc.GetLineByOffset(offset).LineNumber; int newLine = Math.Max(1, Math.Min(doc.LineCount, line + count)); offset = doc.GetLineByNumber(newLine).Offset; break; case TextUnit.Document: offset = count < 0 ? 0 : doc.TextLength; break; } SetEndpoint(endpoint, offset); return count; } private int MoveOffset(int offset, CaretPositioningMode mode, int count) { var direction = count < 0 ? LogicalDirection.Backward : LogicalDirection.Forward; count = Math.Abs(count); for (int i = 0; i < count; i++) { int newOffset = TextUtilities.GetNextCaretPosition(doc, offset, direction, mode); if (newOffset == offset || newOffset < 0) break; offset = newOffset; } return offset; } public void RemoveFromSelection() { Log("{0}.RemoveFromSelection()", ID); } public void ScrollIntoView(bool alignToTop) { Log("{0}.ScrollIntoView({1})", ID, alignToTop); } public void Select() { Log("{0}.Select()", ID); textArea.Selection = new SimpleSelection(textArea, new TextViewPosition(doc.GetLocation(segment.Offset)), new TextViewPosition(doc.GetLocation(segment.EndOffset))); } } }
32.314879
141
0.709605
[ "MIT" ]
YadikarYaqup/UyghurEditPP
Editing/TextRangeProvider.cs
9,341
C#
// Copyright Allen Institute for Artificial Intelligence 2017 using UnityEngine; using System.Collections; using System; using System.Collections.Generic; using UnityEngine.SceneManagement; public static class SimUtil { //how fast smooth-animated s / cabinets / etc animate public const float SmoothAnimationSpeed = 0.5f; public const int RaycastVisibleLayer = 8; public const int RaycastHiddenLayer = 9; public const int RaycastVisibleLayerMask = 1 << RaycastVisibleLayer; public const int RaycastHiddenLayerMask = 1 << RaycastHiddenLayer; public const string ReceptacleTag = "Receptacle"; public const string SimObjTag = "SimObj"; public const string StructureTag = "Structure"; public const float ViewPointRangeHigh = 1f; public const float ViewPointRangeLow = 0f; public const int VisibilityCheckSteps = 10; public const float DownwardRangeExtension = 2.0f;//1.45f; changes this so the agent can see low enough to open all drawers public const float MinDownwardLooKangle = 15f; public const float MaxDownwardLookAngle = 60f; public const string DefaultBuildDirectory = ""; public static bool ShowBasePivots = true; public static bool ShowIDs = true; public static bool ShowCustomBounds = true; public static bool ShowObjectVisibility = true; #region SimObj utility functions public static SimObj[] GetAllVisibleSimObjs (Camera agentCamera, float maxDistance) { #if UNITY_EDITOR if (ShowObjectVisibility) { //set all objects to invisible before starting - THIS IS EXPENSIVE if (SceneManager.Current != null) { foreach (SimObj obj in SceneManager.Current.ObjectsInScene) { if (obj != null) { obj.VisibleNow = false; } } } } #endif //the final list of visible items List<SimObj> items = new List<SimObj>(); //a temporary hashset to prevent duplicates HashSet<SimObj> uniqueItems = new HashSet<SimObj>(); //get a list of all the colliders we intersect with in a sphere Vector3 agentCameraPos = agentCamera.transform.position; Collider[] colliders = Physics.OverlapSphere(agentCameraPos, maxDistance * DownwardRangeExtension, SimUtil.RaycastVisibleLayerMask, QueryTriggerInteraction.Collide); //go through them one by one and determine if they're actually simObjs for (int i = 0; i < colliders.Length; i++) { if (colliders [i].CompareTag (SimUtil.SimObjTag) || colliders[i].CompareTag (SimUtil.ReceptacleTag)) { SimObj o = null; if (GetSimObjFromCollider (colliders [i], out o)) { //this may result in duplicates because of 'open' receptacles //but using a hashset cancels that out //don't worry about items contained in receptacles until visibility uniqueItems.Add (o); } } } //now check to see if they're actually visible RaycastHit hit = new RaycastHit(); foreach (SimObj item in uniqueItems) { if (!CheckItemBounds (item, agentCameraPos)) { //if the camera isn't in bounds, skip this item continue; } //check whether we can see the point in a sweep from top to bottom bool canSeeItem = false; //if it's a receptacle //raycast against every pivot in the receptacle just to make sure we don't miss anything if (item.IsReceptacle) { foreach (Transform pivot in item.Receptacle.Pivots) { canSeeItem = CheckPointVisibility ( item, pivot.position, agentCamera, agentCameraPos, SimUtil.RaycastVisibleLayerMask, true, maxDistance, out hit); //if we can see it no need for more checks! if (canSeeItem) break; } } if (!canSeeItem) { for (int i = 0; i < VisibilityCheckSteps; i++) { canSeeItem = CheckPointVisibility ( item, Vector3.Lerp (item.TopPoint, item.BottomPoint, (float)i / VisibilityCheckSteps), agentCamera, agentCameraPos, SimUtil.RaycastVisibleLayerMask, true, maxDistance, out hit); //if we can see it no need for more checks! if (canSeeItem) break; } } if (canSeeItem) { //if it's the same object, add it to the list #if UNITY_EDITOR item.VisibleNow = ShowObjectVisibility & true; #endif items.Add (item); //now check to see if it's a receptacle interior if (item.IsReceptacle && hit.collider.CompareTag (SimUtil.ReceptacleTag)) { //if it is, add the items in the receptacle as well items.AddRange (GetVisibleItemsFromReceptacle (item.Receptacle, agentCamera, agentCameraPos, maxDistance)); } } } //now sort the items by distance to camera items.Sort((x, y) => Vector3.Distance(x.transform.position, agentCameraPos).CompareTo(Vector3.Distance(y.transform.position, agentCameraPos))); //we're done! return items.ToArray(); } //checks whether a point is in view of the camera public static bool CheckPointVisibility(Vector3 itemTargetPoint, Camera agentCamera) { Vector3 viewPoint = agentCamera.WorldToViewportPoint(itemTargetPoint); if (viewPoint.z > 0//in front of camera && viewPoint.x < ViewPointRangeHigh && viewPoint.x > ViewPointRangeLow//within x bounds && viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow) { //within y bounds return true; } return false; } //checks whether a point is in view of the camera //and whether it can be seen via raycast static bool CheckPointVisibility (SimObj item, Vector3 itemTargetPoint, Camera agentCamera, Vector3 agentCameraPos, int raycastLayerMask, bool checkTrigger, float maxDistance, out RaycastHit hit) { hit = new RaycastHit (); Vector3 viewPoint = agentCamera.WorldToViewportPoint(itemTargetPoint); if (viewPoint.z > 0//in front of camera && viewPoint.x < ViewPointRangeHigh && viewPoint.x > ViewPointRangeLow//within x bounds && viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow) { //within y bounds Vector3 itemDirection = Vector3.zero; //do a raycast in the direction of the item itemDirection = (itemTargetPoint - agentCameraPos).normalized; //extend the range depending on how much we're looking downward //base this on the angle of the RAYCAST direction not the camera direction Vector3 agentForward = agentCamera.transform.forward; agentForward.y = 0f; agentForward.Normalize (); //clap the angle so we can't wrap around float maxDistanceLerp = 0f; float lookAngle = Mathf.Clamp (Vector3.Angle (agentForward, itemDirection), 0f, MaxDownwardLookAngle) - MinDownwardLooKangle; maxDistanceLerp = lookAngle / MaxDownwardLookAngle; maxDistance = Mathf.Lerp (maxDistance, maxDistance * DownwardRangeExtension, maxDistanceLerp); //try to raycast for the object if (Physics.Raycast ( agentCameraPos, itemDirection, out hit, maxDistance, raycastLayerMask, (checkTrigger ? QueryTriggerInteraction.Collide : QueryTriggerInteraction.Ignore))) { //check to see if we hit the item we're after if (hit.collider.attachedRigidbody != null && hit.collider.attachedRigidbody.gameObject == item.gameObject) { #if UNITY_EDITOR Debug.DrawLine (agentCameraPos, hit.point, Color.Lerp (Color.green, Color.blue, maxDistanceLerp)); #endif return true; } #if UNITY_EDITOR //Debug.DrawRay (agentCameraPos, itemDirection, Color.Lerp (Color.red, Color.clear, 0.75f)); #endif } } return false; } //Puts an item back where you originally found it //returns true if successful, false if unsuccessful //if successful, object is placed into the world and activated //this only works on objects of SimObjManipulation type 'inventory' //if an object was spawned in a Receptacle, this function will also return false public static bool PutItemBackInStartupPosition (SimObj item) { if (item == null) { Debug.LogError ("Item is null, not putting item back"); return false; } bool result = false; switch (item.Manipulation) { case SimObjManipType.Inventory: if (item.StartupTransform != null) { item.transform.position = item.StartupTransform.position; item.transform.rotation = item.StartupTransform.rotation; item.transform.localScale = item.StartupTransform.localScale; item.gameObject.SetActive (true); result = true; } else { Debug.LogWarning ("Item had no startup transform. This probably means it was spawned in a receptacle."); } break; default: break; } return result; } //TAKES an item //removes it from any receptacles, then disables it entirely //this works whether the item is standalone or in a receptacle public static void TakeItem (SimObj item) { //make item visible to raycasts //unparent in case it's in a receptacle item.VisibleToRaycasts = true; item.transform.parent = null; //disable the item entirely item.gameObject.SetActive (false); //set the position to 'up' so it's rotated correctly when it comes back item.transform.up = Vector3.up; //reset the scale (to prevent floating point weirdness) item.ResetScale (); } //checks whether the item public static bool CheckItemBounds (SimObj item, Vector3 agentPosition) { //if the item doesn't use custom bounds this is an automatic pass if (!item.UseCustomBounds) return true; //use the item's bounds transform as a bounding box //this is NOT axis-aligned so objects rotated strangely may return unexpected results //but it should work for 99% of cases Bounds itemBounds = new Bounds (item.BoundsTransform.position, item.BoundsTransform.lossyScale); return itemBounds.Contains (agentPosition); } //searches for a SimObj item under a receptacle by ID //this does not TAKE the item, it just searches for it public static bool FindItemFromReceptacleByID (string itemID, Receptacle r, out SimObj item) { item = null; //make sure we're not doing something insane if (r == null) { Debug.LogError ("Receptacle was null, not searching for item"); return false; } if (!IsUniqueIDValid (itemID)) { Debug.LogError ("itemID " + itemID.ToString() + " is NOT valid, not searching for item"); return false; } SimObj checkItem = null; for (int i = 0; i < r.Pivots.Length; i++) { if (r.Pivots [i].childCount > 0) { checkItem = r.Pivots [i].GetChild (0).GetComponent <SimObj> (); if (checkItem != null && checkItem.UniqueID == itemID) { //if the item under the pivot is a SimObj with the right id //we've found what we're after item = checkItem; return true; } } } //couldn't find it! return false; } //searches for a SimObj item under a receptacle by ID //this does not TAKE the item, it just searches for it public static bool FindItemFromReceptacleByType (SimObjType itemType, Receptacle r, out SimObj item) { item = null; //make sure we're not doing something insane if (r == null) { Debug.LogError ("Receptacle was null, not searching for item"); return false; } if (itemType == SimObjType.Undefined) { Debug.LogError ("Can't search for type UNDEFINED, not searching for item"); return false; } SimObj checkItem = null; for (int i = 0; i < r.Pivots.Length; i++) { if (r.Pivots [i].childCount > 0) { checkItem = r.Pivots [i].GetChild (0).GetComponent <SimObj> (); if (checkItem != null && checkItem.Type == itemType) { //if the item under the pivot is a SimObj of the right type //we've found what we're after item = checkItem; return true; } } } //couldn't find it! return false; } //adds the item to a receptacle //enabled the object, parents it under an empty pivot, then makes it invisible to raycasts //returns false if there are no available pivots in the receptacle public static bool AddItemToVisibleReceptacle (SimObj item, Receptacle r, Camera camera) { //make sure we're not doing something insane if (item == null) { Debug.LogError ("Can't add null item to receptacle"); return false; } if (r == null) { Debug.LogError ("Receptacle was null, not adding item"); return false; } if (item.gameObject == r.gameObject) { Debug.LogError ("Receptacle and item were same object, can't add item to itself"); return false; } //make sure there's room in the recepticle Transform emptyPivot = null; if (!GetFirstEmptyVisibleReceptaclePivot (r, camera, out emptyPivot)) { Debug.Log ("No visible Pivots found"); return false; } return AddItemToReceptaclePivot (item, emptyPivot); } //adds the item to a receptacle //enabled the object, parents it under an empty pivot, then makes it invisible to raycasts //returns false if there are no available pivots in the receptacle public static bool AddItemToReceptacle (SimObj item, Receptacle r) { //make sure we're not doing something insane if (item == null) { Debug.LogError ("Can't add null item to receptacle"); return false; } if (r == null) { Debug.LogError ("Receptacle was null, not adding item"); return false; } if (item.gameObject == r.gameObject) { Debug.LogError ("Receptacle and item were same object, can't add item to itself"); return false; } //make sure there's room in the recepticle Transform emptyPivot = null; if (!GetFirstEmptyReceptaclePivot (r, out emptyPivot)) { //Debug.Log ("Receptacle is full"); return false; } return AddItemToReceptaclePivot (item, emptyPivot); } //adds the item to a receptacle //enabled the object, parents it under an empty pivot, then makes it invisible to raycasts //returns false if there are no available pivots in the receptacle public static bool AddItemToReceptaclePivot (SimObj item, Transform pivot) { if (item == null) { Debug.LogError ("SimObj item was null in AddItemToReceptaclePivot, not adding"); return false; } if (pivot == null) { Debug.LogError ("Pivot was null when attempting to add item " + item.name + " to Receptacle pivot, not adding"); return false; } //if there's room, parent it under the empty pivot item.transform.parent = pivot; item.transform.localPosition = Vector3.zero; item.transform.localRotation = Quaternion.identity; //don't scale the item //make sure the item is active (in case it's been in inventory) item.gameObject.SetActive (true); item.RecalculatePoints (); //disable the item's colliders (since we're no longer raycasting it directly) item.VisibleToRaycasts = false; //we're done! return true; } public static bool GetFirstEmptyReceptaclePivot (Receptacle r, out Transform emptyPivot) { emptyPivot = null; for (int i = 0; i < r.Pivots.Length; i++) { if (r.Pivots [i].childCount == 0) { emptyPivot = r.Pivots [i]; break; } } return emptyPivot != null; } public static bool GetFirstEmptyVisibleReceptaclePivot (Receptacle r, Camera camera, out Transform emptyPivot) { Plane[] planes = GeometryUtility.CalculateFrustumPlanes(camera); emptyPivot = null; for (int i = 0; i < r.Pivots.Length; i++) { Transform t = r.Pivots [i]; Bounds bounds = new Bounds (t.position, new Vector3 (0.05f, 0.05f, 0.05f)); if (t.childCount == 0 && GeometryUtility.TestPlanesAABB (planes, bounds)) { emptyPivot = r.Pivots [i]; break; } } return emptyPivot != null; } //tries to get a SimObj from a collider, returns false if none found public static bool GetSimObjFromCollider (Collider c, out SimObj o) { o = null; if (c.attachedRigidbody == null) { //all sim objs must have a kinematic rigidbody return false; } o = c.attachedRigidbody.GetComponent <SimObj> (); return o != null; } //tries to get a receptacle from a collider, returns false if none found public static bool GetReceptacleFromCollider (Collider c, out Receptacle r) { r = null; if (c.attachedRigidbody == null) { //all sim objs must have a kinematic rigidbody return false; } r = c.attachedRigidbody.GetComponent <Receptacle> (); return r != null; } //gets all SimObjs contained in a receptacle //this does not TAKE any of these items public static SimObj[] GetItemsFromReceptacle (Receptacle r) { List<SimObj> items = new List<SimObj>(); foreach (Transform t in r.Pivots) { if (t.childCount > 0) { items.Add(t.GetChild(0).GetComponent<SimObj>()); } } return items.ToArray(); } //gets all VISIBILE SimObjs contained in a receptacle //this does not TAKE any of these items public static SimObj[] GetVisibleItemsFromReceptacle (Receptacle r, Camera agentCamera, Vector3 agentCameraPos, float maxDistance) { List<SimObj> items = new List<SimObj>(); //RaycastHit hit = new RaycastHit(); foreach (Transform t in r.Pivots) { if (t.childCount > 0) { SimObj item = t.GetChild (0).GetComponent <SimObj> (); //check whether the item is visible (center point only) //since it's inside a receptacle, it will be on the invisible layer if (CheckPointVisibility (item.CenterPoint, agentCamera)) { item.VisibleNow = true; items.Add (item); } else { item.VisibleNow = false; } } } return items.ToArray(); } public static bool IsUniqueIDValid (string uniqueID) { return !string.IsNullOrEmpty (uniqueID); } #endregion #region editor commands #if UNITY_EDITOR [UnityEditor.MenuItem ("Thor/Set Up Base Objects")] public static void SetUpBaseObjects () { foreach (GameObject go in UnityEditor.Selection.gameObjects) { if (go.transform.childCount > 0 && go.transform.GetChild (0).name == "Base") { continue; } GameObject newGo = new GameObject (go.name); Vector3 newPos = go.transform.position; newPos.y = 0f; newGo.transform.position = newPos; go.transform.parent = newGo.transform; go.name = "Base"; BoxCollider bc = go.GetComponent<BoxCollider> (); if (bc == null) { go.AddComponent<BoxCollider> (); } } } public static void BuildScene (string scenePath, string buildName, string outputPath, UnityEditor.BuildTarget buildTarget, bool launchOnBuild) { Debug.Log ("Building scene '" + scenePath + "' to '" + outputPath + "'"); //set up the player correctly UnityEditor.PlayerSettings.companyName = "Allen Institute for Artificial Intelligence"; UnityEditor.PlayerSettings.productName = "RoboSims Platform - " + buildName; UnityEditor.PlayerSettings.defaultScreenWidth = 400; UnityEditor.PlayerSettings.defaultScreenWidth = 300; UnityEditor.PlayerSettings.runInBackground = true; UnityEditor.PlayerSettings.captureSingleScreen = false; UnityEditor.PlayerSettings.displayResolutionDialog = UnityEditor.ResolutionDialogSetting.Disabled; UnityEditor.PlayerSettings.usePlayerLog = true; UnityEditor.PlayerSettings.resizableWindow = false; UnityEditor.PlayerSettings.macFullscreenMode = UnityEditor.MacFullscreenMode.FullscreenWindowWithDockAndMenuBar; UnityEditor.PlayerSettings.d3d11FullscreenMode = UnityEditor.D3D11FullscreenMode.FullscreenWindow; //UnityEditor.PlayerSettings.d3d9FullscreenMode = UnityEditor.D3D9FullscreenMode.FullscreenWindow; UnityEditor.PlayerSettings.visibleInBackground = false; UnityEditor.PlayerSettings.allowFullscreenSwitch = true; UnityEditor.BuildPipeline.BuildPlayer ( new UnityEditor.EditorBuildSettingsScene [] { new UnityEditor.EditorBuildSettingsScene (scenePath, true) }, System.IO.Path.Combine (outputPath, buildName), buildTarget, launchOnBuild ? UnityEditor.BuildOptions.AutoRunPlayer : UnityEditor.BuildOptions.None); } [UnityEditor.MenuItem ("Thor/Replace Generic Prefabs in All Scenes")] static void ReplacePrefabsInAllScenes () { UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes (); for (int i = 1; i <= 30; i++) { string scenePath = "Assets/Scenes/FloorPlan" + i.ToString () + ".unity"; UnityEditor.EditorUtility.DisplayProgressBar ("Replacing generics...", scenePath, (1f / 30) * i); UnityEngine.SceneManagement.Scene openScene = new UnityEngine.SceneManagement.Scene (); try { openScene = UnityEditor.SceneManagement.EditorSceneManager.OpenScene (scenePath); } catch (Exception e) { Debug.LogException (e); continue; } //find the scene manager and tell it to replace all prefabs SceneManager sm = GameObject.FindObjectOfType<SceneManager> (); sm.ReplaceGenerics (); //save the scene and close it UnityEditor.SceneManagement.EditorSceneManager.SaveScene(openScene); if (UnityEditor.SceneManagement.EditorSceneManager.loadedSceneCount > 1) { UnityEditor.SceneManagement.EditorSceneManager.CloseScene(openScene, true); } } UnityEditor.EditorUtility.ClearProgressBar (); } [UnityEditor.MenuItem ("Thor/Set SceneManager Scene Number")] static void SetSceneManagerSceneNumber () { UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes (); for (int i = 1; i <= 30; i++) { string scenePath = "Assets/Scenes/FloorPlan" + (i + 200).ToString () + ".unity"; UnityEditor.EditorUtility.DisplayProgressBar ("Setting scene numbers...", scenePath, (1f / 30) * i); UnityEngine.SceneManagement.Scene openScene = new UnityEngine.SceneManagement.Scene (); try { openScene = UnityEditor.SceneManagement.EditorSceneManager.OpenScene (scenePath); } catch (Exception e) { Debug.LogException (e); continue; } //find the scene manager and tell it to replace all prefabs SceneManager sm = GameObject.FindObjectOfType<SceneManager> (); sm.SceneNumber = i; //save the scene and close it UnityEditor.SceneManagement.EditorSceneManager.SaveScene(openScene); if (UnityEditor.SceneManagement.EditorSceneManager.loadedSceneCount > 1) { UnityEditor.SceneManagement.EditorSceneManager.CloseScene(openScene, true); } } UnityEditor.EditorUtility.ClearProgressBar (); } [UnityEditor.MenuItem ("Thor/Set Pivot Scales to 1")] static void SetPivotScalesToOne () { Transform[] transforms = GameObject.FindObjectsOfType<Transform> (); foreach (Transform t in transforms) { if (t.name.Contains ("Pivot")) { GameObject prefabParent = null; if (UnityEditor.EditorUtility.IsPersistent (t)) { prefabParent = UnityEditor.PrefabUtility.GetPrefabParent (t) as GameObject; } Transform pivot = t; Transform tempParent = pivot.parent; Transform child = null; if (pivot.childCount > 0) { child = pivot.GetChild (0); child.parent = null; } pivot.parent = null; if (pivot.localScale != Vector3.one) { Debug.Log ("Found pivot with non-uniform scale (" + pivot.localScale.ToString() + ") " + pivot.name); } pivot.localScale = Vector3.one; if (child != null) { child.parent = pivot; } pivot.parent = tempParent; if (prefabParent != null) { Debug.Log ("Reconnecting to " + prefabParent.name); //UnityEditor.EditorUtility.ReconnectToLastPrefab (t.gameObject); depricated call, now use PrefabUtility UnityEditor.PrefabUtility.ReconnectToLastPrefab(t.gameObject); } } } UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty (UnityEngine.SceneManagement.SceneManager.GetActiveScene());//(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene ()); } #endif #endregion }
36.678233
199
0.71106
[ "Apache-2.0" ]
jsanmiya/ai2thor
unity/Assets/Scripts/SimUtil.cs
23,254
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable namespace Microsoft.AspNetCore.Routing.Patterns; internal class DefaultRoutePatternTransformer : RoutePatternTransformer { private readonly ParameterPolicyFactory _policyFactory; public DefaultRoutePatternTransformer(ParameterPolicyFactory policyFactory) { if (policyFactory == null) { throw new ArgumentNullException(nameof(policyFactory)); } _policyFactory = policyFactory; } public override RoutePattern SubstituteRequiredValues(RoutePattern original, object requiredValues) { if (original == null) { throw new ArgumentNullException(nameof(original)); } return SubstituteRequiredValuesCore(original, new RouteValueDictionary(requiredValues)); } private RoutePattern SubstituteRequiredValuesCore(RoutePattern original, RouteValueDictionary requiredValues) { // Process each required value in sequence. Bail if we find any rejection criteria. The goal // of rejection is to avoid creating RoutePattern instances that can't *ever* match. // // If we succeed, then we need to create a new RoutePattern with the provided required values. // // Substitution can merge with existing RequiredValues already on the RoutePattern as long // as all of the success criteria are still met at the end. foreach (var kvp in requiredValues) { // There are three possible cases here: // 1. Required value is null-ish // 2. Required value is *any* // 3. Required value corresponds to a parameter // 4. Required value corresponds to a matching default value // // If none of these are true then we can reject this substitution. RoutePatternParameterPart parameter; if (RouteValueEqualityComparer.Default.Equals(kvp.Value, string.Empty)) { // 1. Required value is null-ish - check to make sure that this route doesn't have a // parameter or filter-like default. if (original.GetParameter(kvp.Key) != null) { // Fail: we can't 'require' that a parameter be null. In theory this would be possible // for an optional parameter, but that's not really in line with the usage of this feature // so we don't handle it. // // Ex: {controller=Home}/{action=Index}/{id?} - with required values: { controller = "" } return null; } else if (original.Defaults.TryGetValue(kvp.Key, out var defaultValue) && !RouteValueEqualityComparer.Default.Equals(kvp.Value, defaultValue)) { // Fail: this route has a non-parameter default that doesn't match. // // Ex: Admin/{controller=Home}/{action=Index}/{id?} defaults: { area = "Admin" } - with required values: { area = "" } return null; } // Success: (for this parameter at least) // // Ex: {controller=Home}/{action=Index}/{id?} - with required values: { area = "", ... } continue; } else if (RoutePattern.IsRequiredValueAny(kvp.Value)) { // 2. Required value is *any* - this is allowed for a parameter with a default, but not // a non-parameter default. if (original.GetParameter(kvp.Key) == null && original.Defaults.TryGetValue(kvp.Key, out var defaultValue) && !RouteValueEqualityComparer.Default.Equals(string.Empty, defaultValue)) { // Fail: this route as a non-parameter default that is stricter than *any*. // // Ex: Admin/{controller=Home}/{action=Index}/{id?} defaults: { area = "Admin" } - with required values: { area = *any* } return null; } // Success: (for this parameter at least) // // Ex: {controller=Home}/{action=Index}/{id?} - with required values: { controller = *any*, ... } continue; } else if ((parameter = original.GetParameter(kvp.Key)) != null) { // 3. Required value corresponds to a parameter - check to make sure that this value matches // any IRouteConstraint implementations. if (!MatchesConstraints(original, parameter, kvp.Key, requiredValues)) { // Fail: this route has a constraint that failed. // // Ex: Admin/{controller:regex(Home|Login)}/{action=Index}/{id?} - with required values: { controller = "Store" } return null; } // Success: (for this parameter at least) // // Ex: {area}/{controller=Home}/{action=Index}/{id?} - with required values: { area = "", ... } continue; } else if (original.Defaults.TryGetValue(kvp.Key, out var defaultValue) && RouteValueEqualityComparer.Default.Equals(kvp.Value, defaultValue)) { // 4. Required value corresponds to a matching default value - check to make sure that this value matches // any IRouteConstraint implementations. It's unlikely that this would happen in practice but it doesn't // hurt for us to check. if (!MatchesConstraints(original, parameter: null, kvp.Key, requiredValues)) { // Fail: this route has a constraint that failed. // // Ex: // Admin/Home/{action=Index}/{id?} // defaults: { area = "Admin" } // constraints: { area = "Blog" } // with required values: { area = "Admin" } return null; } // Success: (for this parameter at least) // // Ex: Admin/{controller=Home}/{action=Index}/{id?} defaults: { area = "Admin" }- with required values: { area = "Admin", ... } continue; } else { // Fail: this is a required value for a key that doesn't appear in the templates, or the route // pattern has a different default value for a non-parameter. // // Ex: Admin/{controller=Home}/{action=Index}/{id?} defaults: { area = "Admin" }- with required values: { area = "Blog", ... } // OR (less likely) // Ex: Admin/{controller=Home}/{action=Index}/{id?} with required values: { page = "/Index", ... } return null; } } List<RoutePatternParameterPart> updatedParameters = null; List<RoutePatternPathSegment> updatedSegments = null; RouteValueDictionary updatedDefaults = null; // So if we get here, we're ready to update the route pattern. We need to update two things: // 1. Remove any default values that conflict with the required values. // 2. Merge any existing required values foreach (var kvp in requiredValues) { var parameter = original.GetParameter(kvp.Key); // We only need to handle the case where the required value maps to a parameter. That's the only // case where we allow a default and a required value to disagree, and we already validated the // other cases. // // If the required value is *any* then don't remove the default. if (parameter != null && !RoutePattern.IsRequiredValueAny(kvp.Value) && original.Defaults.TryGetValue(kvp.Key, out var defaultValue) && !RouteValueEqualityComparer.Default.Equals(kvp.Value, defaultValue)) { if (updatedDefaults == null && updatedSegments == null && updatedParameters == null) { updatedDefaults = new RouteValueDictionary(original.Defaults); updatedSegments = new List<RoutePatternPathSegment>(original.PathSegments); updatedParameters = new List<RoutePatternParameterPart>(original.Parameters); } updatedDefaults.Remove(kvp.Key); RemoveParameterDefault(updatedSegments, updatedParameters, parameter); } } foreach (var kvp in original.RequiredValues) { requiredValues.TryAdd(kvp.Key, kvp.Value); } return new RoutePattern( original.RawText, updatedDefaults ?? original.Defaults, original.ParameterPolicies, requiredValues, updatedParameters ?? original.Parameters, updatedSegments ?? original.PathSegments); } private bool MatchesConstraints(RoutePattern pattern, RoutePatternParameterPart parameter, string key, RouteValueDictionary requiredValues) { if (pattern.ParameterPolicies.TryGetValue(key, out var policies)) { for (var i = 0; i < policies.Count; i++) { var policy = _policyFactory.Create(parameter, policies[i]); if (policy is IRouteConstraint constraint) { if (!constraint.Match(httpContext: null, NullRouter.Instance, key, requiredValues, RouteDirection.IncomingRequest)) { return false; } } } } return true; } private static void RemoveParameterDefault(List<RoutePatternPathSegment> segments, List<RoutePatternParameterPart> parameters, RoutePatternParameterPart parameter) { // We know that a parameter can only appear once, so we only need to rewrite one segment and one parameter. for (var i = 0; i < segments.Count; i++) { var segment = segments[i]; for (var j = 0; j < segment.Parts.Count; j++) { if (object.ReferenceEquals(parameter, segment.Parts[j])) { // Found it! var updatedParameter = RoutePatternFactory.ParameterPart(parameter.Name, @default: null, parameter.ParameterKind, parameter.ParameterPolicies); var updatedParts = new List<RoutePatternPart>(segment.Parts); updatedParts[j] = updatedParameter; segments[i] = RoutePatternFactory.Segment(updatedParts); for (var k = 0; k < parameters.Count; k++) { if (ReferenceEquals(parameter, parameters[k])) { parameters[k] = updatedParameter; break; } } return; } } } } }
45.932
167
0.553601
[ "MIT" ]
Aezura/aspnetcore
src/Http/Routing/src/Patterns/DefaultRoutePatternTransformer.cs
11,483
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; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel { /// <summary> /// Represents a collection of events. /// </summary> public class EventDescriptorCollection : ICollection, IList { private EventDescriptor[] _events; private readonly string[] _namedSort; private readonly IComparer _comparer; private bool _eventsOwned; private bool _needSort; private readonly bool _readOnly; /// <summary> /// An empty AttributeCollection that can used instead of creating a new one with no items. /// </summary> public static readonly EventDescriptorCollection Empty = new EventDescriptorCollection(null, true); /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.EventDescriptorCollection'/> class. /// </summary> public EventDescriptorCollection(EventDescriptor[] events) { if (events == null) { _events = Array.Empty<EventDescriptor>(); } else { _events = events; Count = events.Length; } _eventsOwned = true; } /// <summary> /// Initializes a new instance of an event descriptor collection, and allows you to mark the /// collection as read-only so it cannot be modified. /// </summary> public EventDescriptorCollection(EventDescriptor[] events, bool readOnly) : this(events) { _readOnly = readOnly; } private EventDescriptorCollection(EventDescriptor[] events, int eventCount, string[] namedSort, IComparer comparer) { _eventsOwned = false; if (namedSort != null) { _namedSort = (string[])namedSort.Clone(); } _comparer = comparer; _events = events; Count = eventCount; _needSort = true; } /// <summary> /// Gets the number of event descriptors in the collection. /// </summary> public int Count { get; private set; } /// <summary> /// Gets the event with the specified index number. /// </summary> public virtual EventDescriptor this[int index] { get { if (index >= Count) { throw new IndexOutOfRangeException(); } EnsureEventsOwned(); return _events[index]; } } /// <summary> /// Gets the event with the specified name. /// </summary> public virtual EventDescriptor this[string name] => Find(name, false); public int Add(EventDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } EnsureSize(Count + 1); _events[Count++] = value; return Count - 1; } public void Clear() { if (_readOnly) { throw new NotSupportedException(); } Count = 0; } public bool Contains(EventDescriptor value) => IndexOf(value) >= 0; void ICollection.CopyTo(Array array, int index) { EnsureEventsOwned(); Array.Copy(_events, 0, array, index, Count); } private void EnsureEventsOwned() { if (!_eventsOwned) { _eventsOwned = true; if (_events != null) { EventDescriptor[] newEvents = new EventDescriptor[Count]; Array.Copy(_events, newEvents, Count); _events = newEvents; } } if (_needSort) { _needSort = false; InternalSort(_namedSort); } } private void EnsureSize(int sizeNeeded) { if (sizeNeeded <= _events.Length) { return; } if (_events.Length == 0) { Count = 0; _events = new EventDescriptor[sizeNeeded]; return; } EnsureEventsOwned(); int newSize = Math.Max(sizeNeeded, _events.Length * 2); EventDescriptor[] newEvents = new EventDescriptor[newSize]; Array.Copy(_events, newEvents, Count); _events = newEvents; } /// <summary> /// Gets the description of the event with the specified /// name in the collection. /// </summary> public virtual EventDescriptor Find(string name, bool ignoreCase) { EventDescriptor p = null; if (ignoreCase) { for (int i = 0; i < Count; i++) { if (string.Equals(_events[i].Name, name, StringComparison.OrdinalIgnoreCase)) { p = _events[i]; break; } } } else { for (int i = 0; i < Count; i++) { if (string.Equals(_events[i].Name, name, StringComparison.Ordinal)) { p = _events[i]; break; } } } return p; } public int IndexOf(EventDescriptor value) => Array.IndexOf(_events, value, 0, Count); public void Insert(int index, EventDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } EnsureSize(Count + 1); if (index < Count) { Array.Copy(_events, index, _events, index + 1, Count - index); } _events[index] = value; Count++; } public void Remove(EventDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } int index = IndexOf(value); if (index != -1) { RemoveAt(index); } } public void RemoveAt(int index) { if (_readOnly) { throw new NotSupportedException(); } if (index < Count - 1) { Array.Copy(_events, index + 1, _events, index, Count - index - 1); } _events[Count - 1] = null; Count--; } /// <summary> /// Gets an enumerator for this <see cref='System.ComponentModel.EventDescriptorCollection'/>. /// </summary> public IEnumerator GetEnumerator() { // We can only return an enumerator on the events we actually have. if (_events.Length == Count) { return _events.GetEnumerator(); } else { return new ArraySubsetEnumerator(_events, Count); } } /// <summary> /// Sorts the members of this EventDescriptorCollection, using the default sort for this collection, /// which is usually alphabetical. /// </summary> public virtual EventDescriptorCollection Sort() { return new EventDescriptorCollection(_events, Count, _namedSort, _comparer); } /// <summary> /// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </summary> public virtual EventDescriptorCollection Sort(string[] names) { return new EventDescriptorCollection(_events, Count, names, _comparer); } /// <summary> /// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </summary> public virtual EventDescriptorCollection Sort(string[] names, IComparer comparer) { return new EventDescriptorCollection(_events, Count, names, comparer); } /// <summary> /// Sorts the members of this EventDescriptorCollection, using the specified IComparer to compare, /// the EventDescriptors contained in the collection. /// </summary> public virtual EventDescriptorCollection Sort(IComparer comparer) { return new EventDescriptorCollection(_events, Count, _namedSort, comparer); } /// <summary> /// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </summary> protected void InternalSort(string[] names) { if (_events.Length == 0) { return; } InternalSort(_comparer); if (names != null && names.Length > 0) { List<EventDescriptor> eventList = new List<EventDescriptor>(_events); int foundCount = 0; int eventCount = _events.Length; for (int i = 0; i < names.Length; i++) { for (int j = 0; j < eventCount; j++) { EventDescriptor currentEvent = eventList[j]; // Found a matching event. Here, we add it to our array. We also // mark it as null in our array list so we don't add it twice later. // if (currentEvent != null && currentEvent.Name.Equals(names[i])) { _events[foundCount++] = currentEvent; eventList[j] = null; break; } } } // At this point we have filled in the first "foundCount" number of propeties, one for each // name in our name array. If a name didn't match, then it is ignored. Next, we must fill // in the rest of the properties. We now have a sparse array containing the remainder, so // it's easy. // for (int i = 0; i < eventCount; i++) { if (eventList[i] != null) { _events[foundCount++] = eventList[i]; } } Debug.Assert(foundCount == eventCount, "We did not completely fill our event array"); } } /// <summary> /// Sorts the members of this EventDescriptorCollection using the specified IComparer. /// </summary> protected void InternalSort(IComparer sorter) { if (sorter == null) { TypeDescriptor.SortDescriptorArray(this); } else { Array.Sort(_events, sorter); } } bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => null; int ICollection.Count => Count; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); object IList.this[int index] { get => this[index]; set { if (_readOnly) { throw new NotSupportedException(); } if (index >= Count) { throw new IndexOutOfRangeException(); } EnsureEventsOwned(); _events[index] = (EventDescriptor)value; } } int IList.Add(object value) => Add((EventDescriptor)value); bool IList.Contains(object value) => Contains((EventDescriptor)value); void IList.Clear() => Clear(); int IList.IndexOf(object value) => IndexOf((EventDescriptor)value); void IList.Insert(int index, object value) => Insert(index, (EventDescriptor)value); void IList.Remove(object value) => Remove((EventDescriptor)value); void IList.RemoveAt(int index) => RemoveAt(index); bool IList.IsReadOnly => _readOnly; bool IList.IsFixedSize => _readOnly; private class ArraySubsetEnumerator : IEnumerator { private readonly Array _array; private readonly int _total; private int _current; public ArraySubsetEnumerator(Array array, int count) { Debug.Assert(count == 0 || array != null, "if array is null, count should be 0"); Debug.Assert(array == null || count <= array.Length, "Trying to enumerate more than the array contains"); _array = array; _total = count; _current = -1; } public bool MoveNext() { if (_current < _total - 1) { _current++; return true; } else { return false; } } public void Reset() => _current = -1; public object Current { get { if (_current == -1) { throw new InvalidOperationException(); } else { return _array.GetValue(_current); } } } } } }
31.222944
123
0.490607
[ "MIT" ]
06needhamt/runtime
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/EventDescriptorCollection.cs
14,425
C#
using NBitcoin; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using WalletWasabi.BitcoinCore; using WalletWasabi.Blockchain.Blocks; using WalletWasabi.Blockchain.Mempool; using WalletWasabi.Blockchain.Transactions; using WalletWasabi.Helpers; using WalletWasabi.Services; using WalletWasabi.Stores; using WalletWasabi.Tests.Helpers; using WalletWasabi.Wallets; using Xunit; namespace WalletWasabi.Tests.UnitTests.BitcoinCore { /// <seealso cref="XunitConfiguration.SerialCollectionDefinition"/> [Collection("Serial unit tests collection")] public class P2pBasedTests { [Fact] public async Task MempoolNotifiesAsync() { using var services = new HostedServices(); var coreNode = await TestNodeBuilder.CreateAsync(services); await services.StartAllAsync(CancellationToken.None); using var node = await coreNode.CreateNewP2pNodeAsync(); try { var network = coreNode.Network; var rpc = coreNode.RpcClient; var dir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName()); var indexStore = new IndexStore(Path.Combine(dir, "indexStore"), network, new SmartHeaderChain()); var transactionStore = new AllTransactionStore(Path.Combine(dir, "transactionStore"), network); var mempoolService = new MempoolService(); var blocks = new FileSystemBlockRepository(Path.Combine(dir, "blocks"), network); var bitcoinStore = new BitcoinStore(indexStore, transactionStore, mempoolService, blocks); await bitcoinStore.InitializeAsync(); await rpc.GenerateAsync(101); node.Behaviors.Add(bitcoinStore.CreateUntrustedP2pBehavior()); node.VersionHandshake(); var addr = new Key().PubKey.GetSegwitAddress(network); var txNum = 10; var eventAwaiter = new EventsAwaiter<SmartTransaction>( h => bitcoinStore.MempoolService.TransactionReceived += h, h => bitcoinStore.MempoolService.TransactionReceived -= h, txNum); var txTasks = new List<Task<uint256>>(); var batch = rpc.PrepareBatch(); for (int i = 0; i < txNum; i++) { txTasks.Add(batch.SendToAddressAsync(addr, Money.Coins(1))); } var batchTask = batch.SendBatchAsync(); var stxs = await eventAwaiter.WaitAsync(TimeSpan.FromSeconds(21)); await batchTask; var hashes = await Task.WhenAll(txTasks); foreach (var stx in stxs) { Assert.Contains(stx.GetHash(), hashes); } } finally { await services.StopAllAsync(CancellationToken.None); node.Disconnect(); await coreNode.TryStopAsync(); } } [Fact] public async Task TrustedNotifierNotifiesTxAsync() { using var services = new HostedServices(); var coreNode = await TestNodeBuilder.CreateAsync(services); await services.StartAllAsync(CancellationToken.None); try { var rpc = coreNode.RpcClient; await rpc.GenerateAsync(101); var network = rpc.Network; var dir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName(), EnvironmentHelpers.GetMethodName()); var addr = new Key().PubKey.GetSegwitAddress(network); var notifier = coreNode.MempoolService; var txNum = 10; var txEventAwaiter = new EventsAwaiter<SmartTransaction>( h => notifier.TransactionReceived += h, h => notifier.TransactionReceived -= h, txNum); var txTasks = new List<Task<uint256>>(); var batch = rpc.PrepareBatch(); for (int i = 0; i < txNum; i++) { txTasks.Add(batch.SendToAddressAsync(addr, Money.Coins(1))); } var batchTask = batch.SendBatchAsync(); var arrivedTxs = await txEventAwaiter.WaitAsync(TimeSpan.FromSeconds(21)); await batchTask; var hashes = await Task.WhenAll(txTasks); foreach (var hash in arrivedTxs.Select(x => x.GetHash())) { Assert.Contains(hash, hashes); } } finally { await services.StopAllAsync(CancellationToken.None); await coreNode.TryStopAsync(); } } [Fact] public async Task BlockNotifierTestsAsync() { using var services = new HostedServices(); var coreNode = await TestNodeBuilder.CreateAsync(services); await services.StartAllAsync(CancellationToken.None); try { var rpc = coreNode.RpcClient; BlockNotifier notifier = services.FirstOrDefault<BlockNotifier>(); // Make sure we get notification for one block. var blockEventAwaiter = new EventAwaiter<Block>( h => notifier.OnBlock += h, h => notifier.OnBlock -= h); var hash = (await rpc.GenerateAsync(1)).First(); var block = await blockEventAwaiter.WaitAsync(TimeSpan.FromSeconds(21)); Assert.Equal(hash, block.GetHash()); // Make sure we get notifications about 10 blocks created at the same time. var blockNum = 10; var blockEventsAwaiter = new EventsAwaiter<Block>( h => notifier.OnBlock += h, h => notifier.OnBlock -= h, blockNum); var hashes = (await rpc.GenerateAsync(blockNum)).ToArray(); var arrivedBlocks = (await blockEventsAwaiter.WaitAsync(TimeSpan.FromSeconds(21))).ToArray(); for (int i = 0; i < hashes.Length; i++) { var expected = hashes[i]; var actual = arrivedBlocks[i].GetHash(); Assert.Equal(expected, actual); } // Make sure we get reorg notifications. var reorgNum = 3; var newBlockNum = reorgNum + 1; var reorgEventsAwaiter = new EventsAwaiter<uint256>( h => notifier.OnReorg += h, h => notifier.OnReorg -= h, reorgNum); blockEventsAwaiter = new EventsAwaiter<Block>( h => notifier.OnBlock += h, h => notifier.OnBlock -= h, newBlockNum); var reorgedHashes = hashes.TakeLast(reorgNum).ToArray(); await rpc.InvalidateBlockAsync(reorgedHashes[0]); var newHashes = (await rpc.GenerateAsync(newBlockNum)).ToArray(); var reorgedHeaders = (await reorgEventsAwaiter.WaitAsync(TimeSpan.FromSeconds(21))).ToArray(); var newBlocks = (await blockEventsAwaiter.WaitAsync(TimeSpan.FromSeconds(21))).ToArray(); reorgedHashes = reorgedHashes.Reverse().ToArray(); for (int i = 0; i < reorgedHashes.Length; i++) { var expected = reorgedHashes[i]; var actual = reorgedHeaders[i]; Assert.Equal(expected, actual); } for (int i = 0; i < newHashes.Length; i++) { var expected = newHashes[i]; var actual = newBlocks[i].GetHash(); Assert.Equal(expected, actual); } } finally { await services.StopAllAsync(CancellationToken.None); await coreNode.TryStopAsync(); } } } }
31.5
128
0.69932
[ "MIT" ]
zero77/WalletWasabi
WalletWasabi.Tests/UnitTests/BitcoinCore/P2pBasedTests.cs
6,615
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PipelineR.StartingSample.Models { public class DepositAccountModel { public string Nome { get; set; } } }
18.076923
41
0.723404
[ "MIT" ]
eduardosbcabral/pipeliner2
src/PipelineR.StartingSample/Models/DepositAccountModel.cs
237
C#
using DFC.Digital.Data.Interfaces; using System; namespace DFC.Digital.Data.Model { public class PreSearchFilter : IDigitalDataModel { public Guid? Id { get; set; } public string UrlName { get; set; } public string Title { get; set; } public string Description { get; set; } public decimal? Order { get; set; } public bool? NotApplicable { get; set; } } }
21.1
52
0.613744
[ "MIT" ]
Muthuramana/dfc-digital
DFC.Digital/DFC.Digital.Data/Model/PreSearchFilter.cs
424
C#
using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace WipHello.Services.NavigationService { public class NavigationService { private readonly NavigationFacade _frame; private const string EmptyNavigation = "1,0"; string LastNavigationParameter { get; set; /* TODO: persist */ } string LastNavigationType { get; set; /* TODO: persist */ } public NavigationService(Frame frame) { _frame = new NavigationFacade(frame); _frame.Navigating += (s, e) => NavigateFrom(false); _frame.Navigated += (s, e) => NavigateTo(e.NavigationMode, e.Parameter); } void NavigateFrom(bool suspending) { var page = _frame.Content as FrameworkElement; if (page != null) { var dataContext = page.DataContext as INavigatable; if (dataContext != null) { dataContext.OnNavigatedFrom(null, suspending); } } } void NavigateTo(NavigationMode mode, string parameter) { LastNavigationParameter = parameter; LastNavigationType = _frame.Content.GetType().FullName; if (mode == NavigationMode.New) { // TODO: clear existing state } var page = _frame.Content as FrameworkElement; if (page != null) { var dataContext = page.DataContext as INavigatable; if (dataContext != null) { dataContext.OnNavigatedTo(parameter, mode, null); } } } public bool Navigate(Type page, string parameter = null) { if (page == null) throw new ArgumentNullException(nameof(page)); if (page.FullName.Equals(LastNavigationType) && parameter == LastNavigationParameter) return false; return _frame.Navigate(page, parameter); } public void RestoreSavedNavigation() { /* TODO */ } public void GoBack() { if (_frame.CanGoBack) _frame.GoBack(); } public bool CanGoBack { get { return _frame.CanGoBack; } } public void GoForward() { _frame.GoForward(); } public bool CanGoForward { get { return _frame.CanGoForward; } } public void ClearHistory() { _frame.SetNavigationState(EmptyNavigation); } public void Suspending() { NavigateFrom(true); } public void Show(SettingsFlyout flyout, string parameter = null) { if (flyout == null) throw new ArgumentNullException(nameof(flyout)); var dataContext = flyout.DataContext as INavigatable; if (dataContext != null) { dataContext.OnNavigatedTo(parameter, NavigationMode.New, null); } flyout.Show(); } public Type CurrentPageType { get { return _frame.CurrentPageType; } } public string CurrentPageParam { get { return _frame.CurrentPageParam; } } } }
32.373737
84
0.566927
[ "MIT" ]
NoleHealth/Win10TPNoleDev
HelloWorld1/WipHello/Services/NavigationService/NavigationService.cs
3,207
C#
using System.Threading.Tasks; using FCMDotNet.Model; namespace FCMDotNet { public interface IFCMClient { /// <summary> /// Posts a message to Firebase /// </summary> /// <param name="message">Message to send. Use FCMMessageBuilder to construct it</param> /// <returns></returns> Task<FCMResponse> PostMessage(FCMMessage message); } }
26.266667
96
0.629442
[ "Apache-2.0" ]
chedabob/FCMDotNet
FCMDotNet/IFCMClient.cs
394
C#
// _ _ _ ____ _ _____ // / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___ // / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \ // / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | | // /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_| // | // Copyright 2015-2020 Łukasz "JustArchi" Domeradzki // Contact: JustArchi@JustArchi.net // | // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // | // http://www.apache.org/licenses/LICENSE-2.0 // | // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.IO; using System.Text; using SteamKit2; using SteamKit2.Internal; namespace ArchiSteamFarm.CMsgs { internal sealed class CMsgClientAcknowledgeClanInvite : ISteamSerializableMessage { internal bool AcceptInvite { private get; set; } internal ulong ClanID { private get; set; } void ISteamSerializable.Deserialize(Stream stream) { if (stream == null) { ASF.ArchiLogger.LogNullError(nameof(stream)); return; } using BinaryReader binaryReader = new BinaryReader(stream, Encoding.UTF8, true); ClanID = binaryReader.ReadUInt64(); AcceptInvite = binaryReader.ReadBoolean(); } EMsg ISteamSerializableMessage.GetEMsg() => EMsg.ClientAcknowledgeClanInvite; void ISteamSerializable.Serialize(Stream stream) { if (stream == null) { ASF.ArchiLogger.LogNullError(nameof(stream)); return; } using BinaryWriter binaryWriter = new BinaryWriter(stream, Encoding.UTF8, true); binaryWriter.Write(ClanID); binaryWriter.Write(AcceptInvite); } } }
34.901639
97
0.636919
[ "Apache-2.0" ]
JARVIS-AI/ArchiSteamFarm
ArchiSteamFarm/CMsgs/CMsgClientAcknowledgeClanInvite.cs
2,130
C#
using System.Collections.Generic; namespace Polo.Abstractions.Parameters { public interface IParameterInfo { // TODO LA - Remove public static string Name { get; } public static IReadOnlyCollection<string> PossibleValues { get; } public static string Description { get; } } }
21.6
73
0.666667
[ "MIT" ]
LA777/photo-organizer-light-ops
Polo.Abstractions/Parameters/IParameterInfo.cs
326
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Precedence; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses { internal abstract class AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer< TLanguageKindEnum, TParenthesizedExpressionSyntax> : AbstractParenthesesDiagnosticAnalyzer where TLanguageKindEnum : struct where TParenthesizedExpressionSyntax : SyntaxNode { /// <summary> /// A diagnostic descriptor used to squiggle and message the span. /// </summary> private static readonly DiagnosticDescriptor s_diagnosticDescriptor = CreateDescriptorWithId( IDEDiagnosticIds.RemoveUnnecessaryParenthesesDiagnosticId, new LocalizableResourceString(nameof(AnalyzersResources.Remove_unnecessary_parentheses), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Parentheses_can_be_removed), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), isUnnecessary: true); protected AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer() : base(ImmutableArray.Create(s_diagnosticDescriptor)) { } protected abstract TLanguageKindEnum GetSyntaxKind(); protected abstract ISyntaxFacts GetSyntaxFacts(); public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, GetSyntaxKind()); protected abstract bool CanRemoveParentheses( TParenthesizedExpressionSyntax parenthesizedExpression, SemanticModel semanticModel, out PrecedenceKind precedence, out bool clarifiesPrecedence); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var parenthesizedExpression = (TParenthesizedExpressionSyntax)context.Node; if (!CanRemoveParentheses(parenthesizedExpression, context.SemanticModel, out var precedence, out var clarifiesPrecedence)) { return; } // Do not remove parentheses from these expressions when there are different kinds // between the parent and child of the parenthesized expr.. This is because removing // these parens can significantly decrease readability and can confuse many people // (including several people quizzed on Roslyn). For example, most people see // "1 + 2 << 3" as "1 + (2 << 3)", when it's actually "(1 + 2) << 3". To avoid // making code bases more confusing, we just do not touch parens for these constructs // unless both the child and parent have the same kinds. switch (precedence) { case PrecedenceKind.Shift: case PrecedenceKind.Bitwise: case PrecedenceKind.Coalesce: var syntaxFacts = GetSyntaxFacts(); var child = syntaxFacts.GetExpressionOfParenthesizedExpression(parenthesizedExpression); var parentKind = parenthesizedExpression.Parent?.RawKind; var childKind = child.RawKind; if (parentKind != childKind) { return; } // Ok to remove if it was the exact same kind. i.e. ```(a | b) | c``` // not ok to remove if kinds changed. i.e. ```(a + b) << c``` break; } var option = GetLanguageOption(precedence); var preference = context.GetOption(option, parenthesizedExpression.Language); if (preference.Notification.Severity == ReportDiagnostic.Suppress) { // User doesn't care about these parens. So nothing for us to do. return; } if (preference.Value == ParenthesesPreference.AlwaysForClarity && clarifiesPrecedence) { // User wants these parens if they clarify precedence, and these parens // clarify precedence. So keep these around. return; } // either they don't want unnecessary parentheses, or they want them only for // clarification purposes and this does not make things clear. Debug.Assert(preference.Value == ParenthesesPreference.NeverIfUnnecessary || !clarifiesPrecedence); var severity = preference.Notification.Severity; var additionalLocations = ImmutableArray.Create( parenthesizedExpression.GetLocation()); var additionalUnnecessaryLocations = ImmutableArray.Create( parenthesizedExpression.GetFirstToken().GetLocation(), parenthesizedExpression.GetLastToken().GetLocation()); context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags( s_diagnosticDescriptor, GetDiagnosticSquiggleLocation(parenthesizedExpression, context.CancellationToken), severity, additionalLocations, additionalUnnecessaryLocations)); } /// <summary> /// Gets the span of text to squiggle underline. /// If the expression is contained within a single line, the entire expression span is returned. /// Otherwise it will return the span from the expression start to the end of the same line. /// </summary> private static Location GetDiagnosticSquiggleLocation(TParenthesizedExpressionSyntax parenthesizedExpression, CancellationToken cancellationToken) { var parenthesizedExpressionLocation = parenthesizedExpression.GetLocation(); var lines = parenthesizedExpression.SyntaxTree.GetText(cancellationToken).Lines; var expressionFirstLine = lines.GetLineFromPosition(parenthesizedExpressionLocation.SourceSpan.Start); var textSpanEndPosition = Math.Min(parenthesizedExpressionLocation.SourceSpan.End, expressionFirstLine.Span.End); return Location.Create(parenthesizedExpression.SyntaxTree, TextSpan.FromBounds(parenthesizedExpressionLocation.SourceSpan.Start, textSpanEndPosition)); } } }
48.625
169
0.668952
[ "MIT" ]
BrianFreemanAtlanta/roslyn
src/Analyzers/Core/Analyzers/RemoveUnnecessaryParentheses/AbstractRemoveUnnecessaryParenthesesDiagnosticAnalyzer.cs
7,004
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using Boilerplate.Application.DTOs; using Boilerplate.Application.DTOs.Person; using Boilerplate.Application.Extensions; using Boilerplate.Application.Filters; using Boilerplate.Application.Interfaces; using Boilerplate.Domain.Entities; using Boilerplate.Domain.Interfaces.Repositories; using Microsoft.EntityFrameworkCore; namespace Boilerplate.Application.Services { public class PersonAppService : IPersonAppService { private readonly IPersonRepository _PersonRepository; private readonly IMapper _mapper; public PersonAppService(IMapper mapper, IPersonRepository PersonRepository) { _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); _PersonRepository = PersonRepository ?? throw new ArgumentNullException(nameof(PersonRepository)); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) _PersonRepository.Dispose(); } #region Person Methods public async Task<PaginatedList<GetPersonDto>> GetAllPersons(GetPersonsFilter filter) { filter ??= new GetPersonsFilter(); var Persons = _PersonRepository .GetAll() .WhereIf(!string.IsNullOrEmpty(filter.Name), x => EF.Functions.Like(x.Name, $"%{filter.Name}%")) .WhereIf(!string.IsNullOrEmpty(filter.Nickname), x => EF.Functions.Like(x.Nickname, $"%{filter.Nickname}%")) .WhereIf(filter.Age != null, x => x.Age == filter.Age) .WhereIf(filter.Sex != null, x => x.Sex == filter.Sex) .WhereIf(!string.IsNullOrEmpty(filter.Job), x => EF.Functions.Like(x.Job, $"%{filter.Job}%")); return await _mapper.ProjectTo<GetPersonDto>(Persons).ToPaginatedListAsync(filter.CurrentPage, filter.PageSize); } public async Task<GetPersonDto> GetPersonById(Guid id) { return _mapper.Map<GetPersonDto>(await _PersonRepository.GetById(id)); } public async Task<GetPersonDto> CreatePerson(InsertPersonDto Person) { var created = _PersonRepository.Create(_mapper.Map<Person>(Person)); await _PersonRepository.SaveChangesAsync(); return _mapper.Map<GetPersonDto>(created); } public async Task<GetPersonDto> UpdatePerson(Guid id, UpdatePersonDto updatedPerson) { var originalPerson = await _PersonRepository.GetById(id); if (originalPerson == null) return null; originalPerson.Name = updatedPerson.Name; originalPerson.Nickname = updatedPerson.Nickname; originalPerson.Job = updatedPerson.Job; originalPerson.Age = updatedPerson.Age; originalPerson.Sex = updatedPerson.Sex; _PersonRepository.Update(originalPerson); await _PersonRepository.SaveChangesAsync(); return _mapper.Map<GetPersonDto>(originalPerson); } public async Task<bool> DeletePerson(Guid id) { await _PersonRepository.Delete(id); return await _PersonRepository.SaveChangesAsync() > 0; } #endregion } }
37.922222
124
0.656607
[ "MIT" ]
RenanPessotti/netcore-api-boilerplate
src/Boilerplate.Application/Services/PersonAppService.cs
3,415
C#
using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Dinner.Models { public class SQLRecipeRepository : IRecipeRepository { private readonly AppDbContext context; public SQLRecipeRepository(AppDbContext context) { this.context = context; } public Recipe Add(Recipe recipe) { context.Recipes.Add(recipe); context.SaveChanges(); return recipe; } public Recipe Delete(int id) { Recipe recipe = context.Recipes.Find(id); if (recipe != null) { context.Recipes.Remove(recipe); context.SaveChanges(); } return recipe; } public IEnumerable<Recipe> GetAllRecipe() { return context.Recipes; } public IEnumerable<Recipe> GetNewRecipes() { var recipeList = context.Recipes.ToList(); recipeList.Sort((x, y) => DateTime.Compare(x.AddedTime, y.AddedTime)); var elements = recipeList.Take(15); return elements; } public IEnumerable<Recipe> GetBestRecipesFromLastDays() { DateTime today = DateTime.Today; DateTime lastDay = today.AddDays(-30); var recipeList = context.Recipes.ToList(); var lastRecipes = recipeList.Where(e => e.AddedTime <= today && e.AddedTime >= lastDay).ToList(); var values = lastRecipes.OrderByDescending(p => p.Rating).ToList(); var elements = values.Take(15); return elements; } public Recipe GetRecipe(int id) { return context.Recipes.Find(id); } public Recipe Update(Recipe recipeChanges) { var recipe = context.Recipes.Attach(recipeChanges); recipe.State = Microsoft.EntityFrameworkCore.EntityState.Modified; context.SaveChanges(); return recipeChanges; } public IEnumerable<Recipe> GetAllBreakfastRecipes() { return context.Recipes; } public IEnumerable<Recipe> GetAllRecipesWithQuery(string querry) { if (querry != null) { return context.Recipes.Where(e => e.Name.ToLower().Contains(querry)); } else { return context.Recipes; } } public IEnumerable<Recipe> GetAllRecipesOfUser(string userId) { return context.Recipes.Where(e => e.AuthorId == userId); } public IEnumerable<Recipe> GetThreeRandomUserRecipes(string userId) { List<Recipe> _recipes = context.Recipes.Where(e => e.AuthorId == userId).ToList(); Random rand = new Random(); List<Recipe> chosedRecipes = new List<Recipe>(); int amount = _recipes.Count(); if (amount > 3) { amount = 3; } for (int i =0; i < amount; i++) { int index = rand.Next(0, _recipes.Count()); chosedRecipes.Add(_recipes.ElementAt(index)); _recipes.RemoveAt(index); } return chosedRecipes; } public IEnumerable<Recipe> GetThreeRandomRecipes() { List<Recipe> _recipes = context.Recipes.ToList(); Random rand = new Random(); List<Recipe> chosedRecipes = new List<Recipe>(); for (int i = 0; i < 3; i++) { int index = rand.Next(0, _recipes.Count()); chosedRecipes.Add(_recipes.ElementAt(index)); } return chosedRecipes; } public Recipe GetRandomRecipe() { Random rand = new Random(); int index = rand.Next(0, context.Recipes.Count()); List<Recipe> _recipes = context.Recipes.ToList(); Recipe recipe = _recipes.ElementAt(index); return recipe; } public IEnumerable<Recipe> GetAllRecipesForCollections(string querry) { return context.Recipes.Where(e => e.Tags.ToLower().Contains(querry)); } public IQueryable<Recipe> GetAdvancedSearchRecipes(AdvancedSearchModel searchModel) { var result = context.Recipes.AsQueryable(); if (searchModel != null) { if (!string.IsNullOrEmpty(searchModel.Name)) { result = result.Where(e => e.Name.ToLower().Contains(searchModel.Name)); } if (searchModel.Tags != null) { foreach (var tag in searchModel.Tags) { if (tag != null) result = result.Where(x => x.Tags.ToLower().Contains(tag)); } } if (searchModel.Ingridients != null) { foreach (var ingridient in searchModel.Ingridients) { if(ingridient != null) result = result.Where(x => x.Ingridients.ToLower().Contains(ingridient)); } } if (searchModel.DifficultLevel.HasValue) { result = result.Where(x => x.DifficultLevel == searchModel.DifficultLevel); } if (searchModel.TimeMin.HasValue || (searchModel.TimeMax.HasValue)) { if (!searchModel.TimeMin.HasValue) searchModel.TimeMin = 0; if (!searchModel.TimeMax.HasValue) searchModel.TimeMax = 999999999; result = result.Where(x => x.Time >= searchModel.TimeMin && x.Time <= searchModel.TimeMax); } if (searchModel.Rating.HasValue) { result = result.Where(x => x.Rating == searchModel.Rating); } } return result; } } }
35.348315
111
0.512397
[ "MIT" ]
Artist2305/ChefMaster
Models/SQLRecipeRepository.cs
6,294
C#
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2015 FUJIWARA, Yusuke // // 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. // #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; #if ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY using System.Runtime.InteropServices.ComTypes; #endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY namespace MsgPack.Serialization.DefaultSerializers { internal static class InternalDateTimeExtensions { #if SILVERLIGHT // Porting of reference sources ToBinary(). // See https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/datetime.cs private const UInt64 LocalMask = 0x8000000000000000; private const Int64 TicksCeiling = 0x4000000000000000; private const Int32 KindShift = 62; public static Int64 ToBinary( this DateTime source ) { if ( source.Kind == DateTimeKind.Local ) { // Local times need to be adjusted as you move from one time zone to another, // just as they are when serializing in text. As such the format for local times // changes to store the ticks of the UTC time, but with flags that look like a // local date. // To match serialization in text we need to be able to handle cases where // the UTC value would be out of range. Unused parts of the ticks range are // used for this, so that values just past max value are stored just past the // end of the maximum range, and values just below minimum value are stored // at the end of the ticks area, just below 2^62. var offset = TimeZoneInfo.Local.GetUtcOffset( source ); var ticks = source.Ticks; var storedTicks = ticks - offset.Ticks; if ( storedTicks < 0 ) { storedTicks = TicksCeiling + storedTicks; } return storedTicks | ( unchecked( ( Int64 )LocalMask ) ); } else { return ( Int64 )( ( ulong )source.Ticks | ( ( ulong )source.Kind << KindShift ) ); } } // End porting #endif // SILVERLIGHT #if ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY private static readonly DateTime _fileTimeEpocUtc = new DateTime( 1601, 1, 1, 0, 0, 0, DateTimeKind.Utc ); public static DateTime ToDateTime( this FILETIME source ) { // DateTime.FromFileTimeUtc in Mono 2.10.x does not return Utc DateTime (Mono issue #2936), so do convert manually to ensure returned DateTime is UTC. return _fileTimeEpocUtc.AddTicks( unchecked( ( ( long )source.dwHighDateTime << 32 ) | ( source.dwLowDateTime & 0xffffffff ) ) ); } public static FILETIME ToWin32FileTimeUtc( this DateTime source ) { var value = source.ToFileTimeUtc(); return new FILETIME { dwHighDateTime = unchecked( ( int ) ( value >> 32 ) ), dwLowDateTime = unchecked( ( int ) ( value & 0xffffffff ) ) }; } #endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY } }
36.285714
176
0.694038
[ "MIT" ]
BeamNG/msgpackInspector
MsgPack/Serialization/DefaultSerializers/InternalDateTimeExtensions.cs
3,556
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace Charlotte.Tools { public class FaultOperation : Exception { public FaultOperation(Exception e = null) : this("失敗しました。", e) { } public FaultOperation(string message, Exception e = null) : base(message, e) { } public static void caught(Exception e, string title = Program.APP_TITLE) { e = getCarried(e); if (e is Completed) { MessageBox.Show( getMessage(e), title + " / 完了", MessageBoxButtons.OK, MessageBoxIcon.Information ); } else if (e is Ended) { // noop } else if (e is Cancelled) { MessageBox.Show( getMessage(e), title + " / 中止", MessageBoxButtons.OK, MessageBoxIcon.Warning ); } else if (e is FaultOperation) { MessageBox.Show( getMessage(e), title + " / 失敗", MessageBoxButtons.OK, MessageBoxIcon.Warning ); } else { MessageBox.Show( getMessage(e) + "\n----\n" + e, title + " / エラー", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } public static Exception getCarried(Exception e) { while (e != null && e is ExceptionCarrier && e.InnerException != null) { e = e.InnerException; } return e; } public static string getMessage(Exception e) { List<string> lines = new List<string>(); while (e != null) { lines.Add(e.Message); e = e.InnerException; } return string.Join("\n", lines); } } }
18.011494
74
0.598596
[ "MIT" ]
stackprobe/Kirara2
KiraraConv/KiraraConv/Tools/FaultOperation.cs
1,601
C#
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Dynamic; using System.Linq; using System.Threading.Tasks; using Piranha.Extend; using Piranha.Extend.Fields; using Piranha.Manager.Extensions; using Piranha.Models; using Piranha.Manager.Models; using Piranha.Manager.Models.Content; using Piranha.Services; namespace Piranha.Manager.Services { public class PostService { private readonly IApi _api; private readonly IContentFactory _factory; public PostService(IApi api, IContentFactory factory) { _api = api; _factory = factory; } public async Task<PostModalModel> GetArchiveMap(Guid? siteId, Guid? archiveId) { var model = new PostModalModel(); // Get default site if none is selected if (!siteId.HasValue) { var site = await _api.Sites.GetDefaultAsync(); if (site != null) { siteId = site.Id; } } model.SiteId = siteId.Value; // Get the sites available model.Sites = (await _api.Sites.GetAllAsync()) .Select(s => new PostModalModel.SiteItem { Id = s.Id, Title = s.Title }) .OrderBy(s => s.Title) .ToList(); // Get the current site title var currentSite = model.Sites.FirstOrDefault(s => s.Id == siteId.Value); if (currentSite != null) { model.SiteTitle = currentSite.Title; } // Get the blogs available model.Archives = (await _api.Pages.GetAllBlogsAsync<PageInfo>(siteId.Value)) .Select(p => new PostModalModel.ArchiveItem { Id = p.Id, Title = p.Title, Slug = p.Slug }) .OrderBy(p => p.Title) .ToList(); if (model.Archives.Any()) { if (!archiveId.HasValue) { // Select the first blog archiveId = model.Archives.First().Id; } var archive = model.Archives.FirstOrDefault(b => b.Id == archiveId.Value); if (archive != null) { model.ArchiveId = archive.Id; model.ArchiveTitle = archive.Title; model.ArchiveSlug = archive.Slug; } // Get the available posts model.Posts = (await _api.Posts.GetAllAsync<PostInfo>(archiveId.Value)) .Select(p => new PostModalModel.PostModalItem { Id = p.Id, Title = p.Title, Permalink = "/" + model.ArchiveSlug + "/" + p.Slug, Published = p.Published?.ToString("yyyy-MM-dd HH:mm") }).ToList(); // Sort so we show unpublished drafts first model.Posts = model.Posts.Where(p => string.IsNullOrEmpty(p.Published)) .Concat(model.Posts.Where(p => !string.IsNullOrEmpty(p.Published))) .ToList(); } return model; } public async Task<PostListModel> GetList(Guid archiveId, int index = 0) { var page = await _api.Pages.GetByIdAsync<PageInfo>(archiveId); if (page == null) { return new PostListModel(); } var pageType = App.PageTypes.GetById(page.TypeId); var pageSize = 0; using (var config = new Config(_api)) { pageSize = config.ManagerPageSize; } var model = new PostListModel { PostTypes = App.PostTypes.Select(t => new PostListModel.PostTypeItem { Id = t.Id, Title = t.Title, AddUrl = "manager/post/add/" }).ToList(), TotalPosts = await _api.Posts.GetCountAsync(archiveId) }; model.TotalPages = Convert.ToInt32(Math.Ceiling(model.TotalPosts / Convert.ToDouble(pageSize))); model.Index = index; // We have specified the post types that should be available // in this archive. Filter them accordingly if (pageType.ArchiveItemTypes.Count > 0) { model.PostTypes = model.PostTypes .Where(t => pageType.ArchiveItemTypes.Contains(t.Id)) .ToList(); } // Get drafts var drafts = await _api.Posts.GetAllDraftsAsync(archiveId); // Get posts model.Posts = (await _api.Posts.GetAllAsync<PostInfo>(archiveId, index, pageSize)) .Select(p => new PostListModel.PostItem { Id = p.Id.ToString(), Title = p.Title, TypeName = model.PostTypes.First(t => t.Id == p.TypeId).Title, Category = p.Category.Title, Published = p.Published?.ToString("yyyy-MM-dd HH:mm"), Status = p.GetState(drafts.Contains(p.Id)), isScheduled = p.Published.HasValue && p.Published.Value > DateTime.Now, EditUrl = "manager/post/edit/" }).ToList(); // Get categories model.Categories = (await _api.Posts.GetAllCategoriesAsync(archiveId)) .Select(c => new PostListModel.CategoryItem { Id = c.Id.ToString(), Title = c.Title }).ToList(); return model; } public async Task<PostEditModel> GetById(Guid id, bool useDraft = true) { var isDraft = true; var post = useDraft ? await _api.Posts.GetDraftByIdAsync(id) : null; if (post == null) { post = await _api.Posts.GetByIdAsync(id); isDraft = false; } if (post != null) { // Perform manager init await _factory.InitDynamicManagerAsync(post, App.PostTypes.GetById(post.TypeId)); var postModel = Transform(post, isDraft); postModel.Categories = (await _api.Posts.GetAllCategoriesAsync(post.BlogId)) .Select(c => c.Title).ToList(); postModel.Tags = (await _api.Posts.GetAllTagsAsync(post.BlogId)) .Select(t => t.Title).ToList(); postModel.PendingCommentCount = (await _api.Posts.GetAllPendingCommentsAsync(id)) .Count(); postModel.SelectedCategory = post.Category.Title; postModel.SelectedTags = post.Tags.Select(t => t.Title).ToList(); return postModel; } return null; } public async Task<PostEditModel> Create(Guid archiveId, string typeId) { var post = await _api.Posts.CreateAsync<DynamicPost>(typeId); if (post != null) { post.Id = Guid.NewGuid(); post.BlogId = archiveId; // Perform manager init await _factory.InitDynamicManagerAsync(post, App.PostTypes.GetById(post.TypeId)); var postModel = Transform(post, false); postModel.Categories = (await _api.Posts.GetAllCategoriesAsync(post.BlogId)) .Select(c => c.Title).ToList(); postModel.Tags = (await _api.Posts.GetAllTagsAsync(post.BlogId)) .Select(t => t.Title).ToList(); postModel.SelectedCategory = post.Category?.Title; postModel.SelectedTags = post.Tags.Select(t => t.Title).ToList(); return postModel; } return null; } public async Task Save(PostEditModel model, bool draft) { var postType = App.PostTypes.GetById(model.TypeId); if (postType != null) { if (model.Id == Guid.Empty) { model.Id = Guid.NewGuid(); } var post = await _api.Posts.GetByIdAsync(model.Id); if (post == null) { post = await _factory.CreateAsync<DynamicPost>(postType); post.Id = model.Id; } post.BlogId = model.BlogId; post.TypeId = model.TypeId; post.Title = model.Title; post.Slug = model.Slug; post.MetaTitle = model.MetaTitle; post.MetaKeywords = model.MetaKeywords; post.MetaDescription = model.MetaDescription; post.MetaIndex = model.MetaIndex; post.MetaFollow = model.MetaFollow; post.MetaPriority = model.MetaPriority; post.OgTitle = model.OgTitle; post.OgDescription = model.OgDescription; post.OgImage = model.OgImage; post.Excerpt = model.Excerpt; post.Published = !string.IsNullOrEmpty(model.Published) ? DateTime.Parse(model.Published) : (DateTime?)null; post.RedirectUrl = model.RedirectUrl; post.RedirectType = (RedirectType)Enum.Parse(typeof(RedirectType), model.RedirectType); post.EnableComments = model.EnableComments; post.CloseCommentsAfterDays = model.CloseCommentsAfterDays; post.Permissions = model.SelectedPermissions; post.PrimaryImage = model.PrimaryImage; if (postType.Routes.Count > 1) { post.Route = postType.Routes.FirstOrDefault(r => r.Route == model.SelectedRoute?.Route) ?? postType.Routes.First(); } // Save category post.Category = new Taxonomy { Title = model.SelectedCategory }; // Save tags post.Tags.Clear(); foreach (var tag in model.SelectedTags) { post.Tags.Add(new Taxonomy { Title = tag }); } // Save regions foreach (var region in postType.Regions) { var modelRegion = model.Regions .FirstOrDefault(r => r.Meta.Id == region.Id); if (region.Collection) { var listRegion = (IRegionList)((IDictionary<string, object>)post.Regions)[region.Id]; listRegion.Clear(); foreach (var item in modelRegion.Items) { if (region.Fields.Count == 1) { listRegion.Add(item.Fields[0].Model); } else { var postRegion = new ExpandoObject(); foreach (var field in region.Fields) { var modelField = item.Fields .FirstOrDefault(f => f.Meta.Id == field.Id); ((IDictionary<string, object>)postRegion)[field.Id] = modelField.Model; } listRegion.Add(postRegion); } } } else { var postRegion = ((IDictionary<string, object>)post.Regions)[region.Id]; if (region.Fields.Count == 1) { ((IDictionary<string, object>)post.Regions)[region.Id] = modelRegion.Items[0].Fields[0].Model; } else { foreach (var field in region.Fields) { var modelField = modelRegion.Items[0].Fields .FirstOrDefault(f => f.Meta.Id == field.Id); ((IDictionary<string, object>)postRegion)[field.Id] = modelField.Model; } } } } // Save blocks post.Blocks.Clear(); foreach (var block in model.Blocks) { if (block is BlockGroupModel blockGroup) { var groupType = App.Blocks.GetByType(blockGroup.Type); if (groupType != null) { var postBlock = (BlockGroup)Activator.CreateInstance(groupType.Type); postBlock.Id = blockGroup.Id; postBlock.Type = blockGroup.Type; foreach (var field in blockGroup.Fields) { var prop = postBlock.GetType().GetProperty(field.Meta.Id, App.PropertyBindings); prop.SetValue(postBlock, field.Model); } foreach (var item in blockGroup.Items) { if (item is BlockItemModel blockItem) { postBlock.Items.Add(blockItem.Model); } else if (item is BlockGenericModel blockGeneric) { var transformed = ContentUtils.TransformGenericBlock(blockGeneric); if (transformed != null) { postBlock.Items.Add(transformed); } } } post.Blocks.Add(postBlock); } } else if (block is BlockItemModel blockItem) { post.Blocks.Add(blockItem.Model); } else if (block is BlockGenericModel blockGeneric) { var transformed = ContentUtils.TransformGenericBlock(blockGeneric); if (transformed != null) { post.Blocks.Add(transformed); } } } // Save post if (draft) { await _api.Posts.SaveDraftAsync(post); } else { await _api.Posts.SaveAsync(post); } } else { throw new ValidationException("Invalid Post Type."); } } /// <summary> /// Deletes the post with the given id. /// </summary> /// <param name="id">The unique id</param> public Task Delete(Guid id) { return _api.Posts.DeleteAsync(id); } private PostEditModel Transform(DynamicPost post, bool isDraft) { var config = new Config(_api); var type = App.PostTypes.GetById(post.TypeId); var route = type.Routes.FirstOrDefault(r => r.Route == post.Route) ?? type.Routes.FirstOrDefault(); var model = new PostEditModel { Id = post.Id, BlogId = post.BlogId, TypeId = post.TypeId, PrimaryImage = post.PrimaryImage, Title = post.Title, Slug = post.Slug, MetaTitle = post.MetaTitle, MetaKeywords = post.MetaKeywords, MetaDescription = post.MetaDescription, MetaIndex = post.MetaIndex, MetaFollow = post.MetaFollow, MetaPriority = post.MetaPriority, OgTitle = post.OgTitle, OgDescription = post.OgDescription, OgImage = post.OgImage, Excerpt = post.Excerpt, Published = post.Published?.ToString("yyyy-MM-dd HH:mm"), RedirectUrl = post.RedirectUrl, RedirectType = post.RedirectType.ToString(), EnableComments = post.EnableComments, CloseCommentsAfterDays = post.CloseCommentsAfterDays, CommentCount = post.CommentCount, State = post.GetState(isDraft), UseBlocks = type.UseBlocks, UsePrimaryImage = type.UsePrimaryImage, UseExcerpt = type.UseExcerpt, UseHtmlExcerpt = config.HtmlExcerpt, SelectedRoute = route == null ? null : new RouteModel { Title = route.Title, Route = route.Route }, Permissions = App.Permissions .GetPublicPermissions() .Select(p => new KeyValuePair<string, string>(p.Name, p.Title)) .ToList(), SelectedPermissions = post.Permissions }; foreach (var r in type.Routes) { model.Routes.Add(new RouteModel { Title = r.Title, Route = r.Route }); } foreach (var regionType in type.Regions) { var region = new RegionModel { Meta = new RegionMeta { Id = regionType.Id, Name = regionType.Title, Description = regionType.Description, Placeholder = regionType.ListTitlePlaceholder, IsCollection = regionType.Collection, Expanded = regionType.ListExpand, Icon = regionType.Icon, Display = regionType.Display.ToString().ToLower() } }; var regionListModel = ((IDictionary<string, object>)post.Regions)[regionType.Id]; if (!regionType.Collection) { var regionModel = (IRegionList)Activator.CreateInstance(typeof(RegionList<>).MakeGenericType(regionListModel.GetType())); regionModel.Add(regionListModel); regionListModel = regionModel; } foreach (var regionModel in (IEnumerable)regionListModel) { var regionItem = new RegionItemModel(); foreach (var fieldType in regionType.Fields) { var appFieldType = App.Fields.GetByType(fieldType.Type); var field = new FieldModel { Meta = new FieldMeta { Id = fieldType.Id, Name = fieldType.Title, Component = appFieldType.Component, Placeholder = fieldType.Placeholder, IsHalfWidth = fieldType.Options.HasFlag(FieldOption.HalfWidth), Description = fieldType.Description } }; if (typeof(SelectFieldBase).IsAssignableFrom(appFieldType.Type)) { foreach(var item in ((SelectFieldBase)Activator.CreateInstance(appFieldType.Type)).Items) { field.Meta.Options.Add(Convert.ToInt32(item.Value), item.Title); } } if (regionType.Fields.Count > 1) { field.Model = (IField)((IDictionary<string, object>)regionModel)[fieldType.Id]; if (regionType.ListTitleField == fieldType.Id) { regionItem.Title = field.Model.GetTitle(); field.Meta.NotifyChange = true; } } else { field.Model = (IField)regionModel; field.Meta.NotifyChange = true; regionItem.Title = field.Model.GetTitle(); } regionItem.Fields.Add(field); } if (string.IsNullOrWhiteSpace(regionItem.Title)) { regionItem.Title = "..."; } region.Items.Add(regionItem); } model.Regions.Add(region); } foreach (var block in post.Blocks) { var blockType = App.Blocks.GetByType(block.Type); if (block is BlockGroup blockGroup) { var group = new BlockGroupModel { Id = block.Id, Type = block.Type, Meta = new BlockMeta { Name = blockType.Name, Icon = blockType.Icon, Component = blockType.Component, IsGroup = true, isCollapsed = config.ManagerDefaultCollapsedBlocks, ShowHeader = !config.ManagerDefaultCollapsedBlockGroupHeaders } }; group.Fields = ContentUtils.GetBlockFields(block); bool firstChild = true; foreach (var child in blockGroup.Items) { blockType = App.Blocks.GetByType(child.Type); if (!blockType.IsGeneric) { group.Items.Add(new BlockItemModel { IsActive = firstChild, Model = child, Meta = new BlockMeta { Name = blockType.Name, Title = child.GetTitle(), Icon = blockType.Icon, Component = blockType.Component } }); } else { // Generic block item model group.Items.Add(new BlockGenericModel { IsActive = firstChild, Model = ContentUtils.GetBlockFields(child), Type = child.Type, Meta = new BlockMeta { Name = blockType.Name, Title = child.GetTitle(), Icon = blockType.Icon, Component = blockType.Component, } }); } firstChild = false; } model.Blocks.Add(group); } else { if (!blockType.IsGeneric) { // Regular block item model model.Blocks.Add(new BlockItemModel { Model = block, Meta = new BlockMeta { Name = blockType.Name, Title = block.GetTitle(), Icon = blockType.Icon, Component = blockType.Component, isCollapsed = config.ManagerDefaultCollapsedBlocks } }); } else { // Generic block item model model.Blocks.Add(new BlockGenericModel { Model = ContentUtils.GetBlockFields(block), Type = block.Type, Meta = new BlockMeta { Name = blockType.Name, Title = block.GetTitle(), Icon = blockType.Icon, Component = blockType.Component, isCollapsed = config.ManagerDefaultCollapsedBlocks } }); } } } // Custom editors foreach (var editor in type.CustomEditors) { model.Editors.Add(new EditorModel { Component = editor.Component, Icon = editor.Icon, Name = editor.Title }); } return model; } } }
38.775072
141
0.4276
[ "MIT" ]
StackAnalysis/piranha.core
core/Piranha.Manager/Services/PostService.cs
27,065
C#
#pragma checksum "C:\Users\hamedsa\Documents\GitHub\Master\Master\PivotApp1\PivotApp1 - Copy\PivotApp1\MainPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "110A060C9A872DD001F1747D48D829F1" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using Microsoft.Advertising.Mobile.UI; using Microsoft.Phone.Controls; using System; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Resources; using System.Windows.Shapes; using System.Windows.Threading; namespace PivotApp1 { public partial class MainPage : Microsoft.Phone.Controls.PhoneApplicationPage { internal System.Windows.Controls.Grid LayoutRoot; internal Microsoft.Phone.Controls.Pivot mainPivot; internal Microsoft.Phone.Controls.PivotItem Stew; internal Microsoft.Phone.Controls.LongListSelector stewsMenue; internal Microsoft.Phone.Controls.PivotItem Kebabs; internal Microsoft.Phone.Controls.LongListSelector kebabMenue; internal Microsoft.Phone.Controls.PivotItem rices; internal Microsoft.Phone.Controls.LongListSelector riceMenue; internal Microsoft.Phone.Controls.PivotItem soups; internal Microsoft.Phone.Controls.LongListSelector soupMenue; internal Microsoft.Phone.Controls.PivotItem others; internal Microsoft.Phone.Controls.LongListSelector otherMenue; internal Microsoft.Phone.Controls.PivotItem Torshi; internal Microsoft.Phone.Controls.LongListSelector torshiMenue; internal Microsoft.Phone.Controls.PivotItem deserts; internal Microsoft.Phone.Controls.LongListSelector desertMenue; internal Microsoft.Advertising.Mobile.UI.AdControl AddControllMain; private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(this, new System.Uri("/PivotApp1;component/MainPage.xaml", System.UriKind.Relative)); this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot"))); this.mainPivot = ((Microsoft.Phone.Controls.Pivot)(this.FindName("mainPivot"))); this.Stew = ((Microsoft.Phone.Controls.PivotItem)(this.FindName("Stew"))); this.stewsMenue = ((Microsoft.Phone.Controls.LongListSelector)(this.FindName("stewsMenue"))); this.Kebabs = ((Microsoft.Phone.Controls.PivotItem)(this.FindName("Kebabs"))); this.kebabMenue = ((Microsoft.Phone.Controls.LongListSelector)(this.FindName("kebabMenue"))); this.rices = ((Microsoft.Phone.Controls.PivotItem)(this.FindName("rices"))); this.riceMenue = ((Microsoft.Phone.Controls.LongListSelector)(this.FindName("riceMenue"))); this.soups = ((Microsoft.Phone.Controls.PivotItem)(this.FindName("soups"))); this.soupMenue = ((Microsoft.Phone.Controls.LongListSelector)(this.FindName("soupMenue"))); this.others = ((Microsoft.Phone.Controls.PivotItem)(this.FindName("others"))); this.otherMenue = ((Microsoft.Phone.Controls.LongListSelector)(this.FindName("otherMenue"))); this.Torshi = ((Microsoft.Phone.Controls.PivotItem)(this.FindName("Torshi"))); this.torshiMenue = ((Microsoft.Phone.Controls.LongListSelector)(this.FindName("torshiMenue"))); this.deserts = ((Microsoft.Phone.Controls.PivotItem)(this.FindName("deserts"))); this.desertMenue = ((Microsoft.Phone.Controls.LongListSelector)(this.FindName("desertMenue"))); this.AddControllMain = ((Microsoft.Advertising.Mobile.UI.AdControl)(this.FindName("AddControllMain"))); } } }
44.925234
194
0.6684
[ "Apache-2.0" ]
hsneshat/Master
PivotApp1/PivotApp1 - Copy/PivotApp1/obj/Debug/MainPage.g.i.cs
4,809
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.Connect; using Amazon.Connect.Model; namespace Amazon.PowerShell.Cmdlets.CONN { /// <summary> /// This API is in preview release for Amazon Connect and is subject to change. /// /// /// <para> /// Updates agent status. /// </para> /// </summary> [Cmdlet("Update", "CONNAgentStatus", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("None")] [AWSCmdlet("Calls the Amazon Connect Service UpdateAgentStatus API operation.", Operation = new[] {"UpdateAgentStatus"}, SelectReturnType = typeof(Amazon.Connect.Model.UpdateAgentStatusResponse))] [AWSCmdletOutput("None or Amazon.Connect.Model.UpdateAgentStatusResponse", "This cmdlet does not generate any output." + "The service response (type Amazon.Connect.Model.UpdateAgentStatusResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class UpdateCONNAgentStatusCmdlet : AmazonConnectClientCmdlet, IExecutor { #region Parameter AgentStatusId /// <summary> /// <para> /// <para>The identifier of the agent status.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String AgentStatusId { get; set; } #endregion #region Parameter Description /// <summary> /// <para> /// <para>The description of the agent status.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String Description { get; set; } #endregion #region Parameter DisplayOrder /// <summary> /// <para> /// <para>The display order of the agent status.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Int32? DisplayOrder { get; set; } #endregion #region Parameter InstanceId /// <summary> /// <para> /// <para>The identifier of the Amazon Connect instance. You can find the instanceId in the /// ARN of the instance.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String InstanceId { get; set; } #endregion #region Parameter Name /// <summary> /// <para> /// <para>The name of the agent status.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String Name { get; set; } #endregion #region Parameter ResetOrderNumber /// <summary> /// <para> /// <para>A number indicating the reset order of the agent status.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Boolean? ResetOrderNumber { get; set; } #endregion #region Parameter State /// <summary> /// <para> /// <para>The state of the agent status.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [AWSConstantClassSource("Amazon.Connect.AgentStatusState")] public Amazon.Connect.AgentStatusState State { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Connect.Model.UpdateAgentStatusResponse). /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the InstanceId parameter. /// The -PassThru parameter is deprecated, use -Select '^InstanceId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^InstanceId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.InstanceId), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Update-CONNAgentStatus (UpdateAgentStatus)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.Connect.Model.UpdateAgentStatusResponse, UpdateCONNAgentStatusCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.InstanceId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.AgentStatusId = this.AgentStatusId; #if MODULAR if (this.AgentStatusId == null && ParameterWasBound(nameof(this.AgentStatusId))) { WriteWarning("You are passing $null as a value for parameter AgentStatusId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.Description = this.Description; context.DisplayOrder = this.DisplayOrder; context.InstanceId = this.InstanceId; #if MODULAR if (this.InstanceId == null && ParameterWasBound(nameof(this.InstanceId))) { WriteWarning("You are passing $null as a value for parameter InstanceId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.Name = this.Name; context.ResetOrderNumber = this.ResetOrderNumber; context.State = this.State; // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.Connect.Model.UpdateAgentStatusRequest(); if (cmdletContext.AgentStatusId != null) { request.AgentStatusId = cmdletContext.AgentStatusId; } if (cmdletContext.Description != null) { request.Description = cmdletContext.Description; } if (cmdletContext.DisplayOrder != null) { request.DisplayOrder = cmdletContext.DisplayOrder.Value; } if (cmdletContext.InstanceId != null) { request.InstanceId = cmdletContext.InstanceId; } if (cmdletContext.Name != null) { request.Name = cmdletContext.Name; } if (cmdletContext.ResetOrderNumber != null) { request.ResetOrderNumber = cmdletContext.ResetOrderNumber.Value; } if (cmdletContext.State != null) { request.State = cmdletContext.State; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.Connect.Model.UpdateAgentStatusResponse CallAWSServiceOperation(IAmazonConnect client, Amazon.Connect.Model.UpdateAgentStatusRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Connect Service", "UpdateAgentStatus"); try { #if DESKTOP return client.UpdateAgentStatus(request); #elif CORECLR return client.UpdateAgentStatusAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String AgentStatusId { get; set; } public System.String Description { get; set; } public System.Int32? DisplayOrder { get; set; } public System.String InstanceId { get; set; } public System.String Name { get; set; } public System.Boolean? ResetOrderNumber { get; set; } public Amazon.Connect.AgentStatusState State { get; set; } public System.Func<Amazon.Connect.Model.UpdateAgentStatusResponse, UpdateCONNAgentStatusCmdlet, object> Select { get; set; } = (response, cmdlet) => null; } } }
42.94864
284
0.59827
[ "Apache-2.0" ]
aws/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/Connect/Basic/Update-CONNAgentStatus-Cmdlet.cs
14,216
C#
namespace OnlineExamPrep.Models.Common { public interface IUserClaim { int Id { get; set; } string UserId { get; set; } string ClaimType { get; set; } string ClaimValue { get; set; } } }
21.090909
39
0.568966
[ "MIT" ]
isimic413/OnlineExamPrep
src/OnlineExamPrep.Models.Common/IUserClaim.cs
234
C#
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class DarwinSanoy : IAmACommunityMember { public string FirstName => "Darwin"; public string LastName => "Sanoy"; public string ShortBioOrTagLine => "Cloudifying Windows Everyday"; public string StateOrRegion => "Phoenixville, PA"; public string EmailAddress => string.Empty; public string TwitterHandle => "DarwinTheorizes"; public string GravatarHash => "566be8d4a7b78dc25ab07bd61a48116b"; public string GitHubHandle => "DarwinJS"; public GeoPosition Position => new GeoPosition(40.1303822,-75.5149128); public Uri WebSite => new Uri("https://cloudywindows.io"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://cloudywindows.io/tags/powershell/index.xml"); } } public string FeedLanguageCode => "en"; } }
36.793103
95
0.683224
[ "MIT" ]
DarwinJS/planetpowershell
src/Firehose.Web/Authors/DarwinSanoy.cs
1,069
C#
using System.Security.Cryptography; namespace Oocx.Acme.Services { public class KeyContainerStore : IKeyStore { private readonly CspProviderFlags flags; public KeyContainerStore(string storeType) { flags = storeType == "machine" ? CspProviderFlags.UseMachineKeyStore : CspProviderFlags.UseUserProtectedKey; } public RSA GetOrCreateKey(string keyName) { return new RSACryptoServiceProvider(2048, new CspParameters { KeyContainerName = keyName, Flags = flags, }); } } }
27.541667
74
0.573374
[ "MIT" ]
pieszynski/letsencrypt-net-update
src/acme.net/src/Oocx.Acme/Services/KeyContainerStore.cs
661
C#
namespace Menees { #region Using Directives using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; #endregion /// <summary> /// Methods for getting metadata about assemblies, types, members, etc. /// </summary> public static class ReflectionUtility { #region Public Methods /// <summary> /// Gets the assembly's copyright information. /// </summary> /// <param name="assembly">The assembly to get the copyright from.</param> /// <returns>User-friendly copyright information.</returns> public static string? GetCopyright(Assembly assembly) { Conditions.RequireReference(assembly, nameof(assembly)); string? result = null; var copyrights = (AssemblyCopyrightAttribute[])assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), true); if (copyrights.Length > 0) { result = copyrights[0].Copyright; } return result; } /// <summary> /// Gets the assembly's version. /// </summary> /// <param name="assembly">The assembly to get the version from</param> /// <returns>The assembly version</returns> public static Version? GetVersion(Assembly assembly) { Conditions.RequireReference(assembly, nameof(assembly)); Version? result = assembly.GetName(false).Version; return result; } /// <summary> /// Gets the UTC build timestamp from the assembly. /// </summary> /// <param name="assembly">The assembly to get the BuildTime metadata from.</param> /// <returns>The assembly's build time as a UTC datetime if an <see cref="AssemblyMetadataAttribute"/> is found /// with Key="BuildTime" and Value equal to a parsable UTC datetime. Returns null otherwise.</returns> public static DateTime? GetBuildTime(Assembly assembly) { Conditions.RequireReference(assembly, nameof(assembly)); const DateTimeStyles UseUtc = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal; DateTime? result = assembly.GetCustomAttributes<AssemblyMetadataAttribute>() .Where(metadata => string.Equals(metadata.Key, "BuildTime")) .Select(metadata => DateTime.TryParse(metadata.Value, null, UseUtc, out DateTime value) ? value : (DateTime?)null) .FirstOrDefault(value => value != null); if (result != null) { result = result.Value.Kind switch { DateTimeKind.Unspecified => DateTime.SpecifyKind(result.Value, DateTimeKind.Utc), DateTimeKind.Local => result.Value.ToUniversalTime(), _ => result.Value, }; } return result; } /// <summary> /// Gets the ProductUrl from the assembly metadata. /// </summary> /// <param name="assembly">The assembly to get the ProductUrl metadata from.</param> /// <returns>The assembly's build time as a Uri if an <see cref="AssemblyMetadataAttribute"/> is found /// with Key="ProductUrl" and Value equal to a parsable absolute Uri. Returns null otherwise.</returns> public static Uri? GetProductUrl(Assembly assembly) { Conditions.RequireReference(assembly, nameof(assembly)); Uri? result = assembly.GetCustomAttributes<AssemblyMetadataAttribute>() .Where(metadata => string.Equals(metadata.Key, "ProductUrl")) .Select(metadata => Uri.TryCreate(metadata.Value, UriKind.Absolute, out Uri? value) ? value : null) .FirstOrDefault(value => value != null); return result; } /// <summary> /// Gets whether the assembly was built with a debug configuration. /// </summary> /// <param name="assembly">The assembly to check.</param> /// <returns>True if the <see cref="AssemblyConfigurationAttribute"/> is present /// and the configuration string contains "Debug". False otherwise.</returns> public static bool IsDebugBuild(Assembly assembly) { Conditions.RequireReference(assembly, nameof(assembly)); bool result = false; if (assembly != null) { var configuration = (AssemblyConfigurationAttribute?)assembly.GetCustomAttribute(typeof(AssemblyConfigurationAttribute)); result = configuration?.Configuration?.Contains("Debug") ?? false; } return result; } #endregion } }
33.139535
125
0.717661
[ "MIT" ]
bmenees/Libraries
src/Menees.Common/ReflectionUtility.cs
4,275
C#
#region using System; using System.Collections.Generic; using System.Linq; using System.Text; using WinterLeaf.Engine; using WinterLeaf.Engine.Classes; using WinterLeaf.Engine.Containers; using WinterLeaf.Engine.Enums; using System.ComponentModel; using System.Threading; using WinterLeaf.Engine.Classes.Interopt; using WinterLeaf.Engine.Classes.Decorations; using WinterLeaf.Engine.Classes.Extensions; using WinterLeaf.Engine.Classes.Helpers; using WinterLeaf.Demo.Full.Models.Base; #endregion namespace WinterLeaf.Demo.Full.Models.User.Extendable { /// <summary> /// /// </summary> [TypeConverter(typeof(TypeConverterGeneric<EditManager>))] public partial class EditManager: EditManager_Base { #region ProxyObjects Operator Overrides /// <summary> /// /// </summary> /// <param name="ts"></param> /// <param name="simobjectid"></param> /// <returns></returns> public static bool operator ==(EditManager ts, string simobjectid) { return object.ReferenceEquals(ts, null) ? object.ReferenceEquals(simobjectid, null) : ts.Equals(simobjectid); } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { return (this._ID ==(string)myReflections.ChangeType( obj,typeof(string))); } /// <summary> /// /// </summary> /// <param name="ts"></param> /// <param name="simobjectid"></param> /// <returns></returns> public static bool operator !=(EditManager ts, string simobjectid) { if (object.ReferenceEquals(ts, null)) return !object.ReferenceEquals(simobjectid, null); return !ts.Equals(simobjectid); } /// <summary> /// /// </summary> /// <param name="ts"></param> /// <returns></returns> public static implicit operator string( EditManager ts) { return ReferenceEquals(ts, null) ? "0" : ts._ID; } /// <summary> /// /// </summary> /// <param name="ts"></param> /// <returns></returns> public static implicit operator EditManager(string ts) { uint simobjectid = resolveobject(ts); return (EditManager) Omni.self.getSimObject(simobjectid,typeof(EditManager)); } /// <summary> /// /// </summary> /// <param name="ts"></param> /// <returns></returns> public static implicit operator int( EditManager ts) { return (int)ts._iID; } /// <summary> /// /// </summary> /// <param name="simobjectid"></param> /// <returns></returns> public static implicit operator EditManager(int simobjectid) { return (EditManager) Omni.self.getSimObject((uint)simobjectid,typeof(EditManager)); } /// <summary> /// /// </summary> /// <param name="ts"></param> /// <returns></returns> public static implicit operator uint( EditManager ts) { return ts._iID; } /// <summary> /// /// </summary> /// <returns></returns> public static implicit operator EditManager(uint simobjectid) { return (EditManager) Omni.self.getSimObject(simobjectid,typeof(EditManager)); } #endregion }}
29.463235
122
0.522835
[ "MIT", "Unlicense" ]
RichardRanft/OmniEngine.Net
Templates/C#-Empty/Winterleaf.Demo.Full/Models.User/Extendable/EditManager.cs
3,872
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace HRM.Models { public class Section { [key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int id { get; set; } [Display(Name = "Section Code")] [StringLength(10)] public string SectionCode { get; set; } [Display(Name = "Section Name")] [StringLength(150)] public string SectionName { get; set; } public int DeptId { get; set; } [ForeignKey("DeptId")] public virtual Dept Dept { get; set; } } }
26.961538
66
0.647646
[ "MIT" ]
TasniaJamilLamia/hrm-training
HRM/HRM/Models/Section.cs
703
C#
#region license // 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. // ------------------------------------------------------------- #endregion using SpriteSwappingPlugin.SortingGeneration.Data; using SpriteSwappingPlugin.SpriteSwappingDetector; namespace SpriteSwappingPlugin.SortingGeneration.Criteria { public class ContainmentSortingCriterion : SortingCriterion { private ContainmentSortingCriterionData ContainmentSortingCriterionData => (ContainmentSortingCriterionData) sortingCriterionData; public bool IsSortingEnclosedSpriteInForeground => ContainmentSortingCriterionData.isSortingEnclosedSpriteInForeground; public ContainmentSortingCriterion(ContainmentSortingCriterionData sortingCriterionData) : base( sortingCriterionData) { sortingCriterionType = SortingCriterionType.Containment; } protected override void InternalSort(SortingComponent sortingComponent, SortingComponent otherSortingComponent) { if (ContainmentSortingCriterionData.isSortingEnclosedSpriteInForeground || !ContainmentSortingCriterionData.isCheckingAlpha) { return; } var alpha = autoSortingCalculationData.spriteData.spriteDataDictionary[spriteDataItemValidator.AssetGuid] .spriteAnalysisData.averageAlpha; alpha *= sortingComponent.SpriteRenderer.color.a; if (alpha < ContainmentSortingCriterionData.alphaThreshold) { sortingResults[1]++; } } public override bool IsUsingSpriteData() { return !ContainmentSortingCriterionData.isSortingEnclosedSpriteInForeground && ContainmentSortingCriterionData.isCheckingAlpha; } } }
38.970149
119
0.700498
[ "Apache-2.0" ]
TobiasFox/SpriteSwappingTool
SpriteSwappingPlugin/Assets/SpriteSwappingPlugin/Editor/SortingGeneration/Criteria/ContainmentSortingCriterion.cs
2,613
C#
namespace Sandbox { using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using CommandLine; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OrganizeMe.Data; using OrganizeMe.Data.Common; using OrganizeMe.Data.Common.Repositories; using OrganizeMe.Data.Models; using OrganizeMe.Data.Repositories; using OrganizeMe.Data.Seeding; using OrganizeMe.Services.Data; using OrganizeMe.Services.Messaging; public static class Program { public static int Main(string[] args) { Console.WriteLine($"{typeof(Program).Namespace} ({string.Join(" ", args)}) starts working..."); var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(true); // Seed data on application startup using (var serviceScope = serviceProvider.CreateScope()) { var dbContext = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>(); dbContext.Database.Migrate(); new ApplicationDbContextSeeder().SeedAsync(dbContext, serviceScope.ServiceProvider).GetAwaiter().GetResult(); } using (var serviceScope = serviceProvider.CreateScope()) { serviceProvider = serviceScope.ServiceProvider; return Parser.Default.ParseArguments<SandboxOptions>(args).MapResult( opts => SandboxCode(opts, serviceProvider).GetAwaiter().GetResult(), _ => 255); } } private static async Task<int> SandboxCode(SandboxOptions options, IServiceProvider serviceProvider) { var sw = Stopwatch.StartNew(); var settingsService = serviceProvider.GetService<ISettingsService>(); Console.WriteLine($"Count of settings: {settingsService.GetCount()}"); Console.WriteLine(sw.Elapsed); return await Task.FromResult(0); } private static void ConfigureServices(ServiceCollection services) { var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", false, true) .AddEnvironmentVariables() .Build(); services.AddSingleton<IConfiguration>(configuration); services.AddDbContext<ApplicationDbContext>( options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")) .UseLoggerFactory(new LoggerFactory())); services.AddDefaultIdentity<ApplicationUser>(IdentityOptionsProvider.GetIdentityOptions) .AddRoles<ApplicationRole>().AddEntityFrameworkStores<ApplicationDbContext>(); services.AddScoped(typeof(IDeletableEntityRepository<>), typeof(EfDeletableEntityRepository<>)); services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>)); services.AddScoped<IDbQueryRunner, DbQueryRunner>(); // Application services // services.AddTransient<IEmailSender, NullMessageSender>(); services.AddTransient<ISettingsService, SettingsService>(); } } }
40.906977
125
0.659466
[ "MIT" ]
EleonorManolova/BeOrganized
ASP.NET Core/Tests/Sandbox/Program.cs
3,520
C#
using System.Data.Common; using System.Data.Entity.Infrastructure.Interception; using System.Diagnostics; using ContosoUniversity.Core.Logging; namespace ContosoUniversity.Core.DAL { public class SchoolInterceptorLogging : DbCommandInterceptor { private ILogger _logger = new Logger(); private readonly Stopwatch _stopwatch = new Stopwatch(); public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) { base.ScalarExecuting(command, interceptionContext); _stopwatch.Restart(); } public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) { _stopwatch.Stop(); if (interceptionContext.Exception != null) { _logger.Error(interceptionContext.Exception, "Error executing command: {0}", command.CommandText); } else { _logger.TraceApi("SQL Database", "SchoolInterceptor.ScalarExecuted", _stopwatch.Elapsed, "Command: {0}: ", command.CommandText); } base.ScalarExecuted(command, interceptionContext); } public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext) { base.NonQueryExecuting(command, interceptionContext); _stopwatch.Restart(); } public override void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext) { _stopwatch.Stop(); if (interceptionContext.Exception != null) { _logger.Error(interceptionContext.Exception, "Error executing command: {0}", command.CommandText); } else { _logger.TraceApi("SQL Database", "SchoolInterceptor.NonQueryExecuted", _stopwatch.Elapsed, "Command: {0}: ", command.CommandText); } base.NonQueryExecuted(command, interceptionContext); } public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) { base.ReaderExecuting(command, interceptionContext); _stopwatch.Restart(); } public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext) { _stopwatch.Stop(); if (interceptionContext.Exception != null) { _logger.Error(interceptionContext.Exception, "Error executing command: {0}", command.CommandText); } else { _logger.TraceApi("SQL Database", "SchoolInterceptor.ReaderExecuted", _stopwatch.Elapsed, "Command: {0}: ", command.CommandText); } base.ReaderExecuted(command, interceptionContext); } } }
41.472222
146
0.64501
[ "Unlicense" ]
trind09/ContosoUniversity
ContosoUniversity.Core/DAL/SchoolInterceptorLogging.cs
2,988
C#
using System.Net.Http; using System.Threading.Tasks; using Alexa.NET.Management.Api; using Refit; namespace Alexa.NET.Management.Internals { public interface IClientSkillEnablementApi { [Put("/v1/skills/{skillId}/stages/{stage}/enablement")] Task<HttpResponseMessage> Enable(string skillId, SkillStage stage); [Get("/v1/skills/{skillId}/stages/{stage}/enablement")] Task<HttpResponseMessage> CheckEnablement(string skillId, SkillStage stage); [Delete("/v1/skills/{skillId}/stages/{stage}/enablement")] Task<HttpResponseMessage> Disable(string skillId, SkillStage stage); } }
31.95
84
0.713615
[ "MIT" ]
dennis-kuypers-gcx/Alexa.NET.Management
Alexa.NET.Management/Internals/IClientSkillEnablementApi.cs
641
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; using Microsoft.MixedReality.Toolkit.Utilities.Editor; using UnityEngine; using UnityEditor; using System; using System.IO; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// Tools for simulating and recording input as well as playing back input animation in the Unity editor. /// </summary> public class InputSimulationWindow : EditorWindow { private InputAnimation animation { get { return PlaybackService?.Animation; } set { if (PlaybackService != null) PlaybackService.Animation = value; } } private string loadedFilePath = ""; private IInputSimulationService simulationService = null; private IInputSimulationService SimulationService { get { if (simulationService == null) { simulationService = (CoreServices.InputSystem as IMixedRealityDataProviderAccess).GetDataProvider<IInputSimulationService>(); } return simulationService; } } private IMixedRealityInputRecordingService recordingService = null; private IMixedRealityInputRecordingService RecordingService { get { if (recordingService == null) { recordingService = (CoreServices.InputSystem as IMixedRealityDataProviderAccess).GetDataProvider<IMixedRealityInputRecordingService>(); } return recordingService; } } private IMixedRealityInputPlaybackService playbackService = null; private IMixedRealityInputPlaybackService PlaybackService { get { if (playbackService == null) { playbackService = (CoreServices.InputSystem as IMixedRealityDataProviderAccess).GetDataProvider<IMixedRealityInputPlaybackService>(); } return playbackService; } } public enum ToolMode { /// <summary> /// Record input animation and store in the asset. /// </summary> Record, /// <summary> /// Play back input animation as simulated input. /// </summary> Playback, } private ToolMode mode = ToolMode.Record; public ToolMode Mode { get { return mode; } private set { mode = value; } } /// Icon textures private Texture2D iconPlay = null; private Texture2D iconRecord = null; private Texture2D iconRecordActive = null; private Texture2D iconStepFwd = null; private Texture2D iconJumpBack = null; private Texture2D iconJumpFwd = null; [MenuItem("Mixed Reality Toolkit/Utilities/Input Simulation")] private static void ShowWindow() { InputSimulationWindow window = GetWindow<InputSimulationWindow>(); window.titleContent = new GUIContent("Input Simulation"); window.minSize = new Vector2(380.0f, 680.0f); window.Show(); } private void OnGUI() { LoadIcons(); if (!Application.isPlaying) { EditorGUILayout.HelpBox("Input simulation is only available in play mode", MessageType.Info); return; } DrawSimulationGUI(); EditorGUILayout.Separator(); string[] modeStrings = Enum.GetNames(typeof(ToolMode)); Mode = (ToolMode)GUILayout.SelectionGrid((int)Mode, modeStrings, modeStrings.Length); switch (mode) { case ToolMode.Record: DrawRecordingGUI(); break; case ToolMode.Playback: DrawPlaybackGUI(); break; } EditorGUILayout.Space(); // XXX Reloading the scene is currently not supported, // due to the life cycle of the MRTK "instance" object (see see #4530). // Enable the button below once scene reloading is supported! #if false using (new GUIEnabledWrapper(Application.isPlaying)) { bool reloadScene = GUILayout.Button("Reload Scene"); if (reloadScene) { Scene activeScene = SceneManager.GetActiveScene(); if (activeScene.IsValid()) { SceneManager.LoadScene(activeScene.name); return; } } } #endif } private void DrawSimulationGUI() { if (SimulationService == null) { EditorGUILayout.HelpBox("No input simulation service found", MessageType.Info); return; } DrawHeadGUI(); DrawHandsGUI(); } private void DrawHeadGUI() { if (!CameraCache.Main) { return; } using (new GUILayout.VerticalScope(EditorStyles.helpBox)) { GUILayout.Label($"Head:"); Transform headTransform = CameraCache.Main.transform; Vector3 newPosition = EditorGUILayout.Vector3Field("Position", headTransform.position); Vector3 newRotation = DrawRotationGUI("Rotation", headTransform.rotation.eulerAngles); bool resetHand = GUILayout.Button("Reset"); if (newPosition != headTransform.position) { headTransform.position = newPosition; } if (newRotation != headTransform.rotation.eulerAngles) { headTransform.rotation = Quaternion.Euler(newRotation); } if (resetHand) { headTransform.position = Vector3.zero; headTransform.rotation = Quaternion.identity; } } } private void DrawHandsGUI() { HandSimulationMode newHandSimMode = (HandSimulationMode)EditorGUILayout.EnumPopup("Hand Simulation Mode", SimulationService.HandSimulationMode); if (newHandSimMode != SimulationService.HandSimulationMode) { SimulationService.HandSimulationMode = newHandSimMode; } using (new GUILayout.HorizontalScope()) { DrawHandGUI( "Left", SimulationService.IsAlwaysVisibleHandLeft, v => SimulationService.IsAlwaysVisibleHandLeft = v, SimulationService.HandPositionLeft, v => SimulationService.HandPositionLeft = v, SimulationService.HandRotationLeft, v => SimulationService.HandRotationLeft = v, SimulationService.ResetHandLeft); DrawHandGUI( "Right", SimulationService.IsAlwaysVisibleHandRight, v => SimulationService.IsAlwaysVisibleHandRight = v, SimulationService.HandPositionRight, v => SimulationService.HandPositionRight = v, SimulationService.HandRotationRight, v => SimulationService.HandRotationRight = v, SimulationService.ResetHandRight); } } private void DrawHandGUI(string name, bool isAlwaysVisible, Action<bool> setAlwaysVisible, Vector3 position, Action<Vector3> setPosition, Vector3 rotation, Action<Vector3> setRotation, Action reset) { using (new GUILayout.VerticalScope(EditorStyles.helpBox)) { GUILayout.Label($"{name} Hand:"); bool newIsAlwaysVisible = EditorGUILayout.Toggle("Always Visible", isAlwaysVisible); Vector3 newPosition = EditorGUILayout.Vector3Field("Position", position); Vector3 newRotation = DrawRotationGUI("Rotation", rotation); bool resetHand = GUILayout.Button("Reset"); if (newIsAlwaysVisible != isAlwaysVisible) { setAlwaysVisible(newIsAlwaysVisible); } if (newPosition != position) { setPosition(newPosition); } if (newRotation != rotation) { setRotation(newRotation); } if (resetHand) { reset(); } } } private void DrawRecordingGUI() { if (RecordingService == null) { EditorGUILayout.HelpBox("No input recording service found", MessageType.Info); return; } using (new GUILayout.HorizontalScope()) { bool newUseTimeLimit = GUILayout.Toggle(RecordingService.UseBufferTimeLimit, "Use buffer time limit"); if (newUseTimeLimit != RecordingService.UseBufferTimeLimit) { RecordingService.UseBufferTimeLimit = newUseTimeLimit; } using (new GUIEnabledWrapper(RecordingService.UseBufferTimeLimit)) { float newTimeLimit = EditorGUILayout.FloatField(RecordingService.RecordingBufferTimeLimit); if (newTimeLimit != RecordingService.RecordingBufferTimeLimit) { RecordingService.RecordingBufferTimeLimit = newTimeLimit; } } } bool wasRecording = RecordingService.IsRecording; var recordButtonContent = wasRecording ? new GUIContent(iconRecordActive, "Stop recording input animation") : new GUIContent(iconRecord, "Record new input animation"); bool record = GUILayout.Toggle(wasRecording, recordButtonContent, "Button"); if (record != wasRecording) { if (record) { RecordingService.StartRecording(); } else { RecordingService.StopRecording(); SaveAnimation(true); } } DrawAnimationInfo(); } private void DrawPlaybackGUI() { DrawAnimationInfo(); using (new GUILayout.HorizontalScope()) { if (GUILayout.Button("Load ...")) { string filepath = EditorUtility.OpenFilePanel( "Select input animation file", "", InputAnimationSerializationUtils.Extension); LoadAnimation(filepath); } } using (new GUIEnabledWrapper(PlaybackService != null)) { bool wasPlaying = PlaybackService.IsPlaying; bool play, stepFwd, jumpBack, jumpFwd; using (new GUILayout.HorizontalScope()) { jumpBack = GUILayout.Button(new GUIContent(iconJumpBack, "Jump to the start of the input animation"), "Button"); var playButtonContent = wasPlaying ? new GUIContent(iconPlay, "Stop playing input animation") : new GUIContent(iconPlay, "Play back input animation"); play = GUILayout.Toggle(wasPlaying, playButtonContent, "Button"); stepFwd = GUILayout.Button(new GUIContent(iconStepFwd, "Step forward one frame"), "Button"); jumpFwd = GUILayout.Button(new GUIContent(iconJumpFwd, "Jump to the end of the input animation"), "Button"); } float time = PlaybackService.LocalTime; float duration = (animation != null ? animation.Duration : 0.0f); float newTimeField = EditorGUILayout.FloatField("Current time", time); float newTimeSlider = GUILayout.HorizontalSlider(time, 0.0f, duration); if (play != wasPlaying) { if (play) { PlaybackService.Play(); } else { PlaybackService.Pause(); } } if (jumpBack) { PlaybackService.LocalTime = 0.0f; } if (jumpFwd) { PlaybackService.LocalTime = duration; } if (stepFwd) { PlaybackService.LocalTime += Time.deltaTime; } if (newTimeField != time) { PlaybackService.LocalTime = newTimeField; } if (newTimeSlider != time) { PlaybackService.LocalTime = newTimeSlider; } // Repaint while playing to update the timeline if (PlaybackService.IsPlaying) { Repaint(); } } } private void DrawAnimationInfo() { using (new GUILayout.VerticalScope(EditorStyles.helpBox)) { GUILayout.Label("Animation Info:", EditorStyles.boldLabel); if (animation != null) { GUILayout.Label($"File Path: {loadedFilePath}"); GUILayout.Label($"Duration: {animation.Duration} seconds"); } else { GUILayout.Label("No animation loaded"); } } } private Vector3 DrawRotationGUI(string label, Vector3 rotation) { Vector3 newRotation = EditorGUILayout.Vector3Field(label, rotation); return newRotation; } private void SaveAnimation(bool loadAfterExport) { string outputPath; if (loadedFilePath.Length > 0) { string loadedDirectory = Path.GetDirectoryName(loadedFilePath); outputPath = EditorUtility.SaveFilePanel( "Select output path", loadedDirectory, InputAnimationSerializationUtils.GetOutputFilename(), InputAnimationSerializationUtils.Extension); } else { outputPath = EditorUtility.SaveFilePanelInProject( "Select output path", InputAnimationSerializationUtils.GetOutputFilename(), InputAnimationSerializationUtils.Extension, "Enter filename for exporting input animation"); } if (outputPath.Length > 0) { string filename = Path.GetFileName(outputPath); string directory = Path.GetDirectoryName(outputPath); string result = RecordingService.SaveInputAnimation(filename, directory); RecordingService.DiscardRecordedInput(); if (loadAfterExport) { LoadAnimation(result); } } } private void LoadAnimation(string filepath) { if (PlaybackService.LoadInputAnimation(filepath)) { loadedFilePath = filepath; } else { loadedFilePath = ""; } } private void LoadIcons() { LoadTexture(ref iconPlay, "MRTK_TimelinePlay.png"); LoadTexture(ref iconRecord, "MRTK_TimelineRecord.png"); LoadTexture(ref iconRecordActive, "MRTK_TimelineRecordActive.png"); LoadTexture(ref iconStepFwd, "MRTK_TimelineStepFwd.png"); LoadTexture(ref iconJumpFwd, "MRTK_TimelineJumpFwd.png"); LoadTexture(ref iconJumpBack, "MRTK_TimelineJumpBack.png"); } private static void LoadTexture(ref Texture2D tex, string filename) { const string assetPath = "StandardAssets/Textures"; if (tex == null) { tex = (Texture2D)AssetDatabase.LoadAssetAtPath(MixedRealityToolkitFiles.MapRelativeFilePath(Path.Combine(assetPath, filename)), typeof(Texture2D)); } } } }
35.629938
163
0.527599
[ "MIT" ]
GooDtoLivE/VRByMRTK
MRTK2_2/Assets/MixedRealityToolkit.Services/InputSimulation/Editor/InputSimulationWindow.cs
17,138
C#
// <copyright file="InMemoryPropertyStoreFactory.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using FubarDev.WebDavServer.FileSystem; using FubarDev.WebDavServer.Props.Dead; using JetBrains.Annotations; using Microsoft.Extensions.Logging; namespace FubarDev.WebDavServer.Props.Store.InMemory { /// <summary> /// The factory for the <see cref="InMemoryPropertyStore"/> /// </summary> public class InMemoryPropertyStoreFactory : IPropertyStoreFactory { [NotNull] private readonly ILogger<InMemoryPropertyStore> _logger; [NotNull] private readonly IDeadPropertyFactory _deadPropertyFactory; /// <summary> /// Initializes a new instance of the <see cref="InMemoryPropertyStoreFactory"/> class. /// </summary> /// <param name="logger">The logger for the property store factory</param> /// <param name="deadPropertyFactory">The factory for dead properties</param> public InMemoryPropertyStoreFactory([NotNull] ILogger<InMemoryPropertyStore> logger, [NotNull] IDeadPropertyFactory deadPropertyFactory) { _logger = logger; _deadPropertyFactory = deadPropertyFactory; } /// <inheritdoc /> public IPropertyStore Create(IFileSystem fileSystem) { return new InMemoryPropertyStore(_deadPropertyFactory, _logger); } } }
34.348837
144
0.69262
[ "MIT" ]
FubarDevelopment/WebDavServer
src/FubarDev.WebDavServer.Props.Store.InMemory/InMemoryPropertyStoreFactory.cs
1,479
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. */ namespace Apache.Ignite.Core.Client { using System; using System.Diagnostics.CodeAnalysis; using System.Net; /// <summary> /// Represents Ignite client connection. /// </summary> public interface IClientConnection { /// <summary> /// Gets the remote EndPoint. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Consistency with EndPoint class name.")] EndPoint RemoteEndPoint { get; } /// <summary> /// Gets the local EndPoint. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Consistency with EndPoint class name.")] EndPoint LocalEndPoint { get; } /// <summary> /// Gets the server node id. /// </summary> Guid NodeId { get; } } }
36.4375
90
0.669525
[ "CC0-1.0" ]
10088/ignite
modules/platforms/dotnet/Apache.Ignite.Core/Client/IClientConnection.cs
1,749
C#
// // System.Collections.Generic.LinkedListNode // // Author: // David Waite // // (C) 2005 David Waite (mass@akuma.org) // // // Copyright (C) 2005 David Waite // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using System; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Permissions; using System.Collections.Generic; namespace System.Collections.Generic { [Serializable, ComVisible (false)] public class LinkedList <T> : ICollection <T>, ICollection, ISerializable #if NOT_PFX , ideserializationcallback #endif { const string DataArrayKey = "DataArray"; const string VersionKey = "version"; uint count, version; object syncRoot; // Internally a circular list - first.back == last internal LinkedListNode <T> first; internal SerializationInfo si; public LinkedList () { syncRoot = new object (); first = null; count = version = 0; } public LinkedList (IEnumerable <T> collection) : this () { foreach (T item in collection) AddLast (item); } protected LinkedList (SerializationInfo info, StreamingContext context) : this () { si = info; syncRoot = new object (); } void VerifyReferencedNode (LinkedListNode <T> node) { if (node == null) throw new ArgumentNullException ("node"); if (node.List != this) throw new InvalidOperationException (); } static void VerifyBlankNode (LinkedListNode <T> newNode) { if (newNode == null) throw new ArgumentNullException ("newNode"); if (newNode.List != null) throw new InvalidOperationException (); } public LinkedListNode <T> AddAfter (LinkedListNode <T> node, T value) { VerifyReferencedNode (node); LinkedListNode <T> newNode = new LinkedListNode <T> (this, value, node, node.forward); count++; version++; return newNode; } public void AddAfter (LinkedListNode <T> node, LinkedListNode <T> newNode) { VerifyReferencedNode (node); VerifyBlankNode (newNode); newNode.InsertBetween (node, node.forward, this); count++; version++; } public LinkedListNode <T> AddBefore (LinkedListNode <T> node, T value) { VerifyReferencedNode (node); LinkedListNode <T> newNode = new LinkedListNode <T> (this, value, node.back, node); count++; version++; if (node == first) first = newNode; return newNode; } public void AddBefore (LinkedListNode <T> node, LinkedListNode <T> newNode) { VerifyReferencedNode (node); VerifyBlankNode (newNode); newNode.InsertBetween (node.back, node, this); count++; version++; if (node == first) first = newNode; } public void AddFirst (LinkedListNode <T> node) { VerifyBlankNode (node); if (first == null) node.SelfReference (this); else node.InsertBetween (first.back, first, this); count++; version++; first = node; } public LinkedListNode <T> AddFirst (T value) { LinkedListNode <T> newNode; if (first == null) newNode = new LinkedListNode <T> (this, value); else newNode = new LinkedListNode <T> (this, value, first.back, first); count++; version++; first = newNode; return newNode; } public LinkedListNode <T> AddLast (T value) { LinkedListNode <T> newNode; if (first == null) { newNode = new LinkedListNode <T> (this, value); first = newNode; } else newNode = new LinkedListNode <T> (this, value, first.back, first); count++; version++; return newNode; } public void AddLast (LinkedListNode <T> node) { VerifyBlankNode (node); if (first == null) { node.SelfReference (this); first = node; } else node.InsertBetween (first.back, first, this); count++; version++; } public void Clear () { count = 0; first = null; version++; } public bool Contains (T value) { LinkedListNode <T> node = first; if (node == null) return false; do { if (value.Equals (node.Value)) return true; node = node.forward; } while (node != first); return false; } public void CopyTo (T [] array, int index) { if (array == null) throw new ArgumentNullException ("array"); if ( (uint) index < (uint) array.GetLowerBound (0)) throw new ArgumentOutOfRangeException ("index"); if (array.Rank != 1) throw new ArgumentException ("array", "Array is multidimensional"); if (array.Length - index + array.GetLowerBound (0) < count) throw new ArgumentException ("number of items exceeds capacity"); LinkedListNode <T> node = first; if (first == null) return; do { array [index] = node.Value; index++; node = node.forward; } while (node != first); } public LinkedListNode <T> Find (T value) { LinkedListNode <T> node = first; if (node == null) return null; do { if ( (value == null && node.Value == null) || value.Equals (node.Value)) return node; node = node.forward; } while (node != first); return null; } public LinkedListNode <T> FindLast (T value) { LinkedListNode <T> node = first; if (node == null) return null; do { node = node.back; if (value.Equals (node.Value)) return node; } while (node != first); return null; } public Enumerator GetEnumerator () { return new Enumerator (this); } [SecurityPermission (SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)] public virtual void GetObjectData (SerializationInfo info, StreamingContext context) { T [] data = new T [count]; CopyTo (data, 0); info.AddValue (DataArrayKey, data, typeof (T [])); info.AddValue (VersionKey, version); } public virtual void OnDeserialization (object sender) { if (si != null) { T [] data = (T []) si.GetValue (DataArrayKey, typeof (T [])); if (data != null) foreach (T item in data) AddLast (item); version = si.GetUInt32 (VersionKey); si = null; } } public bool Remove (T value) { LinkedListNode <T> node = Find (value); if (node == null) return false; Remove (node); return true; } public void Remove (LinkedListNode <T> node) { VerifyReferencedNode (node); count--; if (count == 0) first = null; if (node == first) first = first.forward; version++; node.Detach (); } public void RemoveFirst () { if (first != null) Remove (first); } public void RemoveLast () { if (first != null) Remove (first.back); } void ICollection <T>.Add (T value) { AddLast (value); } void ICollection.CopyTo (Array array, int index) { T [] Tarray = array as T []; if (Tarray == null) throw new ArgumentException ("array"); CopyTo (Tarray, index); } IEnumerator <T> IEnumerable <T>.GetEnumerator () { return GetEnumerator (); } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } public int Count { get { return (int) count; } } public LinkedListNode <T> First { get { return first; } } public LinkedListNode <T> Last { get { return (first != null) ? first.back : null; } } bool ICollection <T>.IsReadOnly { get { return false; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return syncRoot; } } [Serializable, StructLayout (LayoutKind.Sequential)] public struct Enumerator : IEnumerator <T>, IDisposable, IEnumerator #if !NET_2_1 , ISerializable #if NOT_PFX , IDeserializationCallback #endif #endif { const String VersionKey = "version"; const String IndexKey = "index"; const String ListKey = "list"; LinkedList <T> list; LinkedListNode <T> current; int index; uint version; #if !NET_2_1 SerializationInfo si; internal Enumerator (SerializationInfo info, StreamingContext context) { si = info; list = (LinkedList <T>) si.GetValue (ListKey, typeof (LinkedList <T>)); index = si.GetInt32 (IndexKey); version = si.GetUInt32 (VersionKey); current = null; } #endif internal Enumerator (LinkedList <T> parent) { #if !NET_2_1 si = null; #endif this.list = parent; current = null; index = -1; version = parent.version; } public T Current { get { if (list == null) throw new ObjectDisposedException (null); if (current == null) throw new InvalidOperationException (); return current.Value; } } object IEnumerator.Current { get { return Current; } } public bool MoveNext () { if (list == null) throw new ObjectDisposedException (null); if (version != list.version) throw new InvalidOperationException ("list modified"); if (current == null) current = list.first; else { current = current.forward; if (current == list.first) current = null; } if (current == null) { index = -1; return false; } ++index; return true; } void IEnumerator.Reset () { if (list == null) throw new ObjectDisposedException (null); if (version != list.version) throw new InvalidOperationException ("list modified"); current = null; index = -1; } public void Dispose () { if (list == null) throw new ObjectDisposedException (null); current = null; list = null; } #if NOT_PFX #if !NET_2_1 [SecurityPermission (SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)] void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) { if (list == null) throw new ObjectDisposedException (null); info.AddValue (VersionKey, version); info.AddValue (IndexKey, index); } void IDeserializationCallback.OnDeserialization (object sender) { if (si == null) return; if (list.si != null) ( (IDeserializationCallback) list).OnDeserialization (this); si = null; if (version == list.version && index != -1) { LinkedListNode <T> node = list.First; for (int i = 0; i < index; i++) node = node.forward; current = node; } } #endif #endif } } } #endif
23.365234
105
0.606788
[ "MIT" ]
GrapeCity/pagefx
mono/mcs/class/System/System.Collections.Generic/LinkedList.cs
11,963
C#
using System; using System.IO; using Microsoft.Win32; using System.Drawing; using System.Windows.Forms; namespace StartupEdit { /// <summary> /// this class responsible for reading all the entries whether in the registry or in the folders /// this class has the folloing methods /// 1)internal void ReadRegistry ( string hkey, string SubBranch, string Suffix, bool TrueIfDisabled ) /// 2)internal void ReadStartUpFolders ( string Root ) /// 3)internal void GetMSConfigNoneXPRegistry ( string hkey, string Key, string EntryType, string StatusMsg ) /// 4)internal void GetMSConfigNoneXPFolders( string Path, string EntryType, string StatusMsg ) /// 5)internal void GetMSConfigXPRegistry() /// 6)internal void GetMSConfigXPFolders() /// 7)internal void GetLocalMahine( bool TrueIfDisabled ) /// 8)internal void GetCurrentUser( bool TrueIfDisabled ) /// 9)internal void GetStartupFolder( bool GetDisabled ) /// </summary> public class FetchMan { #region Some Instance Variables, Property And The Constructor /// <summary> /// Main Reg For Manipulating Registry /// </summary> private RegistryKey GlobalReg; /// <summary> /// Main Dir For Startup Directory /// </summary> private DirectoryInfo GlobalDir; /// <summary> /// The ListView Which Holds Th Main Target /// </summary> private ListView GlobalView; /// <summary> /// This Instance Of SomeActionHere Class Has The (Analyze) Method /// Which Is Responsble For Analyzing Strings and AHandle Method to get the handle to an icon /// </summary> private ClsAddOns GlobalGet = new ClsAddOns(); /// <summary> /// ImageList For Holding The Icons Extracted From The Entries Larg 32*32 /// </summary> private ImageList GlobalImageLarg; /// <summary> /// ImageList For Holding The Icons Extracted From The Entries Larg 16*16 /// </summary> private ImageList GlobalImageSmall; /// <summary> /// To Increment The Imagelist /// </summary> private static int GlobalImageCounter = 0; /// <summary> /// To Create The ListViewItem /// </summary> private ListViewItem GlobalEntry; /// <summary> /// To Manipulate The Entries /// </summary> private string GlobalString; /// <summary> /// Use this class to get enabled and disabled Entries from both /// windows registry and startup folder /// </summary> public FetchMan() { // Initialize the imagelist that holds the larg icons GlobalImageLarg = new ImageList(); // Some Properties GlobalImageLarg.TransparentColor = System.Drawing.Color.Transparent; GlobalImageLarg.ColorDepth = ColorDepth.Depth32Bit; GlobalImageLarg.ImageSize = new Size( 32, 32 ); // Initialize the imagelist that holds the larg icons GlobalImageSmall = new ImageList(); GlobalImageSmall.TransparentColor = System.Drawing.Color.Transparent; GlobalImageSmall.ColorDepth = ColorDepth.Depth32Bit; GlobalImageSmall.ImageSize = new Size( 16, 16 ); } /// <summary> /// Gets Or Sets The ListView Object /// </summary> internal ListView TheGlobalView { get { return GlobalView; } set { GlobalView = value; // Imagelists used by the listview assign it now GlobalView.LargeImageList = GlobalImageLarg; GlobalView.SmallImageList = GlobalImageSmall; } } #endregion #region Get Items #region Windows Registry /// <summary> /// To Read From windows Registry everything Enabled and Disabled /// </summary> /// <param name="hkey">Root Key LM, CU. CR</param> /// <param name="SubBranch">With disabled entries"LM" Or Environment.UserName</param> /// <param name="Suffix"> Run, RunOnce</param> /// <param name="TrueIfDisabled">if you are calling a disabled Item</param> internal void ReadRegistry ( string hkey, string SubBranch, string Suffix, bool TrueIfDisabled ) { string TheKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\"; string Status = "Enabled"; if ( TrueIfDisabled ) { TheKey = @"Software\AlQademoUn\StartEdit\" + SubBranch + @"\" ; Status = "Disabled"; } try { switch ( hkey ) { case "HKEY_LOCAL_MACHINE": GlobalReg = Registry.LocalMachine.OpenSubKey ( TheKey + Suffix, true ); break; case "HKEY_CURRENT_USER": GlobalReg = Registry.CurrentUser.OpenSubKey ( TheKey + Suffix, true ); break; case "HKEY_CLASSES_ROOT": GlobalReg = Registry.ClassesRoot.OpenSubKey ( TheKey + Suffix, true ); break; } if ( GlobalReg.ValueCount != 0 ) { foreach ( string SingleIt in GlobalReg.GetValueNames() ) { GlobalString = GlobalReg.GetValue ( SingleIt, "Error" ).ToString(); GlobalEntry = new ListViewItem(); GlobalEntry.ImageIndex = GlobalImageCounter; GlobalImageLarg.Images.Add( Icon.FromHandle ( GlobalGet.AHandle ( GlobalString ) ) ); GlobalImageSmall.Images.Add ( GlobalImageLarg.Images[GlobalImageCounter] ); GlobalEntry.Text = SingleIt; //Name GlobalEntry.SubItems.Add( GlobalString ); // Data GlobalEntry.SubItems.Add( hkey ); // Hive GlobalEntry.SubItems.Add( Suffix ); // Type GlobalEntry.SubItems.Add( Status ); // Status GlobalEntry.SubItems.Add( /* GlobalReg.Name */ TheKey + Suffix ); // Full Key Path GlobalView.Items.Add ( GlobalEntry ); GlobalImageCounter ++; } GlobalReg.Close(); } } catch ( InvalidOperationException MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( hkey + "\\" + TheKey + Suffix + "\n" + MyEx.Message.Trim() ); } catch ( System.Security.SecurityException MyExp ) { MessageBox.Show ( "An error returned while trying to access \n" + hkey + "\\" + TheKey + Suffix + "\n" + "Error is " + MyExp.Message + "\n" + "Startup Editor requires an administrartor privileges to run properly" ,"Access is denied"); return; } catch ( ArgumentNullException MyEx ) { //MyEx.Message.Trim(); MessageBox.Show ( hkey + "\\" + TheKey + Suffix + "\n" + MyEx.Message.Trim() ); } catch ( NullReferenceException MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( hkey + "\\" + TheKey + Suffix + "\n" + MyEx.Message.Trim() ); } catch ( Exception MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( hkey + "\\" + TheKey + Suffix + "\n" + MyEx.Message.Trim() ); } } #endregion #region Startup Folders /// <summary> /// To read all the entries found in the startup folders /// </summary> /// <param name="Root">Put one of the following(Replacing Enabled with Disabled if needed) /// All Users Enabled, User Name Enabled</param> internal void ReadStartUpFolders ( string Root ) { string Status = "Enabled"; try { switch ( Root ) { case "All Users Enabled": Root = "All Users"; GlobalReg = Registry.LocalMachine.OpenSubKey ( @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" , true ); GlobalDir = new DirectoryInfo ( GlobalReg.GetValue( "Common Startup", "C:\\" ).ToString() ); GlobalReg.Close(); break; case "User Name Enabled": Root = Environment.UserName; GlobalDir = new DirectoryInfo ( Environment.GetFolderPath ( Environment.SpecialFolder.Startup )); break; case "All Users Disabled": Root = "All Users"; Status = "Disabled"; GlobalDir = new DirectoryInfo ( Application.StartupPath + @"\BackUps\All Users" ); break; case "User Name Disabled": Root = Environment.UserName ; Status = "Disabled"; GlobalDir = new DirectoryInfo ( Application.StartupPath + @"\BackUps\" + Environment.UserName ); break; } if ( GlobalDir.Exists ) { foreach ( FileInfo SingleIt in GlobalDir.GetFiles ( "*.*" ) ) { GlobalString = SingleIt.FullName; GlobalEntry = new ListViewItem(); GlobalEntry.ImageIndex = GlobalImageCounter; GlobalImageLarg.Images.Add( Icon.FromHandle ( GlobalGet.AHandle ( GlobalString ) ) ); GlobalImageSmall.Images.Add ( GlobalImageLarg.Images[GlobalImageCounter] ); GlobalEntry.Text = SingleIt.Name; GlobalEntry.SubItems.Add ( GlobalString ); GlobalEntry.SubItems.Add( "Startup Folder" ); GlobalEntry.SubItems.Add( Root ); GlobalEntry.SubItems.Add( Status ); GlobalEntry.SubItems.Add( GlobalString ); // Full Key Path GlobalView.Items.Add ( GlobalEntry ); GlobalImageCounter ++; } } } catch ( InvalidOperationException MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( MyEx.Message +"\n" + MyEx.Source ); } catch ( System.Security.SecurityException MyExp ) { MessageBox.Show ( "An error returned while trying to access \n" + "Error is " + MyExp.Message + "\n" + "Startup Editor requires an administrartor privileges to run properly" ,"Access is denied"); return; } catch ( ArgumentNullException MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( MyEx.Message +"\n" + MyEx.Source ); } catch ( NullReferenceException MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( MyEx.Message +"\n" + MyEx.Source ); } catch ( Exception MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( MyEx.Message +"\n" + MyEx.Source ); } } #endregion #endregion #region Microsoft Configuration Utility MSConfig.exe #region A none WinXP Systems internal void GetMSConfigNoneXPRegistry ( string hkey, string Key, string EntryType, string StatusMsg ) { try { switch ( hkey ) { case "HKEY_LOCAL_MACHINE": GlobalReg = Registry.LocalMachine.OpenSubKey ( Key, true ); break; case "HKEY_CURRENT_USER": GlobalReg = Registry.CurrentUser.OpenSubKey ( Key, true ); break; case "HKEY_CLASSES_ROOT": GlobalReg = Registry.ClassesRoot.OpenSubKey ( Key, true ); break; } if ( GlobalReg.ValueCount != 0 ) { foreach ( string SingleCustom in GlobalReg.GetValueNames() ) { GlobalString = GlobalReg.GetValue ( SingleCustom, "Error" ).ToString(); GlobalEntry = new ListViewItem(); GlobalEntry.ImageIndex = GlobalImageCounter; GlobalImageLarg.Images.Add( Icon.FromHandle ( GlobalGet.AHandle ( GlobalString ) ) ); GlobalImageSmall.Images.Add ( GlobalImageLarg.Images[GlobalImageCounter] ); GlobalEntry.Text = SingleCustom; //name GlobalEntry.SubItems.Add( GlobalString ); //data GlobalEntry.SubItems.Add( hkey ); //root GlobalEntry.SubItems.Add( EntryType ); // TYPE GlobalEntry.SubItems.Add( StatusMsg ); // Status GlobalEntry.SubItems.Add( Key ); // Full Key Path GlobalView.Items.Add ( GlobalEntry ); GlobalImageCounter ++; } GlobalReg.Close(); } } catch ( InvalidOperationException MyEx ) { //MyEx.Message.Trim(); MessageBox.Show ( hkey + "\\" + Key + "\n" + MyEx.Message.Trim() ); } catch ( System.Security.SecurityException MyExp ) { MessageBox.Show ( "An error returned while trying to access \n" + hkey + "\\" + "\n" + "Error is " + MyExp.Message + "\n" + "Startup Editor requires an administrartor privileges to run properly" ,"Access is denied"); return; } catch ( ArgumentNullException MyEx ) { //MyEx.Message.Trim(); MessageBox.Show ( hkey + "\\" + Key + "\n" + MyEx.Message.Trim() ); } catch ( NullReferenceException MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( hkey + "\\" + Key + "\n" + MyEx.Message.Trim() ); } catch ( Exception MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( hkey + "\\" + Key + "\n" + MyEx.Message.Trim() ); } } internal void GetMSConfigNoneXPFolders( string Path, string EntryType, string StatusMsg ) { try { GlobalReg = Registry.LocalMachine.OpenSubKey ( @"SOFTWARE\Microsoft\Windows\CurrentVersion" , true ); switch ( Path ) { case "All Users": // This is usually "C:\WINDOWS\ALL USERS\START MENU\PROGRAMS\ Path = GlobalReg.GetValue( "SystemRoot", @"C:\Windows" ).ToString() + @"\All Users\Start Menu\Programs\Disabled Startup Items"; // All Users NONE XP GlobalReg.Close(); break; case "Current User": // This is usually "C:\WINDOWS\START MENU\PROGRAMS\ Path = Environment.GetFolderPath ( Environment.SpecialFolder.Programs ) + @"\Disabled Startup Items"; // this is a Current User in a NONE XP SYSTEMS break; } GlobalDir = new DirectoryInfo ( Path ); if ( GlobalDir.Exists ) { foreach ( FileInfo SingleFile in GlobalDir.GetFiles ( "*.*" ) ) { GlobalString = SingleFile.FullName; GlobalEntry = new ListViewItem(); GlobalEntry.ImageIndex = GlobalImageCounter; GlobalImageLarg.Images.Add( Icon.FromHandle ( GlobalGet.AHandle ( GlobalString ) ) ); GlobalImageSmall.Images.Add ( GlobalImageLarg.Images[GlobalImageCounter] ); GlobalEntry.Text = SingleFile.Name; GlobalEntry.SubItems.Add ( GlobalString ); GlobalEntry.SubItems.Add( "Startup Folder" ); GlobalEntry.SubItems.Add( EntryType ); GlobalEntry.SubItems.Add( StatusMsg ); GlobalEntry.SubItems.Add( GlobalString ); // Full Key Path GlobalView.Items.Add ( GlobalEntry ); GlobalImageCounter ++; } } } catch ( InvalidOperationException MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( MyEx.Message +"\n" + MyEx.Source ); } catch ( System.Security.SecurityException MyExp ) { MessageBox.Show ( "An error returned while trying to access \n" + "Error is " + MyExp.Message + "\n" + "Startup Editor requires an administrartor privileges to run properly" ,"Access is denied"); return; } catch ( ArgumentNullException MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( MyEx.Message +"\n" + MyEx.Source ); } catch ( NullReferenceException MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( MyEx.Message +"\n" + MyEx.Source ); } catch ( Exception MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( MyEx.Message +"\n" + MyEx.Source ); } } #endregion #region XP System internal void GetMSConfigXPRegistry() { string ThePath = @"SOFTWARE\Microsoft\Shared Tools\MSConfig\startupreg"; try { GlobalReg = Registry.LocalMachine.OpenSubKey ( ThePath ,true ); if ( GlobalReg.SubKeyCount != 0 ) { foreach ( string SingleKey in GlobalReg.GetSubKeyNames() ) { GlobalReg = Registry.LocalMachine.OpenSubKey ( ThePath + @"\" + SingleKey, true ); //---------------------------------------------------------------------------- string Entry = GlobalReg.GetValue ( "item", "item" ).ToString(); string command = GlobalReg.GetValue ( "Command", "Command" ).ToString(); string key = GlobalReg.GetValue ( "key", "key" ).ToString(); string hkey = GlobalReg.GetValue ( "hkey", "hkey" ).ToString(); if ( hkey == "HKLM" ) { hkey = "HKEY_LOCAL_MACHINE"; } if ( hkey == "HKCU" ) { hkey = "HKEY_CURRENT_USER"; } //---------------------------------------------------------------------------- GlobalString = GlobalGet.AnalyzeIt ( command ); GlobalEntry = new ListViewItem(); GlobalEntry.ImageIndex = GlobalImageCounter; GlobalImageLarg.Images.Add( Icon.FromHandle ( GlobalGet.AHandle ( GlobalString ) ) ); GlobalImageSmall.Images.Add ( GlobalImageLarg.Images[GlobalImageCounter] ); GlobalEntry.Text = Entry; GlobalEntry.SubItems.Add( command ); GlobalEntry.SubItems.Add( hkey ); GlobalEntry.SubItems.Add( "Run" ); GlobalEntry.SubItems.Add( "Disabled By MSConfig.exe" ); GlobalEntry.SubItems.Add( ThePath + @"\" + SingleKey ); GlobalView.Items.Add ( GlobalEntry ); GlobalImageCounter ++; } } } catch ( System.Security.SecurityException MyExp ) { MessageBox.Show ( "Sorry Man it looks like \n" + MyExp.Message + "\n" + MyExp.GrantedSet ); Application.ExitThread(); Application.Exit(); } catch ( ArgumentNullException MyEx ) { MyEx.Message.Trim(); } catch ( NullReferenceException MyEx ) { MyEx.Message.Trim(); } catch ( Exception MyEx ) { MyEx.Message.Trim(); } } internal void GetMSConfigXPFolders() { string ThePath = @"SOFTWARE\Microsoft\Shared Tools\MSConfig\startupfolder"; try { GlobalReg = Registry.LocalMachine.OpenSubKey ( ThePath ,true ); if ( GlobalReg.SubKeyCount != 0 ) { foreach ( string SingleKey in GlobalReg.GetSubKeyNames() ) { GlobalReg = Registry.LocalMachine.OpenSubKey ( ThePath + @"\" + SingleKey, true ); //---------------------------------------------------------------------------- string Entry = GlobalReg.GetValue ( "item", "item" ).ToString(); string command = GlobalReg.GetValue ( "Command", "Command" ).ToString(); string path = GlobalReg.GetValue ( "path", "path" ).ToString(); string backup = GlobalReg.GetValue ( "backup", "backup" ).ToString(); string location = GlobalReg.GetValue ( "location", "location" ).ToString(); if ( location == "Common Startup" ) { location = "All Users"; } if ( location == "Startup" ) { location = Environment.UserName; } //---------------------------------------------------------------------------- GlobalString = GlobalGet.AnalyzeIt ( path ); GlobalEntry = new ListViewItem(); GlobalEntry.ImageIndex = GlobalImageCounter; GlobalImageLarg.Images.Add( Icon.FromHandle ( GlobalGet.AHandle ( GlobalString ) ) ); GlobalImageSmall.Images.Add ( GlobalImageLarg.Images[GlobalImageCounter] ); GlobalEntry.Text = Entry; GlobalEntry.SubItems.Add( path ); GlobalEntry.SubItems.Add( "Startup Folder" ); GlobalEntry.SubItems.Add( location ); GlobalEntry.SubItems.Add( "Disabled By MSConfig.exe" ); GlobalEntry.SubItems.Add( backup ); GlobalView.Items.Add ( GlobalEntry ); GlobalImageCounter ++; } } } catch ( System.Security.SecurityException MyExp ) { MessageBox.Show ( "An error returned while trying to access MSConfig.exe Entries\n" + "\n" + " Error is " + MyExp.Message + "\n" + "Startup Editor requires an administrartor privileges to run properly" ,"Access is denied"); return; } catch ( ArgumentNullException MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( ThePath + "\n" + MyEx.Message.Trim() ); } catch ( NullReferenceException MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( ThePath + "\n" + MyEx.Message.Trim() ); } catch ( Exception MyEx ) { MyEx.Message.Trim(); //MessageBox.Show ( ThePath + "\n" + MyEx.Message.Trim() ); } } #endregion #endregion MsConfig #region Faciliate The Code Design /// <summary> /// Get Group of Entries /// </summary> /// <param name="Suffix">Put one of (Once, OnceEx, Services, ServicesOnce </param> /// <param name="Disabled">True If Disabled</param> internal void GetLocalMahine( bool TrueIfDisabled ) { ReadRegistry ( "HKEY_LOCAL_MACHINE", "LM", "Run", TrueIfDisabled ); ReadRegistry ( "HKEY_LOCAL_MACHINE", "LM", "RunOnce", TrueIfDisabled ); ReadRegistry ( "HKEY_LOCAL_MACHINE", "LM", "RunOnceEx", TrueIfDisabled ); ReadRegistry ( "HKEY_LOCAL_MACHINE", "LM", "RunServices", TrueIfDisabled ); ReadRegistry ( "HKEY_LOCAL_MACHINE", "LM", "RunServicesOnce", TrueIfDisabled ); } internal void GetCurrentUser( bool TrueIfDisabled ) { string hkey = "HKEY_CURRENT_USER"; if ( TrueIfDisabled ) { hkey = "HKEY_LOCAL_MACHINE"; } ReadRegistry ( hkey, Environment.UserName,"Run", TrueIfDisabled ); ReadRegistry ( hkey, Environment.UserName,"RunOnce", TrueIfDisabled ); } internal void GetStartupFolder( bool GetDisabled ) { string VersionS = " Enabled"; if ( GetDisabled ) { VersionS = " Disabled"; } ReadStartUpFolders ( "User Name" + VersionS ); ReadStartUpFolders ( "All Users" + VersionS ); } internal void GetMSConfigFolder( string caseIs) { switch (caseIs) { case "A None WinXp System": { GetMSConfigNoneXPFolders("Current User", Environment.UserName, "Disabled By MSConfig.exe"); GetMSConfigNoneXPFolders("All Users", "All Users", "Disabled By MSConfig.exe"); break; } case "WinXp With Admin": { GetMSConfigXPFolders(); break; } } } internal void GetMSConfigReg(string caseIs) { string Key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\"; switch (caseIs) { case "A None WinXp System": { // msconfig.exe in a none winxp system only monitors two keys in the HKEY_LOCAL_MACHINE // Run and RunServices, while in the HKEY_CURRENT_USER the program monitors only the Run // Key and it adds the "-" suffix GetMSConfigNoneXPRegistry("HKEY_LOCAL_MACHINE", Key + "Run-", "Run", "Disabled By MSConfig.exe"); GetMSConfigNoneXPRegistry("HKEY_LOCAL_MACHINE", Key + "RunServices-", "Run", "Disabled By MSConfig.exe"); GetMSConfigNoneXPRegistry("HKEY_CURRENT_USER", Key + "Run-", "Run", "Disabled By MSConfig.exe"); break; } case "WinXp With Admin": { GetMSConfigXPRegistry(); break; } } } #endregion } }
30.939691
129
0.622121
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
candseeme/Startup-Edit
Backup/Classes/FetchMan.cs
22,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("RubberPlant.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RubberPlant.Tests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("252c71ce-87d5-4abb-8b75-95e6eafd0ff6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027027
84
0.745558
[ "MIT" ]
joce/RubberPlant
src/RubberPlant.Tests/Properties/AssemblyInfo.cs
1,410
C#
using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Runtime.Caching; using System.Security.Principal; using System.Windows; using System.Windows.Controls; using System.Windows.Forms; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Threading; using ARSoft.Tools.Net.Dns; using AuroraGUI.DnsSvr; using AuroraGUI.Fx; using AuroraGUI.Tools; using MaterialDesignThemes.Wpf; using static System.AppDomain; using WinFormMenuItem = System.Windows.Forms.MenuItem; using WinFormContextMenu = System.Windows.Forms.ContextMenu; using MessageBox = System.Windows.MessageBox; // ReSharper disable NotAccessedField.Local namespace AuroraGUI { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow { public static string SetupBasePath = CurrentDomain.SetupInformation.ApplicationBase; public static IPAddress IntIPAddr = IPAddress.Any; public static IPAddress LocIPAddr = IPAddress.Any; public static NotifyIcon NotifyIcon; private DnsServer MDnsServer; private BackgroundWorker MDnsSvrWorker = new BackgroundWorker(){WorkerSupportsCancellation = true}; public MainWindow() { InitializeComponent(); WindowStyle = WindowStyle.SingleBorderWindow; Grid.Effect = new BlurEffect { Radius = 5, RenderingBias = RenderingBias.Performance }; if (TimeZoneInfo.Local.Id.Contains("China Standard Time") && RegionInfo.CurrentRegion.GeoId == 45) { //Mainland China PRC DnsSettings.SecondDnsIp = IPAddress.Parse("119.29.29.29"); DnsSettings.HttpsDnsUrl = "https://neatdns.ustclug.org/resolve"; UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-CN.list"; UrlSettings.WhatMyIpApi = "https://myip.mili.one/"; } else if (TimeZoneInfo.Local.Id.Contains("Taipei Standard Time") && RegionInfo.CurrentRegion.GeoId == 237) { //Taiwan ROC DnsSettings.SecondDnsIp = IPAddress.Parse("101.101.101.101"); DnsSettings.HttpsDnsUrl = "https://dns.twnic.tw/dns-query"; UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-TW.list"; } else if (RegionInfo.CurrentRegion.GeoId == 104) //HongKong SAR UrlSettings.MDnsList = "https://cdn.jsdelivr.net/gh/mili-tan/AuroraDNS.GUI/List/L10N/DNS-HK.list"; if (!File.Exists($"{SetupBasePath}config.json")) if (MyTools.IsBadSoftExist()) MessageBox.Show("Tips: AuroraDNS 强烈不建议您使用国产安全软件产品!"); if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged")) { try { UrlReg.Reg("doh"); UrlReg.Reg("dns-over-https"); UrlReg.Reg("aurora-doh-list"); File.Create(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged"); File.SetAttributes( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged", FileAttributes.Hidden); } catch (Exception e) { Console.WriteLine(e); } } try { if (File.Exists($"{SetupBasePath}url.json")) UrlSettings.ReadConfig($"{SetupBasePath}url.json"); if (File.Exists($"{SetupBasePath}config.json")) DnsSettings.ReadConfig($"{SetupBasePath}config.json"); if (DnsSettings.BlackListEnable && File.Exists($"{SetupBasePath}black.list")) DnsSettings.ReadBlackList($"{SetupBasePath}black.list"); if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.list")) DnsSettings.ReadWhiteList($"{SetupBasePath}white.list"); if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.list")) DnsSettings.ReadWhiteList($"{SetupBasePath}rewrite.list"); if (DnsSettings.ChinaListEnable && File.Exists("china.list")) DnsSettings.ReadChinaList(SetupBasePath + "china.list"); } catch (UnauthorizedAccessException e) { MessageBoxResult msgResult = MessageBox.Show( "Error: 尝试读取配置文件权限不足或IO安全故障,点击确定现在尝试以管理员权限启动。点击取消中止程序运行。" + $"{Environment.NewLine}Original error: {e}", "错误", MessageBoxButton.OKCancel); if (msgResult == MessageBoxResult.OK) RunAsAdmin(); else Close(); } catch (Exception e) { MessageBox.Show($"Error: 尝试读取配置文件错误{Environment.NewLine}Original error: {e}"); } ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; if (DnsSettings.AllowSelfSignedCert) ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; // switch (0.0) // { // case 1: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // break; // case 1.1: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; // break; // case 1.2: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // break; // default: // ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; // break; // } MDnsServer = new DnsServer(DnsSettings.ListenIp, 10, 10); MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived; MDnsSvrWorker.DoWork += (sender, args) => MDnsServer.Start(); MDnsSvrWorker.Disposed += (sender, args) => MDnsServer.Stop(); using (BackgroundWorker worker = new BackgroundWorker()) { worker.DoWork += (sender, args) => { LocIPAddr = IPAddress.Parse(IpTools.GetLocIp()); IntIPAddr = IPAddress.Parse(IpTools.GetIntIp()); try { if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}white.sub.list")) DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}white.sub.list"); if (DnsSettings.WhiteListEnable && File.Exists($"{SetupBasePath}rewrite.sub.list")) DnsSettings.ReadWhiteListSubscribe($"{SetupBasePath}rewrite.sub.list"); } catch (Exception e) { MessageBox.Show($"Error: 尝试下载订阅列表失败{Environment.NewLine}Original error: {e}"); } MemoryCache.Default.Trim(100); }; worker.RunWorkerAsync(); } NotifyIcon = new NotifyIcon() { Text = @"AuroraDNS", Visible = false, Icon = Properties.Resources.AuroraWhite }; WinFormMenuItem showItem = new WinFormMenuItem("最小化 / 恢复", MinimizedNormal); WinFormMenuItem restartItem = new WinFormMenuItem("重新启动", (sender, args) => { if (MDnsSvrWorker.IsBusy) MDnsSvrWorker.Dispose(); Process.Start(new ProcessStartInfo {FileName = GetType().Assembly.Location}); Environment.Exit(Environment.ExitCode); }); WinFormMenuItem notepadLogItem = new WinFormMenuItem("查阅日志", (sender, args) => { if (File.Exists( $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log")) Process.Start(new ProcessStartInfo( $"{SetupBasePath}Log/{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log")); else MessageBox.Show("找不到当前日志文件,或当前未产生日志文件。"); }); WinFormMenuItem abootItem = new WinFormMenuItem("关于…", (sender, args) => new AboutWindow().Show()); WinFormMenuItem updateItem = new WinFormMenuItem("检查更新…", (sender, args) => MyTools.CheckUpdate(GetType().Assembly.Location)); WinFormMenuItem settingsItem = new WinFormMenuItem("设置…", (sender, args) => new SettingsWindow().Show()); WinFormMenuItem exitItem = new WinFormMenuItem("退出", (sender, args) => { try { UrlReg.UnReg("doh"); UrlReg.UnReg("dns-over-https"); UrlReg.UnReg("aurora-doh-list"); File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\AuroraDNS.UrlReged"); if (!DnsSettings.AutoCleanLogEnable) return; foreach (var item in Directory.GetFiles($"{SetupBasePath}Log")) if (item != $"{SetupBasePath}Log" + $"\\{DateTime.Today.Year}{DateTime.Today.Month:00}{DateTime.Today.Day:00}.log") File.Delete(item); if (File.Exists(Path.GetTempPath() + "setdns.cmd")) File.Delete(Path.GetTempPath() + "setdns.cmd"); } catch (Exception e) { Console.WriteLine(e); } Close(); Environment.Exit(Environment.ExitCode); }); NotifyIcon.ContextMenu = new WinFormContextMenu(new[] { showItem, notepadLogItem, new WinFormMenuItem("-"), abootItem, updateItem, settingsItem, new WinFormMenuItem("-"), restartItem, exitItem }); NotifyIcon.DoubleClick += MinimizedNormal; IsSysDns.IsChecked = MyTools.IsNslookupLocDns(); if (IsSysDns.IsChecked == true) IsSysDns.ToolTip = "已设为系统 DNS"; } private void Window_Loaded(object sender, RoutedEventArgs e) { Visibility = Visibility.Hidden; if (Environment.OSVersion.Version.Major == 10) WindowBlur.SetEnabled(this, true); else { NotifyIcon.Icon = Properties.Resources.AuroraBlack; Background = new SolidColorBrush(Colors.White) {Opacity = 1}; } var desktopWorkingArea = SystemParameters.WorkArea; Left = desktopWorkingArea.Right - Width - 5; Top = desktopWorkingArea.Bottom - Height - 5; FadeIn(0.2); Visibility = Visibility.Visible; NotifyIcon.Visible = true; if (!MyTools.PortIsUse(DnsSettings.ListenPort)) { IsLog.IsChecked = DnsSettings.DebugLog; if (Equals(DnsSettings.ListenIp, IPAddress.Any)) IsGlobal.IsChecked = true; DnsEnable.IsChecked = true; Grid.Effect = null; if (File.Exists($"{SetupBasePath}config.json")) WindowState = WindowState.Minimized; } else { Snackbar.IsActive = true; if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName) .Count(o => o.Id != Process.GetCurrentProcess().Id) > 0) { var snackbarMsg = new SnackbarMessage() { Content = "可能已有一个正在运行的实例, 请不要重复启动!", ActionContent = "退出" }; snackbarMsg.ActionClick += (o, args) => Environment.Exit(Environment.ExitCode); Snackbar.Message = snackbarMsg; NotifyIcon.Text = @"AuroraDNS - [请不要重复启动]"; } else { Snackbar.Message = new SnackbarMessage() {Content = $"DNS 服务器无法启动, {DnsSettings.ListenPort}端口被占用。"}; NotifyIcon.Text = @"AuroraDNS - [端口被占用]"; } DnsEnable.IsEnabled = false; ControlGrid.IsEnabled = false; } if (Equals(DnsSettings.ListenIp, IPAddress.IPv6Any) || Equals(DnsSettings.ListenIp, IPAddress.IPv6Loopback)) new TcpFwder(Equals(DnsSettings.ListenIp, IPAddress.IPv6Any) ? IPAddress.Any : IPAddress.Loopback, 53, IPAddress.IPv6Loopback, 53).Run(); } private void IsGlobal_Checked(object sender, RoutedEventArgs e) { if (MyTools.PortIsUse(DnsSettings.ListenPort)) { MDnsSvrWorker.Dispose(); MDnsServer = new DnsServer(new IPEndPoint(IPAddress.Any, DnsSettings.ListenPort), 10, 10); MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived; Snackbar.MessageQueue.Enqueue(new TextBlock() {Text = "监听地址: 局域网 " + IPAddress.Any}); MDnsSvrWorker.RunWorkerAsync(); } } private void IsGlobal_Unchecked(object sender, RoutedEventArgs e) { if (MyTools.PortIsUse(DnsSettings.ListenPort)) { MDnsSvrWorker.Dispose(); MDnsServer = new DnsServer(new IPEndPoint(IPAddress.Loopback, DnsSettings.ListenPort), 10, 10); MDnsServer.QueryReceived += QueryResolve.ServerOnQueryReceived; Snackbar.MessageQueue.Enqueue(new TextBlock() {Text = "监听地址: 本地 " + IPAddress.Loopback}); MDnsSvrWorker.RunWorkerAsync(); } } private void IsLog_Checked(object sender, RoutedEventArgs e) { DnsSettings.DebugLog = true; if (MyTools.PortIsUse(DnsSettings.ListenPort)) Snackbar.MessageQueue.Enqueue(new TextBlock() {Text = "记录日志:是"}); } private void IsLog_Unchecked(object sender, RoutedEventArgs e) { DnsSettings.DebugLog = false; if (MyTools.PortIsUse(DnsSettings.ListenPort)) Snackbar.MessageQueue.Enqueue(new TextBlock() {Text = "记录日志:否"}); } private void DnsEnable_Checked(object sender, RoutedEventArgs e) { MDnsSvrWorker.RunWorkerAsync(); if (MDnsSvrWorker.IsBusy) { Snackbar.MessageQueue.Enqueue(new TextBlock() { Text = "DNS 服务器已启动" }); NotifyIcon.Text = @"AuroraDNS - Running"; } } private void DnsEnable_Unchecked(object sender, RoutedEventArgs e) { MDnsSvrWorker.Dispose(); if (!MDnsSvrWorker.IsBusy) { Snackbar.MessageQueue.Enqueue(new TextBlock() { Text = "DNS 服务器已停止" }); NotifyIcon.Text = @"AuroraDNS - Stop"; } } private void SettingButton_Click(object sender, RoutedEventArgs e) { var settingsWindow = new SettingsWindow(); settingsWindow.Closed += (o, args) => { IsLog.IsChecked = DnsSettings.DebugLog; IsGlobal.IsChecked = Equals(DnsSettings.ListenIp, IPAddress.Any); }; settingsWindow.Show(); } public void RunAsAdmin() { try { MDnsSvrWorker.Dispose(); ProcessStartInfo startInfo = new ProcessStartInfo { FileName = GetType().Assembly.Location, Verb = "runas" }; Process.Start(startInfo); Environment.Exit(Environment.ExitCode); } catch (Exception exception) { MyTools.BackgroundLog(exception.ToString()); } } private void Window_StateChanged(object sender, EventArgs e) { if (WindowState == WindowState.Normal) { FadeIn(0.2); ShowInTaskbar = true; } else if (WindowState == WindowState.Minimized) ShowInTaskbar = false; GC.Collect(); } private void FadeIn(double sec) { var fadeInStoryboard = new Storyboard(); DoubleAnimation fadeInAnimation = new DoubleAnimation(0.0, 1.0, new Duration(TimeSpan.FromSeconds(sec))); Storyboard.SetTarget(fadeInAnimation, this); Storyboard.SetTargetProperty(fadeInAnimation, new PropertyPath(OpacityProperty)); fadeInStoryboard.Children.Add(fadeInAnimation); Dispatcher.BeginInvoke(new Action(fadeInStoryboard.Begin), DispatcherPriority.Render, null); } private void MinimizedNormal(object sender, EventArgs e) { if (WindowState == WindowState.Normal) { WindowState = WindowState.Minimized; Hide(); } else if (WindowState == WindowState.Minimized) { Show(); WindowState = WindowState.Normal; } } private void IsSysDns_OnClick(object sender, RoutedEventArgs e) { try { if (MyTools.IsNslookupLocDns()) { if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) { SysDnsSet.ResetDns(); Snackbar.MessageQueue.Enqueue(new TextBlock {Text = "已将 DNS 重置为自动获取"}); } else { SysDnsSet.ResetDnsCmd(); Snackbar.MessageQueue.Enqueue(new TextBlock {Text = "已通过 Netsh 将 DNS 重置为自动获取"}); } IsSysDns.ToolTip = "设为系统 DNS"; IsSysDns.IsChecked = false; } else { if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole( WindowsBuiltInRole.Administrator)) { SysDnsSet.SetDns(IPAddress.Loopback.ToString(), DnsSettings.SecondDnsIp.ToString()); IsSysDns.ToolTip = "已设为系统 DNS"; } else { SysDnsSet.SetDnsCmd(IPAddress.Loopback.ToString(), DnsSettings.SecondDnsIp.ToString()); Snackbar.MessageQueue.Enqueue(new TextBlock {Text = "已通过 Netsh 设为系统 DNS"}); } Snackbar.MessageQueue.Enqueue(new TextBlock { Text = "主DNS:" + IPAddress.Loopback + Environment.NewLine + "辅DNS:" + DnsSettings.SecondDnsIp }); IsSysDns.ToolTip = "已设为系统 DNS"; IsSysDns.IsChecked = true; } } catch (Exception exception) { MessageBox.Show(exception.ToString()); } } } }
42.243697
156
0.54073
[ "MIT" ]
ioxuy/AuroraDNS.GUI
AuroraGUI/Forms/MainWindow.xaml.cs
20,646
C#
/* Copyright (c) 2018, Szymon Jakóbczyk, Paweł Płatek, Michał Mielus, Maciej Rajs, Minh Nhật Trịnh, Izabela Musztyfaga All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the [organization] nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections; using System.Collections.Generic; using UnityEngine; public class HexMetrics : MonoBehaviour { public const float outerRadius = 5f; // Hexagon radius on the long symmetry public const float innerRadius = outerRadius * 0.866025404f; // Hexagon radius on the short symmetry public const int chunkSizeX = 10, chunkSizeZ = 10; public static Vector3[] corners = { //Hexagon corners new Vector3(0f, 0f, outerRadius), new Vector3(innerRadius, 0f, 0.5f * outerRadius), new Vector3(innerRadius, 0f, -0.5f * outerRadius), new Vector3(0f, 0f, -outerRadius), new Vector3(-innerRadius, 0f, -0.5f * outerRadius), new Vector3(-innerRadius, 0f, 0.5f * outerRadius), new Vector3(0f, 0f, outerRadius) }; }
56.906977
158
0.741316
[ "Unlicense" ]
Playfloor/Galactromeda
Assets/Scripts/HexLogic/HexMetrics.cs
2,455
C#
// <auto-generated /> using BlogSystem.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using System; namespace BlogSystem.Data.Migrations { [DbContext(typeof(BlogSystemDbContext))] [Migration("20180413125151_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.2-rtm-10011") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("BlogSystem.Data.Models.Comment", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AuthorId") .IsRequired(); b.Property<string>("Content") .IsRequired(); b.Property<DateTime?>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<bool>("IsDeleted"); b.Property<int>("Likes"); b.Property<DateTime?>("ModifiedOn"); b.Property<int>("PostId"); b.HasKey("Id"); b.HasIndex("AuthorId"); b.HasIndex("PostId"); b.ToTable("Comments"); }); modelBuilder.Entity("BlogSystem.Data.Models.Post", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AuthorId") .IsRequired(); b.Property<string>("Content") .IsRequired(); b.Property<DateTime?>("CreatedOn"); b.Property<DateTime?>("DeletedOn"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("ModifiedOn"); b.Property<string>("Title") .IsRequired(); b.HasKey("Id"); b.HasIndex("AuthorId"); b.ToTable("Posts"); }); modelBuilder.Entity("BlogSystem.Data.Models.User", 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("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); 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(); 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("BlogSystem.Data.Models.Comment", b => { b.HasOne("BlogSystem.Data.Models.User", "Author") .WithMany("Comments") .HasForeignKey("AuthorId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("BlogSystem.Data.Models.Post", "Post") .WithMany("Comments") .HasForeignKey("PostId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("BlogSystem.Data.Models.Post", b => { b.HasOne("BlogSystem.Data.Models.User", "Author") .WithMany("Posts") .HasForeignKey("AuthorId") .OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("BlogSystem.Data.Models.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("BlogSystem.Data.Models.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("BlogSystem.Data.Models.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("BlogSystem.Data.Models.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
32.872274
117
0.459249
[ "MIT" ]
simeonovanton/TelerikALPHA_nov2017
09.ASP.NET_MVC/BlogSystem_Steven_Done100/Solution/BlogSystem.Data/Migrations/20180413125151_Initial.Designer.cs
10,554
C#
using System; using System.Collections.Generic; using System.Text; namespace JT808.Gateway.Abstractions.Enums { /// <summary> /// 传输协议类型 /// </summary> public enum JT808TransportProtocolType { tcp=1, udp = 2 } }
15.875
42
0.61811
[ "MIT" ]
Seamless2014/JT808Gateway
src/JT808.Gateway.Abstractions/Enums/JT808TransportProtocolType.cs
268
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Routing; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.AspNet.FriendlyUrls.Resolvers; namespace PlaymoWars { public partial class ViewSwitcher : System.Web.UI.UserControl { protected string CurrentView { get; private set; } protected string AlternateView { get; private set; } protected string SwitchUrl { get; private set; } protected void Page_Load(object sender, EventArgs e) { // Determine current view var isMobile = WebFormsFriendlyUrlResolver.IsMobileView(new HttpContextWrapper(Context)); CurrentView = isMobile ? "Mobile" : "Desktop"; // Determine alternate view AlternateView = isMobile ? "Desktop" : "Mobile"; // Create switch URL from the route, e.g. ~/__FriendlyUrls_SwitchView/Mobile?ReturnUrl=/Page var switchViewRouteName = "AspNet.FriendlyUrls.SwitchView"; var switchViewRoute = RouteTable.Routes[switchViewRouteName]; if (switchViewRoute == null) { // Friendly URLs is not enabled or the name of the switch view route is out of sync this.Visible = false; return; } var url = GetRouteUrl(switchViewRouteName, new { view = AlternateView, __FriendlyUrls_SwitchViews = true }); url += "?ReturnUrl=" + HttpUtility.UrlEncode(Request.RawUrl); SwitchUrl = url; } } }
36.837209
120
0.642677
[ "Apache-2.0" ]
ChinaFred/PlaymoWars-2016
ViewSwitcher.ascx.cs
1,584
C#
namespace Fonet.Fo.Properties { internal class GroupingSizeMaker : NumberProperty.Maker { new public static PropertyMaker Maker(string propName) { return new GroupingSizeMaker(propName); } protected GroupingSizeMaker(string name) : base(name) {} public override bool IsInherited() { return false; } private Property m_defaultProp = null; public override Property Make(PropertyList propertyList) { if (m_defaultProp == null) { m_defaultProp = Make(propertyList, "0", propertyList.getParentFObj()); } return m_defaultProp; } } }
27.24
86
0.609398
[ "Apache-2.0" ]
DaveDezinski/Fo.Net
src/Fo/Properties/GroupingSizeMaker.cs
681
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Moq; using ConsoleApp4; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProject2 { [TestClass] public class BookRepositoryTest { //void Edit(T book); //void Remove(int id); [TestMethod] public void Get_BookExists_ShouldReturn() { var fileMock = new Mock<IFileWorker>(); fileMock.Setup(x => x.ReadFromJsonFile<List<Book>>("output1.json")).Returns(new List<Book> { new Book(8,"title8") }); var subject = new BookRepository(fileMock.Object); var result = subject.Get(8); Assert.IsNotNull(result); Assert.AreEqual(8, result.ID); } [TestMethod] [ExpectedException(typeof(Exception))] public void Get_BookDoesNotExists_ExpectedException() { var fileMock = new Mock<IFileWorker>(); fileMock.Setup(x => x.ReadFromJsonFile<List<Book>>("output1.json")).Returns(new List<Book> { new Book(8, "title8") }); var subject = new BookRepository(fileMock.Object); var result = subject.Get(100); } [TestMethod] public void Add_AddNotNull_ShouldExist() { var fileMock = new Mock<IFileWorker>(); fileMock.Setup(x => x.ReadFromJsonFile<List<Book>>("output1.json")).Returns(new List<Book> ()); var subject = new BookRepository(fileMock.Object); subject.Add(new Book(17,"title17")); var result = subject.Get(17); Assert.IsNotNull(result); Assert.AreEqual(17, result.ID); } [TestMethod] public void Edit_BookExists_ShouldBeChanged() { var fileMock = new Mock<IFileWorker>(); fileMock.Setup(x => x.ReadFromJsonFile<List<Book>>("output1.json")).Returns(new List<Book> { new Book(8, "title8") }); var subject = new BookRepository(fileMock.Object); subject.Edit(new Book(8,"changedtitle")); var result = subject.Get(8); Assert.IsNotNull(result); Assert.AreEqual("changedtitle", result.Title); } [TestMethod] [ExpectedException(typeof(Exception))] public void Edit_BookDoesNotExist_ExpectedException() { var fileMock = new Mock<IFileWorker>(); fileMock.Setup(x => x.ReadFromJsonFile<List<Book>>("output1.json")).Returns(new List<Book> { new Book(8, "title8") }); var subject = new BookRepository(fileMock.Object); subject.Edit(new Book(14, "changedtitle")); } [TestMethod] public void Delete_BookExists_NoException() { var fileMock = new Mock<IFileWorker>(); fileMock.Setup(x => x.ReadFromJsonFile<List<Book>>("output1.json")).Returns(new List<Book> { new Book(8, "title8") }); var subject = new BookRepository(fileMock.Object); subject.Remove(8); } [TestMethod] [ExpectedException(typeof(Exception))] public void Delete_BookDoesNotExist_ExpectedException() { var fileMock = new Mock<IFileWorker>(); fileMock.Setup(x => x.ReadFromJsonFile<List<Book>>("output1.json")).Returns(new List<Book> { new Book(8, "title8") }); var subject = new BookRepository(fileMock.Object); subject.Remove(16); } } }
31.45614
130
0.591746
[ "MIT" ]
chertby/Course-M-ND2-33-19
Bandarin/ConsoleApp3/UnitTestProject2/BookRepositoryTest.cs
3,588
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Reflection; using System.Runtime; using CSJ2K; using Nini.Config; using log4net; using Warp3D; using Mono.Addins; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.PhysicsModules.SharedBase; using OpenSim.Services.Interfaces; using OpenMetaverse; using OpenMetaverse.Assets; using OpenMetaverse.Imaging; using OpenMetaverse.Rendering; using OpenMetaverse.StructuredData; using WarpRenderer = Warp3D.Warp3D; namespace OpenSim.Region.CoreModules.World.Warp3DMap { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Warp3DImageModule")] public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule { private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216); // private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 128); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #pragma warning disable 414 private static string LogHeader = "[WARP 3D IMAGE MODULE]"; #pragma warning restore 414 private const float m_cameraHeight = 4096f; internal Scene m_scene; private IRendering m_primMesher; internal IJ2KDecoder m_imgDecoder; // caches per rendering private Dictionary<UUID, warp_Texture> m_warpTextures = new Dictionary<UUID, warp_Texture>(); private Dictionary<UUID, int> m_colors = new Dictionary<UUID, int>(); private IConfigSource m_config; private bool m_drawPrimVolume = true; // true if should render the prims on the tile private bool m_textureTerrain = true; // true if to create terrain splatting texture private bool m_textureAverageTerrain = false; // replace terrain textures by their average color private bool m_texturePrims = true; // true if should texture the rendered prims private float m_texturePrimSize = 48f; // size of prim before we consider texturing it private bool m_renderMeshes = false; // true if to render meshes rather than just bounding boxes private float m_renderMinHeight = -100f; private float m_renderMaxHeight = 4096f; private bool m_Enabled = false; // private Bitmap lastImage = null; private DateTime lastImageTime = DateTime.MinValue; #region Region Module interface public void Initialise(IConfigSource source) { m_config = source; string[] configSections = new string[] { "Map", "Startup" }; if (Util.GetConfigVarFromSections<string>( m_config, "MapImageModule", configSections, "MapImageModule") != "Warp3DImageModule") return; m_Enabled = true; m_drawPrimVolume = Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, m_drawPrimVolume); m_textureTerrain = Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, m_textureTerrain); m_textureAverageTerrain = Util.GetConfigVarFromSections<bool>(m_config, "AverageTextureColorOnMapTile", configSections, m_textureAverageTerrain); if (m_textureAverageTerrain) m_textureTerrain = true; m_texturePrims = Util.GetConfigVarFromSections<bool>(m_config, "TexturePrims", configSections, m_texturePrims); m_texturePrimSize = Util.GetConfigVarFromSections<float>(m_config, "TexturePrimSize", configSections, m_texturePrimSize); m_renderMeshes = Util.GetConfigVarFromSections<bool>(m_config, "RenderMeshes", configSections, m_renderMeshes); m_renderMaxHeight = Util.GetConfigVarFromSections<float>(m_config, "RenderMaxHeight", configSections, m_renderMaxHeight); m_renderMinHeight = Util.GetConfigVarFromSections<float>(m_config, "RenderMinHeight", configSections, m_renderMinHeight); if (m_renderMaxHeight < 100f) m_renderMaxHeight = 100f; else if (m_renderMaxHeight > m_cameraHeight - 10f) m_renderMaxHeight = m_cameraHeight - 10f; if (m_renderMinHeight < -100f) m_renderMinHeight = -100f; else if (m_renderMinHeight > m_renderMaxHeight - 10f) m_renderMinHeight = m_renderMaxHeight - 10f; } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_scene = scene; List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory()); if (renderers.Count > 0) m_log.Info("[MAPTILE]: Loaded prim mesher " + renderers[0]); else m_log.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled"); m_scene.RegisterModuleInterface<IMapImageGenerator>(this); } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; m_imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>(); } public void RemoveRegion(Scene scene) { } public void Close() { } public string Name { get { return "Warp3DImageModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion #region IMapImageGenerator Members private Vector3 cameraPos; private Vector3 cameraDir; private int viewWitdh = 256; private int viewHeight = 256; private float fov; private bool orto; public Bitmap CreateMapTile() { List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory()); if (renderers.Count > 0) { m_primMesher = RenderingLoader.LoadRenderer(renderers[0]); } cameraPos = new Vector3( (m_scene.RegionInfo.RegionSizeX) * 0.5f, (m_scene.RegionInfo.RegionSizeY) * 0.5f, m_cameraHeight); cameraDir = -Vector3.UnitZ; viewWitdh = (int)m_scene.RegionInfo.RegionSizeX; viewHeight = (int)m_scene.RegionInfo.RegionSizeY; orto = true; // fov = warp_Math.rad2deg(2f * (float)Math.Atan2(viewWitdh, 4096f)); // orto = false; Bitmap tile = GenImage(); // image may be reloaded elsewhere, so no compression format string filename = "MAP-" + m_scene.RegionInfo.RegionID.ToString() + ".png"; tile.Save(filename, ImageFormat.Png); m_primMesher = null; return tile; } public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float pfov, int width, int height, bool useTextures) { List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory()); if (renderers.Count > 0) { m_primMesher = RenderingLoader.LoadRenderer(renderers[0]); } cameraPos = camPos; cameraDir = camDir; viewWitdh = width; viewHeight = height; fov = pfov; orto = false; Bitmap tile = GenImage(); m_primMesher = null; return tile; } private Bitmap GenImage() { m_colors.Clear(); m_warpTextures.Clear(); WarpRenderer renderer = new WarpRenderer(); if (!renderer.CreateScene(viewWitdh, viewHeight)) return new Bitmap(viewWitdh, viewHeight); #region Camera warp_Vector pos = ConvertVector(cameraPos); warp_Vector lookat = warp_Vector.add(pos, ConvertVector(cameraDir)); if (orto) renderer.Scene.defaultCamera.setOrthographic(true, viewWitdh, viewHeight); else renderer.Scene.defaultCamera.setFov(fov); renderer.Scene.defaultCamera.setPos(pos); renderer.Scene.defaultCamera.lookAt(lookat); #endregion Camera renderer.Scene.setAmbient(warp_Color.getColor(192, 191, 173)); renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(0f, 1f, 8f), warp_Color.White, 0, 320, 40)); CreateWater(renderer); CreateTerrain(renderer); if (m_drawPrimVolume) CreateAllPrims(renderer); renderer.Render(); Bitmap bitmap = renderer.Scene.getImage(); renderer.Scene.destroy(); renderer.Reset(); renderer = null; m_colors.Clear(); m_warpTextures.Clear(); GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.Default; return bitmap; } public byte[] WriteJpeg2000Image() { try { using (Bitmap mapbmp = CreateMapTile()) return OpenJPEG.EncodeFromImage(mapbmp, false); } catch (Exception e) { // JPEG2000 encoder failed m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e); } return null; } #endregion #region Rendering Methods // Add a water plane to the renderer. private void CreateWater(WarpRenderer renderer) { float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight; renderer.AddPlane("Water", m_scene.RegionInfo.RegionSizeX * 0.5f, false); renderer.Scene.sceneobject("Water").setPos(m_scene.RegionInfo.RegionSizeX * 0.5f, waterHeight, m_scene.RegionInfo.RegionSizeY * 0.5f); warp_Material waterMaterial = new warp_Material(ConvertColor(WATER_COLOR)); renderer.Scene.addMaterial("WaterMat", waterMaterial); renderer.SetObjectMaterial("Water", "WaterMat"); } // Add a terrain to the renderer. // Note that we create a 'low resolution' 257x257 vertex terrain rather than trying for // full resolution. This saves a lot of memory especially for very large regions. private void CreateTerrain(WarpRenderer renderer) { ITerrainChannel terrain = m_scene.Heightmap; float regionsx = m_scene.RegionInfo.RegionSizeX; float regionsy = m_scene.RegionInfo.RegionSizeY; // 'diff' is the difference in scale between the real region size and the size of terrain we're buiding int bitWidth; int bitHeight; const double log2inv = 1.4426950408889634073599246810019; bitWidth = (int)Math.Ceiling((Math.Log(terrain.Width) * log2inv)); bitHeight = (int)Math.Ceiling((Math.Log(terrain.Height) * log2inv)); if (bitWidth > 8) // more than 256 is very heavy :( bitWidth = 8; if (bitHeight > 8) bitHeight = 8; int twidth = (int)Math.Pow(2, bitWidth); int theight = (int)Math.Pow(2, bitHeight); float diff = regionsx / twidth; int npointsx = (int)(regionsx / diff); int npointsy = (int)(regionsy / diff); float invsx = 1.0f / (npointsx * diff); float invsy = 1.0f / (npointsy * diff); npointsx++; npointsy++; // Create all the vertices for the terrain warp_Object obj = new warp_Object(); warp_Vector pos; float x, y; float tv; for (y = 0; y < regionsy; y += diff) { tv = y * invsy; for (x = 0; x < regionsx; x += diff) { pos = ConvertVector(x, y, (float)terrain[(int)x, (int)y]); obj.addVertex(new warp_Vertex(pos, x * invsx, tv)); } pos = ConvertVector(x, y, (float)terrain[(int)(x - diff), (int)y]); obj.addVertex(new warp_Vertex(pos, 1.0f, tv)); } int lastY = (int)(y - diff); for (x = 0; x < regionsx; x += diff) { pos = ConvertVector(x, y, (float)terrain[(int)x, lastY]); obj.addVertex(new warp_Vertex(pos, x * invsx, 1.0f)); } pos = ConvertVector(x, y, (float)terrain[(int)(x - diff), lastY]); obj.addVertex(new warp_Vertex(pos, 1.0f, 1.0f)); // create triangles. int limx = npointsx - 1; int limy = npointsy - 1; for (int j = 0; j < limy; j++) { for (int i = 0; i < limx; i++) { int v = j * npointsx + i; // Make two triangles for each of the squares in the grid of vertices obj.addTriangle( v, v + 1, v + npointsx); obj.addTriangle( v + npointsx + 1, v + npointsx, v + 1); } } renderer.Scene.addObject("Terrain", obj); UUID[] textureIDs = new UUID[4]; float[] startHeights = new float[4]; float[] heightRanges = new float[4]; OpenSim.Framework.RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings; textureIDs[0] = regionInfo.TerrainTexture1; textureIDs[1] = regionInfo.TerrainTexture2; textureIDs[2] = regionInfo.TerrainTexture3; textureIDs[3] = regionInfo.TerrainTexture4; startHeights[0] = (float)regionInfo.Elevation1SW; startHeights[1] = (float)regionInfo.Elevation1NW; startHeights[2] = (float)regionInfo.Elevation1SE; startHeights[3] = (float)regionInfo.Elevation1NE; heightRanges[0] = (float)regionInfo.Elevation2SW; heightRanges[1] = (float)regionInfo.Elevation2NW; heightRanges[2] = (float)regionInfo.Elevation2SE; heightRanges[3] = (float)regionInfo.Elevation2NE; warp_Texture texture; using (Bitmap image = TerrainSplat.Splat(terrain, textureIDs, startHeights, heightRanges, m_scene.RegionInfo.WorldLocX, m_scene.RegionInfo.WorldLocY, m_scene.AssetService, m_imgDecoder, m_textureTerrain, m_textureAverageTerrain, twidth, twidth)) texture = new warp_Texture(image); warp_Material material = new warp_Material(texture); renderer.Scene.addMaterial("TerrainMat", material); renderer.SetObjectMaterial("Terrain", "TerrainMat"); } private void CreateAllPrims(WarpRenderer renderer) { if (m_primMesher == null) return; m_scene.ForEachSOG( delegate (SceneObjectGroup group) { foreach (SceneObjectPart child in group.Parts) CreatePrim(renderer, child); } ); } private void UVPlanarMap(Vertex v, Vector3 scale, out float tu, out float tv) { Vector3 scaledPos = v.Position * scale; float d = v.Normal.X; if (d >= 0.5f) { tu = 2f * scaledPos.Y; tv = scaledPos.X * v.Normal.Z - scaledPos.Z * v.Normal.X; } else if( d <= -0.5f) { tu = -2f * scaledPos.Y; tv = -scaledPos.X * v.Normal.Z + scaledPos.Z * v.Normal.X; } else if (v.Normal.Y > 0f) { tu = -2f * scaledPos.X; tv = scaledPos.Y * v.Normal.Z - scaledPos.Z * v.Normal.Y; } else { tu = 2f * scaledPos.X; tv = -scaledPos.Y * v.Normal.Z + scaledPos.Z * v.Normal.Y; } tv *= 2f; } private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim) { if ((PCode)prim.Shape.PCode != PCode.Prim) return; Vector3 ppos = prim.GetWorldPosition(); if (ppos.Z < m_renderMinHeight || ppos.Z > m_renderMaxHeight) return; warp_Vector primPos = ConvertVector(ppos); warp_Quaternion primRot = ConvertQuaternion(prim.GetWorldRotation()); warp_Matrix m = warp_Matrix.quaternionMatrix(primRot); float screenFactor = renderer.Scene.EstimateBoxProjectedArea(primPos, ConvertVector(prim.Scale), m); if (screenFactor < 0) return; int p2 = (int)(-(float)Math.Log(screenFactor) * 1.442695f * 0.5 - 1); if (p2 < 0) p2 = 0; else if (p2 > 3) p2 = 3; DetailLevel lod = (DetailLevel)(3 - p2); FacetedMesh renderMesh = null; Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset); if (m_renderMeshes) { if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero) { // Try fetchinng the asset AssetBase sculptAsset = m_scene.AssetService.Get(omvPrim.Sculpt.SculptTexture.ToString()); if (sculptAsset != null) { // Is it a mesh? if (omvPrim.Sculpt.Type == SculptType.Mesh) { AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset.Data); FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, lod, out renderMesh); meshAsset = null; } else // It's sculptie { if (m_imgDecoder != null) { Image sculpt = m_imgDecoder.DecodeToImage(sculptAsset.Data); if (sculpt != null) { renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt, lod); sculpt.Dispose(); } } } } else { m_log.WarnFormat("[Warp3D] failed to get mesh or sculpt asset {0} of prim {1} at {2}", omvPrim.Sculpt.SculptTexture.ToString(), prim.Name, prim.GetWorldPosition().ToString()); } } } // If not a mesh or sculptie, try the regular mesher if (renderMesh == null) { renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, lod); } if (renderMesh == null) return; string primID = prim.UUID.ToString(); // Create the prim faces // TODO: Implement the useTextures flag behavior for (int i = 0; i < renderMesh.Faces.Count; i++) { Face face = renderMesh.Faces[i]; string meshName = primID + i.ToString(); // Avoid adding duplicate meshes to the scene if (renderer.Scene.objectData.ContainsKey(meshName)) continue; warp_Object faceObj = new warp_Object(); Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i); Color4 faceColor = teFace.RGBA; if (faceColor.A == 0) continue; string materialName = String.Empty; if (m_texturePrims) { // if(lod > DetailLevel.Low) { // materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID, lod == DetailLevel.Low); materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID, false, prim); if (String.IsNullOrEmpty(materialName)) continue; int c = renderer.Scene.material(materialName).getColor(); if ((c & warp_Color.MASKALPHA) == 0) continue; } } else materialName = GetOrCreateMaterial(renderer, faceColor); if (renderer.Scene.material(materialName).getTexture() == null) { // uv map details dont not matter for color; for (int j = 0; j < face.Vertices.Count; j++) { Vertex v = face.Vertices[j]; warp_Vector pos = ConvertVector(v.Position); warp_Vertex vert = new warp_Vertex(pos, v.TexCoord.X, v.TexCoord.Y); faceObj.addVertex(vert); } } else { float tu; float tv; float offsetu = teFace.OffsetU + 0.5f; float offsetv = teFace.OffsetV + 0.5f; float scaleu = teFace.RepeatU; float scalev = teFace.RepeatV; float rotation = teFace.Rotation; float rc = 0; float rs = 0; if (rotation != 0) { rc = (float)Math.Cos(rotation); rs = (float)Math.Sin(rotation); } for (int j = 0; j < face.Vertices.Count; j++) { warp_Vertex vert; Vertex v = face.Vertices[j]; warp_Vector pos = ConvertVector(v.Position); if(teFace.TexMapType == MappingType.Planar) UVPlanarMap(v, prim.Scale,out tu, out tv); else { tu = v.TexCoord.X - 0.5f; tv = 0.5f - v.TexCoord.Y; } if (rotation != 0) { float tur = tu * rc - tv * rs; float tvr = tu * rs + tv * rc; tur *= scaleu; tur += offsetu; tvr *= scalev; tvr += offsetv; vert = new warp_Vertex(pos, tur, tvr); } else { tu *= scaleu; tu += offsetu; tv *= scalev; tv += offsetv; vert = new warp_Vertex(pos, tu, tv); } faceObj.addVertex(vert); } } for (int j = 0; j < face.Indices.Count; j += 3) { faceObj.addTriangle( face.Indices[j + 0], face.Indices[j + 1], face.Indices[j + 2]); } faceObj.scaleSelf(prim.Scale.X, prim.Scale.Z, prim.Scale.Y); faceObj.transform(m); faceObj.setPos(primPos); renderer.Scene.addObject(meshName, faceObj); renderer.SetObjectMaterial(meshName, materialName); } } private int GetFaceColor(Primitive.TextureEntryFace face) { int color; Color4 ctmp = Color4.White; if (face.TextureID == UUID.Zero) return warp_Color.White; if (!m_colors.TryGetValue(face.TextureID, out color)) { bool fetched = false; // Attempt to fetch the texture metadata string cacheName = "MAPCLR" + face.TextureID.ToString(); AssetBase metadata = m_scene.AssetService.GetCached(cacheName); if (metadata != null) { OSDMap map = null; try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { } if (map != null) { ctmp = map["X-RGBA"].AsColor4(); fetched = true; } } if (!fetched) { // Fetch the texture, decode and get the average color, // then save it to a temporary metadata asset AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString()); if (textureAsset != null) { int width, height; ctmp = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height); OSDMap data = new OSDMap { { "X-RGBA", OSD.FromColor4(ctmp) } }; metadata = new AssetBase { Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)), Description = "Metadata for texture color" + face.TextureID.ToString(), Flags = AssetFlags.Collectable, FullID = UUID.Zero, ID = cacheName, Local = true, Temporary = true, Name = String.Empty, Type = (sbyte)AssetType.Unknown }; m_scene.AssetService.Store(metadata); } else { ctmp = new Color4(0.5f, 0.5f, 0.5f, 1.0f); } } color = ConvertColor(ctmp); m_colors[face.TextureID] = color; } return color; } private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color) { string name = color.ToString(); warp_Material material = renderer.Scene.material(name); if (material != null) return name; renderer.AddMaterial(name, ConvertColor(color)); return name; } public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID, bool useAverageTextureColor, SceneObjectPart sop) { int color = ConvertColor(faceColor); string idstr = textureID.ToString() + color.ToString(); string materialName = "MAPMAT" + idstr; if (renderer.Scene.material(materialName) != null) return materialName; warp_Material mat = new warp_Material(); warp_Texture texture = GetTexture(textureID, sop); if (texture != null) { if (useAverageTextureColor) color = warp_Color.multiply(color, texture.averageColor); else mat.setTexture(texture); } else color = warp_Color.multiply(color, warp_Color.Grey); mat.setColor(color); renderer.Scene.addMaterial(materialName, mat); return materialName; } private warp_Texture GetTexture(UUID id, SceneObjectPart sop) { warp_Texture ret = null; if (id == UUID.Zero) return ret; if (m_warpTextures.TryGetValue(id, out ret)) return ret; AssetBase asset = m_scene.AssetService.Get(id.ToString()); if (asset != null) { try { using (Bitmap img = (Bitmap)m_imgDecoder.DecodeToImage(asset.Data)) ret = new warp_Texture(img, 8); // reduce textures size to 256x256 } catch (Exception e) { m_log.WarnFormat("[Warp3D]: Failed to decode texture {0} for prim {1} at {2}, exception {3}", id.ToString(), sop.Name, sop.GetWorldPosition().ToString(), e.Message); } } else m_log.WarnFormat("[Warp3D]: missing texture {0} data for prim {1} at {2}", id.ToString(), sop.Name, sop.GetWorldPosition().ToString()); m_warpTextures[id] = ret; return ret; } #endregion Rendering Methods #region Static Helpers // Note: axis change. private static warp_Vector ConvertVector(float x, float y, float z) { return new warp_Vector(x, z, y); } private static warp_Vector ConvertVector(Vector3 vector) { return new warp_Vector(vector.X, vector.Z, vector.Y); } private static warp_Quaternion ConvertQuaternion(Quaternion quat) { return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W); } private static int ConvertColor(Color4 color) { int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f), (byte)(color.A * 255f)); return c; } private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3) { Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z); Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z); Vector3 normal = Vector3.Cross(edge1, edge2); normal.Normalize(); return normal; } public Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height) { ulong r = 0; ulong g = 0; ulong b = 0; ulong a = 0; int pixelBytes; try { using (MemoryStream stream = new MemoryStream(j2kData)) using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream)) { width = bitmap.Width; height = bitmap.Height; BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat); pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4; // Sum up the individual channels unsafe { if (pixelBytes == 4) { for (int y = 0; y < height; y++) { byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride); for (int x = 0; x < width; x++) { b += row[x * pixelBytes + 0]; g += row[x * pixelBytes + 1]; r += row[x * pixelBytes + 2]; a += row[x * pixelBytes + 3]; } } } else { for (int y = 0; y < height; y++) { byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride); for (int x = 0; x < width; x++) { b += row[x * pixelBytes + 0]; g += row[x * pixelBytes + 1]; r += row[x * pixelBytes + 2]; } } } } } // Get the averages for each channel const decimal OO_255 = 1m / 255m; decimal totalPixels = (decimal)(width * height); decimal rm = ((decimal)r / totalPixels) * OO_255; decimal gm = ((decimal)g / totalPixels) * OO_255; decimal bm = ((decimal)b / totalPixels) * OO_255; decimal am = ((decimal)a / totalPixels) * OO_255; if (pixelBytes == 3) am = 1m; return new Color4((float)rm, (float)gm, (float)bm, (float)am); } catch (Exception ex) { m_log.WarnFormat( "[WARP 3D IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}", textureID, j2kData.Length, ex.Message); width = 0; height = 0; return new Color4(0.5f, 0.5f, 0.5f, 1.0f); } } #endregion Static Helpers } public static class ImageUtils { /// <summary> /// Performs bilinear interpolation between four values /// </summary> /// <param name="v00">First, or top left value</param> /// <param name="v01">Second, or top right value</param> /// <param name="v10">Third, or bottom left value</param> /// <param name="v11">Fourth, or bottom right value</param> /// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param> /// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param> /// <returns>The bilinearly interpolated result</returns> public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent) { return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent); } } }
38.916667
185
0.514407
[ "BSD-3-Clause" ]
BillBlight/consortium
OpenSim/Region/CoreModules/World/Warp3DMap/Warp3DImageModule.cs
36,893
C#
using Orchard.Indexing; namespace Orchard.ContentManagement.Handlers { public class IndexContentContext : ContentContextBase { public IDocumentIndex DocumentIndex { get; private set; } public IndexContentContext(ContentItem contentItem, IDocumentIndex documentIndex) : base(contentItem) { DocumentIndex = documentIndex; } } }
29.538462
89
0.703125
[ "BSD-3-Clause" ]
1996dylanriley/Orchard
src/Orchard/ContentManagement/Handlers/IndexContentContext.cs
384
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace CafeRestorantOtomasyonu { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new giris()); } } }
22.695652
65
0.62069
[ "Apache-2.0" ]
receppolat/Cafelania
CafeRestorantOtomasyonu/CafeRestorantOtomasyonu/Program.cs
524
C#
using System.Collections; using System.Linq; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; namespace Assets.Sources { public class Player : MonoBehaviour { public PrefabsHolder prefabsHolder; public GameObject ShockWave; public int Tries; public int CurrentTries; public int Hits; public Image[] Stars; public Image [] Spots; public float finishDelay; public void Awake () { CurrentTries = Tries; Debug.Log("current tries: " + CurrentTries); } public void SuccessHit() { Debug.Log("Player Found something! O_O"); if (Hits != Spots.Count()) return; GameObject.Find("KeepBetweenScenes").GetComponent<Level>().current++; Promises.Promise.WithCoroutine<object>(FinishDelay(finishDelay, "winscreen")); } public static IEnumerator FinishDelay(float delay, string scene) { yield return new WaitForSeconds(delay); SceneManager.LoadScene(scene); } public void FailHit() { // already won if (Hits == Spots.Count()) return; --CurrentTries; Camera.main.GetComponent<CameraShake>().DoShake(); if (CurrentTries == 0) { Promises.Promise.WithCoroutine<object>(FinishDelay(finishDelay, "losescreen")); } } public void Hit(RaycastHit hit) { Debug.Log(hit.transform.gameObject.name); var image = hit.transform.gameObject.GetComponent<Image>(); if (!image.enabled) { image.enabled = true; // world space // star explosion var shockwave = Instantiate(ShockWave) as GameObject; var hitpos = hit.point; hitpos.z = -2; shockwave.transform.position = hitpos; // emitter var pos = hit.point; pos.z = -2; var particles = Instantiate(prefabsHolder.starsParticles); particles.transform.position = pos; particles.SetActive(true); // highlight star color Stars[Hits].color = new Color(1, 1, 1, 1); ++Hits; SuccessHit(); } else { FailHit(); } } } }
27.473118
95
0.517808
[ "Apache-2.0" ]
kibotu/SpotTheDifference
Assets/Sources/Player.cs
2,557
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Runtime.CompilerServices; class ApplicationException : Exception { public ApplicationException(string message) : base(message) { } } namespace Test { public abstract class Base<K> { public abstract string AbstractFinal(); public abstract string AbstractOverrideFinal(); public abstract string AbstractOverrideOverride(); public abstract string AbstractOverrideNil(); public virtual string VirtualFinal() { return "Base.VirtualFinal"; } public virtual string VirtualNilFinal() { return "Base.VirtualNilFinal"; } public virtual string VirtualOverrideFinal() { return "Base.VirtualOverrideFinal"; } public virtual string VirtualNilOverride() { return "Base.VirtualNilOverride"; } public virtual string VirtualNilNil() { return "Base.VirtualNilNil"; } public virtual string VirtualOverrideOverride() { return "Base.VirtualOverrideOverride"; } public virtual string VirtualOverrideNil() { return "Base.VirtualOverrideNil"; } } public class Child<K> : Base<K> { public sealed override string AbstractFinal() { return "Child.AbstractFinal"; } public override string AbstractOverrideFinal() { return "Child.AbstractOverrideFinal"; } public override string AbstractOverrideOverride() { return "Child.AbstractOverrideOverride"; } public override string AbstractOverrideNil() { return "Child.AbstractOverrideNil"; } public sealed override string VirtualFinal() { return "Child.VirtualFinal"; } public override string VirtualOverrideFinal() { return "Child.VirtualOverrideFinal"; } public override string VirtualOverrideOverride() { return "Child.VirtualOverrideOverride"; } public override string VirtualOverrideNil() { return "Child.VirtualOverrideNil"; } public void TestChild() { Console.WriteLine("Call from inside Child"); Assert.AreEqual("Child.AbstractFinal", AbstractFinal()); Assert.AreEqual("Child.AbstractOverrideFinal", AbstractOverrideFinal()); Assert.AreEqual("Child.AbstractOverrideOverride", AbstractOverrideOverride()); Assert.AreEqual("Child.AbstractOverrideNil", AbstractOverrideNil()); Assert.AreEqual("Base.VirtualFinal", base.VirtualFinal()); Assert.AreEqual("Child.VirtualFinal", VirtualFinal()); Assert.AreEqual("Base.VirtualOverrideFinal", base.VirtualOverrideFinal()); Assert.AreEqual("Child.VirtualOverrideFinal", VirtualOverrideFinal()); Assert.AreEqual("Base.VirtualOverrideOverride", base.VirtualOverrideOverride()); Assert.AreEqual("Child.VirtualOverrideOverride", VirtualOverrideOverride()); Assert.AreEqual("Base.VirtualOverrideNil", base.VirtualOverrideNil()); Assert.AreEqual("Child.VirtualOverrideNil", VirtualOverrideNil()); } } public class GrandChild<K> : Child<K> { public sealed override string AbstractOverrideFinal() { return "GrandChild.AbstractOverrideFinal"; } public override string AbstractOverrideOverride() { return "GrandChild.AbstractOverrideOverride"; } public sealed override string VirtualNilFinal() { return "GrandChild.VirtualNilFinal"; } public sealed override string VirtualOverrideFinal() { return "GrandChild.VirtualOverrideFinal"; } public override string VirtualOverrideOverride() { return "GrandChild.VirtualOverrideOverride"; } public override string VirtualNilOverride() { return "GrandChild.VirtualNilOverride"; } public void TestGrandChild() { Console.WriteLine("Call from inside GrandChild"); Assert.AreEqual("Child.AbstractFinal", AbstractFinal()); Assert.AreEqual("Child.AbstractOverrideFinal", base.AbstractOverrideFinal()); Assert.AreEqual("GrandChild.AbstractOverrideFinal", AbstractOverrideFinal()); Assert.AreEqual("Child.AbstractOverrideOverride", base.AbstractOverrideOverride()); Assert.AreEqual("GrandChild.AbstractOverrideOverride", AbstractOverrideOverride()); Assert.AreEqual("Child.AbstractOverrideNil", base.AbstractOverrideNil()); Assert.AreEqual("Child.AbstractOverrideNil", AbstractOverrideNil()); Assert.AreEqual("Child.VirtualFinal", base.VirtualFinal()); Assert.AreEqual("Child.VirtualFinal", VirtualFinal()); Assert.AreEqual("Child.VirtualOverrideFinal", base.VirtualOverrideFinal()); Assert.AreEqual("GrandChild.VirtualOverrideFinal", VirtualOverrideFinal()); Assert.AreEqual("Child.VirtualOverrideOverride", base.VirtualOverrideOverride()); Assert.AreEqual("GrandChild.VirtualOverrideOverride", VirtualOverrideOverride()); Assert.AreEqual("Child.VirtualOverrideNil", base.VirtualOverrideNil()); Assert.AreEqual("Child.VirtualOverrideNil", VirtualOverrideNil()); } } public sealed class SealedGrandChild<K> : GrandChild<K> { } public static class Program { public static void CallSealedGrandChild() { Console.WriteLine("Call SealedGrandChild from outside"); // Calling methods of a sealed class from outside SealedGrandChild<object> o = new SealedGrandChild<object>(); Assert.AreEqual("Child.AbstractFinal", o.AbstractFinal()); Assert.AreEqual("GrandChild.AbstractOverrideFinal", o.AbstractOverrideFinal()); Assert.AreEqual("GrandChild.AbstractOverrideOverride", o.AbstractOverrideOverride()); Assert.AreEqual("Child.AbstractOverrideNil", o.AbstractOverrideNil()); Assert.AreEqual("Child.VirtualFinal", o.VirtualFinal()); Assert.AreEqual("GrandChild.VirtualNilFinal", o.VirtualNilFinal()); Assert.AreEqual("GrandChild.VirtualOverrideFinal", o.VirtualOverrideFinal()); Assert.AreEqual("GrandChild.VirtualNilOverride", o.VirtualNilOverride()); Assert.AreEqual("Base.VirtualNilNil", o.VirtualNilNil()); Assert.AreEqual("GrandChild.VirtualOverrideOverride", o.VirtualOverrideOverride()); Assert.AreEqual("Child.VirtualOverrideNil", o.VirtualOverrideNil()); } public static void CallFromInsideChild() { Child<object> child = new Child<object>(); child.TestChild(); } public static void CallFromInsideGrandChild() { GrandChild<object> child = new GrandChild<object>(); child.TestGrandChild(); } public static int Main(string[] args) { try { CallSealedGrandChild(); CallFromInsideChild(); CallFromInsideGrandChild(); Console.WriteLine("Test SUCCESS"); return 100; } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine("Test FAILED"); return 101; } } } public static class Assert { public static void AreEqual(string left, string right) { if (String.IsNullOrEmpty(left)) throw new ArgumentNullException("left"); if (string.IsNullOrEmpty(right)) throw new ArgumentNullException("right"); if (left != right) { string message = String.Format("[[{0}]] != [[{1}]]", left, right); throw new ApplicationException(message); } } } }
37.435556
97
0.617951
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/Methodical/nonvirtualcall/generics2.cs
8,423
C#
using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using DAS.DigitalEngagement.Application.Services; using DAS.DigitalEngagement.Application.Services.Marketo; using DAS.DigitalEngagement.Application.UnitTests.Helpers; using DAS.DigitalEngagement.Domain.Mapping.BulkImport; using DAS.DigitalEngagement.Domain.Services; using Das.Marketo.RestApiClient.Interfaces; using Das.Marketo.RestApiClient.Models; using FluentAssertions; using Microsoft.Azure.Documents.SystemFunctions; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Refit; using Microsoft.Extensions.Options; using Das.Marketo.RestApiClient.Configuration; namespace DAS.DigitalEngagement.Application.UnitTests.Services { public class BulkImportServiceTests { private MarketoBulkImportService _service; private Mock<IMarketoLeadClient> _marketoLeadClientMock; private Mock<IMarketoBulkImportClient> _marketoBulkImportClientMock; private Mock<ICsvService> _csvServiceMock; private Mock<IBulkImportJobMapper> _bulkImportJobMapperMock; private Mock<IBulkImportStatusMapper> _bulkImportStatusMapperMock; private Mock<IChunkingService> _chunkingServiceMock; private Mock<ILogger<MarketoBulkImportService>> _logger; private IChunkingService _chunkingService; private string _testCsv = CsvTestHelper.GetValidCsv_SingleChunk(); private List<dynamic> _testLeadList = GenerateNewLeads(10); [SetUp] public void Arrange() { _marketoLeadClientMock = new Mock<IMarketoLeadClient>(); _marketoBulkImportClientMock = new Mock<IMarketoBulkImportClient>(); _bulkImportJobMapperMock = new Mock<IBulkImportJobMapper>(); _bulkImportStatusMapperMock = new Mock<IBulkImportStatusMapper>(); _chunkingServiceMock = new Mock<IChunkingService>(); _csvServiceMock = new Mock<ICsvService>(); _logger = new Mock<ILogger<MarketoBulkImportService>>(); var marketoConfig = new Mock<IOptions<MarketoConfiguration>>(); var jobResponse = new Response<BatchJob>() { RequestId = "RequestId", Success = true, Result = new List<BatchJob>() }; marketoConfig.Setup(x => x.Value.ApiRetryCount).Returns(1); marketoConfig.Setup(x => x.Value.ApiRetryInitialBackOffSecs).Returns(1); marketoConfig.Setup(x => x.Value.ChunkSizeKB).Returns(10000); // 10MB chunk size _chunkingService = new ChunkingService(marketoConfig.Object); _chunkingServiceMock.Setup(s => s.GetChunks(172, _testLeadList)) .Returns(_chunkingService.GetChunks(172, _testLeadList)); _csvServiceMock.Setup(s => s.GetByteCount(_testLeadList)).Returns(172); _marketoBulkImportClientMock.Setup(s => s.PushLeads(It.IsAny<StreamPart>())).ReturnsAsync(jobResponse); _marketoLeadClientMock.Setup(s => s.Describe()).ReturnsAsync(GenerateDescribeReturn()); _service = new MarketoBulkImportService(_marketoLeadClientMock.Object, _marketoBulkImportClientMock.Object, _csvServiceMock.Object, _logger.Object, _bulkImportStatusMapperMock.Object, _bulkImportJobMapperMock.Object, _chunkingServiceMock.Object, marketoConfig.Object); } [Test] public async Task When_Valid_Headers_Validated_Then_Return_Validtion_Passed() { var fields = new List<string>() { "attribute-1", "Attribute-2", "Attribute-3" }; var validationResult = await _service.ValidateFields(fields); validationResult.IsValid.Should().BeTrue(); validationResult.Errors.Should().BeEmpty(); } [Test] public async Task When_Invalid_Headers_Validated_Then_Return_Validtion_failed() { var fields = new List<string>() { "attribute-1", "Attribute-2", "Attribute-failed" }; var validationResult = await _service.ValidateFields(fields); validationResult.IsValid.Should().BeFalse(); validationResult.Errors.Should().HaveCount(1); } [Test] public async Task Then_The_List_is_Chunked_Into_Valid_Sizes() { //Arrange //Act var status = await _service.ImportPeople(_testLeadList); //Assert _chunkingServiceMock.Verify(s => s.GetChunks(172, _testLeadList), Times.Once); } [Test] public async Task Then_The_Each_Chunk_Is_Sent_To_Marketo() { //Act var status = await _service.ImportPeople(_testLeadList); //Assert status.Should().NotBeNull(); status.BulkImportJobs.Should().HaveCount(1); _marketoBulkImportClientMock.Verify(v => v.PushLeads(It.IsAny<StreamPart>()), Times.Once()); } private static List<dynamic> GenerateNewLeads(int leadCount) { var Leads = Enumerable .Range(0, leadCount) .Select(i => { dynamic expando = new ExpandoObject(); expando.FirstName = $"Firstname{i}"; expando.LastName = "Surname "; expando.Email = $"Firstname{i}.lastname@Email.com"; expando.Company = $"MyNewCompany{i}"; return (dynamic)expando; }) .ToList(); return Leads; } private static Response<LeadAttribute> GenerateDescribeReturn() { var result = new Response<LeadAttribute>(); result.Success = true; result.Result = new List<LeadAttribute>(); var attributes = Enumerable.Range(0, 20) .Select(i => { var attribute = new LeadAttribute(); attribute.DisplayName = "Attribute"; attribute.Soap = new LeadMapAttribute() { Name = $"attribute-soap-{i}" }; attribute.Rest = new LeadMapAttribute() { Name = $"Attribute-{i}" }; return attribute; }) .ToList(); result.Result = attributes; return result; } } }
36.46114
115
0.584908
[ "MIT" ]
SkillsFundingAgency/das-campaign-functions
src/DAS.DigitalEngagement.Application.UnitTests/Services/BulkImportServiceTests.cs
7,039
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// シングルトンかつシーンに依存しないオブジェクトに使用する /// </summary> public class DontDestroyScript : MonoBehaviour { public string obejct_name = ""; public static Dictionary<string, bool> instances = null; public static Dictionary<string, int> call_cnt = null; void Awake() { Debug.Log("Awake実行"); obejct_name = this.gameObject.name; if (instances == null) { instances = new Dictionary<string, bool>(); call_cnt = new Dictionary<string, int>(); } if (call_cnt.ContainsKey(obejct_name)) { call_cnt[obejct_name]++; } else { call_cnt[obejct_name] = 1; } Debug.Log("[" + obejct_name + "] 呼び出し回数= " + call_cnt[obejct_name].ToString()); if (instances.ContainsKey(name)) { Debug.Log("[" + obejct_name + "] は既に存在しているので破棄 " + call_cnt[obejct_name].ToString()); // 既に存在しているなら削除 Destroy(this.gameObject); } else { Debug.Log("[" + obejct_name + "] 新規生成 "); instances[obejct_name] = true; // シーン遷移では破棄させない DontDestroyOnLoad(this); } } public void Init() { Awake(); } // Use this for initialization void Start() { } // Update is called once per frame void Update() { } }
22.880597
98
0.527723
[ "MIT" ]
ssslib/ssslib
SSSLib/Assets/SSSLib/Audio/DontDestroyScript.cs
1,691
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; namespace PKHeX.Core.Injection { public static class LPBDSP { public static LiveHeXVersion[] BrilliantDiamond = new LiveHeXVersion[] { LiveHeXVersion.BD_v100, LiveHeXVersion.BD_v110, LiveHeXVersion.BD_v111, LiveHeXVersion.BDSP_v112 }; public static LiveHeXVersion[] ShiningPearl = new LiveHeXVersion[] { LiveHeXVersion.SP_v100, LiveHeXVersion.SP_v110, LiveHeXVersion.SP_v111, LiveHeXVersion.BDSP_v112 }; public static LiveHeXVersion[] SupportedVersions = ArrayUtil.ConcatAll(BrilliantDiamond, ShiningPearl); private const int ITEM_BLOCK_SIZE = 0xBB80; private const int ITEM_BLOCK_SIZE_RAM = (0xBB80 / 0x10) * 0xC; private const int UG_ITEM_BLOCK_SIZE = 999 * 0xC; private const int UG_ITEM_BLOCK_SIZE_RAM = 999 * 0x8; private const int DAYCARE_BLOCK_SIZE = 0x2C0; private const int DAYCARE_BLOCK_SIZE_RAM = 0x8 * 4; private const int MYSTATUS_BLOCK_SIZE = 0x50; private const int MYSTATUS_BLOCK_SIZE_RAM = 0x34; #pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. public static Dictionary<string, (Func<PokeSysBotMini, byte[]?>, Action<PokeSysBotMini, byte[]>)> FunctionMap = new () { { "Items", (GetItemBlock, SetItemBlock) }, { "MyStatus", (GetMyStatusBlock, SetMyStatusBlock) }, { "Underground", (GetUGItemBlock, SetUGItemBlock) }, { "Daycare", (GetDaycareBlock, SetDaycareBlock) }, }; public static IEnumerable<Type> types = Assembly.GetAssembly(typeof(ICustomBlock)).GetTypes().Where(t => typeof(ICustomBlock).IsAssignableFrom(t) && !t.IsInterface); #pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types. private static ulong[] GetPokemonPointers(this PokeSysBotMini psb, int box) { var sb = (ICommunicatorNX)psb.com; (string ptr, int count) boxes = RamOffsets.BoxOffsets(psb.Version); var addr = InjectionUtil.GetPointerAddress(sb, boxes.ptr); if (addr == InjectionUtil.INVALID_PTR) throw new Exception("Invalid Pointer string."); var b = psb.com.ReadBytes(addr, boxes.count * 8); var boxptr = Core.ArrayUtil.EnumerateSplit(b, 8).Select(z => BitConverter.ToUInt64(z, 0)).ToArray()[box] + 0x20; // add 0x20 to remove vtable bytes b = sb.ReadBytesAbsolute(boxptr, psb.SlotCount * 8); var pkmptrs = Core.ArrayUtil.EnumerateSplit(b, 8).Select(z => BitConverter.ToUInt64(z, 0)).ToArray(); return pkmptrs; } // relative to: PlayerWork.SaveData_TypeInfo private static string? GetTrainerPointer(LiveHeXVersion lv) { return lv switch { LiveHeXVersion.BDSP_v112 => "[[[main+4E34DD0]+B8]+10]+E0", LiveHeXVersion.BD_v111 => "[[[main+4C1DCF8]+B8]+10]+E0", LiveHeXVersion.SP_v111 => "[[[main+4E34DD0]+B8]+10]+E0", _ => null }; } // relative to: PlayerWork.SaveData_TypeInfo private static string? GetItemPointers(LiveHeXVersion lv) { return lv switch { LiveHeXVersion.BDSP_v112 => "[[[[main+4E34DD0]+B8]+10]+48]+20", LiveHeXVersion.BD_v111 => "[[[[main+4C1DCF8]+B8]+10]+48]+20", LiveHeXVersion.SP_v111 => "[[[[main+4E34DD0]+B8]+10]+48]+20", _ => null }; } // relative to: PlayerWork.SaveData_TypeInfo private static string? GetUndergroundPointers(LiveHeXVersion lv) { return lv switch { LiveHeXVersion.BDSP_v112 => "[[[[main+4E34DD0]+B8]+10]+50]+20", LiveHeXVersion.BD_v111 => "[[[[main+4C1DCF8]+B8]+10]+50]+20", LiveHeXVersion.SP_v111 => "[[[[main+4E34DD0]+B8]+10]+50]+20", _ => null }; } // relative to: PlayerWork.SaveData_TypeInfo private static string? GetDaycarePointers(LiveHeXVersion lv) { return lv switch { LiveHeXVersion.BDSP_v112 => "[[[main+4E34DD0]+B8]+10]+450", LiveHeXVersion.BD_v111 => "[[[main+4C1DCF8]+B8]+10]+450", LiveHeXVersion.SP_v111 => "[[[main+4E34DD0]+B8]+10]+450", _ => null }; } public static byte[] ReadBox(PokeSysBotMini psb, int box, List<byte[]> allpkm) { var use_legacy = false; if (psb.com is not ICommunicatorNX sb) return ArrayUtil.ConcatAll(allpkm.ToArray()); var pkmptrs = psb.GetPokemonPointers(box); if (use_legacy) { foreach (var p in pkmptrs) allpkm.Add(sb.ReadBytesAbsolute(p + 0x20, psb.SlotSize)); return ArrayUtil.ConcatAll(allpkm.ToArray()); } else { Dictionary<ulong, int> offsets = new(); foreach (var p in pkmptrs) offsets.Add(p + 0x20, psb.SlotSize); return sb.ReadBytesAbsoluteMulti(offsets); } } public static byte[] ReadSlot(PokeSysBotMini psb, int box, int slot) { if (psb.com is not ICommunicatorNX sb) return new byte[psb.SlotSize]; var pkmptr = psb.GetPokemonPointers(box)[slot]; return sb.ReadBytesAbsolute(pkmptr + 0x20, psb.SlotSize); } public static void SendSlot(PokeSysBotMini psb, byte[] data, int box, int slot) { if (psb.com is not ICommunicatorNX sb) return; var pkmptr = psb.GetPokemonPointers(box)[slot]; sb.WriteBytesAbsolute(data, pkmptr + 0x20); } public static void SendBox(PokeSysBotMini psb, byte[] boxData, int box) { if (psb.com is not ICommunicatorNX sb) return; byte[][] pkmData = boxData.Split(psb.SlotSize); var pkmptrs = psb.GetPokemonPointers(box); for (int i = 0; i < psb.SlotCount; i++) sb.WriteBytesAbsolute(pkmData[i], pkmptrs[i] + 0x20); } public static Func<PokeSysBotMini, byte[]?> GetTrainerData = psb => { var lv = psb.Version; var ptr = GetTrainerPointer(lv); if (ptr == null || psb.com is not ICommunicatorNX sb) return null; var retval = new byte[MYSTATUS_BLOCK_SIZE]; var ram_block = InjectionUtil.GetPointerAddress(sb, ptr); if (ram_block == InjectionUtil.INVALID_PTR) throw new Exception("Invalid Pointer string."); var trainer_name = ptr.ExtendPointer(0x14); var trainer_name_addr = InjectionUtil.GetPointerAddress(sb, trainer_name); if (trainer_name_addr == InjectionUtil.INVALID_PTR) throw new Exception("Invalid Pointer string."); psb.com.ReadBytes(trainer_name_addr, 0x1A).CopyTo(retval); var extra = psb.com.ReadBytes(ram_block, MYSTATUS_BLOCK_SIZE_RAM); // TID, SID, Money, Male extra.Slice(0x8, 0x9).CopyTo(retval, 0x1C); // Region Code, Badge Count, TrainerView, ROMCode, GameClear extra.Slice(0x11, 0x5).CopyTo(retval, 0x28); // BodyType, Fashion ID extra.Slice(0x16, 0x2).CopyTo(retval, 0x30); // StarterType, DSPlayer, FollowIndex, X, Y, Height, Rotation extra.SliceEnd(0x18).CopyTo(retval, 0x34); return retval; }; public static byte[]? GetItemBlock(PokeSysBotMini psb) { var ptr = GetItemPointers(psb.Version); if (ptr == null) return null; var nx = (ICommunicatorNX)psb.com; var addr = InjectionUtil.GetPointerAddress(nx, ptr); if (addr == InjectionUtil.INVALID_PTR) throw new Exception("Invalid Pointer string."); var item_blk = psb.com.ReadBytes(addr, ITEM_BLOCK_SIZE_RAM); var extra_data = new byte[] { 0x1, 0x0, 0x0, 0x0 }; var items = Core.ArrayUtil.EnumerateSplit(item_blk, 0xC).Select(z => z.Concat(extra_data).ToArray()).ToArray(); return ArrayUtil.ConcatAll(items); } public static void SetItemBlock(PokeSysBotMini psb, byte[] data) { var ptr = GetItemPointers(psb.Version); if (ptr == null) return; var nx = (ICommunicatorNX)psb.com; var addr = InjectionUtil.GetPointerAddress(nx, ptr); if (addr == InjectionUtil.INVALID_PTR) throw new Exception("Invalid Pointer string."); data = data.Slice(0, ITEM_BLOCK_SIZE); var items = Core.ArrayUtil.EnumerateSplit(data, 0x10).Select(z => z.Slice(0, 0xC)).ToArray(); var payload = ArrayUtil.ConcatAll(items); psb.com.WriteBytes(payload, addr); } public static byte[]? GetUGItemBlock(PokeSysBotMini psb) { var ptr = GetUndergroundPointers(psb.Version); if (ptr == null) return null; var nx = (ICommunicatorNX)psb.com; var addr = InjectionUtil.GetPointerAddress(nx, ptr); if (addr == InjectionUtil.INVALID_PTR) throw new Exception("Invalid Pointer string."); var item_blk = psb.com.ReadBytes(addr, UG_ITEM_BLOCK_SIZE_RAM); var extra_data = new byte[] { 0x0, 0x0, 0x0, 0x0 }; var items = Core.ArrayUtil.EnumerateSplit(item_blk, 0x8).Select(z => z.Concat(extra_data).ToArray()).ToArray(); return ArrayUtil.ConcatAll(items); } public static void SetUGItemBlock(PokeSysBotMini psb, byte[] data) { var ptr = GetUndergroundPointers(psb.Version); if (ptr == null) return; var nx = (ICommunicatorNX)psb.com; var addr = InjectionUtil.GetPointerAddress(nx, ptr); if (addr == InjectionUtil.INVALID_PTR) throw new Exception("Invalid Pointer string."); data = data.Slice(0, UG_ITEM_BLOCK_SIZE); var items = Core.ArrayUtil.EnumerateSplit(data, 0xC).Select(z => z.Slice(0, 0x8)).ToArray(); var payload = ArrayUtil.ConcatAll(items); psb.com.WriteBytes(payload, addr); } public static byte[]? GetMyStatusBlock(PokeSysBotMini psb) => GetTrainerData(psb); public static void SetMyStatusBlock(PokeSysBotMini psb, byte[] data) { var lv = psb.Version; var ptr = GetTrainerPointer(lv); if (ptr == null || psb.com is not ICommunicatorNX sb) return; var size = MYSTATUS_BLOCK_SIZE; data = data.Slice(0, size); var trainer_name = ptr.ExtendPointer(0x14); var trainer_name_addr = InjectionUtil.GetPointerAddress(sb, trainer_name); if (trainer_name_addr == InjectionUtil.INVALID_PTR) throw new Exception("Invalid Pointer string."); var retval = new byte[MYSTATUS_BLOCK_SIZE_RAM]; // TID, SID, Money, Male data.Slice(0x1C, 0x9).CopyTo(retval, 0x8); // Region Code, Badge Count, TrainerView, ROMCode, GameClear data.Slice(0x28, 0x5).CopyTo(retval, 0x11); // BodyType, Fashion ID data.Slice(0x30, 0x2).CopyTo(retval, 0x16); // StarterType, DSPlayer, FollowIndex, X, Y, Height, Rotation data.SliceEnd(0x34).CopyTo(retval, 0x18); psb.com.WriteBytes(data.Slice(0, 0x1A), trainer_name_addr); psb.com.WriteBytes(retval.SliceEnd(0x8), InjectionUtil.GetPointerAddress(sb, ptr) + 0x8); } public static byte[]? GetDaycareBlock(PokeSysBotMini psb) { var ptr = GetDaycarePointers(psb.Version); if (ptr == null) return null; var nx = (ICommunicatorNX)psb.com; var addr = InjectionUtil.GetPointerAddress(nx, ptr); var parent_one = psb.com.ReadBytes(InjectionUtil.GetPointerAddress(nx, ptr.ExtendPointer(0x20, 0x20)), 0x158); var parent_two = psb.com.ReadBytes(InjectionUtil.GetPointerAddress(nx, ptr.ExtendPointer(0x28, 0x20)), 0x158); var extra = psb.com.ReadBytes(addr + 0x8, 0x18); var extra_arr = Core.ArrayUtil.EnumerateSplit(extra, 0x8).ToArray(); var block = new byte[DAYCARE_BLOCK_SIZE]; parent_one.CopyTo(block, 0); parent_two.CopyTo(block, 0x158); extra_arr[0].Slice(0, 4).CopyTo(block, 0x158 * 2); extra_arr[1].CopyTo(block, (0x158 * 2) + 0x4); extra_arr[2].Slice(0, 4).CopyTo(block, (0x158 * 2) + 0x4 + 0x8); return block; } public static void SetDaycareBlock(PokeSysBotMini psb, byte[] data) { var ptr = GetDaycarePointers(psb.Version); if (ptr == null) return; var nx = (ICommunicatorNX)psb.com; var addr = InjectionUtil.GetPointerAddress(nx, ptr); var parent_one_addr = InjectionUtil.GetPointerAddress(nx, ptr.ExtendPointer(0x20, 0x20)); var parent_two_addr = InjectionUtil.GetPointerAddress(nx, ptr.ExtendPointer(0x28, 0x20)); data = data.Slice(0, DAYCARE_BLOCK_SIZE); psb.com.WriteBytes(data.Slice(0, 0x158), parent_one_addr); psb.com.WriteBytes(data.Slice(0x158, 0x158), parent_two_addr); var payload = new byte[DAYCARE_BLOCK_SIZE_RAM - 0x8]; data.Slice(0x158 * 2, 4).CopyTo(payload); data.Slice((0x158 * 2) + 0x4, 0x8).CopyTo(payload, 0x8); data.Slice((0x158 * 2) + 0x4 + 0x8, 0x4).CopyTo(payload, 0x8 * 2); psb.com.WriteBytes(payload, addr + 0x8); return; } public static bool ReadBlockFromString(PokeSysBotMini psb, SaveFile sav, string block, out byte[]? read) { read = null; if (!FunctionMap.ContainsKey(block)) { // Check for custom blocks foreach (Type t in types) { if (t.Name != block) continue; var m = t.GetMethod("Getter", BindingFlags.Public | BindingFlags.Static); if (m == null) return false; read = (byte[]?)m.Invoke(null, new object[] {psb}); return true; } return false; } try { var data = sav.GetType().GetProperty(block).GetValue(sav); if (data is SaveBlock sb) { var getter = FunctionMap[block].Item1; read = getter.Invoke(psb); if (read == null) return false; read.CopyTo(sb.Data, sb.Offset); } else { return false; } return true; } catch (Exception e) { Debug.WriteLine(e.StackTrace); return false; } } public static void WriteBlockFromString(PokeSysBotMini psb, string block, byte[] data, object sb) { if (!FunctionMap.ContainsKey(block)) { // Custom Blocks ((ICustomBlock)sb).Setter(psb, data); return; } var setter = FunctionMap[block].Item2; var offset = ((SaveBlock)sb).Offset; setter.Invoke(psb, data.SliceEnd(offset)); } } }
44.482192
180
0.569537
[ "MIT" ]
Lusamine/PKHeX-Plugins
PKHeX.Core.Injection/Protocols/LPBDSP.cs
16,238
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AgileProject.Model { class Movie { public String movieId { get; set; } public String movieName { get; set; } public Int16 year { get; set; } public Int16 movieLength { get; set; } public String genre { get; set; } public Double purchasePrice { get; set; } public String movieDescription { get; set; } public String actors { get; set; } public String producers { get; set; } public String directors { get; set; } public String writers { get; set; } public Movie() { } public Movie(string movieId, string movieName, string genre, double purchasePrice) { this.movieId = movieId; this.movieName = movieName; this.genre = genre; this.purchasePrice = purchasePrice; } public Movie(string movieId, string movieName, short year, short movieLength, string genre, double purchasePrice, string movieDescription, string actors, string producers, string directors, string writers) { this.movieId = movieId; this.movieName = movieName; this.year = year; this.movieLength = movieLength; this.genre = genre; this.purchasePrice = purchasePrice; this.movieDescription = movieDescription; this.actors = actors; this.producers = producers; this.directors = directors; this.writers = writers; } public override string ToString() { return $"{{{nameof(movieId)}={movieId}, {nameof(movieName)}={movieName}, {nameof(year)}={year.ToString()}, {nameof(movieLength)}={movieLength.ToString()}, {nameof(genre)}={genre}, {nameof(purchasePrice)}={purchasePrice.ToString()}, {nameof(movieDescription)}={movieDescription}, {nameof(actors)}={actors}, {nameof(producers)}={producers}, {nameof(directors)}={directors}, {nameof(writers)}={writers}}}"; } } }
38.636364
415
0.616471
[ "MIT" ]
NYCCT-CST4708-SPRING20/AgileProject
AgileProject/Models/movie.cs
2,127
C#
using System; using Framework.DomainDriven.BLL; using Framework.Exceptions; using Framework.Persistent; namespace Framework.DomainDriven { public class DTOMappingVersionService<TBLLContext, TAuditPersistentDomainObjectBase, TIdent, TVersion> : BLLContextContainer<TBLLContext>, IDTOMappingVersionService<TAuditPersistentDomainObjectBase, TVersion> where TBLLContext : class where TAuditPersistentDomainObjectBase : class, IIdentityObject<TIdent> where TVersion : IEquatable<TVersion> { public DTOMappingVersionService(TBLLContext context) : base(context) { } public TVersion GetVersion<TDomainObject>(TVersion mappingObjectVersion, TDomainObject domainObject) where TDomainObject : TAuditPersistentDomainObjectBase, IVersionObject<TVersion> { if (domainObject == null) throw new ArgumentNullException(nameof(domainObject)); if (!mappingObjectVersion.Equals(domainObject.Version)) { throw new StaleDomainObjectStateException(new Exception("Mapping Exception"), typeof(TDomainObject), domainObject.Id); } return mappingObjectVersion; } } }
38.181818
213
0.697619
[ "MIT" ]
Luxoft/BSSFramework
src/_DomainDriven/Framework.DomainDriven.Core/DTO/MappingService/DTOMappingVersionService.cs
1,230
C#
using System; using System.Collections.Generic; using System.Net; using System.Reflection; public static class HttpWebRequestExtensions { public static string[] RestrictedHeaders = new string[] { "Accept", "Connection", "Content-Length", "Content-Type", "Date", "Expect", "Host", "If-Modified-Since", "Keep-Alive", "Proxy-Connection", "Range", "Referer", "Transfer-Encoding", "User-Agent" }; public static Dictionary<string, PropertyInfo> HeaderProperties = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase); static HttpWebRequestExtensions() { Type type = typeof(HttpWebRequest); foreach (string header in RestrictedHeaders) { string propertyName = header.Replace("-", ""); PropertyInfo headerProperty = type.GetProperty(propertyName); HeaderProperties[header] = headerProperty; } } public static void SetRawHeader(this HttpWebRequest request, string name, string value) { if (HeaderProperties.ContainsKey(name)) { PropertyInfo property = HeaderProperties[name]; if (property.PropertyType == typeof(DateTime)) property.SetValue(request, DateTime.Parse(value), null); else if (property.PropertyType == typeof(bool)) property.SetValue(request, Boolean.Parse(value), null); else if (property.PropertyType == typeof(long)) property.SetValue(request, Int64.Parse(value), null); else property.SetValue(request, value, null); } else { request.Headers[name] = value; } } }
30.896552
141
0.598772
[ "MIT" ]
SilasReinagel/Twittimation
Twittimation/Common/HttpWebRequestExtensions.cs
1,794
C#
using MongoDB.Driver; namespace Plus.MongoDb { /// <summary> /// IMongoDatabaseProvider /// </summary> public interface IMongoDatabaseProvider { IMongoClient Client { get; } IMongoDatabase Database { get; } } }
18.071429
43
0.620553
[ "MIT" ]
Meowv/.netcoreplus
src/Plus.MongoDB/IMongoDatabaseProvider.cs
255
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codebuild-2016-10-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CodeBuild.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodeBuild.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ProjectSource Object /// </summary> public class ProjectSourceUnmarshaller : IUnmarshaller<ProjectSource, XmlUnmarshallerContext>, IUnmarshaller<ProjectSource, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ProjectSource IUnmarshaller<ProjectSource, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ProjectSource Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ProjectSource unmarshalledObject = new ProjectSource(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("auth", targetDepth)) { var unmarshaller = SourceAuthUnmarshaller.Instance; unmarshalledObject.Auth = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("buildspec", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Buildspec = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("location", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Location = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("type", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Type = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ProjectSourceUnmarshaller _instance = new ProjectSourceUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ProjectSourceUnmarshaller Instance { get { return _instance; } } } }
35.672727
152
0.609582
[ "Apache-2.0" ]
Bynder/aws-sdk-net
sdk/src/Services/CodeBuild/Generated/Model/Internal/MarshallTransformations/ProjectSourceUnmarshaller.cs
3,924
C#
#region License // <copyright> // iGeospatial Geometries Package // // This is part of the Open Geospatial Library for .NET. // // Package Description: // This is a collection of C# classes that implement the fundamental // operations required to validate a given geo-spatial data set to // a known topological specification. // It aims to provide a complete implementation of the Open Geospatial // Consortium (www.opengeospatial.org) specifications for Simple // Feature Geometry. // // Contact Information: // Paul Selormey (paulselormey@gmail.com or paul@toolscenter.org) // // Credits: // This library is based on the JTS Topology Suite, a Java library by // // Vivid Solutions Inc. (www.vividsolutions.com) // // License: // See the license.txt file in the package directory. // </copyright> #endregion using System; using iGeospatial.Geometries; using iGeospatial.Coordinates; namespace iGeospatial.Geometries.Algorithms { /// <summary> /// Computes a point in the interior of an point geometry. /// </summary> /// <remarks> /// Algorithm /// <para> /// Find a point which is closest to the centroid of the geometry. /// </para> /// </remarks> public sealed class InteriorPointPoint { #region Private Members private Coordinate centroid; private double minDistance; private Coordinate interiorPoint; #endregion #region Constructors and Destructor /// <summary> /// Initializes a new instance of the <see cref="InteriorPointPoint"/> class. /// </summary> /// <param name="g"> /// The point <see cref="Geometry"/> to determine the interior point of. /// </param> public InteriorPointPoint(Geometry g) { if (g == null) { throw new ArgumentNullException("g"); } minDistance = System.Double.MaxValue; centroid = g.Centroid.Coordinate; Add(g); } #endregion /// <summary> /// Gets a coordinate or point in the interior of a point geometry. /// </summary> /// <value> /// The <see cref="iGeospatial.Coordinates.Coordinate"/> of an interior point /// of the geometry. /// </value> public Coordinate InteriorPoint { get { return interiorPoint; } } /// <summary> /// Tests the point(s) defined by a Geometry for the best inside point. /// If a Geometry is not of dimension 0 it is not tested. /// </summary> /// <param name="geom">The geometry to add.</param> private void Add(Geometry geom) { GeometryType geomType = geom.GeometryType; if (geomType == GeometryType.Point) { Add(geom.Coordinate); } else if (geomType == GeometryType.GeometryCollection || geomType == GeometryType.MultiPoint) { GeometryCollection gc = (GeometryCollection) geom; for (int i = 0; i < gc.NumGeometries; i++) { Add(gc.GetGeometry(i)); } } } private void Add(Coordinate point) { double dist = point.Distance(centroid); if (dist < minDistance) { interiorPoint = new Coordinate(point); minDistance = dist; } } } }
25.84375
85
0.613362
[ "MIT" ]
IBAS0742/iGeospatial_change
Geometries/Algorithms/InteriorPointPoint.cs
3,308
C#
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Glass.Mapper.Configuration { /// <summary> /// Class FieldConfiguration /// </summary> public class FieldConfiguration : AbstractPropertyConfiguration { /// <summary> /// Gets or sets a value indicating whether [read only]. /// </summary> /// <value><c>true</c> if [read only]; otherwise, <c>false</c>.</value> public bool ReadOnly { get; set; } } }
28.268293
80
0.660052
[ "Apache-2.0" ]
smithc/Glass.Mapper
Source/Glass.Mapper/Configuration/FieldConfiguration.cs
1,159
C#
using System; namespace System.Collections.Generic { public class SpecifiedListComparer<T> : IComparer<T> { public IList<T> List { get; } public SpecifiedListComparer( IList<T> list) { this.List = list; } public SpecifiedListComparer( params T[] items) { this.List = items; } public int Compare(T x, T y) { var indexOfX = this.List.IndexOf(x); var indexOfY = this.List.IndexOf(y); var xWasFound = IndexHelper.IsFound(indexOfX); var yWasFound = IndexHelper.IsFound(indexOfY); int output; if(xWasFound) { if(yWasFound) { output = indexOfX.CompareTo(indexOfY); } else { // Make sure X appears before any unfound Y. output = ComparisonHelper.LessThan; } } else { if(yWasFound) { // Make sure Y appears before any unfound X. output = ComparisonHelper.GreaterThan; } else { output = ComparisonHelper.EqualTo; } } return output; } } }
23.508197
64
0.426778
[ "MIT" ]
MinexAutomation/R5T.Magyar
source/R5T.Magyar/Code/Classes/SpecifiedListComparer.cs
1,436
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using BlackIris; using UnitTestFile.Support; namespace UnitTestFile.Tests { [TestClass] public class CommandlineContractTests { [TestMethod] public void CommandlineContract_SquashedKeyValuePattern() { string[] argsSquashed = new string[] { "gen", "/o200", "/date2015/03/02", "/amt3456.23", "/asciiD" }; string[] argsDefault = new string[] { "gen", "/o", "200", "/date", "2015/03/02", "/amt", "3456.23", "/ascii", "D" }; CmdlineContractAgent<SquashedKeyValuePatternContract> squashedAgent = new CmdlineContractAgent<SquashedKeyValuePatternContract>(); SquashedKeyValuePatternContract squashedContract = squashedAgent.Deserialize(argsSquashed); CmdlineContractAgent<SquashedKeyValuePatternContract> defaultAgent = new CmdlineContractAgent<SquashedKeyValuePatternContract>(); SquashedKeyValuePatternContract defaultContract = defaultAgent.Deserialize(argsDefault); Assert.AreEqual(squashedContract.Timeout, 200); Assert.AreEqual(squashedContract.RunDate, DateTime.Parse("2015/03/02")); Assert.AreEqual(squashedContract.Amount, 3456.23); Assert.AreEqual(squashedContract.AsciiChar, 'D'); Assert.AreEqual(defaultContract.Timeout, null); Assert.AreEqual(defaultContract.RunDate, null); Assert.AreEqual(defaultContract.Amount, null); Assert.AreEqual(defaultContract.AsciiChar, null); } [TestMethod] public void CommandlineContract_DefaultKeyValuePattern() { string[] argsSquashed = new string[] { "gen", "/o200", "/date2015/03/02", "/amt3456.23", "/asciiD" }; string[] argsDefault = new string[] { "gen", "/o", "200", "/date", "2015/03/02", "/amt", "3456.23", "/ascii", "D" }; CmdlineContractAgent<DefaultKeyValuePatternContract> squashedAgent = new CmdlineContractAgent<DefaultKeyValuePatternContract>(); DefaultKeyValuePatternContract squashedContract = squashedAgent.Deserialize(argsSquashed); CmdlineContractAgent<DefaultKeyValuePatternContract> defaultAgent = new CmdlineContractAgent<DefaultKeyValuePatternContract>(); DefaultKeyValuePatternContract defaultContract = defaultAgent.Deserialize(argsDefault); Assert.AreEqual(defaultContract.Timeout, 200); Assert.AreEqual(defaultContract.RunDate, DateTime.Parse("2015/03/02")); Assert.AreEqual(defaultContract.Amount, 3456.23); Assert.AreEqual(defaultContract.AsciiChar, 'D'); Assert.AreEqual(squashedContract.Timeout, null); Assert.AreEqual(squashedContract.RunDate, null); Assert.AreEqual(squashedContract.Amount, null); Assert.AreEqual(squashedContract.AsciiChar, null); } [TestMethod] public void CreateCommandlineContracts_CustomSwitchPrefix() { string[] args = new string[] { "gen", "/o", "200", "/date", "2015/03/02", "/amt", "3456.23", "/ascii", "D" }; CmdlineContractAgent<DifferentSwitchContract> agent = new CmdlineContractAgent<DifferentSwitchContract>(); DifferentSwitchContract contract = agent.Deserialize(args); Assert.AreEqual(contract.Timeout, 200); Assert.AreEqual(contract.RunDate, DateTime.Parse("2015/03/02")); Assert.AreEqual(contract.Amount, 3456.23); Assert.AreEqual(contract.AsciiChar, 'D'); } [TestMethod] public void CreateCommandlineContracts_TestNullableTypes() { string[] args = new string[] { "gen", "-o", "200", "-date", "2015/03/02", "-amt", "3456.23", "-ascii", "D" }; CmdlineContractAgent<NullableContract> agent = new CmdlineContractAgent<NullableContract>(); NullableContract contract = agent.Deserialize(args); Assert.AreEqual(contract.Timeout, 200); Assert.AreEqual(contract.RunDate, DateTime.Parse("2015/03/02")); Assert.AreEqual(contract.Amount, 3456.23); Assert.AreEqual(contract.AsciiChar, 'D'); } [TestMethod] public void CreateCommandlineContracts_TestNullableTypes_NotSet() { string[] args = new string[] { "gen", "-i" }; CmdlineContractAgent<NullableContract> agent = new CmdlineContractAgent<NullableContract>(); NullableContract contract = agent.Deserialize(args); Assert.AreEqual(contract.Timeout, null); Assert.AreEqual(contract.RunDate, null); Assert.AreEqual(contract.Amount, null); Assert.AreEqual(contract.AsciiChar, null); } [TestMethod] public void CommandlineContract_KeyValueSwitch_MergedSwitchAndValue() { string[] args = new string[] { "-hostZACTN51", "-dCBMDB", "-tTableName", "-uRob", "-pPassword", "-O2000" }; CmdlineContractAgent<BcpArgContract> agent = new CmdlineContractAgent<BcpArgContract>(); BcpArgContract contract = agent.Deserialize(args); Assert.AreEqual(contract.Host, "ZACTN51"); Assert.AreEqual(contract.Database, "CBMDB"); Assert.AreEqual(contract.Username, "Rob"); Assert.AreEqual(contract.Password, "Password"); Assert.AreEqual(contract.TargetTable, "TableName"); Assert.AreEqual(contract.Timeout, 2000); } [TestMethod] public void CommandlineContract_KeyValueSwitch_AdjacentSwitchAndValue() { string[] args = new string[] { "-hostZACTN51", "-dCBMDB", "-tTableName", "-uRob", "-pPassword", "-O2000" }; CmdlineContractAgent<BcpArgContract> agent = new CmdlineContractAgent<BcpArgContract>(); BcpArgContract contract = agent.Deserialize(args); Assert.AreEqual(contract.Host, "ZACTN51"); Assert.AreEqual(contract.Database, "CBMDB"); Assert.AreEqual(contract.Username, "Rob"); Assert.AreEqual(contract.Password, "Password"); Assert.AreEqual(contract.TargetTable, "TableName"); Assert.AreEqual(contract.Timeout, 2000); } [TestMethod] public void CommandlineContract_KeyValueSwitch_IsCaseSensitive() { string[] args = new string[] { "-hostZACTN51", "-dCBMDB", "-tTableName", "-URob", "-pPassword", "-O2000" }; CmdlineContractAgent<SomeLowerCaseContract> agent = new CmdlineContractAgent<SomeLowerCaseContract>(); SomeLowerCaseContract contract = agent.Deserialize(args); Assert.AreEqual(contract.Host, "ZACTN51"); Assert.AreEqual(contract.Database, "CBMDB"); Assert.AreEqual(contract.Username, null); // upper case switch is not supported Assert.AreEqual(contract.Password, "Password"); Assert.AreEqual(contract.TargetTable, "TableName"); Assert.AreEqual(contract.Timeout, null); // upper case switch is not supported Assert.AreEqual(contract.RunDate, null); // was not provided } [TestMethod] public void CommandlineContract_KeyValueSwitch_Supports_SwitchStartingWithSameChars() { string[] args = new string[] { "-hZACTN51", "-hdatabasetblTableName", "-hdatabaseCMDB", "-userpassPassword", "-userRob", "-tr2010/09/02", "-t200" }; CmdlineContractAgent<SimilarSwitchContract> agent = new CmdlineContractAgent<SimilarSwitchContract>(); SimilarSwitchContract contract = agent.Deserialize(args); Assert.AreEqual(contract.Host, "ZACTN51"); Assert.AreEqual(contract.Database, "CMDB"); Assert.AreEqual(contract.Username, "Rob"); Assert.AreEqual(contract.Password, "Password"); Assert.AreEqual(contract.TargetTable, "TableName"); Assert.AreEqual(contract.Timeout, 200); Assert.AreEqual(contract.RunDate, DateTime.Parse("2010/09/02")); } [TestMethod] public void CommandlineContract_FlagSwitch_PopulatesContract() { string[] args = new string[] { "-h", "-up" }; CmdlineContractAgent<FlagSwitchContract2> agent = new CmdlineContractAgent<FlagSwitchContract2>(); FlagSwitchContract2 contract = agent.Deserialize(args); Assert.IsTrue(contract.BruteForce); Assert.IsFalse(contract.IgnoreWarnings); Assert.IsTrue(contract.UpperCase); } //[TestMethod] //public void CommandlineContract_CommandAndSwitch_PopulatesAll() //{ // string[] args = new string[] { "move", "-hard", "-ignore", "-up", "-u", "Username", "-pPassword" }; // CmdlineAgent<CommandAndSwitchContract> agent = new CmdlineAgent<CommandAndSwitchContract>(); // CommandAndSwitchContract contract = agent.Deserialize(args); // Assert.AreEqual("move", contract.ProcessCmd); // Assert.IsTrue(contract.IgnoreWarnings); // Assert.IsTrue(contract.BruteForce); // Assert.IsTrue(contract.UpperCase); // Assert.AreEqual("Username", contract.Username); // Assert.AreEqual("Password", contract.Password); //} [TestMethod] [ExpectedException(typeof(NotSupportedException))] public void CommandlineContract_ThrowsException_NoContractFound() { string[] args = new string[] { "-host", "ZACTN51", "-dCBMDB", "-tTableName", "-uRob", "-pPassword", "-O2000" }; CmdlineContractAgent<Contractless> agent = new CmdlineContractAgent<Contractless>(); Contractless contract = agent.Deserialize(args); } } }
47.647343
160
0.643719
[ "MIT" ]
bobbyache/BlackIrisConsole
Code/UnitTests/Tests/CommandlineContractTests.cs
9,865
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("BLL")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BLL")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("43bf8e67-fa9d-41f7-b278-7afc56fcb51c")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.054054
56
0.708738
[ "MIT" ]
KaelKong/MVCDemo
DEMO/BLL/Properties/AssemblyInfo.cs
1,278
C#
using System.Collections.Generic; namespace Sys.Workflow.Engine.Impl.Events.Logger.Handlers { using Sys.Workflow.Engine.Delegate.Events; using Sys.Workflow.Engine.Impl.Interceptor; using Sys.Workflow.Engine.Impl.Persistence.Entity; /// public class VariableDeletedEventHandler : VariableEventHandler { public override IEventLogEntryEntity GenerateEventLogEntry(CommandContext<IEventLogEntryEntity> commandContext) { IActivitiVariableEvent variableEvent = (IActivitiVariableEvent)@event; IDictionary<string, object> data = createData(variableEvent); data[FieldsFields.END_TIME] = timeStamp; return CreateEventLogEntry(variableEvent.ProcessDefinitionId, variableEvent.ProcessInstanceId, variableEvent.ExecutionId, variableEvent.TaskId, data); } } }
32.923077
162
0.741822
[ "Apache-2.0" ]
18502079446/cusss
NActiviti/Sys.Bpm.Engine/Engine/impl/event/logger/handler/VariableDeletedEventHandler.cs
858
C#
using UnityEngine; namespace RubicalMe { namespace RenderTools { public class GUIItem { protected static uint GUIItemsAlive; public Texture2D Texture { get { return texture; } } public Rect Rect { get { return rect; } } public GUISnapMode SnapMode { get { return snapmode; } } public uint ID { get { return mID; } } protected Texture2D texture; protected Rect rect; protected GUISnapMode snapmode; protected uint mID; protected GUIItem () { } public GUIItem (Texture2D texture) { Initialize (texture, new Rect (Vector2.zero, new Vector2 (texture.width, texture.height)), GUISnapMode.TopLeft); } public GUIItem (Texture2D texture, Rect rect) { Initialize (texture, rect, GUISnapMode.TopLeft); } public GUIItem (Texture2D texture, Rect rect, GUISnapMode snapmode) { Initialize (texture, rect, snapmode); } public void SetTexture (Texture2D texture) { this.texture = texture; } public void SetPosition (Rect rect) { this.rect = rect; } public void SetSnapMode (GUISnapMode snapmode) { this.snapmode = snapmode; } public void Draw (Rect r) { GUI.DrawTexture (new Rect (r.position + rect.position + GetOffset (r), rect.size), texture); } public virtual EditorRendererEvent ProcessEvents (Event currentEvent, Rect r) { return null; } public bool Contains (Rect r, Vector2 position) { return new Rect (r.position + rect.position + GetOffset (r), rect.size).Contains (position); } protected Vector2 GetOffset (Rect r) { switch (snapmode) { case GUISnapMode.TopLeft: return Vector2.zero; case GUISnapMode.TopCenter: return new Vector2 (r.width / 2, 0) - new Vector2 (rect.width / 2, 0); case GUISnapMode.TopRight: return new Vector2 (r.width, 0) - new Vector2 (rect.width, 0); case GUISnapMode.MidLeft: return new Vector2 (0, r.height / 2) - new Vector2 (0, rect.height / 2); case GUISnapMode.MidCenter: return new Vector2 (r.width / 2, r.height / 2) - new Vector2 (rect.width / 2, rect.height / 2); case GUISnapMode.MidRight: return new Vector2 (r.width, r.height / 2) - new Vector2 (rect.width, rect.height / 2); case GUISnapMode.BottomLeft: return new Vector2 (0, r.height) - new Vector2 (0, rect.height); case GUISnapMode.BottomCenter: return new Vector2 (r.width / 2, r.height) - new Vector2 (rect.width / 2, rect.height); case GUISnapMode.BottomRight: return r.size - rect.size; default: throw new System.NotImplementedException ("This GUISnapMode has not yet been implemented for SetSnapMode - GUIItem"); } } protected void Initialize (Texture2D texture, Rect rect, GUISnapMode snapmode) { this.texture = texture; this.rect = rect; this.snapmode = snapmode; this.mID = GUIItemsAlive++; } } } }
23.784
122
0.65153
[ "Apache-2.0" ]
Cheezegami/KernM-GameDev-2-_-Tools-_-Weapon-Generator-1
Assets/Editor/RubicalMe/EditorRenderer/RenderTools/GUIItem.cs
2,975
C#
namespace Hexalith.Domain { public abstract class EntityState { } }
13.333333
37
0.6625
[ "MIT" ]
Hexalith/Hexalith
src/Core/Domain/Hexalith.Domain.Abstractions/EntityState.cs
82
C#
// // Authors: // Rafael Mizrahi <rafim@mainsoft.com> // Erez Lotan <erezl@mainsoft.com> // Vladimir Krasnov <vladimirk@mainsoft.com> // // // Copyright (c) 2002-2005 Mainsoft Corporation. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace GHTTests.System_Web_dll.System_Web_UI_WebControls { public class BaseDataList_IsBindableType_T : GHTDataListBase { #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion private Type [] marrBindaleType = {typeof(System.Boolean), typeof(System.Byte), typeof(System.Int16), typeof(System.UInt16), typeof(System.Int32), typeof(System.UInt32), typeof(System.Int64), typeof(System.UInt64), typeof(System.Char), typeof(System.Double), typeof(System.Single), typeof(System.DateTime), typeof(System.Decimal), typeof(System.SByte), typeof(MyPrivateClass), typeof(System.String)}; private void Page_Load(object sender, System.EventArgs e) { //Put user code to initialize the page here HtmlForm frm = (HtmlForm)FindControl("form1"); GHTTestBegin(frm); Test(typeof(System.Web.UI.WebControls.DataGrid)); Test(typeof(System.Web.UI.WebControls.DataList)); GHTTestEnd(); } private void Test(Type CtlType) { Type type1; bool flag1; try { this.GHTSubTestBegin("BaseDataList_" + CtlType.Name + "_IsBindableType1"); Type[] typeArray1 = this.marrBindaleType; for (int num1 = 0; num1 < typeArray1.Length; num1++) { type1 = typeArray1[num1]; flag1 = BaseDataList.IsBindableType(type1); this.GHTSubTestAddResult(type1.ToString() + " is bindable = " + flag1.ToString()); } } catch (Exception exception4) { this.GHTSubTestUnexpectedExceptionCaught(exception4); } this.GHTSubTestEnd(); try { this.GHTSubTestBegin("BaseDataList_" + CtlType.Name + "_IsBindableType2"); type1 = null; flag1 = BaseDataList.IsBindableType(null); this.GHTSubTestAddResult("Nothing is bindable = " + flag1.ToString()); this.GHTSubTestExpectedExceptionNotCaught("NullReferenceException"); } catch (NullReferenceException exception5) { this.GHTSubTestExpectedExceptionCaught(exception5); return; } catch (Exception exception6) { this.GHTSubTestUnexpectedExceptionCaught(exception6); return; } } private class MyPrivateClass { } } }
30.992481
87
0.685104
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Web/Test/mainsoft/MainsoftWebApp/System_Web_UI_WebControls/BaseDataList/BaseDataList_IsBindableType_T.aspx.cs
4,122
C#
using Microsoft.AspNetCore.Routing; namespace RestfulRouting.Mappers { public class RouteMapper : Mapper { private readonly RouteBase _routeBase; public RouteMapper(RouteBase routeBase) { _routeBase = routeBase; } public override void RegisterRoutes(IRouteBuilder routeBuilder) { routeBuilder.Routes.Add(_routeBase); } } }
22
71
0.633971
[ "MIT" ]
khalidabuhakmeh/restful-routing-aspnetcore
src/RestfulRouting.AspNetCore/Mappers/RouteMapper.cs
420
C#
using GalaSoft.MvvmLight; using HDT.Plugins.EndGame.Utilities; namespace HDT.Plugins.EndGame.ViewModels { public class SettingsViewModel : ViewModelBase { public bool WaitUntilBackInMenu { get { return EndGame.Settings.Get(Strings.WaitUntilBackInMenu).Bool; } set { EndGame.Settings.Set(Strings.WaitUntilBackInMenu, value); RaisePropertyChanged(Strings.WaitUntilBackInMenu); } } public string IncludeWild { get { return EndGame.Settings.Get(Strings.IncludeWild); } set { EndGame.Settings.Set(Strings.IncludeWild, value); RaisePropertyChanged(Strings.IncludeWild); } } public bool AutoArchiveArchetypes { get { return EndGame.Settings.Get(Strings.AutoArchiveArchetypes).Bool; } set { EndGame.Settings.Set(Strings.AutoArchiveArchetypes, value); RaisePropertyChanged(Strings.AutoArchiveArchetypes); } } public bool DeletePreviouslyImported { get { return EndGame.Settings.Get(Strings.DeletePreviouslyImported).Bool; } set { EndGame.Settings.Set(Strings.DeletePreviouslyImported, value); RaisePropertyChanged(Strings.DeletePreviouslyImported); } } public bool RemoveClassFromName { get { return EndGame.Settings.Get(Strings.RemoveClassFromName).Bool; } set { EndGame.Settings.Set(Strings.RemoveClassFromName, value); RaisePropertyChanged(Strings.RemoveClassFromName); } } public bool ShowRegularNoteBox { get { return EndGame.Settings.Get(Strings.ShowRegularNoteBox).Bool; } set { EndGame.Settings.Set(Strings.ShowRegularNoteBox, value); RaisePropertyChanged(Strings.ShowRegularNoteBox); } } public bool RecordBrawlArchetypes { get { return EndGame.Settings.Get(Strings.RecordBrawlArchetypes).Bool; } set { EndGame.Settings.Set(Strings.RecordBrawlArchetypes, value); RaisePropertyChanged(Strings.RecordBrawlArchetypes); } } public bool RecordCasualArchetypes { get { return EndGame.Settings.Get(Strings.RecordCasualArchetypes).Bool; } set { EndGame.Settings.Set(Strings.RecordCasualArchetypes, value); RaisePropertyChanged(Strings.RecordCasualArchetypes); } } public bool RecordFriendlyArchetypes { get { return EndGame.Settings.Get(Strings.RecordFriendlyArchetypes).Bool; } set { EndGame.Settings.Set(Strings.RecordFriendlyArchetypes, value); RaisePropertyChanged(Strings.RecordFriendlyArchetypes); } } public bool RecordRankedArchetypes { get { return EndGame.Settings.Get(Strings.RecordRankedArchetypes).Bool; } set { EndGame.Settings.Set(Strings.RecordRankedArchetypes, value); RaisePropertyChanged(Strings.RecordRankedArchetypes); } } public bool RecordOtherArchetypes { get { return EndGame.Settings.Get(Strings.RecordOtherArchetypes).Bool; } set { EndGame.Settings.Set(Strings.RecordOtherArchetypes, value); RaisePropertyChanged(Strings.RecordOtherArchetypes); } } public bool RecordArenaArchetypes { get { return EndGame.Settings.Get(Strings.RecordArenaArchetypes).Bool; } set { EndGame.Settings.Set(Strings.RecordArenaArchetypes, value); RaisePropertyChanged(Strings.RecordArenaArchetypes); } } public int StartRank { get { return EndGame.Settings.Get(Strings.StartRank).Int; } set { EndGame.Settings.Set(Strings.StartRank, value); RaisePropertyChanged(Strings.StartRank); } } public bool IsInDevMode { get { return EndGame.Settings.Get(Strings.DeveloperMode).Bool; } set { EndGame.Settings.Set(Strings.DeveloperMode, value); RaisePropertyChanged("IsInDevMode"); } } public bool EnableDebugLog { get { return EndGame.Settings.Get(Strings.DebugLog).Bool; } set { EndGame.Settings.Set(Strings.DebugLog, value); RaisePropertyChanged("EnableDebugLog"); } } public SettingsViewModel() { PropertyChanged += SettingsViewModel_PropertyChanged; } private void SettingsViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "EnableDebugLog") { EndGame.UpdateLogger(); } } } }
19.99537
113
0.706645
[ "MIT" ]
andburn/hdt-plugin-endgame
EndGame/ViewModels/SettingsViewModel.cs
4,321
C#
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using XenAdmin.Controls; namespace XenAdmin.XenSearch { internal class TreeNodeGroupAcceptor : IAcceptGroups { private readonly IHaveNodes parent; private readonly bool? needToBeExpanded; private int index; public TreeNodeGroupAcceptor(IHaveNodes parent, bool? needToBeExpanded) { this.parent = parent; this.needToBeExpanded = needToBeExpanded; } public IAcceptGroups Add(Grouping grouping, Object group, int indent) { if (group == null) return null; VirtualTreeNode node = new VirtualTreeNode(group.ToString()); node.Tag = group; parent.Nodes.Insert(index, node); index++; return new TreeNodeGroupAcceptor(node, null); } public void FinishedInThisGroup(bool defaultExpand) { if (needToBeExpanded.HasValue ? needToBeExpanded.Value : defaultExpand) parent.Expand(); else parent.Collapse(); } } }
35.76
84
0.658837
[ "BSD-2-Clause" ]
AaronRobson/xenadmin
XenAdmin/XenSearch/TreeNodeGroupAcceptor.cs
2,684
C#
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Chapter 8.10 Architecture and Organization * * * * Copyright © 2018 Alex Okita * * * * This software may be modified and distributed under the terms * * of the MIT license. See the LICENSE file for details. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ namespace GameCo.ZombieGame { using System.Collections; using System.Collections.Generic; using UnityEngine; public class BaseItem : Behavior { public BaseItemInfo ZombieItemInfo; public virtual void Start() { ZombieItemInfo = new BaseItemInfo(); } } }
37
75
0.383784
[ "MIT" ]
Adam331166/BookContents
Chapters/Chapter8/Assets/GameCo/Scripts/ZombieGame/BaseItem.cs
928
C#
using System; using System.Collections.Generic; using MoreCollection.Extensions; using Neutronium.Core.Navigation.Routing; namespace Neutronium.BuildingBlocks.Application.Navigation.Internals { /// <summary> /// Object that build navigation based on convention /// </summary> internal class ConventionRouter : IExtendedConventionRouter { private readonly IRouterBuilder _RouterBuilder; private readonly Func<Type, string, Tuple<RouteSpecification, RouteDestination>> _RouteInformationGetter; /// <summary> /// Construct a template based convention router /// </summary> /// <param name="routerBuilder"></param> /// <param name="format">Route name using template string where {vm} is the class name without postfix, /// {namespace} is the namespace, and {id} is the id provided in the register method /// </param> /// <param name="lowerPath">true to use class name in lower case</param> /// <param name="postFix">Class name post fix to be discarded- default to "ViewModel"</param> internal ConventionRouter(IRouterBuilder routerBuilder, string format, bool lowerPath = true, string postFix = null) { _RouterBuilder = routerBuilder; var templateConvention = new TemplateConvention(format, lowerPath, postFix); _RouteInformationGetter = templateConvention.GetRouteInformation; } /// <summary> /// Construct convention router using a factory method /// </summary> /// <param name="routerBuilder"></param> /// <param name="routeInformationGetter"></param> internal ConventionRouter(IRouterBuilder routerBuilder, Func<Type, string, Tuple<RouteSpecification, RouteDestination>> routeInformationGetter) { _RouterBuilder = routerBuilder; _RouteInformationGetter = routeInformationGetter; } /// <summary> /// Add the corresponding types to the convention /// </summary> /// <param name="types"></param> /// <returns></returns> public IConventionRouter Register(IEnumerable<Type> types) { types.ForEach(t => Register(t)); return this; } /// <summary> /// Add the corresponding type to the convention, using option id /// </summary> /// <typeparam name="T">type to register</typeparam> /// <param name="id"></param> /// <returns></returns> public IConventionRouter Register<T>(string id = null) { return Register(typeof(T), id); } /// <summary> /// Add the corresponding type to the convention, using option id /// </summary> /// <param name="type">type to register</param> /// <param name="id"></param> /// <returns></returns> public IConventionRouter Register(Type type, string id = null) { var (route, routeDestination) = _RouteInformationGetter(type, id); _RouterBuilder.Register(route, routeDestination); return this; } } }
40.063291
151
0.624329
[ "MIT" ]
NeutroniumCore/Neutronium.BuildingBlocks
Neutronium.BuildingBlocks.Application/Navigation/Internals/ConventionRouter.cs
3,167
C#
#pragma checksum "C:\迅雷下载\Projects\Lab2-INotifyProperyChanged\Lab2-INotifyProperyChanged\MainPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "7A6F62821F3F1A5B243C0AFC94DD5F73" //------------------------------------------------------------------------------ // <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 Lab2INotifyProperyChanged { partial class MainPage : global::Windows.UI.Xaml.Controls.Page, global::Windows.UI.Xaml.Markup.IComponentConnector, global::Windows.UI.Xaml.Markup.IComponentConnector2 { /// <summary> /// Connect() /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public void Connect(int connectionId, object target) { switch(connectionId) { case 1: { this.btnChange = (global::Windows.UI.Xaml.Controls.Button)(target); #line 51 "..\..\..\MainPage.xaml" ((global::Windows.UI.Xaml.Controls.Button)this.btnChange).Click += this.btnChange_Click; #line default } break; case 2: { this.tbxArg1 = (global::Windows.UI.Xaml.Controls.TextBox)(target); } break; case 3: { this.tbxArg2 = (global::Windows.UI.Xaml.Controls.TextBox)(target); } break; case 4: { this.tblAnswer = (global::Windows.UI.Xaml.Controls.TextBox)(target); #line 47 "..\..\..\MainPage.xaml" ((global::Windows.UI.Xaml.Controls.TextBox)this.tblAnswer).TextChanged += this.tblAnswer_TextChanged; #line default } break; default: break; } this._contentLoaded = true; } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public global::Windows.UI.Xaml.Markup.IComponentConnector GetBindingConnector(int connectionId, object target) { global::Windows.UI.Xaml.Markup.IComponentConnector returnValue = null; return returnValue; } } }
40.347826
180
0.530891
[ "Apache-2.0" ]
w326004741/MobileApps-3-Labs
Lab2-INotifyProperyChanged/Lab2-INotifyProperyChanged/obj/x86/Debug/MainPage.g.cs
2,794
C#
namespace UnityWinForms.Examples.Panels { using System.Windows.Forms; public class PanelRadioButton : BaseExamplePanel { public override void Initialize() { var radio = this.Create<RadioButton>("AutoCheck = false"); radio.AutoCheck = false; radio.Width = 200; var groupBox = this.Create<GroupBox>(); var r1 = groupBox.Create<RadioButton>("First"); var r2 = groupBox.Create<RadioButton>("Second"); var r3 = groupBox.Create<RadioButton>("Third"); // hack: to make sure tabulation will work fine. r1.TabIndex = 1; r2.TabIndex = 2; r3.TabIndex = 3; } } }
29.72
70
0.550471
[ "MIT" ]
Meragon/Unity-WinForms
Examples/Panels/PanelRadioButton.cs
745
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("JSONParse")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("JSONParse")] [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("b2208fb1-cebb-4a6e-98c0-1d2491ec9332")] // 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.594595
84
0.744069
[ "MIT" ]
AnaKostadinova/Programming-Fundamentals-C-Sharp-Exercises
Strings/JSONParse/Properties/AssemblyInfo.cs
1,394
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; namespace TheLastWizard { #region messages public class KilledEnemyMessage { public int Points; } public class TimeBonusMessage { public int Points; } public class HowManyPointsMessage { public Component Sender; public int Points; public int KilledEnemies; } public class ScoreMessage { } #endregion public class PlayerScore : MonoBehaviour { private int _Score = 0; private int _KilledEnemies = 0; [SerializeField] private Canvas _Canvas; private HudView _HUD; private void Awake() { PlayerPrefs.SetInt("Last Score", 0); PlayerPrefs.SetInt("Last Killed Enemies", 0); _HUD = _Canvas.GetComponent<HudView>(); } private void Receive(KilledEnemyMessage message) { _Score += message.Points; _HUD.Score = _Score; _KilledEnemies++; _HUD.KilledEnemies = _KilledEnemies; } private void Receive(TimeBonusMessage message) { _Score += message.Points; _HUD.Score = _Score; } private void Receive(HowManyPointsMessage message) { Debug.Log("Player score received howmanypointsmessage"); message.Points = _Score; message.KilledEnemies = _KilledEnemies; } } }
22.833333
69
0.566302
[ "Apache-2.0" ]
tmachows/the-last-wizard
Assets/Scripts/Player/PlayerScore.cs
1,575
C#
using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using Gatling.Runner.Models; using Gatling.Runner.Services; namespace Gatling.Runner.Queuing { public interface IBackgroundTaskQueue { void QueueBackgroundWorkItem(string jobId, Func<CancellationToken, Task> workItem); Task<(string jobId, Func<CancellationToken, Task> func)> DequeueAsync( CancellationToken cancellationToken); } public class BackgroundTaskQueue : IBackgroundTaskQueue { private readonly IJobStatusService _jobStatusService; public BackgroundTaskQueue(IJobStatusService jobStatusService) { _jobStatusService = jobStatusService; } private readonly ConcurrentQueue<(string jobId, Func<CancellationToken, Task> func)> _workItems = new ConcurrentQueue<(string jobId, Func<CancellationToken, Task> func)>(); private readonly SemaphoreSlim _signal = new SemaphoreSlim(0); public void QueueBackgroundWorkItem(string jobId, Func<CancellationToken, Task> workItem) { if (workItem == null) { throw new ArgumentNullException(nameof(workItem)); } _workItems.Enqueue((jobId, workItem)); _jobStatusService.SetState(jobId, State.Started); _signal.Release(); } public async Task<(string jobId, Func<CancellationToken, Task> func)> DequeueAsync( CancellationToken cancellationToken) { await _signal.WaitAsync(cancellationToken); _workItems.TryDequeue(out var workItem); return workItem; } } }
30.892857
105
0.66474
[ "MIT" ]
dantheman999301/AspNetCore.Gatling
src/Gatling.Runner/Queuing/BackgroundTaskQueue.cs
1,732
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace RockIdentificationTool.Server.Pages { [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); private readonly ILogger<ErrorModel> _logger; public ErrorModel(ILogger<ErrorModel> logger) { _logger = logger; } public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
26.9375
89
0.662413
[ "MIT" ]
JaredVigil/RockIdentificationTool
RockIdentificationTool/Server/Pages/Error.cshtml.cs
864
C#
using SmallTalks.Core.Models; using SmallTalks.Core.Services.Interfaces; using System; using System.Collections.Generic; using System.Text; namespace SmallTalks.Core.Services { public class LocalSourceProviderService : ISourceProviderService { public SourceProvider GetSourceProvider() { return new SourceProvider { Intents = "Resources.v1.intents.json", StopWords = "Resources.stopwords.txt", CurseWords = "Resources.cursewords.txt", SourceType = SourceProviderType.Local }; } public SourceProvider GetSourceProviderv2() { return new SourceProvider { Intents = "Resources.v2.intents.json", StopWords = "Resources.stopwords.txt", CurseWords = "Resources.cursewords.txt", SourceType = SourceProviderType.Local }; } } }
28.852941
68
0.588175
[ "MIT" ]
ceifa/smalltalks
SmallTalks/SmallTalks.Core/Services/LocalSourceProviderService.cs
983
C#
using Algorithms.Strings; using Algorithms.Strings.Substrings; using Xunit; namespace Algorithms.Test.Strings.Substrings { public sealed class BoyerMooreSearchTest { [Fact] public void Test_Found() { BoyerMooreSearch bm = new BoyerMooreSearch("cro", Alphabet.ASCII); Assert.Equal(2, bm.Search("Microsoft")); } [Fact] public void Test_NotFound() { BoyerMooreSearch bm = new BoyerMooreSearch("gl", Alphabet.ASCII); Assert.Equal(-1, bm.Search("Microsoft")); } } }
22.692308
78
0.601695
[ "MIT" ]
gfurtadoalmeida/study-algorithms
book-01/Algorithms.Test/Strings/Substrings/BoyerMooreSearch.cs
592
C#
using System.Runtime.Serialization; namespace ESRI.ArcLogistics.Tracking.TrackingService.Json { /// <summary> /// Stores information about attribute parameter. /// </summary> [DataContract] internal sealed class ParameterInfo { #region constructor /// <summary> /// Constructor. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="value">Parameter value.</param> /// <param name="isRestrictionUsage">'True' if it is restriction usage parameter, /// 'false' otherwise.</param> public ParameterInfo(string name, string value, bool isRestrictionUsage) { Name = name; Value = value; UsageType = isRestrictionUsage ? RESTICTION : GENERAL; } #endregion #region public properties /// <summary> /// Parameter name. /// </summary> [DataMember(Name = "name")] public string Name { get; set; } /// <summary> /// Parameter value. /// </summary> [DataMember(Name = "value")] public string Value { get; set; } /// <summary> /// Parameter usage type. /// </summary> [DataMember(Name = "usageType")] public string UsageType { get; set; } #endregion #region private members /// <summary> /// UsageType property possible values. /// </summary> private const string RESTICTION = @"Restriction"; private const string GENERAL = @"General"; #endregion } }
26.209677
89
0.551385
[ "Apache-2.0" ]
Esri/route-planner-csharp
RoutePlanner_DeveloperTools/Source/ArcLogistics/Tracking/TrackingService/Json/ParameterInfo.cs
1,627
C#
using Jobsity.Chat.Contracts.Commands; using Jobsity.Chat.Contracts.Interfaces; using Jobsity.Chat.Contracts.Messaging; using Jobsity.Chat.Service.MessageBrokerService; using Xunit; using Xunit.Abstractions; namespace Jobsity.Chat.IntegrationTests.Services { public class RabbitMqServiceFixture { ITestOutputHelper _testOutput; IRabbitMqService _rabbitMeService; public RabbitMqServiceFixture(ITestOutputHelper testOutput) { _testOutput = testOutput; _rabbitMeService = new RabbitMqService(ConfigurationSingletonFactory.GetMessageBrokerSettings(), null); } [Theory] [InlineData("AAPL.US")] public void ShouldAskForQuoteData(string symbol) { // Arrange _rabbitMeService.OnQuoteDataReceived -= new NotifyCallerDelegate(OnQuoteReceived); _rabbitMeService.OnQuoteDataReceived += new NotifyCallerDelegate(OnQuoteReceived); // Act _rabbitMeService.AskForQuote(symbol); } protected void OnQuoteReceived(MessageEventArgs<StockQuoteCommand> args) { // Assert Assert.True(args.Message != null); Assert.True(args.Message.Price > 0m); _testOutput.WriteLine($"{args.Message.Symbol} quote is ${args.Message.Price} per share"); } } }
32.690476
115
0.675164
[ "MIT" ]
magupisoft/chat-challenge
Jobsity.Chat.IntegrationTests/Services/RabbitMqServiceFixture.cs
1,375
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; namespace CodeCracker.CSharp.Style { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class ConvertToSwitchAnalyzer : DiagnosticAnalyzer { internal const string Title = "Use 'switch'"; internal const string MessageFormat = "You could use 'switch' instead of 'if'."; internal const string Category = SupportedCategories.Style; const string Description = "Multiple 'if' and 'else if' on the same variable can be replaced with a 'switch'" + "on the variable\r\n\r\n" + "Note: This diagnostic trigger for 3 or more 'case' statements"; internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId.ConvertToSwitch.ToDiagnosticId(), Title, MessageFormat, Category, DiagnosticSeverity.Info, isEnabledByDefault: true, description: Description, helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.ConvertToSwitch)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.IfStatement); private static void AnalyzeNode(SyntaxNodeAnalysisContext context) { if (context.IsGenerated()) return; var ifStatement = (IfStatementSyntax)context.Node; // ignoring else if if (ifStatement.Parent is ElseClauseSyntax) return; // ignoring simple if statement if (ifStatement.Else == null) return; var nestedIfs = FindNestedIfs(ifStatement).ToArray(); // ignoring less than 3 nested ifs if (nestedIfs.Length < 3) return; // ignoring when not all conditionals are "equals" IdentifierNameSyntax common = null; for (int i = 0; i < nestedIfs.Length; i++) { var condition = nestedIfs[i].Condition as BinaryExpressionSyntax; // all ifs should have binary expressions as conditions if (condition == null) return; // all conditions should be "equal" if (!condition.IsKind(SyntaxKind.EqualsExpression)) return; var left = condition.Left as IdentifierNameSyntax; // all conditions should have an identifier in the left if (left == null) return; if (i == 0) { common = left; } else if (!left.Identifier.IsEquivalentTo(common.Identifier)) { // all conditions should have the same identifier in the left return; } var right = context.SemanticModel.GetConstantValue(condition.Right); // only constants in the right side if (!right.HasValue) return; } var diagnostic = Diagnostic.Create(Rule, ifStatement.GetLocation()); context.ReportDiagnostic(diagnostic); } internal static IEnumerable<IfStatementSyntax> FindNestedIfs(IfStatementSyntax ifStatement) { do { yield return ifStatement; if (ifStatement.Else == null) yield break; ifStatement = ifStatement.Else.ChildNodes().FirstOrDefault() as IfStatementSyntax; } while (ifStatement != null); } } }
39.309278
138
0.615788
[ "Apache-2.0" ]
ComputerScience1-Period3/code-cracker
src/CSharp/CodeCracker/Style/ConvertToSwitchAnalyzer.cs
3,815
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Demo.Localization")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Demo.Localization")] [assembly: System.Reflection.AssemblyTitleAttribute("Demo.Localization")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.708333
80
0.651349
[ "MIT" ]
itasouza/Demo.Localization
Demo.Localization/obj/Debug/netcoreapp2.2/Demo.Localization.AssemblyInfo.cs
1,001
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TemPHPlate { public class ScriptFile : ScriptDefinition { public string FileName { get => default(string); set { } } public override string Draw() { throw new NotImplementedException(); } } }
17.826087
48
0.536585
[ "Apache-2.0" ]
manuth/TemPHPlate
Documents/TemPHPlate/ScriptFile.cs
412
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Body_draw : MonoBehaviour { private Body_part p; public Body_part part { set { if (p == value) return; p = value; StartCoroutine(ReLoad()); } } public SpriteGender gender { set { if(value != p.gender) { part = ITEMS.main.body_parts[gender][skin][type][p.InListID]; } } get { return p.gender; } } public Skin_type skin { set { if (value != p.skin) { part = ITEMS.main.body_parts[gender][skin][type][p.InListID]; } } get { return p.skin; } } public body_part type { get { return p.type; } } public Texture2D source; public GameObject spritesRoot; private Sprite[,] sprite; private SpriteRenderer sr; private AddSpriteN Parent; private bool Draw = false; private LoadExternalAsSprite LES; public int SortingOrder { get { return sr.sortingOrder; } set { sr.sortingOrder = value; } } void Start() { sr = GetComponent<SpriteRenderer>(); sr.sortingLayerName = "all"; } public void LoadSR() { sr = GetComponent<SpriteRenderer>(); sr.sortingLayerName = "all"; } private bool LoadSprites(int id) { LES = DataBase.LoadedSpritesDataBase; if (LES == null) return false; Parent = transform.parent.GetComponent<AddSpriteN>(); sr = GetComponent<SpriteRenderer>(); sr.sortingLayerName = "all"; StartCoroutine(getTexture(id)); Destroy(source); return true; } IEnumerator ReLoad() { yield return new WaitForSeconds(Time.deltaTime); sr.color = p.color; LoadSprites(p.id); } IEnumerator getTexture(int id) { Draw = false; Sprite[,] Load = null; while (Load == null) { Load = LES.GetSprite(id); yield return new WaitForSeconds(Time.deltaTime * 10); } sprite = Load; Draw = true; } public Color color { get { return sr.color; } set { if (sr != null) sr.color = value; } } public void UpdateAnimation() { if (Draw) sr.sprite = sprite[Parent.ImageIndex, 20 - Parent.SpriteColumn]; } }
18.651007
77
0.483267
[ "MIT" ]
miko-t/2016RpgGame
Assets/character/Body_draw.cs
2,781
C#
using Strive.Core.Services.WhiteboardService.Actions; namespace Strive.Core.Services.WhiteboardService.PushActions { public record PanCanvasPushAction(double PanX, double PanY) : CanvasPushAction { public override CanvasAction ConvertToAction(string participantId) { return new PanCanvasAction(PanX, PanY, participantId); } } }
29.076923
82
0.724868
[ "Apache-2.0" ]
Anapher/PaderConference
src/Services/ConferenceManagement/Strive.Core/Services/WhiteboardService/PushActions/PanCanvasPushAction.cs
380
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/dwrite_3.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("F3744D80-21F7-42EB-B35D-995BC72FC223")] public unsafe partial struct IDWriteFactory6 { public void** lpVtbl; [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* stdcall<IDWriteFactory6*, Guid*, void**, int>)(lpVtbl[0]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), riid, ppvObject); } [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* stdcall<IDWriteFactory6*, uint>)(lpVtbl[1]))((IDWriteFactory6*)Unsafe.AsPointer(ref this)); } [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* stdcall<IDWriteFactory6*, uint>)(lpVtbl[2]))((IDWriteFactory6*)Unsafe.AsPointer(ref this)); } [return: NativeTypeName("HRESULT")] public int GetSystemFontCollection([NativeTypeName("IDWriteFontCollection **")] IDWriteFontCollection** fontCollection, [NativeTypeName("BOOL")] int checkForUpdates = 0) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontCollection**, int, int>)(lpVtbl[3]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontCollection, checkForUpdates); } [return: NativeTypeName("HRESULT")] public int CreateCustomFontCollection([NativeTypeName("IDWriteFontCollectionLoader *")] IDWriteFontCollectionLoader* collectionLoader, [NativeTypeName("const void *")] void* collectionKey, [NativeTypeName("UINT32")] uint collectionKeySize, [NativeTypeName("IDWriteFontCollection **")] IDWriteFontCollection** fontCollection) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontCollectionLoader*, void*, uint, IDWriteFontCollection**, int>)(lpVtbl[4]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), collectionLoader, collectionKey, collectionKeySize, fontCollection); } [return: NativeTypeName("HRESULT")] public int RegisterFontCollectionLoader([NativeTypeName("IDWriteFontCollectionLoader *")] IDWriteFontCollectionLoader* fontCollectionLoader) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontCollectionLoader*, int>)(lpVtbl[5]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontCollectionLoader); } [return: NativeTypeName("HRESULT")] public int UnregisterFontCollectionLoader([NativeTypeName("IDWriteFontCollectionLoader *")] IDWriteFontCollectionLoader* fontCollectionLoader) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontCollectionLoader*, int>)(lpVtbl[6]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontCollectionLoader); } [return: NativeTypeName("HRESULT")] public int CreateFontFileReference([NativeTypeName("const WCHAR *")] ushort* filePath, [NativeTypeName("const FILETIME *")] FILETIME* lastWriteTime, [NativeTypeName("IDWriteFontFile **")] IDWriteFontFile** fontFile) { return ((delegate* stdcall<IDWriteFactory6*, ushort*, FILETIME*, IDWriteFontFile**, int>)(lpVtbl[7]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), filePath, lastWriteTime, fontFile); } [return: NativeTypeName("HRESULT")] public int CreateCustomFontFileReference([NativeTypeName("const void *")] void* fontFileReferenceKey, [NativeTypeName("UINT32")] uint fontFileReferenceKeySize, [NativeTypeName("IDWriteFontFileLoader *")] IDWriteFontFileLoader* fontFileLoader, [NativeTypeName("IDWriteFontFile **")] IDWriteFontFile** fontFile) { return ((delegate* stdcall<IDWriteFactory6*, void*, uint, IDWriteFontFileLoader*, IDWriteFontFile**, int>)(lpVtbl[8]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontFileReferenceKey, fontFileReferenceKeySize, fontFileLoader, fontFile); } [return: NativeTypeName("HRESULT")] public int CreateFontFace(DWRITE_FONT_FACE_TYPE fontFaceType, [NativeTypeName("UINT32")] uint numberOfFiles, [NativeTypeName("IDWriteFontFile *const *")] IDWriteFontFile** fontFiles, [NativeTypeName("UINT32")] uint faceIndex, DWRITE_FONT_SIMULATIONS fontFaceSimulationFlags, [NativeTypeName("IDWriteFontFace **")] IDWriteFontFace** fontFace) { return ((delegate* stdcall<IDWriteFactory6*, DWRITE_FONT_FACE_TYPE, uint, IDWriteFontFile**, uint, DWRITE_FONT_SIMULATIONS, IDWriteFontFace**, int>)(lpVtbl[9]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontFaceType, numberOfFiles, fontFiles, faceIndex, fontFaceSimulationFlags, fontFace); } [return: NativeTypeName("HRESULT")] public int CreateRenderingParams([NativeTypeName("IDWriteRenderingParams **")] IDWriteRenderingParams** renderingParams) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteRenderingParams**, int>)(lpVtbl[10]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), renderingParams); } [return: NativeTypeName("HRESULT")] public int CreateMonitorRenderingParams([NativeTypeName("HMONITOR")] IntPtr monitor, [NativeTypeName("IDWriteRenderingParams **")] IDWriteRenderingParams** renderingParams) { return ((delegate* stdcall<IDWriteFactory6*, IntPtr, IDWriteRenderingParams**, int>)(lpVtbl[11]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), monitor, renderingParams); } [return: NativeTypeName("HRESULT")] public int CreateCustomRenderingParams([NativeTypeName("FLOAT")] float gamma, [NativeTypeName("FLOAT")] float enhancedContrast, [NativeTypeName("FLOAT")] float clearTypeLevel, DWRITE_PIXEL_GEOMETRY pixelGeometry, DWRITE_RENDERING_MODE renderingMode, [NativeTypeName("IDWriteRenderingParams **")] IDWriteRenderingParams** renderingParams) { return ((delegate* stdcall<IDWriteFactory6*, float, float, float, DWRITE_PIXEL_GEOMETRY, DWRITE_RENDERING_MODE, IDWriteRenderingParams**, int>)(lpVtbl[12]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), gamma, enhancedContrast, clearTypeLevel, pixelGeometry, renderingMode, renderingParams); } [return: NativeTypeName("HRESULT")] public int RegisterFontFileLoader([NativeTypeName("IDWriteFontFileLoader *")] IDWriteFontFileLoader* fontFileLoader) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontFileLoader*, int>)(lpVtbl[13]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontFileLoader); } [return: NativeTypeName("HRESULT")] public int UnregisterFontFileLoader([NativeTypeName("IDWriteFontFileLoader *")] IDWriteFontFileLoader* fontFileLoader) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontFileLoader*, int>)(lpVtbl[14]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontFileLoader); } [return: NativeTypeName("HRESULT")] public int CreateTextFormat([NativeTypeName("const WCHAR *")] ushort* fontFamilyName, [NativeTypeName("IDWriteFontCollection *")] IDWriteFontCollection* fontCollection, DWRITE_FONT_WEIGHT fontWeight, DWRITE_FONT_STYLE fontStyle, DWRITE_FONT_STRETCH fontStretch, [NativeTypeName("FLOAT")] float fontSize, [NativeTypeName("const WCHAR *")] ushort* localeName, [NativeTypeName("IDWriteTextFormat **")] IDWriteTextFormat** textFormat) { return ((delegate* stdcall<IDWriteFactory6*, ushort*, IDWriteFontCollection*, DWRITE_FONT_WEIGHT, DWRITE_FONT_STYLE, DWRITE_FONT_STRETCH, float, ushort*, IDWriteTextFormat**, int>)(lpVtbl[15]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontFamilyName, fontCollection, fontWeight, fontStyle, fontStretch, fontSize, localeName, textFormat); } [return: NativeTypeName("HRESULT")] public int CreateTypography([NativeTypeName("IDWriteTypography **")] IDWriteTypography** typography) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteTypography**, int>)(lpVtbl[16]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), typography); } [return: NativeTypeName("HRESULT")] public int GetGdiInterop([NativeTypeName("IDWriteGdiInterop **")] IDWriteGdiInterop** gdiInterop) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteGdiInterop**, int>)(lpVtbl[17]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), gdiInterop); } [return: NativeTypeName("HRESULT")] public int CreateTextLayout([NativeTypeName("const WCHAR *")] ushort* @string, [NativeTypeName("UINT32")] uint stringLength, [NativeTypeName("IDWriteTextFormat *")] IDWriteTextFormat* textFormat, [NativeTypeName("FLOAT")] float maxWidth, [NativeTypeName("FLOAT")] float maxHeight, [NativeTypeName("IDWriteTextLayout **")] IDWriteTextLayout** textLayout) { return ((delegate* stdcall<IDWriteFactory6*, ushort*, uint, IDWriteTextFormat*, float, float, IDWriteTextLayout**, int>)(lpVtbl[18]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), @string, stringLength, textFormat, maxWidth, maxHeight, textLayout); } [return: NativeTypeName("HRESULT")] public int CreateGdiCompatibleTextLayout([NativeTypeName("const WCHAR *")] ushort* @string, [NativeTypeName("UINT32")] uint stringLength, [NativeTypeName("IDWriteTextFormat *")] IDWriteTextFormat* textFormat, [NativeTypeName("FLOAT")] float layoutWidth, [NativeTypeName("FLOAT")] float layoutHeight, [NativeTypeName("FLOAT")] float pixelsPerDip, [NativeTypeName("const DWRITE_MATRIX *")] DWRITE_MATRIX* transform, [NativeTypeName("BOOL")] int useGdiNatural, [NativeTypeName("IDWriteTextLayout **")] IDWriteTextLayout** textLayout) { return ((delegate* stdcall<IDWriteFactory6*, ushort*, uint, IDWriteTextFormat*, float, float, float, DWRITE_MATRIX*, int, IDWriteTextLayout**, int>)(lpVtbl[19]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), @string, stringLength, textFormat, layoutWidth, layoutHeight, pixelsPerDip, transform, useGdiNatural, textLayout); } [return: NativeTypeName("HRESULT")] public int CreateEllipsisTrimmingSign([NativeTypeName("IDWriteTextFormat *")] IDWriteTextFormat* textFormat, [NativeTypeName("IDWriteInlineObject **")] IDWriteInlineObject** trimmingSign) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteTextFormat*, IDWriteInlineObject**, int>)(lpVtbl[20]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), textFormat, trimmingSign); } [return: NativeTypeName("HRESULT")] public int CreateTextAnalyzer([NativeTypeName("IDWriteTextAnalyzer **")] IDWriteTextAnalyzer** textAnalyzer) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteTextAnalyzer**, int>)(lpVtbl[21]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), textAnalyzer); } [return: NativeTypeName("HRESULT")] public int CreateNumberSubstitution(DWRITE_NUMBER_SUBSTITUTION_METHOD substitutionMethod, [NativeTypeName("const WCHAR *")] ushort* localeName, [NativeTypeName("BOOL")] int ignoreUserOverride, [NativeTypeName("IDWriteNumberSubstitution **")] IDWriteNumberSubstitution** numberSubstitution) { return ((delegate* stdcall<IDWriteFactory6*, DWRITE_NUMBER_SUBSTITUTION_METHOD, ushort*, int, IDWriteNumberSubstitution**, int>)(lpVtbl[22]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), substitutionMethod, localeName, ignoreUserOverride, numberSubstitution); } [return: NativeTypeName("HRESULT")] public int CreateGlyphRunAnalysis([NativeTypeName("const DWRITE_GLYPH_RUN *")] DWRITE_GLYPH_RUN* glyphRun, [NativeTypeName("FLOAT")] float pixelsPerDip, [NativeTypeName("const DWRITE_MATRIX *")] DWRITE_MATRIX* transform, DWRITE_RENDERING_MODE renderingMode, DWRITE_MEASURING_MODE measuringMode, [NativeTypeName("FLOAT")] float baselineOriginX, [NativeTypeName("FLOAT")] float baselineOriginY, [NativeTypeName("IDWriteGlyphRunAnalysis **")] IDWriteGlyphRunAnalysis** glyphRunAnalysis) { return ((delegate* stdcall<IDWriteFactory6*, DWRITE_GLYPH_RUN*, float, DWRITE_MATRIX*, DWRITE_RENDERING_MODE, DWRITE_MEASURING_MODE, float, float, IDWriteGlyphRunAnalysis**, int>)(lpVtbl[23]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), glyphRun, pixelsPerDip, transform, renderingMode, measuringMode, baselineOriginX, baselineOriginY, glyphRunAnalysis); } [return: NativeTypeName("HRESULT")] public int GetEudcFontCollection([NativeTypeName("IDWriteFontCollection **")] IDWriteFontCollection** fontCollection, [NativeTypeName("BOOL")] int checkForUpdates = 0) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontCollection**, int, int>)(lpVtbl[24]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontCollection, checkForUpdates); } [return: NativeTypeName("HRESULT")] public int CreateCustomRenderingParams([NativeTypeName("FLOAT")] float gamma, [NativeTypeName("FLOAT")] float enhancedContrast, [NativeTypeName("FLOAT")] float enhancedContrastGrayscale, [NativeTypeName("FLOAT")] float clearTypeLevel, DWRITE_PIXEL_GEOMETRY pixelGeometry, DWRITE_RENDERING_MODE renderingMode, [NativeTypeName("IDWriteRenderingParams1 **")] IDWriteRenderingParams1** renderingParams) { return ((delegate* stdcall<IDWriteFactory6*, float, float, float, float, DWRITE_PIXEL_GEOMETRY, DWRITE_RENDERING_MODE, IDWriteRenderingParams1**, int>)(lpVtbl[25]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), gamma, enhancedContrast, enhancedContrastGrayscale, clearTypeLevel, pixelGeometry, renderingMode, renderingParams); } [return: NativeTypeName("HRESULT")] public int GetSystemFontFallback([NativeTypeName("IDWriteFontFallback **")] IDWriteFontFallback** fontFallback) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontFallback**, int>)(lpVtbl[26]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontFallback); } [return: NativeTypeName("HRESULT")] public int CreateFontFallbackBuilder([NativeTypeName("IDWriteFontFallbackBuilder **")] IDWriteFontFallbackBuilder** fontFallbackBuilder) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontFallbackBuilder**, int>)(lpVtbl[27]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontFallbackBuilder); } [return: NativeTypeName("HRESULT")] public int TranslateColorGlyphRun([NativeTypeName("FLOAT")] float baselineOriginX, [NativeTypeName("FLOAT")] float baselineOriginY, [NativeTypeName("const DWRITE_GLYPH_RUN *")] DWRITE_GLYPH_RUN* glyphRun, [NativeTypeName("const DWRITE_GLYPH_RUN_DESCRIPTION *")] DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription, DWRITE_MEASURING_MODE measuringMode, [NativeTypeName("const DWRITE_MATRIX *")] DWRITE_MATRIX* worldToDeviceTransform, [NativeTypeName("UINT32")] uint colorPaletteIndex, [NativeTypeName("IDWriteColorGlyphRunEnumerator **")] IDWriteColorGlyphRunEnumerator** colorLayers) { return ((delegate* stdcall<IDWriteFactory6*, float, float, DWRITE_GLYPH_RUN*, DWRITE_GLYPH_RUN_DESCRIPTION*, DWRITE_MEASURING_MODE, DWRITE_MATRIX*, uint, IDWriteColorGlyphRunEnumerator**, int>)(lpVtbl[28]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), baselineOriginX, baselineOriginY, glyphRun, glyphRunDescription, measuringMode, worldToDeviceTransform, colorPaletteIndex, colorLayers); } [return: NativeTypeName("HRESULT")] public int CreateCustomRenderingParams([NativeTypeName("FLOAT")] float gamma, [NativeTypeName("FLOAT")] float enhancedContrast, [NativeTypeName("FLOAT")] float grayscaleEnhancedContrast, [NativeTypeName("FLOAT")] float clearTypeLevel, DWRITE_PIXEL_GEOMETRY pixelGeometry, DWRITE_RENDERING_MODE renderingMode, DWRITE_GRID_FIT_MODE gridFitMode, [NativeTypeName("IDWriteRenderingParams2 **")] IDWriteRenderingParams2** renderingParams) { return ((delegate* stdcall<IDWriteFactory6*, float, float, float, float, DWRITE_PIXEL_GEOMETRY, DWRITE_RENDERING_MODE, DWRITE_GRID_FIT_MODE, IDWriteRenderingParams2**, int>)(lpVtbl[29]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), gamma, enhancedContrast, grayscaleEnhancedContrast, clearTypeLevel, pixelGeometry, renderingMode, gridFitMode, renderingParams); } [return: NativeTypeName("HRESULT")] public int CreateGlyphRunAnalysis([NativeTypeName("const DWRITE_GLYPH_RUN *")] DWRITE_GLYPH_RUN* glyphRun, [NativeTypeName("const DWRITE_MATRIX *")] DWRITE_MATRIX* transform, DWRITE_RENDERING_MODE renderingMode, DWRITE_MEASURING_MODE measuringMode, DWRITE_GRID_FIT_MODE gridFitMode, DWRITE_TEXT_ANTIALIAS_MODE antialiasMode, [NativeTypeName("FLOAT")] float baselineOriginX, [NativeTypeName("FLOAT")] float baselineOriginY, [NativeTypeName("IDWriteGlyphRunAnalysis **")] IDWriteGlyphRunAnalysis** glyphRunAnalysis) { return ((delegate* stdcall<IDWriteFactory6*, DWRITE_GLYPH_RUN*, DWRITE_MATRIX*, DWRITE_RENDERING_MODE, DWRITE_MEASURING_MODE, DWRITE_GRID_FIT_MODE, DWRITE_TEXT_ANTIALIAS_MODE, float, float, IDWriteGlyphRunAnalysis**, int>)(lpVtbl[30]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), glyphRun, transform, renderingMode, measuringMode, gridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis); } [return: NativeTypeName("HRESULT")] public int CreateGlyphRunAnalysis([NativeTypeName("const DWRITE_GLYPH_RUN *")] DWRITE_GLYPH_RUN* glyphRun, [NativeTypeName("const DWRITE_MATRIX *")] DWRITE_MATRIX* transform, DWRITE_RENDERING_MODE1 renderingMode, DWRITE_MEASURING_MODE measuringMode, DWRITE_GRID_FIT_MODE gridFitMode, DWRITE_TEXT_ANTIALIAS_MODE antialiasMode, [NativeTypeName("FLOAT")] float baselineOriginX, [NativeTypeName("FLOAT")] float baselineOriginY, [NativeTypeName("IDWriteGlyphRunAnalysis **")] IDWriteGlyphRunAnalysis** glyphRunAnalysis) { return ((delegate* stdcall<IDWriteFactory6*, DWRITE_GLYPH_RUN*, DWRITE_MATRIX*, DWRITE_RENDERING_MODE1, DWRITE_MEASURING_MODE, DWRITE_GRID_FIT_MODE, DWRITE_TEXT_ANTIALIAS_MODE, float, float, IDWriteGlyphRunAnalysis**, int>)(lpVtbl[31]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), glyphRun, transform, renderingMode, measuringMode, gridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis); } [return: NativeTypeName("HRESULT")] public int CreateCustomRenderingParams([NativeTypeName("FLOAT")] float gamma, [NativeTypeName("FLOAT")] float enhancedContrast, [NativeTypeName("FLOAT")] float grayscaleEnhancedContrast, [NativeTypeName("FLOAT")] float clearTypeLevel, DWRITE_PIXEL_GEOMETRY pixelGeometry, DWRITE_RENDERING_MODE1 renderingMode, DWRITE_GRID_FIT_MODE gridFitMode, [NativeTypeName("IDWriteRenderingParams3 **")] IDWriteRenderingParams3** renderingParams) { return ((delegate* stdcall<IDWriteFactory6*, float, float, float, float, DWRITE_PIXEL_GEOMETRY, DWRITE_RENDERING_MODE1, DWRITE_GRID_FIT_MODE, IDWriteRenderingParams3**, int>)(lpVtbl[32]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), gamma, enhancedContrast, grayscaleEnhancedContrast, clearTypeLevel, pixelGeometry, renderingMode, gridFitMode, renderingParams); } [return: NativeTypeName("HRESULT")] public int CreateFontFaceReference([NativeTypeName("const WCHAR *")] ushort* filePath, [NativeTypeName("const FILETIME *")] FILETIME* lastWriteTime, [NativeTypeName("UINT32")] uint faceIndex, DWRITE_FONT_SIMULATIONS fontSimulations, [NativeTypeName("IDWriteFontFaceReference **")] IDWriteFontFaceReference** fontFaceReference) { return ((delegate* stdcall<IDWriteFactory6*, ushort*, FILETIME*, uint, DWRITE_FONT_SIMULATIONS, IDWriteFontFaceReference**, int>)(lpVtbl[33]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), filePath, lastWriteTime, faceIndex, fontSimulations, fontFaceReference); } [return: NativeTypeName("HRESULT")] public int CreateFontFaceReference([NativeTypeName("IDWriteFontFile *")] IDWriteFontFile* fontFile, [NativeTypeName("UINT32")] uint faceIndex, DWRITE_FONT_SIMULATIONS fontSimulations, [NativeTypeName("IDWriteFontFaceReference **")] IDWriteFontFaceReference** fontFaceReference) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontFile*, uint, DWRITE_FONT_SIMULATIONS, IDWriteFontFaceReference**, int>)(lpVtbl[34]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontFile, faceIndex, fontSimulations, fontFaceReference); } [return: NativeTypeName("HRESULT")] public int GetSystemFontSet([NativeTypeName("IDWriteFontSet **")] IDWriteFontSet** fontSet) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontSet**, int>)(lpVtbl[35]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontSet); } [return: NativeTypeName("HRESULT")] public int CreateFontSetBuilder([NativeTypeName("IDWriteFontSetBuilder **")] IDWriteFontSetBuilder** fontSetBuilder) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontSetBuilder**, int>)(lpVtbl[36]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontSetBuilder); } [return: NativeTypeName("HRESULT")] public int CreateFontCollectionFromFontSet([NativeTypeName("IDWriteFontSet *")] IDWriteFontSet* fontSet, [NativeTypeName("IDWriteFontCollection1 **")] IDWriteFontCollection1** fontCollection) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontSet*, IDWriteFontCollection1**, int>)(lpVtbl[37]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontSet, fontCollection); } [return: NativeTypeName("HRESULT")] public int GetSystemFontCollection([NativeTypeName("BOOL")] int includeDownloadableFonts, [NativeTypeName("IDWriteFontCollection1 **")] IDWriteFontCollection1** fontCollection, [NativeTypeName("BOOL")] int checkForUpdates = 0) { return ((delegate* stdcall<IDWriteFactory6*, int, IDWriteFontCollection1**, int, int>)(lpVtbl[38]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), includeDownloadableFonts, fontCollection, checkForUpdates); } [return: NativeTypeName("HRESULT")] public int GetFontDownloadQueue([NativeTypeName("IDWriteFontDownloadQueue **")] IDWriteFontDownloadQueue** fontDownloadQueue) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontDownloadQueue**, int>)(lpVtbl[39]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontDownloadQueue); } [return: NativeTypeName("HRESULT")] public int TranslateColorGlyphRun([NativeTypeName("D2D1_POINT_2F")] D2D_POINT_2F baselineOrigin, [NativeTypeName("const DWRITE_GLYPH_RUN *")] DWRITE_GLYPH_RUN* glyphRun, [NativeTypeName("const DWRITE_GLYPH_RUN_DESCRIPTION *")] DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription, DWRITE_GLYPH_IMAGE_FORMATS desiredGlyphImageFormats, DWRITE_MEASURING_MODE measuringMode, [NativeTypeName("const DWRITE_MATRIX *")] DWRITE_MATRIX* worldAndDpiTransform, [NativeTypeName("UINT32")] uint colorPaletteIndex, [NativeTypeName("IDWriteColorGlyphRunEnumerator1 **")] IDWriteColorGlyphRunEnumerator1** colorLayers) { return ((delegate* stdcall<IDWriteFactory6*, D2D_POINT_2F, DWRITE_GLYPH_RUN*, DWRITE_GLYPH_RUN_DESCRIPTION*, DWRITE_GLYPH_IMAGE_FORMATS, DWRITE_MEASURING_MODE, DWRITE_MATRIX*, uint, IDWriteColorGlyphRunEnumerator1**, int>)(lpVtbl[40]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), baselineOrigin, glyphRun, glyphRunDescription, desiredGlyphImageFormats, measuringMode, worldAndDpiTransform, colorPaletteIndex, colorLayers); } [return: NativeTypeName("HRESULT")] public int ComputeGlyphOrigins([NativeTypeName("const DWRITE_GLYPH_RUN *")] DWRITE_GLYPH_RUN* glyphRun, DWRITE_MEASURING_MODE measuringMode, [NativeTypeName("D2D1_POINT_2F")] D2D_POINT_2F baselineOrigin, [NativeTypeName("const DWRITE_MATRIX *")] DWRITE_MATRIX* worldAndDpiTransform, [NativeTypeName("D2D1_POINT_2F *")] D2D_POINT_2F* glyphOrigins) { return ((delegate* stdcall<IDWriteFactory6*, DWRITE_GLYPH_RUN*, DWRITE_MEASURING_MODE, D2D_POINT_2F, DWRITE_MATRIX*, D2D_POINT_2F*, int>)(lpVtbl[41]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), glyphRun, measuringMode, baselineOrigin, worldAndDpiTransform, glyphOrigins); } [return: NativeTypeName("HRESULT")] public int ComputeGlyphOrigins([NativeTypeName("const DWRITE_GLYPH_RUN *")] DWRITE_GLYPH_RUN* glyphRun, [NativeTypeName("D2D1_POINT_2F")] D2D_POINT_2F baselineOrigin, [NativeTypeName("D2D1_POINT_2F *")] D2D_POINT_2F* glyphOrigins) { return ((delegate* stdcall<IDWriteFactory6*, DWRITE_GLYPH_RUN*, D2D_POINT_2F, D2D_POINT_2F*, int>)(lpVtbl[42]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), glyphRun, baselineOrigin, glyphOrigins); } [return: NativeTypeName("HRESULT")] public int CreateFontSetBuilder([NativeTypeName("IDWriteFontSetBuilder1 **")] IDWriteFontSetBuilder1** fontSetBuilder) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontSetBuilder1**, int>)(lpVtbl[43]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontSetBuilder); } [return: NativeTypeName("HRESULT")] public int CreateInMemoryFontFileLoader([NativeTypeName("IDWriteInMemoryFontFileLoader **")] IDWriteInMemoryFontFileLoader** newLoader) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteInMemoryFontFileLoader**, int>)(lpVtbl[44]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), newLoader); } [return: NativeTypeName("HRESULT")] public int CreateHttpFontFileLoader([NativeTypeName("const wchar_t *")] ushort* referrerUrl, [NativeTypeName("const wchar_t *")] ushort* extraHeaders, [NativeTypeName("IDWriteRemoteFontFileLoader **")] IDWriteRemoteFontFileLoader** newLoader) { return ((delegate* stdcall<IDWriteFactory6*, ushort*, ushort*, IDWriteRemoteFontFileLoader**, int>)(lpVtbl[45]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), referrerUrl, extraHeaders, newLoader); } public DWRITE_CONTAINER_TYPE AnalyzeContainerType([NativeTypeName("const void *")] void* fileData, [NativeTypeName("UINT32")] uint fileDataSize) { return ((delegate* stdcall<IDWriteFactory6*, void*, uint, DWRITE_CONTAINER_TYPE>)(lpVtbl[46]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fileData, fileDataSize); } [return: NativeTypeName("HRESULT")] public int UnpackFontFile(DWRITE_CONTAINER_TYPE containerType, [NativeTypeName("const void *")] void* fileData, [NativeTypeName("UINT32")] uint fileDataSize, [NativeTypeName("IDWriteFontFileStream **")] IDWriteFontFileStream** unpackedFontStream) { return ((delegate* stdcall<IDWriteFactory6*, DWRITE_CONTAINER_TYPE, void*, uint, IDWriteFontFileStream**, int>)(lpVtbl[47]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), containerType, fileData, fileDataSize, unpackedFontStream); } [return: NativeTypeName("HRESULT")] public int CreateFontFaceReference([NativeTypeName("IDWriteFontFile *")] IDWriteFontFile* fontFile, [NativeTypeName("UINT32")] uint faceIndex, DWRITE_FONT_SIMULATIONS fontSimulations, [NativeTypeName("const DWRITE_FONT_AXIS_VALUE *")] DWRITE_FONT_AXIS_VALUE* fontAxisValues, [NativeTypeName("UINT32")] uint fontAxisValueCount, [NativeTypeName("IDWriteFontFaceReference1 **")] IDWriteFontFaceReference1** fontFaceReference) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontFile*, uint, DWRITE_FONT_SIMULATIONS, DWRITE_FONT_AXIS_VALUE*, uint, IDWriteFontFaceReference1**, int>)(lpVtbl[48]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontFile, faceIndex, fontSimulations, fontAxisValues, fontAxisValueCount, fontFaceReference); } [return: NativeTypeName("HRESULT")] public int CreateFontResource([NativeTypeName("IDWriteFontFile *")] IDWriteFontFile* fontFile, [NativeTypeName("UINT32")] uint faceIndex, [NativeTypeName("IDWriteFontResource **")] IDWriteFontResource** fontResource) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontFile*, uint, IDWriteFontResource**, int>)(lpVtbl[49]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontFile, faceIndex, fontResource); } [return: NativeTypeName("HRESULT")] public int GetSystemFontSet([NativeTypeName("BOOL")] int includeDownloadableFonts, [NativeTypeName("IDWriteFontSet1 **")] IDWriteFontSet1** fontSet) { return ((delegate* stdcall<IDWriteFactory6*, int, IDWriteFontSet1**, int>)(lpVtbl[50]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), includeDownloadableFonts, fontSet); } [return: NativeTypeName("HRESULT")] public int GetSystemFontCollection([NativeTypeName("BOOL")] int includeDownloadableFonts, DWRITE_FONT_FAMILY_MODEL fontFamilyModel, [NativeTypeName("IDWriteFontCollection2 **")] IDWriteFontCollection2** fontCollection) { return ((delegate* stdcall<IDWriteFactory6*, int, DWRITE_FONT_FAMILY_MODEL, IDWriteFontCollection2**, int>)(lpVtbl[51]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), includeDownloadableFonts, fontFamilyModel, fontCollection); } [return: NativeTypeName("HRESULT")] public int CreateFontCollectionFromFontSet([NativeTypeName("IDWriteFontSet *")] IDWriteFontSet* fontSet, DWRITE_FONT_FAMILY_MODEL fontFamilyModel, [NativeTypeName("IDWriteFontCollection2 **")] IDWriteFontCollection2** fontCollection) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontSet*, DWRITE_FONT_FAMILY_MODEL, IDWriteFontCollection2**, int>)(lpVtbl[52]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontSet, fontFamilyModel, fontCollection); } [return: NativeTypeName("HRESULT")] public int CreateFontSetBuilder([NativeTypeName("IDWriteFontSetBuilder2 **")] IDWriteFontSetBuilder2** fontSetBuilder) { return ((delegate* stdcall<IDWriteFactory6*, IDWriteFontSetBuilder2**, int>)(lpVtbl[53]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontSetBuilder); } [return: NativeTypeName("HRESULT")] public int CreateTextFormat([NativeTypeName("const WCHAR *")] ushort* fontFamilyName, [NativeTypeName("IDWriteFontCollection *")] IDWriteFontCollection* fontCollection, [NativeTypeName("const DWRITE_FONT_AXIS_VALUE *")] DWRITE_FONT_AXIS_VALUE* fontAxisValues, [NativeTypeName("UINT32")] uint fontAxisValueCount, [NativeTypeName("FLOAT")] float fontSize, [NativeTypeName("const WCHAR *")] ushort* localeName, [NativeTypeName("IDWriteTextFormat3 **")] IDWriteTextFormat3** textFormat) { return ((delegate* stdcall<IDWriteFactory6*, ushort*, IDWriteFontCollection*, DWRITE_FONT_AXIS_VALUE*, uint, float, ushort*, IDWriteTextFormat3**, int>)(lpVtbl[54]))((IDWriteFactory6*)Unsafe.AsPointer(ref this), fontFamilyName, fontCollection, fontAxisValues, fontAxisValueCount, fontSize, localeName, textFormat); } } }
90.449568
607
0.743484
[ "MIT" ]
john-h-k/terrafx.interop.windows
sources/Interop/Windows/um/dwrite_3/IDWriteFactory6.cs
31,388
C#
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation.Tracing; namespace System.Management.Automation.PerformanceData { /// <summary> /// Powershell Performance Counters Manager class shall provide a mechanism /// for components using SYstem.Management.Automation assembly to register /// performance counters with Performance Counters susbsystem. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public class PSPerfCountersMgr { #region Private Members private static PSPerfCountersMgr s_PSPerfCountersMgrInstance; private ConcurrentDictionary<Guid, CounterSetInstanceBase> _CounterSetIdToInstanceMapping; private ConcurrentDictionary<string, Guid> _CounterSetNameToIdMapping; private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); #region Constructors private PSPerfCountersMgr() { _CounterSetIdToInstanceMapping = new ConcurrentDictionary<Guid, CounterSetInstanceBase>(); _CounterSetNameToIdMapping = new ConcurrentDictionary<string, Guid>(); } #endregion #endregion #region Desctructor /// <summary> /// Destructor which will trigger the cleanup of internal data structures and /// disposal of counter set instances. /// </summary> ~PSPerfCountersMgr() { RemoveAllCounterSets(); } #endregion #region Public Methods /// <summary> /// Getter method to retrieve the singleton instance of the PSPerfCountersMgr. /// </summary> public static PSPerfCountersMgr Instance { get { return s_PSPerfCountersMgrInstance ?? (s_PSPerfCountersMgrInstance = new PSPerfCountersMgr()); } } /// <summary> /// Helper method to generate an instance name for a counter set. /// </summary> public string GetCounterSetInstanceName() { Process currentProcess = Process.GetCurrentProcess(); string pid = String.Format(CultureInfo.InvariantCulture, "{0}", currentProcess.Id); return pid; } /// <summary> /// Method to determine whether the counter set given by 'counterSetName' is /// registered with the system. If true, then counterSetId is populated. /// </summary> public bool IsCounterSetRegistered(string counterSetName, out Guid counterSetId) { counterSetId = new Guid(); if (counterSetName == null) { ArgumentNullException argNullException = new ArgumentNullException("counterSetName"); _tracer.TraceException(argNullException); return false; } return _CounterSetNameToIdMapping.TryGetValue(counterSetName, out counterSetId); } /// <summary> /// Method to determine whether the counter set given by 'counterSetId' is /// registered with the system. If true, then CounterSetInstance is populated. /// </summary> public bool IsCounterSetRegistered(Guid counterSetId, out CounterSetInstanceBase counterSetInst) { return _CounterSetIdToInstanceMapping.TryGetValue(counterSetId, out counterSetInst); } /// <summary> /// Method to register a counter set with the Performance Counters Manager. /// </summary> public bool AddCounterSetInstance(CounterSetRegistrarBase counterSetRegistrarInstance) { if (counterSetRegistrarInstance == null) { ArgumentNullException argNullException = new ArgumentNullException("counterSetRegistrarInstance"); _tracer.TraceException(argNullException); return false; } Guid counterSetId = counterSetRegistrarInstance.CounterSetId; string counterSetName = counterSetRegistrarInstance.CounterSetName; CounterSetInstanceBase counterSetInst = null; if (this.IsCounterSetRegistered(counterSetId, out counterSetInst)) { InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "A Counter Set Instance with id '{0}' is already registered", counterSetId)); _tracer.TraceException(invalidOperationException); return false; } try { if (!string.IsNullOrWhiteSpace(counterSetName)) { Guid retrievedCounterSetId; // verify that there doesn't exist another counter set with the same name if (this.IsCounterSetRegistered(counterSetName, out retrievedCounterSetId)) { InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "A Counter Set Instance with name '{0}' is already registered", counterSetName)); _tracer.TraceException(invalidOperationException); return false; } _CounterSetNameToIdMapping.TryAdd(counterSetName, counterSetId); } _CounterSetIdToInstanceMapping.TryAdd( counterSetId, counterSetRegistrarInstance.CounterSetInstance); } catch (OverflowException overflowException) { _tracer.TraceException(overflowException); return false; } return true; } /// <summary> /// If IsNumerator is true, then updates the numerator component /// of target counter 'counterId' in Counter Set 'counterSetId' /// by 'stepAmount'. /// Otherwise, updates the denominator component by 'stepAmount'. /// </summary> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public bool UpdateCounterByValue( Guid counterSetId, int counterId, long stepAmount = 1, bool isNumerator = true) { CounterSetInstanceBase counterSetInst = null; if (this.IsCounterSetRegistered(counterSetId, out counterSetInst)) { return counterSetInst.UpdateCounterByValue(counterId, stepAmount, isNumerator); } else { InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "No Counter Set Instance with id '{0}' is registered", counterSetId)); _tracer.TraceException(invalidOperationException); return false; } } /// <summary> /// If IsNumerator is true, then updates the numerator component /// of target counter 'counterName' in Counter Set 'counterSetId' /// by 'stepAmount'. /// Otherwise, updates the denominator component by 'stepAmount'. /// </summary> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public bool UpdateCounterByValue( Guid counterSetId, string counterName, long stepAmount = 1, bool isNumerator = true) { CounterSetInstanceBase counterSetInst = null; if (this.IsCounterSetRegistered(counterSetId, out counterSetInst)) { return counterSetInst.UpdateCounterByValue(counterName, stepAmount, isNumerator); } else { InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "No Counter Set Instance with id '{0}' is registered", counterSetId)); _tracer.TraceException(invalidOperationException); return false; } } /// <summary> /// If IsNumerator is true, then updates the numerator component /// of target counter 'counterId' in Counter Set 'counterSetName' /// by 'stepAmount'. /// Otherwise, updates the denominator component by 'stepAmount'. /// </summary> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public bool UpdateCounterByValue( string counterSetName, int counterId, long stepAmount = 1, bool isNumerator = true) { if (counterSetName == null) { ArgumentNullException argNullException = new ArgumentNullException("counterSetName"); _tracer.TraceException(argNullException); return false; } Guid counterSetId; if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) { CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; return counterSetInst.UpdateCounterByValue(counterId, stepAmount, isNumerator); } else { InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "No Counter Set Instance with id '{0}' is registered", counterSetId)); _tracer.TraceException(invalidOperationException); return false; } } /// <summary> /// If IsNumerator is true, then updates the numerator component /// of target counter 'counterName' in Counter Set 'counterSetName' /// by 'stepAmount'. /// Otherwise, updates the denominator component by 'stepAmount'. /// </summary> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public bool UpdateCounterByValue( string counterSetName, string counterName, long stepAmount = 1, bool isNumerator = true) { Guid counterSetId; if (counterSetName == null) { ArgumentNullException argNullException = new ArgumentNullException("counterSetName"); _tracer.TraceException(argNullException); return false; } if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) { CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; return counterSetInst.UpdateCounterByValue(counterName, stepAmount, isNumerator); } else { InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "No Counter Set Instance with name {0} is registered", counterSetName)); _tracer.TraceException(invalidOperationException); return false; } } /// <summary> /// If IsNumerator is true, then sets the numerator component /// of target counter 'counterId' in Counter Set 'counterSetId' /// to 'counterValue'. /// Otherwise, updates the denominator component to 'counterValue'. /// </summary> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public bool SetCounterValue( Guid counterSetId, int counterId, long counterValue = 1, bool isNumerator = true) { CounterSetInstanceBase counterSetInst = null; if (this.IsCounterSetRegistered(counterSetId, out counterSetInst)) { return counterSetInst.SetCounterValue(counterId, counterValue, isNumerator); } else { InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "No Counter Set Instance with id '{0}' is registered", counterSetId)); _tracer.TraceException(invalidOperationException); return false; } } /// <summary> /// If IsNumerator is true, then sets the numerator component /// of target counter 'counterName' in Counter Set 'counterSetId' /// to 'counterValue'. /// Otherwise, updates the denominator component to 'counterValue'. /// </summary> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public bool SetCounterValue( Guid counterSetId, string counterName, long counterValue = 1, bool isNumerator = true) { CounterSetInstanceBase counterSetInst = null; if (this.IsCounterSetRegistered(counterSetId, out counterSetInst)) { return counterSetInst.SetCounterValue(counterName, counterValue, isNumerator); } else { InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "No Counter Set Instance with id '{0}' is registered", counterSetId)); _tracer.TraceException(invalidOperationException); return false; } } /// <summary> /// If IsNumerator is true, then sets the numerator component /// of target counter 'counterId' in Counter Set 'counterSetName' /// to 'counterValue'. /// Otherwise, updates the denominator component to 'counterValue'. /// </summary> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public bool SetCounterValue( string counterSetName, int counterId, long counterValue = 1, bool isNumerator = true) { if (counterSetName == null) { ArgumentNullException argNullException = new ArgumentNullException("counterSetName"); _tracer.TraceException(argNullException); return false; } Guid counterSetId; if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) { CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; return counterSetInst.SetCounterValue(counterId, counterValue, isNumerator); } else { InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "No Counter Set Instance with name '{0}' is registered", counterSetName)); _tracer.TraceException(invalidOperationException); return false; } } /// <summary> /// If IsNumerator is true, then sets the numerator component /// of target counter 'counterName' in Counter Set 'counterSetName' /// to 'counterValue'. /// Otherwise, updates the denominator component to 'counterValue'. /// </summary> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public bool SetCounterValue( string counterSetName, string counterName, long counterValue = 1, bool isNumerator = true) { if (counterSetName == null) { ArgumentNullException argNullException = new ArgumentNullException("counterSetName"); _tracer.TraceException(argNullException); return false; } Guid counterSetId; if (this.IsCounterSetRegistered(counterSetName, out counterSetId)) { CounterSetInstanceBase counterSetInst = _CounterSetIdToInstanceMapping[counterSetId]; return counterSetInst.SetCounterValue(counterName, counterValue, isNumerator); } else { InvalidOperationException invalidOperationException = new InvalidOperationException( String.Format( CultureInfo.InvariantCulture, "No Counter Set Instance with name '{0}' is registered", counterSetName)); _tracer.TraceException(invalidOperationException); return false; } } #endregion #region Internal Methods /// <summary> /// NOTE: This method is provided solely for testing purposes. /// </summary> internal void RemoveAllCounterSets() { ICollection<Guid> counterSetIdKeys = _CounterSetIdToInstanceMapping.Keys; foreach (Guid counterSetId in counterSetIdKeys) { CounterSetInstanceBase currentCounterSetInstance = _CounterSetIdToInstanceMapping[counterSetId]; currentCounterSetInstance.Dispose(); } _CounterSetIdToInstanceMapping.Clear(); _CounterSetNameToIdMapping.Clear(); } #endregion } }
41.088553
119
0.57848
[ "Apache-2.0", "MIT" ]
HydAu/PowerShell
src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs
19,026
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace DotNetFileUtils { /// <summary> /// Represents a search scope. /// </summary> public enum SearchScope { /// <summary> /// The current directory. /// </summary> Current, /// <summary> /// The current directory and child directories. /// </summary> Recursive } }
25.636364
71
0.599291
[ "MIT" ]
systemmetaphor/shapeflow
src/external/DotNetFileUtils/SearchScope.cs
566
C#
using System; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Media.Effects; using AuroraGUI.Fx; using Microsoft.Win32; namespace AuroraGUI { /// <summary> /// ExpertWindow.xaml 的交互逻辑 /// </summary> public partial class ExpertWindow { public ExpertWindow() { InitializeComponent(); WindowBlur.SetEnabled(this, true); Snackbar.IsActive = true; Card.Effect = new BlurEffect() { Radius = 10 , RenderingBias = RenderingBias.Quality }; } private void SnackbarMessage_OnActionClick(object sender, RoutedEventArgs e) { Card.IsEnabled = true; Snackbar.IsActive = false; Card.Effect = null; } private void ReadDoHListButton_OnClick(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "list files (*.list)|*.list|txt files (*.txt)|*.txt|All files (*.*)|*.*", RestoreDirectory = true }; if (openFileDialog.ShowDialog() == true) { try { if (string.IsNullOrWhiteSpace(File.ReadAllText(openFileDialog.FileName))) Snackbar.MessageQueue.Enqueue(new TextBlock() { Text = @"Error: 无效的空文件。" }); else { File.Copy(openFileDialog.FileName, $"{MainWindow.SetupBasePath}doh.list"); Snackbar.MessageQueue.Enqueue(new TextBlock() { Text = @"导入成功!" }); } } catch (Exception ex) { MessageBox.Show("Error: 无法写入文件 \n\rOriginal error: " + ex.Message); } } } private void ReadDNSListButton_OnClick(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "list files (*.list)|*.list|txt files (*.txt)|*.txt|All files (*.*)|*.*", RestoreDirectory = true }; if (openFileDialog.ShowDialog() == true) { try { if (string.IsNullOrWhiteSpace(File.ReadAllText(openFileDialog.FileName))) Snackbar.MessageQueue.Enqueue(new TextBlock() { Text = @"Error: 无效的空文件。" }); else { File.Copy(openFileDialog.FileName, $"{MainWindow.SetupBasePath}dns.list"); Snackbar.MessageQueue.Enqueue(new TextBlock() { Text = @"导入成功!" }); } } catch (Exception ex) { MessageBox.Show("Error: 无法写入文件 \n\rOriginal error: " + ex.Message); } } } private void ReadChinaListButton_OnClick(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "list files (*.list)|*.list|txt files (*.txt)|*.txt|All files (*.*)|*.*", RestoreDirectory = true }; if (openFileDialog.ShowDialog() == true) { try { if (string.IsNullOrWhiteSpace(File.ReadAllText(openFileDialog.FileName))) Snackbar.MessageQueue.Enqueue(new TextBlock() { Text = @"Error: 无效的空文件。" }); else { File.Copy(openFileDialog.FileName, $"{MainWindow.SetupBasePath}china.list"); Snackbar.MessageQueue.Enqueue(new TextBlock() { Text = @"导入成功!" }); } } catch (Exception ex) { MessageBox.Show("Error: 无法写入文件 \n\rOriginal error: " + ex.Message); } } } private void Boom_OnClick(object sender, RoutedEventArgs e) { throw new Exception("Boom"); } } }
35.516949
100
0.491768
[ "MIT" ]
jarodvip/AuroraDNS.GUI
AuroraGUI/ExpertWindow.xaml.cs
4,305
C#
using System; using Microsoft.Extensions.DependencyInjection; namespace Shiny.Net.Http { public static class ServiceCollectionExtensions { public static void UseHttpClientTransfers<T>(this IServiceCollection builder) where T : class, IHttpTransferDelegate { builder.AddSingleton<IHttpTransferDelegate, T>(); builder.AddStartupSingleton<IHttpTransferManager, HttpClientHttpTransferManager>(); } public static void UseHttpTransfers<T>(this IServiceCollection builder) where T : class, IHttpTransferDelegate { #if NETSTANDARD builder.UseHttpClientTransfers<T>(); #elif WINDOWS_UWP || __IOS__ builder.AddSingleton<IHttpTransferDelegate, T>(); builder.AddStartupSingleton<IHttpTransferManager, HttpTransferManager>(); #elif __ANDROID__ builder.AddSingleton<IHttpTransferDelegate, T>(); builder.AddSingleton<IHttpTransferManager, HttpTransferManager>(); #endif } } }
33.666667
124
0.711881
[ "MIT" ]
jamesmontemagno/shiny
src/Shiny.Net.Http/Platforms/Shared/ServiceCollectionExtensions.cs
1,012
C#