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.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("XFDemo01.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XFDemo01.iOS")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("72bdc44f-c588-44f3-b6df-9aace7daafdd")] // 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.756757
84
0.743737
[ "Apache-2.0" ]
g1357/XamarinFormsDemo
XFDemo01/XFDemo01/XFDemo01.iOS/Properties/AssemblyInfo.cs
1,400
C#
using Lasm.UAlive; using Ludiq.Bolt; [assembly: RegisterCodeGenerator(typeof(Break), typeof(BreakLiveGenerator))] namespace Lasm.UAlive { public class BreakLiveGenerator : LiveUnitGenerator<Break> { public BreakLiveGenerator(Break unit) : base(unit) { } public override string GenerateControlInput(ControlInput input, int indent) { return "break;"; } public override string GenerateValueOutput(ValueOutput output, int indent) { return string.Empty; } } }
21.884615
83
0.637961
[ "MIT" ]
Tanner555/UAlive
UAlive/Editor/Generation/Units/Flow/BreakLiveGenerator.cs
571
C#
using System.Xml.Linq; namespace Xbrl.Discovery.Entities.xbrldt { public class DimensionLoc : ItemLoc { public DimensionLoc(link.DefinitionLink parent, XElement xElement) : base(parent, xElement) { } } }
21.272727
99
0.683761
[ "MIT" ]
OpenSBR/RGS.Taxonomy.Reader
Xbrl Discovery/Entities/xbrldt/DimensionLoc.cs
236
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace VitDeck.Validator.BoundsIndicators { [ExecuteInEditMode] public class BoothRangeIndicator : MonoBehaviour, IBoothRoot { [System.NonSerialized] bool initialized = false; private Bounds bounds; public void Initialize(Bounds bounds, ResetToken token) { this.bounds = bounds; if (token != null) { token.Reset += Token_Reset; } initialized = true; } private void Token_Reset() { SafeDestroy(); } private void Update() { if (!initialized) { SafeDestroy(); } } private void SafeDestroy() { if (Application.isPlaying) { Destroy(this); } else { DestroyImmediate(this); } } public Bounds GetBounds() { return GetActiveBounds(); } private void OnDrawGizmos() { var activeBounds = GetActiveBounds(); Gizmos.color = Color.green; Gizmos.matrix = GetLocalToWorld(); Gizmos.DrawWireCube(activeBounds.center, activeBounds.size); } Bounds GetActiveBounds() { //var activeBounds = bounds; //activeBounds.center = activeBounds.center + transform.position; return bounds; } public Matrix4x4 GetWorldToLocal() { return transform.worldToLocalMatrix; } public Matrix4x4 GetLocalToWorld() { return transform.localToWorldMatrix; } private TransformMemory memory = null; public void ClearTransformTemporarily() { if (memory == null) { memory = TransformMemory.SaveAndReset(transform); } } public void RestorePosition() { memory.Apply(transform); memory = null; } } }
22.854167
77
0.502735
[ "MIT" ]
Morijellyfish/VitDeck-for-paraket
Assets/VitDeck/Validator/Runtime/BoundsIndicators/BoothRangeIndicator.cs
2,194
C#
using System.Collections.Generic; using System; using System.IO; using System.Text.Json; using System.Text.Json.Serialization; using System.Linq; using Microsoft.AspNetCore.Hosting; using webapp.Models; namespace webapp.Services { public class JsonFileAccountService { public IEnumerable<Account> GetAccounts() { String file = "data/account.json"; using (StreamReader r = new StreamReader(file)) { string data = r.ReadToEnd(); var json = JsonSerializer.Deserialize<Account[]>( data, new JsonSerializerOptions { PropertyNameCaseInsensitive = true } ); return json; } } } }
25.1875
65
0.555831
[ "MIT" ]
thecaptainfluffy/websoft
work/s07/webapp/Services/JsonFileAccountService.cs
806
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DocumentDB.V20200401.Outputs { [OutputType] public sealed class DatabaseAccountConnectionStringResponseResult { /// <summary> /// Value of the connection string /// </summary> public readonly string ConnectionString; /// <summary> /// Description of the connection string /// </summary> public readonly string Description; [OutputConstructor] private DatabaseAccountConnectionStringResponseResult( string connectionString, string description) { ConnectionString = connectionString; Description = description; } } }
27.944444
81
0.66004
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/DocumentDB/V20200401/Outputs/DatabaseAccountConnectionStringResponseResult.cs
1,006
C#
using NLog.Layouts; namespace PeinearyDevelopment.Framework.Logging.NLog.Core.TargetGenerators { public interface IBaseParameterInformation { string Name { get; set; } Layout Layout { get; set; } } }
20.909091
74
0.686957
[ "MIT" ]
PdFramework/Logging
NLog.Core/TargetGenerators/IBaseParameterInformation.cs
232
C#
using Sabio.Web.Domain; using Sabio.Web.Models; using Sabio.Web.Models.Requests; using Sabio.Web.Models.Responses; using Sabio.Web.Requests; using Sabio.Web.Services; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace Sabio.Web.Controllers.Api { [RoutePrefix("api/globalevents")] public class GlobalEventsApiController : ApiController { IGlobalEventService _globalEventService = null; INotificationService _notificationService = null; public GlobalEventsApiController(IGlobalEventService globalEventService, INotificationService notificationService) { _globalEventService = globalEventService; _notificationService = notificationService; } [Route, HttpPost] public HttpResponseMessage Create(GlobalEventAddRequest model) { if (!ModelState.IsValid) { return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } ItemResponse<int> response = new ItemResponse<int>(); response.Item = _globalEventService.Insert(model); _notificationService.GlobalEvent(response.Item, Enums.EventActionType.Created); return Request.CreateResponse(HttpStatusCode.Created, response); } [Route("{id:int}"), HttpPut] public HttpResponseMessage Update(GlobalEventUpdateRequest model) { if (!ModelState.IsValid) { return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState); } _globalEventService.Update(model); _notificationService.GlobalEvent(model.Id, Enums.EventActionType.Modified); SuccessResponse response = new SuccessResponse(); return Request.CreateResponse(HttpStatusCode.OK, response); } [Route("{id:int}"), HttpGet] public HttpResponseMessage ReadById(int id) { ItemResponse<GlobalEvent> response = new ItemResponse<GlobalEvent>(); response.Item = _globalEventService.SelectById(id); return Request.CreateResponse(HttpStatusCode.OK, response); } [Route, HttpGet] public HttpResponseMessage ReadAll() { ItemsResponse<GlobalEvent> response = new ItemsResponse<GlobalEvent>(); response.Items = _globalEventService.SelectAll(); return Request.CreateResponse(HttpStatusCode.OK, response); } [Route("c"), HttpGet] public HttpResponseMessage ReadAllCalendar() { ItemsResponse<GlobalEvent> response = new ItemsResponse<GlobalEvent>(); response.Items = _globalEventService.SelectAllCalendar(); return Request.CreateResponse(HttpStatusCode.OK, response); } [Route("{id:int}"), HttpDelete] public HttpResponseMessage Delete(int id) { _globalEventService.Delete(id); _notificationService.GlobalEvent(id, Enums.EventActionType.Cancelled); SuccessResponse response = new SuccessResponse(); return Request.CreateResponse(HttpStatusCode.OK, response); } [Route("cancel/{id:int}"), HttpPut] public HttpResponseMessage Cancel(int id) { _globalEventService.Cancel(id); SuccessResponse response = new SuccessResponse(); return Request.CreateResponse(HttpStatusCode.OK, response); } [Route("radius"), HttpGet] public HttpResponseMessage SearchByRadius([FromUri]GlobalEventSearchRadiusRequest model) { ItemsResponse<GlobalEvent> response = new ItemsResponse<GlobalEvent>(); response.Items = _globalEventService.SearchByRadius(model); return Request.CreateResponse(HttpStatusCode.OK, response); } [Route("search"), HttpGet] public HttpResponseMessage Search([FromUri]GlobalEventSearchRequest model) { ItemsResponse<GlobalEvent> response = new ItemsResponse<GlobalEvent>(); response.Items = _globalEventService.Search(model); return Request.CreateResponse(HttpStatusCode.OK, response); } } }
33.030534
122
0.657499
[ "MIT" ]
entrotech/deployapp
Sabio.Web/Controllers/Api/GlobalEventsApiController.cs
4,329
C#
using Xamarin.Forms; namespace SmartHotel.Clients.Core.Effects { public class UnderlineTextEffect : RoutingEffect { public UnderlineTextEffect() : base("SmartHotel.UnderlineTextEffect") { } } }
19.333333
77
0.668103
[ "MIT" ]
ATH89/SmartHotel360_w8bghybo
Source/SmartHotel.Clients/SmartHotel.Clients/Effects/UnderlineTextEffect.cs
234
C#
// Copyright (c) Jan Škoruba. All Rights Reserved. // Licensed under the Apache License, Version 2.0. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace SkorubaDuende.IdentityServerAdmin.Admin.Api.Dtos.Clients { public class ClientApiDto { public ClientApiDto() { AllowedScopes = new List<string>(); PostLogoutRedirectUris = new List<string>(); RedirectUris = new List<string>(); IdentityProviderRestrictions = new List<string>(); AllowedCorsOrigins = new List<string>(); AllowedGrantTypes = new List<string>(); Claims = new List<ClientClaimApiDto>(); Properties = new List<ClientPropertyApiDto>(); } public int AbsoluteRefreshTokenLifetime { get; set; } = 2592000; public int AccessTokenLifetime { get; set; } = 3600; public int? ConsentLifetime { get; set; } public int AccessTokenType { get; set; } public bool AllowAccessTokensViaBrowser { get; set; } public bool AllowOfflineAccess { get; set; } public bool AllowPlainTextPkce { get; set; } public bool AllowRememberConsent { get; set; } = true; public bool AlwaysIncludeUserClaimsInIdToken { get; set; } public bool AlwaysSendClientClaims { get; set; } public int AuthorizationCodeLifetime { get; set; } = 300; public string FrontChannelLogoutUri { get; set; } public bool FrontChannelLogoutSessionRequired { get; set; } = true; public string BackChannelLogoutUri { get; set; } public bool BackChannelLogoutSessionRequired { get; set; } = true; [Required] public string ClientId { get; set; } [Required] public string ClientName { get; set; } public string ClientUri { get; set; } public string Description { get; set; } public bool Enabled { get; set; } = true; public bool EnableLocalLogin { get; set; } = true; public int Id { get; set; } public int IdentityTokenLifetime { get; set; } = 300; public bool IncludeJwtId { get; set; } public string LogoUri { get; set; } public string ClientClaimsPrefix { get; set; } = "client_"; public string PairWiseSubjectSalt { get; set; } public string ProtocolType { get; set; } = "oidc"; public int RefreshTokenExpiration { get; set; } = 1; public int RefreshTokenUsage { get; set; } = 1; public int SlidingRefreshTokenLifetime { get; set; } = 1296000; public bool RequireClientSecret { get; set; } = true; public bool RequireConsent { get; set; } = true; public bool RequirePkce { get; set; } public bool UpdateAccessTokenClaimsOnRefresh { get; set; } public List<string> PostLogoutRedirectUris { get; set; } public List<string> IdentityProviderRestrictions { get; set; } public List<string> RedirectUris { get; set; } public List<string> AllowedCorsOrigins { get; set; } public List<string> AllowedGrantTypes { get; set; } public List<string> AllowedScopes { get; set; } public List<ClientClaimApiDto> Claims { get; set; } public List<ClientPropertyApiDto> Properties { get; set; } public DateTime? Updated { get; set; } public DateTime? LastAccessed { get; set; } public int? UserSsoLifetime { get; set; } public string UserCodeType { get; set; } public int DeviceCodeLifetime { get; set; } = 300; public bool RequireRequestObject { get; set; } public int? CibaLifetime { get; set; } public int? PollingInterval { get; set; } public List<string> AllowedIdentityTokenSigningAlgorithms { get; set; } public bool NonEditable { get; set; } } }
32.831933
79
0.630151
[ "Apache-2.0" ]
CentauriConsulting/Duende.IdentityServer.Admin
templates/template-publish/content/src/SkorubaDuende.IdentityServerAdmin.Admin.Api/Dtos/Clients/ClientApiDto.cs
3,910
C#
using System; using System.Collections.Generic; using System.Linq; namespace IEnumerableExtensionsMain { public static class IEnumerableExtensions { public static T Sum<T>(this IEnumerable<T> collection) where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T> { if (collection == null) { throw new ArgumentNullException("The collection is empty or isn't initialized!"); } else { T sum = default(T); foreach (var item in collection) { sum += (dynamic)item; } return sum; } } public static T Product<T>(this IEnumerable<T> collection) where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T> { if (collection == null) { throw new ArgumentNullException("The collection is empty or isn't initialized!"); } else { T product = (dynamic)1; foreach (var item in collection) { product *= (dynamic)item; } return product; } } public static T Min<T>(this IEnumerable<T> collection) where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T> { if (collection == null) { throw new ArgumentNullException("The collection is empty or isn't initialized!"); } else { T min = collection.First(); foreach (var item in collection) { if (min.CompareTo(item) > 0) { min = item; } } return min; } } public static T Max<T>(this IEnumerable<T> collection) where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T> { if (collection == null) { throw new ArgumentNullException("The collection is empty or isn't initialized!"); } else { T max = default(T); foreach (var item in collection) { if (max.CompareTo(item) < 0) { max = item; } } return max; } } public static T Average<T>(this IEnumerable<T> collection) where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T> { if (collection == null) { throw new ArgumentNullException("The collection is empty or isn't initialized!"); } else { T result = default(T); int counter = 0; foreach (var item in collection) { result += (dynamic)item; counter++; } return result / (dynamic)counter; } } } }
28.516949
97
0.451412
[ "MIT" ]
frostblooded/TelerikHomework
OOP/ExtensionMethodsDelegatesLambdaLINQ/IEnumerableExtensionsMain/IEnumerableExtensions.cs
3,367
C#
using System.Net; using System.Threading.Tasks; using Lykke.Service.ConfirmationCodes.Client.Models.Request; using Lykke.Service.ConfirmationCodes.Client.Models.Response; using Lykke.Service.ConfirmationCodes.Core.Entities; using Lykke.Service.ConfirmationCodes.Core.Services; using Lykke.Service.ConfirmationCodes.Services; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.SwaggerGen; namespace Lykke.Service.ConfirmationCodes.Controllers { [Route("api/[controller]")] [ModelStateValidationActionFilter] public class EmailConfirmationController : Controller { private readonly IEmailConfirmationService _emailConfirmationService; public EmailConfirmationController(IEmailConfirmationService emailConfirmationService) { _emailConfirmationService = emailConfirmationService; } /// <summary> /// Generates code and sends it to specified phone number using email. Code will be persisted. /// </summary> /// <returns></returns> [HttpPost] [ProducesResponseType((int)HttpStatusCode.OK)] public async Task<IActionResult> Post([FromBody]SendEmailConfirmationRequest model) { await _emailConfirmationService.SendConfirmEmail(model.Email, model.PartnerId, model.IsPriority); return Ok(); } /// <summary> /// Verifies code for specified email. /// </summary> /// <returns> /// VerificationResult /// If code matched to stored one, IsValid flag will be set to "true" /// </returns> [HttpPost] [SwaggerOperation("VerifyCode")] [Route("VerifyCode")] [ProducesResponseType(typeof(VerificationResult), (int)HttpStatusCode.OK)] public async Task<IActionResult> VerifyCode([FromBody]VerifyEmailConfirmationRequest model) { var isValid = await _emailConfirmationService.CheckAsync(model.Email, model.PartnerId, model.Code); return Ok(new VerificationResult{IsValid = isValid }); } /// <summary> /// Get actual code /// </summary> /// <returns></returns> [HttpGet] [SwaggerOperation("GetEmailPriorityCode")] [Route("GetEmailPriorityCode")] [ProducesResponseType(typeof(EmailVerificationCode), (int) HttpStatusCode.OK)] public async Task<IActionResult> GetEmailPriorityCode(EmailConfirmationRequest model) { var result = await _emailConfirmationService.GetPriorityCode(model.Email, model.PartnerId); if (result == null) { return BadRequest("Code not found."); } var response = new EmailVerificationCode(result.Code, result.CreationDateTime, result.ExpirationDate); return Ok(response); } /// <summary> /// Removes codes /// </summary> /// <returns></returns> [HttpDelete] [SwaggerOperation("Delete")] [ProducesResponseType(typeof(string), (int)HttpStatusCode.OK)] public async Task<IActionResult> Delete([FromBody]EmailConfirmationRequest model) { await _emailConfirmationService.DeleteCodes(model.Email, model.PartnerId); return Ok(); } } }
36.593407
114
0.656156
[ "MIT" ]
LykkeCity/Lykke.Service.ConfirmationCodes
src/Lykke.Service.ConfirmationCodes/Controllers/EmailConfirmationController.cs
3,332
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace Sample { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } } }
17.368421
47
0.672727
[ "MIT" ]
AswinPG/ImageFromXamarinUI
Sample/Sample/MainPage.xaml.cs
332
C#
using System; using System.Threading.Tasks; namespace Plugin.Firebase.Firestore { /// <summary> /// Represents a Firestore Database and is the entry point for all Firestore operations. /// </summary> public interface IFirebaseFirestore : IDisposable { /// <summary> /// Gets a <c>ICollectionReference</c> object referring to the collection at the specified path within the database. /// </summary> /// <param name="collectionPath">The slash-separated path of the collection for which to get a <c>ICollectionReference</c>.</param> /// <returns></returns> ICollectionReference GetCollection(string collectionPath); /// <summary> /// Gets a <c>IDocumentReference</c> object referring to the document at the specified path within the database. /// </summary> /// <param name="documentPath">The slash-separated path of the document for which to get a <c>IDocumentReference</c>.</param> /// <returns></returns> IDocumentReference GetDocument(string documentPath); /// <summary> /// Executes the given updateBlock and then attempts to commit the changes applied within an atomic transaction. /// </summary> /// <param name="updateFunc">The func to execute within the transaction context.</param> /// <typeparam name="TResult">The type of the result returned by updateFunc.</typeparam> /// <returns></returns> Task<TResult> RunTransactionAsync<TResult>(Func<ITransaction, TResult> updateFunc); /// <summary> /// Creates a write batch, used for performing multiple writes as a single atomic operation. /// </summary> /// <returns></returns> IWriteBatch CreateBatch(); /// <summary> /// Modifies this FirebaseDatabase instance to communicate with the Cloud Firestore emulator. /// Note: Call this method before using the instance to do any database operations. /// </summary> /// <param name="host">The emulator host (for example, 10.0.2.2 on android and localhost on iOS)</param> /// <param name="port">The emulator port (for example, 8080)</param> void UseEmulator(string host, int port); /// <summary> /// Custom settings used to configure this <c>IFirebaseFirestore</c> object. /// </summary> FirestoreSettings Settings { get; set; } } }
46.942308
139
0.650553
[ "MIT" ]
Kapusch/Plugin.Firebase
src/Shared/Firestore/IFirebaseFirestore.cs
2,441
C#
//----------------------------------------------------------------------- // <copyright file="TransitionSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Immutable; using System.Linq; using Akka.Actor; using Akka.Cluster.TestKit; using Akka.Configuration; using Akka.Remote.TestKit; using FluentAssertions; namespace Akka.Cluster.Tests.MultiNode { public class TransitionSpecConfig : MultiNodeConfig { public RoleName First { get; } public RoleName Second { get; } public RoleName Third { get; } public TransitionSpecConfig() { First = Role("first"); Second = Role("second"); Third = Role("third"); CommonConfig = DebugConfig(false) .WithFallback(ConfigurationFactory.ParseString(@" akka.cluster.periodic-tasks-initial-delay = 300s akka.cluster.publish-stats-interval = 0s ")) .WithFallback(MultiNodeClusterSpec.ClusterConfigWithFailureDetectorPuppet()); } } public class TransitionSpec : MultiNodeClusterSpec { private readonly TransitionSpecConfig _config; public TransitionSpec() : this(new TransitionSpecConfig()) { } protected TransitionSpec(TransitionSpecConfig config) : base(config, typeof(TransitionSpec)) { _config = config; } private RoleName Leader(params RoleName[] roles) { // sorts the addresses and provides the address of the node with the lowest port number // as that node will be the leader return roles.Select(x => Tuple.Create(x, GetAddress(x).Port)).OrderBy(x => x.Item2).First().Item1; } private RoleName[] NonLeader(params RoleName[] roles) { return roles.Skip(1).ToArray(); } private MemberStatus MemberStatus(Address address) { var status = ClusterView.Members.Union(ClusterView.UnreachableMembers) .Where(m => m.Address == address) .Select(m => m.Status) .ToList(); if (status.Any()) { return status.First(); } else { return Akka.Cluster.MemberStatus.Removed; } } private ImmutableHashSet<Address> MemberAddresses() { return ClusterView.Members.Select(c => c.Address).ToImmutableHashSet(); } private ImmutableHashSet<RoleName> Members() { return MemberAddresses().Select(RoleName).ToImmutableHashSet(); } private ImmutableHashSet<RoleName> SeenLatestGossip() { return ClusterView.SeenBy.Select(RoleName).ToImmutableHashSet(); } private void AwaitSeen(params Address[] addresses) { AwaitAssert(() => { SeenLatestGossip().Select(GetAddress).Should().BeEquivalentTo(addresses.ToImmutableHashSet()); }); } private void AwaitMembers(params Address[] addresses) { AwaitAssert(() => { ClusterView.RefreshCurrentState(); MemberAddresses().Should().BeEquivalentTo(addresses.ToImmutableHashSet()); }); } private void AwaitMemberStatus(Address address, MemberStatus status) { AwaitAssert(() => { ClusterView.RefreshCurrentState(); MemberStatus(address).Should().Be(status); }); } private void LeaderActions() { Cluster.ClusterCore.Tell(InternalClusterAction.LeaderActionsTick.Instance); } private void ReapUnreachable() { Cluster.ClusterCore.Tell(InternalClusterAction.ReapUnreachableTick.Instance); } private int _gossipBarrierCounter = 0; private void GossipTo(RoleName fromRole, RoleName toRole) { _gossipBarrierCounter++; RunOn(() => { var oldCount = ClusterView.LatestStats.GossipStats.ReceivedGossipCount; EnterBarrier("before-gossip-" + _gossipBarrierCounter); AwaitCondition(() => ClusterView.LatestStats.GossipStats.ReceivedGossipCount != oldCount); // received gossip AwaitCondition(() => ImmutableHashSet.Create(fromRole, toRole).Except(SeenLatestGossip()).IsEmpty); EnterBarrier("after-gossip-" + _gossipBarrierCounter); }, toRole); RunOn(() => { EnterBarrier("before-gossip-" + _gossipBarrierCounter); // send gossip Cluster.ClusterCore.Tell(new InternalClusterAction.SendGossipTo(GetAddress(toRole))); // gossip chat will synchronize the views AwaitCondition(() => ImmutableHashSet.Create(fromRole, toRole).Except(SeenLatestGossip()).IsEmpty); EnterBarrier("after-gossip-" + _gossipBarrierCounter); }, fromRole); RunOn(() => { EnterBarrier("before-gossip-" + _gossipBarrierCounter); EnterBarrier("after-gossip-" + _gossipBarrierCounter); }, Roles.Where(r => r != fromRole && r != toRole).ToArray()); } [MultiNodeFact] public void TransitionSpecs() { A_Cluster_must_start_nodes_as_singleton_clusters(); A_Cluster_must_perform_correct_transitions_when_second_joining_first(); A_Cluster_must_perform_correct_transitions_when_third_joins_second(); A_Cluster_must_perform_correct_transitions_when_second_becomes_unavailable(); } private void A_Cluster_must_start_nodes_as_singleton_clusters() { RunOn(() => { Cluster.Join(GetAddress(Myself)); // first joining itself will immediately be moved to Up AwaitMemberStatus(GetAddress(Myself), Akka.Cluster.MemberStatus.Up); AwaitCondition(() => ClusterView.IsSingletonCluster); }, _config.First); EnterBarrier("after-1"); } private void A_Cluster_must_perform_correct_transitions_when_second_joining_first() { RunOn(() => { Cluster.Join(GetAddress(_config.First)); }, _config.Second); RunOn(() => { // gossip chat from the join will synchronize the views AwaitMembers(GetAddress(_config.First), GetAddress(_config.Second)); AwaitMemberStatus(GetAddress(_config.First), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Joining); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.First, _config.Second))); }, _config.First, _config.Second); EnterBarrier("convergence-joining-2"); RunOn(() => { LeaderActions(); AwaitMemberStatus(GetAddress(_config.First), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Up); }, _config.First); EnterBarrier("leader-actions-2"); GossipTo(_config.First, _config.Second); RunOn(() => { // gossip chat will synchronize the views AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Up); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.First, _config.Second))); AwaitMemberStatus(GetAddress(_config.First), Akka.Cluster.MemberStatus.Up); }, _config.First, _config.Second); EnterBarrier("after-2"); } private void A_Cluster_must_perform_correct_transitions_when_third_joins_second() { RunOn(() => { Cluster.Join(GetAddress(_config.Second)); }, _config.Third); RunOn(() => { // gossip chat from the join will synchronize the views AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.Second, _config.Third))); }, _config.Second, _config.Third); EnterBarrier("third-joined-second"); GossipTo(_config.Second, _config.First); RunOn(() => { // gossip chat will synchronize the views AwaitMembers(GetAddress(_config.First), GetAddress(_config.Second), GetAddress(_config.Third)); AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Joining); AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Up); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.First, _config.Second, _config.Third))); }, _config.First, _config.Second); GossipTo(_config.First, _config.Third); RunOn(() => { AwaitMembers(GetAddress(_config.First), GetAddress(_config.Second), GetAddress(_config.Third)); AwaitMemberStatus(GetAddress(_config.First), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Joining); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.First, _config.Second, _config.Third))); }, _config.First, _config.Second, _config.Third); EnterBarrier("convergence-joining-3"); var leader12 = Leader(_config.First, _config.Second); Log.Debug("Leader: {0}", leader12); var tmp = Roles.Where(x => x != leader12).ToList(); var other1 = tmp.First(); var other2 = tmp.Skip(1).First(); RunOn(() => { LeaderActions(); AwaitMemberStatus(GetAddress(_config.First), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Up); }, leader12); EnterBarrier("leader-actions-3"); // leader gossipTo first non-leader GossipTo(leader12, other1); RunOn(() => { AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Up); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(leader12, Myself))); }, other1); // first non-leader gossipTo the other non-leader GossipTo(other1, other2); RunOn(() => { // send gossip Cluster.ClusterCore.Tell(new InternalClusterAction.SendGossipTo(GetAddress(other2))); }, other1); RunOn(() => { AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Up); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.First, _config.Second, _config.Third))); }, other2); // first non-leader gossipTo the leader GossipTo(other1, leader12); RunOn(() => { AwaitMemberStatus(GetAddress(_config.First), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Up); AwaitMemberStatus(GetAddress(_config.Third), Akka.Cluster.MemberStatus.Up); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.First, _config.Second, _config.Third))); }, _config.First, _config.Second, _config.Third); EnterBarrier("after-3"); } private void A_Cluster_must_perform_correct_transitions_when_second_becomes_unavailable() { RunOn(() => { MarkNodeAsUnavailable(GetAddress(_config.Second)); ReapUnreachable(); AwaitAssert(() => ClusterView.UnreachableMembers.Select(c => c.Address).Should().Contain(GetAddress(_config.Second))); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.Third))); }, _config.Third); EnterBarrier("after-second-unavailable"); GossipTo(_config.Third, _config.First); RunOn(() => { AwaitAssert(() => ClusterView.UnreachableMembers.Select(c => c.Address).Should().Contain(GetAddress(_config.Second))); }, _config.First, _config.Third); RunOn(() => { Cluster.Down(GetAddress(_config.Second)); }, _config.First); EnterBarrier("after-second-down"); GossipTo(_config.First, _config.Third); RunOn(() => { AwaitAssert(() => ClusterView.UnreachableMembers.Select(c => c.Address).Should().Contain(GetAddress(_config.Second))); AwaitMemberStatus(GetAddress(_config.Second), Akka.Cluster.MemberStatus.Down); AwaitAssert(() => SeenLatestGossip().Should().BeEquivalentTo(ImmutableHashSet.Create(_config.First, _config.Third))); }, _config.First, _config.Third); EnterBarrier("after-4"); } } }
40.907781
149
0.586051
[ "Apache-2.0" ]
IgorFedchenko/akka.net
src/core/Akka.Cluster.Tests.MultiNode/TransitionSpec.cs
14,197
C#
//----------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //----------------------------------------------------------------------- using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Runtime.Serialization; namespace HR.TA.Common.Common.Common.Email.Contracts { /// <summary> /// Specifies the Data Contract for Email Attachment Request /// </summary> [DataContract] public class FileAttachmentRequest { /// <summary> /// Gets or sets file which has attachment content /// </summary> [DataMember(Name = "files")] public IFormFileCollection Files { get; set; } /// <summary> /// Gets or sets name with which attachment should be tagged. /// </summary> [DataMember(Name = "fileLabels")] public IEnumerable<string> FileLabels { get; set; } } }
32.333333
73
0.54433
[ "MIT" ]
QPC-database/msrecruit-scheduling-engine
common/HR.TA.CommonLibrary/HR.TA.Common/Common/Common.Email/Contracts/FileAttachmentRequest.cs
970
C#
#region Copyright (c) 2017 Leoxia Ltd // -------------------------------------------------------------------------------------------------------------------- // <copyright file="ITextWriter.cs" company="Leoxia Ltd"> // Copyright (c) 2017 Leoxia Ltd // </copyright> // // .NET Software Development // https://www.leoxia.com // Build. Tomorrow. Together // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // -------------------------------------------------------------------------------------------------------------------- #endregion #region Usings using System; using System.Text; using System.Threading.Tasks; #endregion namespace Leoxia.Abstractions.IO { /// <summary>Represents a writer that can write a sequential series of characters. This class is abstract.</summary> /// <filterpriority>2</filterpriority> public interface ITextWriter : IDisposable { /// <summary>When overridden in a derived class, returns the character encoding in which the output is written.</summary> /// <returns>The character encoding in which the output is written.</returns> /// <filterpriority>1</filterpriority> Encoding Encoding { get; } /// <summary>Gets an object that controls formatting.</summary> /// <returns> /// An <see cref="T:System.IFormatProvider" /> object for a specific culture, or the formatting of the current /// culture if no other culture is specified. /// </returns> /// <filterpriority>2</filterpriority> IFormatProvider FormatProvider { get; } /// <summary>Gets or sets the line terminator string used by the current TextWriter.</summary> /// <returns>The line terminator string for the current TextWriter.</returns> /// <filterpriority>2</filterpriority> string NewLine { get; set; } /// <summary>Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.</summary> /// <filterpriority>1</filterpriority> void Flush(); /// <summary>Writes the text representation of a Boolean value to the text string or stream.</summary> /// <param name="value">The Boolean value to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void Write(bool value); /// <summary>Writes a character to the text string or stream.</summary> /// <param name="value">The character to write to the text stream. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void Write(char value); /// <summary>Writes a character array to the text string or stream.</summary> /// <param name="buffer">The character array to write to the text stream. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void Write(char[] buffer); /// <summary>Writes a subarray of characters to the text string or stream.</summary> /// <param name="buffer">The character array to write data from. </param> /// <param name="index">The character position in the buffer at which to start retrieving data. </param> /// <param name="count">The number of characters to write. </param> /// <exception cref="T:System.ArgumentException"> /// The buffer length minus <paramref name="index" /> is less than /// <paramref name="count" />. /// </exception> /// <exception cref="T:System.ArgumentNullException">The <paramref name="buffer" /> parameter is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index" /> or <paramref name="count" /> is negative. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void Write(char[] buffer, int index, int count); /// <summary>Writes the text representation of a decimal value to the text string or stream.</summary> /// <param name="value">The decimal value to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void Write(decimal value); /// <summary>Writes the text representation of an 8-byte floating-point value to the text string or stream.</summary> /// <param name="value">The 8-byte floating-point value to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void Write(double value); /// <summary>Writes the text representation of a 4-byte signed integer to the text string or stream.</summary> /// <param name="value">The 4-byte signed integer to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void Write(int value); /// <summary>Writes the text representation of an 8-byte signed integer to the text string or stream.</summary> /// <param name="value">The 8-byte signed integer to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void Write(long value); /// <summary> /// Writes the text representation of an object to the text string or stream by calling the ToString method on /// that object. /// </summary> /// <param name="value">The object to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void Write(object value); /// <summary>Writes the text representation of a 4-byte floating-point value to the text string or stream.</summary> /// <param name="value">The 4-byte floating-point value to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void Write(float value); /// <summary>Writes a string to the text string or stream.</summary> /// <param name="value">The string to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void Write(string value); /// <summary> /// Writes a formatted string to the text string or stream, using the same semantics as the /// <see cref="M:System.String.Format(System.String,System.Object)" /> method. /// </summary> /// <param name="format">A composite format string (see Remarks). </param> /// <param name="arg0">The object to format and write. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="format" /> is null. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.FormatException"> /// <paramref name="format" /> is not a valid composite format string.-or- The index of a format item is less than 0 /// (zero), or greater than or equal to the number of objects to be formatted (which, for this method overload, is /// one). /// </exception> /// <filterpriority>1</filterpriority> void Write(string format, object arg0); /// <summary> /// Writes a formatted string to the text string or stream, using the same semantics as the /// <see cref="M:System.String.Format(System.String,System.Object,System.Object)" /> method. /// </summary> /// <param name="format">A composite format string (see Remarks). </param> /// <param name="arg0">The first object to format and write. </param> /// <param name="arg1">The second object to format and write. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="format" /> is null. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.FormatException"> /// <paramref name="format" /> is not a valid composite format string.-or- The index of a format item is less than 0 /// (zero) or greater than or equal to the number of objects to be formatted (which, for this method overload, is two). /// </exception> /// <filterpriority>1</filterpriority> void Write(string format, object arg0, object arg1); /// <summary> /// Writes a formatted string to the text string or stream, using the same semantics as the /// <see cref="M:System.String.Format(System.String,System.Object,System.Object,System.Object)" /> method. /// </summary> /// <param name="format">A composite format string (see Remarks). </param> /// <param name="arg0">The first object to format and write. </param> /// <param name="arg1">The second object to format and write. </param> /// <param name="arg2">The third object to format and write. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="format" /> is null. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.FormatException"> /// <paramref name="format" /> is not a valid composite format string.-or- The index of a format item is less than 0 /// (zero), or greater than or equal to the number of objects to be formatted (which, for this method overload, is /// three). /// </exception> /// <filterpriority>1</filterpriority> void Write(string format, object arg0, object arg1, object arg2); /// <summary> /// Writes a formatted string to the text string or stream, using the same semantics as the /// <see cref="M:System.String.Format(System.String,System.Object[])" /> method. /// </summary> /// <param name="format">A composite format string (see Remarks). </param> /// <param name="arg">An object array that contains zero or more objects to format and write. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="format" /> or <paramref name="arg" /> is null. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.FormatException"> /// <paramref name="format" /> is not a valid composite format string.-or- The index of a format item is less than 0 /// (zero), or greater than or equal to the length of the <paramref name="arg" /> array. /// </exception> /// <filterpriority>1</filterpriority> void Write(string format, params object[] arg); /// <summary>Writes a line terminator to the text string or stream.</summary> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(); /// <summary>Writes the text representation of a Boolean value followed by a line terminator to the text string or stream.</summary> /// <param name="value">The Boolean value to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(bool value); /// <summary>Writes a character followed by a line terminator to the text string or stream.</summary> /// <param name="value">The character to write to the text stream. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(char value); /// <summary>Writes an array of characters followed by a line terminator to the text string or stream.</summary> /// <param name="buffer">The character array from which data is read. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(char[] buffer); /// <summary>Writes a subarray of characters followed by a line terminator to the text string or stream.</summary> /// <param name="buffer">The character array from which data is read. </param> /// <param name="index">The character position in <paramref name="buffer" /> at which to start reading data. </param> /// <param name="count">The maximum number of characters to write. </param> /// <exception cref="T:System.ArgumentException"> /// The buffer length minus <paramref name="index" /> is less than /// <paramref name="count" />. /// </exception> /// <exception cref="T:System.ArgumentNullException">The <paramref name="buffer" /> parameter is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index" /> or <paramref name="count" /> is negative. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(char[] buffer, int index, int count); /// <summary>Writes the text representation of a decimal value followed by a line terminator to the text string or stream.</summary> /// <param name="value">The decimal value to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(decimal value); /// <summary> /// Writes the text representation of a 8-byte floating-point value followed by a line terminator to the text /// string or stream. /// </summary> /// <param name="value">The 8-byte floating-point value to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(double value); /// <summary> /// Writes the text representation of a 4-byte signed integer followed by a line terminator to the text string or /// stream. /// </summary> /// <param name="value">The 4-byte signed integer to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(int value); /// <summary> /// Writes the text representation of an 8-byte signed integer followed by a line terminator to the text string or /// stream. /// </summary> /// <param name="value">The 8-byte signed integer to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(long value); /// <summary> /// Writes the text representation of an object by calling the ToString method on that object, followed by a line /// terminator to the text string or stream. /// </summary> /// <param name="value">The object to write. If <paramref name="value" /> is null, only the line terminator is written. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(object value); /// <summary> /// Writes the text representation of a 4-byte floating-point value followed by a line terminator to the text /// string or stream. /// </summary> /// <param name="value">The 4-byte floating-point value to write. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(float value); /// <summary>Writes a string followed by a line terminator to the text string or stream.</summary> /// <param name="value">The string to write. If <paramref name="value" /> is null, only the line terminator is written. </param> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <filterpriority>1</filterpriority> void WriteLine(string value); /// <summary> /// Writes a formatted string and a new line to the text string or stream, using the same semantics as the /// <see cref="M:System.String.Format(System.String,System.Object)" /> method. /// </summary> /// <param name="format">A composite format string (see Remarks).</param> /// <param name="arg0">The object to format and write. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="format" /> is null. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.FormatException"> /// <paramref name="format" /> is not a valid composite format string.-or- The index of a format item is less than 0 /// (zero), or greater than or equal to the number of objects to be formatted (which, for this method overload, is /// one). /// </exception> /// <filterpriority>1</filterpriority> void WriteLine(string format, object arg0); /// <summary> /// Writes a formatted string and a new line to the text string or stream, using the same semantics as the /// <see cref="M:System.String.Format(System.String,System.Object,System.Object)" /> method. /// </summary> /// <param name="format">A composite format string (see Remarks).</param> /// <param name="arg0">The first object to format and write. </param> /// <param name="arg1">The second object to format and write. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="format" /> is null. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.FormatException"> /// <paramref name="format" /> is not a valid composite format string.-or- The index of a format item is less than 0 /// (zero), or greater than or equal to the number of objects to be formatted (which, for this method overload, is /// two). /// </exception> /// <filterpriority>1</filterpriority> void WriteLine(string format, object arg0, object arg1); /// <summary> /// Writes out a formatted string and a new line, using the same semantics as /// <see cref="M:System.String.Format(System.String,System.Object)" />. /// </summary> /// <param name="format">A composite format string (see Remarks).</param> /// <param name="arg0">The first object to format and write. </param> /// <param name="arg1">The second object to format and write. </param> /// <param name="arg2">The third object to format and write. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="format" /> is null. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.FormatException"> /// <paramref name="format" /> is not a valid composite format string.-or- The index of a format item is less than 0 /// (zero), or greater than or equal to the number of objects to be formatted (which, for this method overload, is /// three). /// </exception> /// <filterpriority>1</filterpriority> void WriteLine(string format, object arg0, object arg1, object arg2); /// <summary> /// Writes out a formatted string and a new line, using the same semantics as /// <see cref="M:System.String.Format(System.String,System.Object)" />. /// </summary> /// <param name="format">A composite format string (see Remarks).</param> /// <param name="arg">An object array that contains zero or more objects to format and write. </param> /// <exception cref="T:System.ArgumentNullException">A string or object is passed in as null. </exception> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.IO.TextWriter" /> is closed. </exception> /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception> /// <exception cref="T:System.FormatException"> /// <paramref name="format" /> is not a valid composite format string.-or- The index of a format item is less than 0 /// (zero), or greater than or equal to the length of the <paramref name="arg" /> array. /// </exception> /// <filterpriority>1</filterpriority> void WriteLine(string format, params object[] arg); #if (!NET40) /// <summary> /// Asynchronously clears all buffers for the current writer and causes any buffered data to be written to the /// underlying device. /// </summary> /// <returns>A task that represents the asynchronous flush operation. </returns> /// <exception cref="T:System.ObjectDisposedException">The text writer is disposed.</exception> /// <exception cref="T:System.InvalidOperationException">The writer is currently in use by a previous write operation. </exception> Task FlushAsync(); /// <summary>Writes a character to the text string or stream asynchronously.</summary> /// <returns>A task that represents the asynchronous write operation.</returns> /// <param name="value">The character to write to the text stream.</param> /// <exception cref="T:System.ObjectDisposedException">The text writer is disposed.</exception> /// <exception cref="T:System.InvalidOperationException">The text writer is currently in use by a previous write operation. </exception> Task WriteAsync(char value); /// <summary>Writes a character array to the text string or stream asynchronously.</summary> /// <returns>A task that represents the asynchronous write operation.</returns> /// <param name="buffer"> /// The character array to write to the text stream. If <paramref name="buffer" /> is null, nothing is /// written. /// </param> /// <exception cref="T:System.ObjectDisposedException">The text writer is disposed.</exception> /// <exception cref="T:System.InvalidOperationException">The text writer is currently in use by a previous write operation. </exception> Task WriteAsync(char[] buffer); /// <summary>Writes a subarray of characters to the text string or stream asynchronously. </summary> /// <returns>A task that represents the asynchronous write operation.</returns> /// <param name="buffer">The character array to write data from. </param> /// <param name="index">The character position in the buffer at which to start retrieving data. </param> /// <param name="count">The number of characters to write. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="buffer" /> is null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="index" /> plus <paramref name="count" /> is greater /// than the buffer length. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index" /> or <paramref name="count" /> is negative. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The text writer is disposed.</exception> /// <exception cref="T:System.InvalidOperationException">The text writer is currently in use by a previous write operation. </exception> Task WriteAsync(char[] buffer, int index, int count); /// <summary>Writes a string to the text string or stream asynchronously.</summary> /// <returns>A task that represents the asynchronous write operation. </returns> /// <param name="value">The string to write. If <paramref name="value" /> is null, nothing is written to the text stream.</param> /// <exception cref="T:System.ObjectDisposedException">The text writer is disposed.</exception> /// <exception cref="T:System.InvalidOperationException">The text writer is currently in use by a previous write operation. </exception> Task WriteAsync(string value); /// <summary>Writes a line terminator asynchronously to the text string or stream.</summary> /// <returns>A task that represents the asynchronous write operation. </returns> /// <exception cref="T:System.ObjectDisposedException">The text writer is disposed.</exception> /// <exception cref="T:System.InvalidOperationException">The text writer is currently in use by a previous write operation. </exception> Task WriteLineAsync(); /// <summary>Writes a character followed by a line terminator asynchronously to the text string or stream.</summary> /// <returns>A task that represents the asynchronous write operation.</returns> /// <param name="value">The character to write to the text stream.</param> /// <exception cref="T:System.ObjectDisposedException">The text writer is disposed.</exception> /// <exception cref="T:System.InvalidOperationException">The text writer is currently in use by a previous write operation. </exception> Task WriteLineAsync(char value); /// <summary>Writes an array of characters followed by a line terminator asynchronously to the text string or stream.</summary> /// <returns>A task that represents the asynchronous write operation.</returns> /// <param name="buffer"> /// The character array to write to the text stream. If the character array is null, only the line /// terminator is written. /// </param> /// <exception cref="T:System.ObjectDisposedException">The text writer is disposed.</exception> /// <exception cref="T:System.InvalidOperationException">The text writer is currently in use by a previous write operation. </exception> Task WriteLineAsync(char[] buffer); /// <summary>Writes a subarray of characters followed by a line terminator asynchronously to the text string or stream.</summary> /// <returns>A task that represents the asynchronous write operation.</returns> /// <param name="buffer">The character array to write data from. </param> /// <param name="index">The character position in the buffer at which to start retrieving data. </param> /// <param name="count">The number of characters to write. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="buffer" /> is null. /// </exception> /// <exception cref="T:System.ArgumentException"> /// The <paramref name="index" /> plus <paramref name="count" /> is greater /// than the buffer length. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index" /> or <paramref name="count" /> is negative. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The text writer is disposed.</exception> /// <exception cref="T:System.InvalidOperationException">The text writer is currently in use by a previous write operation. </exception> Task WriteLineAsync(char[] buffer, int index, int count); /// <summary>Writes a string followed by a line terminator asynchronously to the text string or stream. </summary> /// <returns>A task that represents the asynchronous write operation.</returns> /// <param name="value">The string to write. If the value is null, only a line terminator is written. </param> /// <exception cref="T:System.ObjectDisposedException">The text writer is disposed.</exception> /// <exception cref="T:System.InvalidOperationException">The text writer is currently in use by a previous write operation. </exception> Task WriteLineAsync(string value); #endif } }
65.409434
145
0.63259
[ "MIT" ]
leoxialtd/Leoxia.Abstractions
src/Leoxia.Abstractions.IO/ITextWriter.cs
34,667
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> //------------------------------------------------------------------------------ #pragma warning disable 1591 namespace BaarDanaTraderPOS { /// <summary> ///Represents a strongly typed in-memory cache of data. ///</summary> [global::System.Serializable()] [global::System.ComponentModel.DesignerCategoryAttribute("code")] [global::System.ComponentModel.ToolboxItem(true)] [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")] [global::System.Xml.Serialization.XmlRootAttribute("DataSet1")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")] public partial class DataSet1 : global::System.Data.DataSet { private Sales_reportDataTable tableSales_report; private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public DataSet1() { this.BeginInit(); this.InitClass(); global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); base.Tables.CollectionChanged += schemaChangedHandler; base.Relations.CollectionChanged += schemaChangedHandler; this.EndInit(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected DataSet1(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : base(info, context, false) { if ((this.IsBinarySerialized(info, context) == true)) { this.InitVars(false); global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler1 = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); this.Tables.CollectionChanged += schemaChangedHandler1; this.Relations.CollectionChanged += schemaChangedHandler1; return; } string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string)))); if ((this.DetermineSchemaSerializationMode(info, context) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { global::System.Data.DataSet ds = new global::System.Data.DataSet(); ds.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); if ((ds.Tables["Sales_report"] != null)) { base.Tables.Add(new Sales_reportDataTable(ds.Tables["Sales_report"])); } this.DataSetName = ds.DataSetName; this.Prefix = ds.Prefix; this.Namespace = ds.Namespace; this.Locale = ds.Locale; this.CaseSensitive = ds.CaseSensitive; this.EnforceConstraints = ds.EnforceConstraints; this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); this.InitVars(); } else { this.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema))); } this.GetSerializationData(info, context); global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged); base.Tables.CollectionChanged += schemaChangedHandler; this.Relations.CollectionChanged += schemaChangedHandler; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Browsable(false)] [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] public Sales_reportDataTable Sales_report { get { return this.tableSales_report; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.BrowsableAttribute(true)] [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Visible)] public override global::System.Data.SchemaSerializationMode SchemaSerializationMode { get { return this._schemaSerializationMode; } set { this._schemaSerializationMode = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] public new global::System.Data.DataTableCollection Tables { get { return base.Tables; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)] public new global::System.Data.DataRelationCollection Relations { get { return base.Relations; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override void InitializeDerivedDataSet() { this.BeginInit(); this.InitClass(); this.EndInit(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public override global::System.Data.DataSet Clone() { DataSet1 cln = ((DataSet1)(base.Clone())); cln.InitVars(); cln.SchemaSerializationMode = this.SchemaSerializationMode; return cln; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override bool ShouldSerializeTables() { return false; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override bool ShouldSerializeRelations() { return false; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) { if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) { this.Reset(); global::System.Data.DataSet ds = new global::System.Data.DataSet(); ds.ReadXml(reader); if ((ds.Tables["Sales_report"] != null)) { base.Tables.Add(new Sales_reportDataTable(ds.Tables["Sales_report"])); } this.DataSetName = ds.DataSetName; this.Prefix = ds.Prefix; this.Namespace = ds.Namespace; this.Locale = ds.Locale; this.CaseSensitive = ds.CaseSensitive; this.EnforceConstraints = ds.EnforceConstraints; this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add); this.InitVars(); } else { this.ReadXml(reader); this.InitVars(); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override global::System.Xml.Schema.XmlSchema GetSchemaSerializable() { global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream(); this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null)); stream.Position = 0; return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] internal void InitVars() { this.InitVars(true); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] internal void InitVars(bool initTable) { this.tableSales_report = ((Sales_reportDataTable)(base.Tables["Sales_report"])); if ((initTable == true)) { if ((this.tableSales_report != null)) { this.tableSales_report.InitVars(); } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private void InitClass() { this.DataSetName = "DataSet1"; this.Prefix = ""; this.Namespace = "http://tempuri.org/DataSet1.xsd"; this.EnforceConstraints = true; this.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema; this.tableSales_report = new Sales_reportDataTable(); base.Tables.Add(this.tableSales_report); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private bool ShouldSerializeSales_report() { return false; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private void SchemaChanged(object sender, global::System.ComponentModel.CollectionChangeEventArgs e) { if ((e.Action == global::System.ComponentModel.CollectionChangeAction.Remove)) { this.InitVars(); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) { DataSet1 ds = new DataSet1(); global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny(); any.Namespace = ds.Namespace; sequence.Items.Add(any); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte())); ) { ; } if ((s1.Position == s1.Length)) { return type; } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return type; } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public delegate void Sales_reportRowChangeEventHandler(object sender, Sales_reportRowChangeEvent e); /// <summary> ///Represents the strongly named DataTable class. ///</summary> [global::System.Serializable()] [global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")] public partial class Sales_reportDataTable : global::System.Data.TypedTableBase<Sales_reportRow> { private global::System.Data.DataColumn columnSale_id; private global::System.Data.DataColumn columnDate; private global::System.Data.DataColumn columnQuantity; private global::System.Data.DataColumn columnPrice; private global::System.Data.DataColumn columnTotal; private global::System.Data.DataColumn columnProduct; private global::System.Data.DataColumn columnCustomer_name; private global::System.Data.DataColumn columnInvoice_id; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public Sales_reportDataTable() { this.TableName = "Sales_report"; this.BeginInit(); this.InitClass(); this.EndInit(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] internal Sales_reportDataTable(global::System.Data.DataTable table) { this.TableName = table.TableName; if ((table.CaseSensitive != table.DataSet.CaseSensitive)) { this.CaseSensitive = table.CaseSensitive; } if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) { this.Locale = table.Locale; } if ((table.Namespace != table.DataSet.Namespace)) { this.Namespace = table.Namespace; } this.Prefix = table.Prefix; this.MinimumCapacity = table.MinimumCapacity; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected Sales_reportDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) : base(info, context) { this.InitVars(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public global::System.Data.DataColumn Sale_idColumn { get { return this.columnSale_id; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public global::System.Data.DataColumn DateColumn { get { return this.columnDate; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public global::System.Data.DataColumn QuantityColumn { get { return this.columnQuantity; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public global::System.Data.DataColumn PriceColumn { get { return this.columnPrice; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public global::System.Data.DataColumn TotalColumn { get { return this.columnTotal; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public global::System.Data.DataColumn ProductColumn { get { return this.columnProduct; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public global::System.Data.DataColumn Customer_nameColumn { get { return this.columnCustomer_name; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public global::System.Data.DataColumn Invoice_idColumn { get { return this.columnInvoice_id; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Browsable(false)] public int Count { get { return this.Rows.Count; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public Sales_reportRow this[int index] { get { return ((Sales_reportRow)(this.Rows[index])); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public event Sales_reportRowChangeEventHandler Sales_reportRowChanging; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public event Sales_reportRowChangeEventHandler Sales_reportRowChanged; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public event Sales_reportRowChangeEventHandler Sales_reportRowDeleting; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public event Sales_reportRowChangeEventHandler Sales_reportRowDeleted; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public void AddSales_reportRow(Sales_reportRow row) { this.Rows.Add(row); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public Sales_reportRow AddSales_reportRow(System.DateTime Date, int Quantity, int Price, int Total, string Product, string Customer_name, int Invoice_id) { Sales_reportRow rowSales_reportRow = ((Sales_reportRow)(this.NewRow())); object[] columnValuesArray = new object[] { null, Date, Quantity, Price, Total, Product, Customer_name, Invoice_id}; rowSales_reportRow.ItemArray = columnValuesArray; this.Rows.Add(rowSales_reportRow); return rowSales_reportRow; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public Sales_reportRow FindBySale_id(int Sale_id) { return ((Sales_reportRow)(this.Rows.Find(new object[] { Sale_id}))); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public override global::System.Data.DataTable Clone() { Sales_reportDataTable cln = ((Sales_reportDataTable)(base.Clone())); cln.InitVars(); return cln; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override global::System.Data.DataTable CreateInstance() { return new Sales_reportDataTable(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] internal void InitVars() { this.columnSale_id = base.Columns["Sale_id"]; this.columnDate = base.Columns["Date"]; this.columnQuantity = base.Columns["Quantity"]; this.columnPrice = base.Columns["Price"]; this.columnTotal = base.Columns["Total"]; this.columnProduct = base.Columns["Product"]; this.columnCustomer_name = base.Columns["Customer_name"]; this.columnInvoice_id = base.Columns["Invoice_id"]; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private void InitClass() { this.columnSale_id = new global::System.Data.DataColumn("Sale_id", typeof(int), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnSale_id); this.columnDate = new global::System.Data.DataColumn("Date", typeof(global::System.DateTime), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnDate); this.columnQuantity = new global::System.Data.DataColumn("Quantity", typeof(int), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnQuantity); this.columnPrice = new global::System.Data.DataColumn("Price", typeof(int), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnPrice); this.columnTotal = new global::System.Data.DataColumn("Total", typeof(int), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnTotal); this.columnProduct = new global::System.Data.DataColumn("Product", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnProduct); this.columnCustomer_name = new global::System.Data.DataColumn("Customer_name", typeof(string), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnCustomer_name); this.columnInvoice_id = new global::System.Data.DataColumn("Invoice_id", typeof(int), null, global::System.Data.MappingType.Element); base.Columns.Add(this.columnInvoice_id); this.Constraints.Add(new global::System.Data.UniqueConstraint("Constraint1", new global::System.Data.DataColumn[] { this.columnSale_id}, true)); this.columnSale_id.AutoIncrement = true; this.columnSale_id.AutoIncrementSeed = -1; this.columnSale_id.AutoIncrementStep = -1; this.columnSale_id.AllowDBNull = false; this.columnSale_id.ReadOnly = true; this.columnSale_id.Unique = true; this.columnDate.AllowDBNull = false; this.columnQuantity.AllowDBNull = false; this.columnPrice.AllowDBNull = false; this.columnTotal.AllowDBNull = false; this.columnProduct.MaxLength = 2147483647; this.columnCustomer_name.MaxLength = 2147483647; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public Sales_reportRow NewSales_reportRow() { return ((Sales_reportRow)(this.NewRow())); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) { return new Sales_reportRow(builder); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override global::System.Type GetRowType() { return typeof(Sales_reportRow); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) { base.OnRowChanged(e); if ((this.Sales_reportRowChanged != null)) { this.Sales_reportRowChanged(this, new Sales_reportRowChangeEvent(((Sales_reportRow)(e.Row)), e.Action)); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) { base.OnRowChanging(e); if ((this.Sales_reportRowChanging != null)) { this.Sales_reportRowChanging(this, new Sales_reportRowChangeEvent(((Sales_reportRow)(e.Row)), e.Action)); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) { base.OnRowDeleted(e); if ((this.Sales_reportRowDeleted != null)) { this.Sales_reportRowDeleted(this, new Sales_reportRowChangeEvent(((Sales_reportRow)(e.Row)), e.Action)); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) { base.OnRowDeleting(e); if ((this.Sales_reportRowDeleting != null)) { this.Sales_reportRowDeleting(this, new Sales_reportRowChangeEvent(((Sales_reportRow)(e.Row)), e.Action)); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public void RemoveSales_reportRow(Sales_reportRow row) { this.Rows.Remove(row); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); DataSet1 ds = new DataSet1(); global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); any1.Namespace = "http://www.w3.org/2001/XMLSchema"; any1.MinOccurs = new decimal(0); any1.MaxOccurs = decimal.MaxValue; any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any1); global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; any2.MinOccurs = new decimal(1); any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any2); global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute1.Name = "namespace"; attribute1.FixedValue = ds.Namespace; type.Attributes.Add(attribute1); global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute2.Name = "tableTypeName"; attribute2.FixedValue = "Sales_reportDataTable"; type.Attributes.Add(attribute2); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte())); ) { ; } if ((s1.Position == s1.Length)) { return type; } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return type; } } /// <summary> ///Represents strongly named DataRow class. ///</summary> public partial class Sales_reportRow : global::System.Data.DataRow { private Sales_reportDataTable tableSales_report; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] internal Sales_reportRow(global::System.Data.DataRowBuilder rb) : base(rb) { this.tableSales_report = ((Sales_reportDataTable)(this.Table)); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public int Sale_id { get { return ((int)(this[this.tableSales_report.Sale_idColumn])); } set { this[this.tableSales_report.Sale_idColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public System.DateTime Date { get { return ((global::System.DateTime)(this[this.tableSales_report.DateColumn])); } set { this[this.tableSales_report.DateColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public int Quantity { get { return ((int)(this[this.tableSales_report.QuantityColumn])); } set { this[this.tableSales_report.QuantityColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public int Price { get { return ((int)(this[this.tableSales_report.PriceColumn])); } set { this[this.tableSales_report.PriceColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public int Total { get { return ((int)(this[this.tableSales_report.TotalColumn])); } set { this[this.tableSales_report.TotalColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public string Product { get { try { return ((string)(this[this.tableSales_report.ProductColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'Product\' in table \'Sales_report\' is DBNull.", e); } } set { this[this.tableSales_report.ProductColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public string Customer_name { get { try { return ((string)(this[this.tableSales_report.Customer_nameColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'Customer_name\' in table \'Sales_report\' is DBNull.", e); } } set { this[this.tableSales_report.Customer_nameColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public int Invoice_id { get { try { return ((int)(this[this.tableSales_report.Invoice_idColumn])); } catch (global::System.InvalidCastException e) { throw new global::System.Data.StrongTypingException("The value for column \'Invoice_id\' in table \'Sales_report\' is DBNull.", e); } } set { this[this.tableSales_report.Invoice_idColumn] = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public bool IsProductNull() { return this.IsNull(this.tableSales_report.ProductColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public void SetProductNull() { this[this.tableSales_report.ProductColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public bool IsCustomer_nameNull() { return this.IsNull(this.tableSales_report.Customer_nameColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public void SetCustomer_nameNull() { this[this.tableSales_report.Customer_nameColumn] = global::System.Convert.DBNull; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public bool IsInvoice_idNull() { return this.IsNull(this.tableSales_report.Invoice_idColumn); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public void SetInvoice_idNull() { this[this.tableSales_report.Invoice_idColumn] = global::System.Convert.DBNull; } } /// <summary> ///Row event argument class ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public class Sales_reportRowChangeEvent : global::System.EventArgs { private Sales_reportRow eventRow; private global::System.Data.DataRowAction eventAction; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public Sales_reportRowChangeEvent(Sales_reportRow row, global::System.Data.DataRowAction action) { this.eventRow = row; this.eventAction = action; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public Sales_reportRow Row { get { return this.eventRow; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public global::System.Data.DataRowAction Action { get { return this.eventAction; } } } } } namespace BaarDanaTraderPOS.DataSet1TableAdapters { /// <summary> ///Represents the connection and commands used to retrieve and save data. ///</summary> [global::System.ComponentModel.DesignerCategoryAttribute("code")] [global::System.ComponentModel.ToolboxItem(true)] [global::System.ComponentModel.DataObjectAttribute(true)] [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterDesigner, Microsoft.VSDesigner" + ", Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] public partial class Sales_reportTableAdapter : global::System.ComponentModel.Component { private global::System.Data.SqlClient.SqlDataAdapter _adapter; private global::System.Data.SqlClient.SqlConnection _connection; private global::System.Data.SqlClient.SqlTransaction _transaction; private global::System.Data.SqlClient.SqlCommand[] _commandCollection; private bool _clearBeforeFill; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public Sales_reportTableAdapter() { this.ClearBeforeFill = true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected internal global::System.Data.SqlClient.SqlDataAdapter Adapter { get { if ((this._adapter == null)) { this.InitAdapter(); } return this._adapter; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] internal global::System.Data.SqlClient.SqlConnection Connection { get { if ((this._connection == null)) { this.InitConnection(); } return this._connection; } set { this._connection = value; if ((this.Adapter.InsertCommand != null)) { this.Adapter.InsertCommand.Connection = value; } if ((this.Adapter.DeleteCommand != null)) { this.Adapter.DeleteCommand.Connection = value; } if ((this.Adapter.UpdateCommand != null)) { this.Adapter.UpdateCommand.Connection = value; } for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { if ((this.CommandCollection[i] != null)) { ((global::System.Data.SqlClient.SqlCommand)(this.CommandCollection[i])).Connection = value; } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] internal global::System.Data.SqlClient.SqlTransaction Transaction { get { return this._transaction; } set { this._transaction = value; for (int i = 0; (i < this.CommandCollection.Length); i = (i + 1)) { this.CommandCollection[i].Transaction = this._transaction; } if (((this.Adapter != null) && (this.Adapter.DeleteCommand != null))) { this.Adapter.DeleteCommand.Transaction = this._transaction; } if (((this.Adapter != null) && (this.Adapter.InsertCommand != null))) { this.Adapter.InsertCommand.Transaction = this._transaction; } if (((this.Adapter != null) && (this.Adapter.UpdateCommand != null))) { this.Adapter.UpdateCommand.Transaction = this._transaction; } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected global::System.Data.SqlClient.SqlCommand[] CommandCollection { get { if ((this._commandCollection == null)) { this.InitCommandCollection(); } return this._commandCollection; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public bool ClearBeforeFill { get { return this._clearBeforeFill; } set { this._clearBeforeFill = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private void InitAdapter() { this._adapter = new global::System.Data.SqlClient.SqlDataAdapter(); global::System.Data.Common.DataTableMapping tableMapping = new global::System.Data.Common.DataTableMapping(); tableMapping.SourceTable = "Table"; tableMapping.DataSetTable = "Sales_report"; tableMapping.ColumnMappings.Add("Sale_id", "Sale_id"); tableMapping.ColumnMappings.Add("Date", "Date"); tableMapping.ColumnMappings.Add("Quantity", "Quantity"); tableMapping.ColumnMappings.Add("Price", "Price"); tableMapping.ColumnMappings.Add("Total", "Total"); tableMapping.ColumnMappings.Add("Product", "Product"); tableMapping.ColumnMappings.Add("Customer_name", "Customer_name"); tableMapping.ColumnMappings.Add("Invoice_id", "Invoice_id"); this._adapter.TableMappings.Add(tableMapping); this._adapter.DeleteCommand = new global::System.Data.SqlClient.SqlCommand(); this._adapter.DeleteCommand.Connection = this.Connection; this._adapter.DeleteCommand.CommandText = @"DELETE FROM [dbo].[Sales_report] WHERE (([Sale_id] = @Original_Sale_id) AND ([Date] = @Original_Date) AND ([Quantity] = @Original_Quantity) AND ([Price] = @Original_Price) AND ([Total] = @Original_Total) AND ((@IsNull_Invoice_id = 1 AND [Invoice_id] IS NULL) OR ([Invoice_id] = @Original_Invoice_id)))"; this._adapter.DeleteCommand.CommandType = global::System.Data.CommandType.Text; this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Sale_id", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Sale_id", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Date", global::System.Data.SqlDbType.Date, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Date", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Quantity", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Quantity", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Price", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Price", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Total", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Total", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_Invoice_id", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Invoice_id", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); this._adapter.DeleteCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Invoice_id", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Invoice_id", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.InsertCommand = new global::System.Data.SqlClient.SqlCommand(); this._adapter.InsertCommand.Connection = this.Connection; this._adapter.InsertCommand.CommandText = @"INSERT INTO [dbo].[Sales_report] ([Date], [Quantity], [Price], [Total], [Product], [Customer_name], [Invoice_id]) VALUES (@Date, @Quantity, @Price, @Total, @Product, @Customer_name, @Invoice_id); SELECT Sale_id, Date, Quantity, Price, Total, Product, Customer_name, Invoice_id FROM Sales_report WHERE (Sale_id = SCOPE_IDENTITY())"; this._adapter.InsertCommand.CommandType = global::System.Data.CommandType.Text; this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Date", global::System.Data.SqlDbType.Date, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Date", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Quantity", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Quantity", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Price", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Price", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Total", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Total", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Product", global::System.Data.SqlDbType.VarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Product", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Customer_name", global::System.Data.SqlDbType.VarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Customer_name", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.InsertCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Invoice_id", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Invoice_id", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.UpdateCommand = new global::System.Data.SqlClient.SqlCommand(); this._adapter.UpdateCommand.Connection = this.Connection; this._adapter.UpdateCommand.CommandText = @"UPDATE [dbo].[Sales_report] SET [Date] = @Date, [Quantity] = @Quantity, [Price] = @Price, [Total] = @Total, [Product] = @Product, [Customer_name] = @Customer_name, [Invoice_id] = @Invoice_id WHERE (([Sale_id] = @Original_Sale_id) AND ([Date] = @Original_Date) AND ([Quantity] = @Original_Quantity) AND ([Price] = @Original_Price) AND ([Total] = @Original_Total) AND ((@IsNull_Invoice_id = 1 AND [Invoice_id] IS NULL) OR ([Invoice_id] = @Original_Invoice_id))); SELECT Sale_id, Date, Quantity, Price, Total, Product, Customer_name, Invoice_id FROM Sales_report WHERE (Sale_id = @Sale_id)"; this._adapter.UpdateCommand.CommandType = global::System.Data.CommandType.Text; this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Date", global::System.Data.SqlDbType.Date, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Date", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Quantity", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Quantity", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Price", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Price", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Total", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Total", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Product", global::System.Data.SqlDbType.VarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Product", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Customer_name", global::System.Data.SqlDbType.VarChar, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Customer_name", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Invoice_id", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Invoice_id", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Sale_id", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Sale_id", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Date", global::System.Data.SqlDbType.Date, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Date", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Quantity", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Quantity", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Price", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Price", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Total", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Total", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@IsNull_Invoice_id", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Invoice_id", global::System.Data.DataRowVersion.Original, true, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Original_Invoice_id", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, 0, 0, "Invoice_id", global::System.Data.DataRowVersion.Original, false, null, "", "", "")); this._adapter.UpdateCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@Sale_id", global::System.Data.SqlDbType.Int, 4, global::System.Data.ParameterDirection.Input, 0, 0, "Sale_id", global::System.Data.DataRowVersion.Current, false, null, "", "", "")); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private void InitConnection() { this._connection = new global::System.Data.SqlClient.SqlConnection(); this._connection.ConnectionString = global::BaarDanaTraderPOS.Properties.Settings.Default.BaarDanaTradersConnectionString; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private void InitCommandCollection() { this._commandCollection = new global::System.Data.SqlClient.SqlCommand[1]; this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand(); this._commandCollection[0].Connection = this.Connection; this._commandCollection[0].CommandText = "SELECT Sale_id, Date, Quantity, Price, Total, Product, Customer_name, Invoice_id " + "FROM dbo.Sales_report"; this._commandCollection[0].CommandType = global::System.Data.CommandType.Text; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Fill, true)] public virtual int Fill(DataSet1.Sales_reportDataTable dataTable) { this.Adapter.SelectCommand = this.CommandCollection[0]; if ((this.ClearBeforeFill == true)) { dataTable.Clear(); } int returnValue = this.Adapter.Fill(dataTable); return returnValue; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Select, true)] public virtual DataSet1.Sales_reportDataTable GetData() { this.Adapter.SelectCommand = this.CommandCollection[0]; DataSet1.Sales_reportDataTable dataTable = new DataSet1.Sales_reportDataTable(); this.Adapter.Fill(dataTable); return dataTable; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] public virtual int Update(DataSet1.Sales_reportDataTable dataTable) { return this.Adapter.Update(dataTable); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] public virtual int Update(DataSet1 dataSet) { return this.Adapter.Update(dataSet, "Sales_report"); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] public virtual int Update(global::System.Data.DataRow dataRow) { return this.Adapter.Update(new global::System.Data.DataRow[] { dataRow}); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] public virtual int Update(global::System.Data.DataRow[] dataRows) { return this.Adapter.Update(dataRows); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Delete, true)] public virtual int Delete(int Original_Sale_id, System.DateTime Original_Date, int Original_Quantity, int Original_Price, int Original_Total, global::System.Nullable<int> Original_Invoice_id) { this.Adapter.DeleteCommand.Parameters[0].Value = ((int)(Original_Sale_id)); this.Adapter.DeleteCommand.Parameters[1].Value = ((System.DateTime)(Original_Date)); this.Adapter.DeleteCommand.Parameters[2].Value = ((int)(Original_Quantity)); this.Adapter.DeleteCommand.Parameters[3].Value = ((int)(Original_Price)); this.Adapter.DeleteCommand.Parameters[4].Value = ((int)(Original_Total)); if ((Original_Invoice_id.HasValue == true)) { this.Adapter.DeleteCommand.Parameters[5].Value = ((object)(0)); this.Adapter.DeleteCommand.Parameters[6].Value = ((int)(Original_Invoice_id.Value)); } else { this.Adapter.DeleteCommand.Parameters[5].Value = ((object)(1)); this.Adapter.DeleteCommand.Parameters[6].Value = global::System.DBNull.Value; } global::System.Data.ConnectionState previousConnectionState = this.Adapter.DeleteCommand.Connection.State; if (((this.Adapter.DeleteCommand.Connection.State & global::System.Data.ConnectionState.Open) != global::System.Data.ConnectionState.Open)) { this.Adapter.DeleteCommand.Connection.Open(); } try { int returnValue = this.Adapter.DeleteCommand.ExecuteNonQuery(); return returnValue; } finally { if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { this.Adapter.DeleteCommand.Connection.Close(); } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Insert, true)] public virtual int Insert(System.DateTime Date, int Quantity, int Price, int Total, string Product, string Customer_name, global::System.Nullable<int> Invoice_id) { this.Adapter.InsertCommand.Parameters[0].Value = ((System.DateTime)(Date)); this.Adapter.InsertCommand.Parameters[1].Value = ((int)(Quantity)); this.Adapter.InsertCommand.Parameters[2].Value = ((int)(Price)); this.Adapter.InsertCommand.Parameters[3].Value = ((int)(Total)); if ((Product == null)) { this.Adapter.InsertCommand.Parameters[4].Value = global::System.DBNull.Value; } else { this.Adapter.InsertCommand.Parameters[4].Value = ((string)(Product)); } if ((Customer_name == null)) { this.Adapter.InsertCommand.Parameters[5].Value = global::System.DBNull.Value; } else { this.Adapter.InsertCommand.Parameters[5].Value = ((string)(Customer_name)); } if ((Invoice_id.HasValue == true)) { this.Adapter.InsertCommand.Parameters[6].Value = ((int)(Invoice_id.Value)); } else { this.Adapter.InsertCommand.Parameters[6].Value = global::System.DBNull.Value; } global::System.Data.ConnectionState previousConnectionState = this.Adapter.InsertCommand.Connection.State; if (((this.Adapter.InsertCommand.Connection.State & global::System.Data.ConnectionState.Open) != global::System.Data.ConnectionState.Open)) { this.Adapter.InsertCommand.Connection.Open(); } try { int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery(); return returnValue; } finally { if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { this.Adapter.InsertCommand.Connection.Close(); } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)] public virtual int Update(System.DateTime Date, int Quantity, int Price, int Total, string Product, string Customer_name, global::System.Nullable<int> Invoice_id, int Original_Sale_id, System.DateTime Original_Date, int Original_Quantity, int Original_Price, int Original_Total, global::System.Nullable<int> Original_Invoice_id, int Sale_id) { this.Adapter.UpdateCommand.Parameters[0].Value = ((System.DateTime)(Date)); this.Adapter.UpdateCommand.Parameters[1].Value = ((int)(Quantity)); this.Adapter.UpdateCommand.Parameters[2].Value = ((int)(Price)); this.Adapter.UpdateCommand.Parameters[3].Value = ((int)(Total)); if ((Product == null)) { this.Adapter.UpdateCommand.Parameters[4].Value = global::System.DBNull.Value; } else { this.Adapter.UpdateCommand.Parameters[4].Value = ((string)(Product)); } if ((Customer_name == null)) { this.Adapter.UpdateCommand.Parameters[5].Value = global::System.DBNull.Value; } else { this.Adapter.UpdateCommand.Parameters[5].Value = ((string)(Customer_name)); } if ((Invoice_id.HasValue == true)) { this.Adapter.UpdateCommand.Parameters[6].Value = ((int)(Invoice_id.Value)); } else { this.Adapter.UpdateCommand.Parameters[6].Value = global::System.DBNull.Value; } this.Adapter.UpdateCommand.Parameters[7].Value = ((int)(Original_Sale_id)); this.Adapter.UpdateCommand.Parameters[8].Value = ((System.DateTime)(Original_Date)); this.Adapter.UpdateCommand.Parameters[9].Value = ((int)(Original_Quantity)); this.Adapter.UpdateCommand.Parameters[10].Value = ((int)(Original_Price)); this.Adapter.UpdateCommand.Parameters[11].Value = ((int)(Original_Total)); if ((Original_Invoice_id.HasValue == true)) { this.Adapter.UpdateCommand.Parameters[12].Value = ((object)(0)); this.Adapter.UpdateCommand.Parameters[13].Value = ((int)(Original_Invoice_id.Value)); } else { this.Adapter.UpdateCommand.Parameters[12].Value = ((object)(1)); this.Adapter.UpdateCommand.Parameters[13].Value = global::System.DBNull.Value; } this.Adapter.UpdateCommand.Parameters[14].Value = ((int)(Sale_id)); global::System.Data.ConnectionState previousConnectionState = this.Adapter.UpdateCommand.Connection.State; if (((this.Adapter.UpdateCommand.Connection.State & global::System.Data.ConnectionState.Open) != global::System.Data.ConnectionState.Open)) { this.Adapter.UpdateCommand.Connection.Open(); } try { int returnValue = this.Adapter.UpdateCommand.ExecuteNonQuery(); return returnValue; } finally { if ((previousConnectionState == global::System.Data.ConnectionState.Closed)) { this.Adapter.UpdateCommand.Connection.Close(); } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")] [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Update, true)] public virtual int Update(System.DateTime Date, int Quantity, int Price, int Total, string Product, string Customer_name, global::System.Nullable<int> Invoice_id, int Original_Sale_id, System.DateTime Original_Date, int Original_Quantity, int Original_Price, int Original_Total, global::System.Nullable<int> Original_Invoice_id) { return this.Update(Date, Quantity, Price, Total, Product, Customer_name, Invoice_id, Original_Sale_id, Original_Date, Original_Quantity, Original_Price, Original_Total, Original_Invoice_id, Original_Sale_id); } } /// <summary> ///TableAdapterManager is used to coordinate TableAdapters in the dataset to enable Hierarchical Update scenarios ///</summary> [global::System.ComponentModel.DesignerCategoryAttribute("code")] [global::System.ComponentModel.ToolboxItem(true)] [global::System.ComponentModel.DesignerAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerDesigner, Microsoft.VSD" + "esigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapterManager")] public partial class TableAdapterManager : global::System.ComponentModel.Component { private UpdateOrderOption _updateOrder; private Sales_reportTableAdapter _sales_reportTableAdapter; private bool _backupDataSetBeforeUpdate; private global::System.Data.IDbConnection _connection; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public UpdateOrderOption UpdateOrder { get { return this._updateOrder; } set { this._updateOrder = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.EditorAttribute("Microsoft.VSDesigner.DataSource.Design.TableAdapterManagerPropertyEditor, Microso" + "ft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3" + "a", "System.Drawing.Design.UITypeEditor")] public Sales_reportTableAdapter Sales_reportTableAdapter { get { return this._sales_reportTableAdapter; } set { this._sales_reportTableAdapter = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public bool BackupDataSetBeforeUpdate { get { return this._backupDataSetBeforeUpdate; } set { this._backupDataSetBeforeUpdate = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Browsable(false)] public global::System.Data.IDbConnection Connection { get { if ((this._connection != null)) { return this._connection; } if (((this._sales_reportTableAdapter != null) && (this._sales_reportTableAdapter.Connection != null))) { return this._sales_reportTableAdapter.Connection; } return null; } set { this._connection = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] [global::System.ComponentModel.Browsable(false)] public int TableAdapterInstanceCount { get { int count = 0; if ((this._sales_reportTableAdapter != null)) { count = (count + 1); } return count; } } /// <summary> ///Update rows in top-down order. ///</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private int UpdateUpdatedRows(DataSet1 dataSet, global::System.Collections.Generic.List<global::System.Data.DataRow> allChangedRows, global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows) { int result = 0; if ((this._sales_reportTableAdapter != null)) { global::System.Data.DataRow[] updatedRows = dataSet.Sales_report.Select(null, null, global::System.Data.DataViewRowState.ModifiedCurrent); updatedRows = this.GetRealUpdatedRows(updatedRows, allAddedRows); if (((updatedRows != null) && (0 < updatedRows.Length))) { result = (result + this._sales_reportTableAdapter.Update(updatedRows)); allChangedRows.AddRange(updatedRows); } } return result; } /// <summary> ///Insert rows in top-down order. ///</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private int UpdateInsertedRows(DataSet1 dataSet, global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows) { int result = 0; if ((this._sales_reportTableAdapter != null)) { global::System.Data.DataRow[] addedRows = dataSet.Sales_report.Select(null, null, global::System.Data.DataViewRowState.Added); if (((addedRows != null) && (0 < addedRows.Length))) { result = (result + this._sales_reportTableAdapter.Update(addedRows)); allAddedRows.AddRange(addedRows); } } return result; } /// <summary> ///Delete rows in bottom-up order. ///</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private int UpdateDeletedRows(DataSet1 dataSet, global::System.Collections.Generic.List<global::System.Data.DataRow> allChangedRows) { int result = 0; if ((this._sales_reportTableAdapter != null)) { global::System.Data.DataRow[] deletedRows = dataSet.Sales_report.Select(null, null, global::System.Data.DataViewRowState.Deleted); if (((deletedRows != null) && (0 < deletedRows.Length))) { result = (result + this._sales_reportTableAdapter.Update(deletedRows)); allChangedRows.AddRange(deletedRows); } } return result; } /// <summary> ///Remove inserted rows that become updated rows after calling TableAdapter.Update(inserted rows) first ///</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private global::System.Data.DataRow[] GetRealUpdatedRows(global::System.Data.DataRow[] updatedRows, global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows) { if (((updatedRows == null) || (updatedRows.Length < 1))) { return updatedRows; } if (((allAddedRows == null) || (allAddedRows.Count < 1))) { return updatedRows; } global::System.Collections.Generic.List<global::System.Data.DataRow> realUpdatedRows = new global::System.Collections.Generic.List<global::System.Data.DataRow>(); for (int i = 0; (i < updatedRows.Length); i = (i + 1)) { global::System.Data.DataRow row = updatedRows[i]; if ((allAddedRows.Contains(row) == false)) { realUpdatedRows.Add(row); } } return realUpdatedRows.ToArray(); } /// <summary> ///Update all changes to the dataset. ///</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public virtual int UpdateAll(DataSet1 dataSet) { if ((dataSet == null)) { throw new global::System.ArgumentNullException("dataSet"); } if ((dataSet.HasChanges() == false)) { return 0; } if (((this._sales_reportTableAdapter != null) && (this.MatchTableAdapterConnection(this._sales_reportTableAdapter.Connection) == false))) { throw new global::System.ArgumentException("All TableAdapters managed by a TableAdapterManager must use the same connection s" + "tring."); } global::System.Data.IDbConnection workConnection = this.Connection; if ((workConnection == null)) { throw new global::System.ApplicationException("TableAdapterManager contains no connection information. Set each TableAdapterMana" + "ger TableAdapter property to a valid TableAdapter instance."); } bool workConnOpened = false; if (((workConnection.State & global::System.Data.ConnectionState.Broken) == global::System.Data.ConnectionState.Broken)) { workConnection.Close(); } if ((workConnection.State == global::System.Data.ConnectionState.Closed)) { workConnection.Open(); workConnOpened = true; } global::System.Data.IDbTransaction workTransaction = workConnection.BeginTransaction(); if ((workTransaction == null)) { throw new global::System.ApplicationException("The transaction cannot begin. The current data connection does not support transa" + "ctions or the current state is not allowing the transaction to begin."); } global::System.Collections.Generic.List<global::System.Data.DataRow> allChangedRows = new global::System.Collections.Generic.List<global::System.Data.DataRow>(); global::System.Collections.Generic.List<global::System.Data.DataRow> allAddedRows = new global::System.Collections.Generic.List<global::System.Data.DataRow>(); global::System.Collections.Generic.List<global::System.Data.Common.DataAdapter> adaptersWithAcceptChangesDuringUpdate = new global::System.Collections.Generic.List<global::System.Data.Common.DataAdapter>(); global::System.Collections.Generic.Dictionary<object, global::System.Data.IDbConnection> revertConnections = new global::System.Collections.Generic.Dictionary<object, global::System.Data.IDbConnection>(); int result = 0; global::System.Data.DataSet backupDataSet = null; if (this.BackupDataSetBeforeUpdate) { backupDataSet = new global::System.Data.DataSet(); backupDataSet.Merge(dataSet); } try { // ---- Prepare for update ----------- // if ((this._sales_reportTableAdapter != null)) { revertConnections.Add(this._sales_reportTableAdapter, this._sales_reportTableAdapter.Connection); this._sales_reportTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(workConnection)); this._sales_reportTableAdapter.Transaction = ((global::System.Data.SqlClient.SqlTransaction)(workTransaction)); if (this._sales_reportTableAdapter.Adapter.AcceptChangesDuringUpdate) { this._sales_reportTableAdapter.Adapter.AcceptChangesDuringUpdate = false; adaptersWithAcceptChangesDuringUpdate.Add(this._sales_reportTableAdapter.Adapter); } } // //---- Perform updates ----------- // if ((this.UpdateOrder == UpdateOrderOption.UpdateInsertDelete)) { result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows)); result = (result + this.UpdateInsertedRows(dataSet, allAddedRows)); } else { result = (result + this.UpdateInsertedRows(dataSet, allAddedRows)); result = (result + this.UpdateUpdatedRows(dataSet, allChangedRows, allAddedRows)); } result = (result + this.UpdateDeletedRows(dataSet, allChangedRows)); // //---- Commit updates ----------- // workTransaction.Commit(); if ((0 < allAddedRows.Count)) { global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count]; allAddedRows.CopyTo(rows); for (int i = 0; (i < rows.Length); i = (i + 1)) { global::System.Data.DataRow row = rows[i]; row.AcceptChanges(); } } if ((0 < allChangedRows.Count)) { global::System.Data.DataRow[] rows = new System.Data.DataRow[allChangedRows.Count]; allChangedRows.CopyTo(rows); for (int i = 0; (i < rows.Length); i = (i + 1)) { global::System.Data.DataRow row = rows[i]; row.AcceptChanges(); } } } catch (global::System.Exception ex) { workTransaction.Rollback(); // ---- Restore the dataset ----------- if (this.BackupDataSetBeforeUpdate) { global::System.Diagnostics.Debug.Assert((backupDataSet != null)); dataSet.Clear(); dataSet.Merge(backupDataSet); } else { if ((0 < allAddedRows.Count)) { global::System.Data.DataRow[] rows = new System.Data.DataRow[allAddedRows.Count]; allAddedRows.CopyTo(rows); for (int i = 0; (i < rows.Length); i = (i + 1)) { global::System.Data.DataRow row = rows[i]; row.AcceptChanges(); row.SetAdded(); } } } throw ex; } finally { if (workConnOpened) { workConnection.Close(); } if ((this._sales_reportTableAdapter != null)) { this._sales_reportTableAdapter.Connection = ((global::System.Data.SqlClient.SqlConnection)(revertConnections[this._sales_reportTableAdapter])); this._sales_reportTableAdapter.Transaction = null; } if ((0 < adaptersWithAcceptChangesDuringUpdate.Count)) { global::System.Data.Common.DataAdapter[] adapters = new System.Data.Common.DataAdapter[adaptersWithAcceptChangesDuringUpdate.Count]; adaptersWithAcceptChangesDuringUpdate.CopyTo(adapters); for (int i = 0; (i < adapters.Length); i = (i + 1)) { global::System.Data.Common.DataAdapter adapter = adapters[i]; adapter.AcceptChangesDuringUpdate = true; } } } return result; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected virtual void SortSelfReferenceRows(global::System.Data.DataRow[] rows, global::System.Data.DataRelation relation, bool childFirst) { global::System.Array.Sort<global::System.Data.DataRow>(rows, new SelfReferenceComparer(relation, childFirst)); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] protected virtual bool MatchTableAdapterConnection(global::System.Data.IDbConnection inputConnection) { if ((this._connection != null)) { return true; } if (((this.Connection == null) || (inputConnection == null))) { return true; } if (string.Equals(this.Connection.ConnectionString, inputConnection.ConnectionString, global::System.StringComparison.Ordinal)) { return true; } return false; } /// <summary> ///Update Order Option ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public enum UpdateOrderOption { InsertUpdateDelete = 0, UpdateInsertDelete = 1, } /// <summary> ///Used to sort self-referenced table's rows ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private class SelfReferenceComparer : object, global::System.Collections.Generic.IComparer<global::System.Data.DataRow> { private global::System.Data.DataRelation _relation; private int _childFirst; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] internal SelfReferenceComparer(global::System.Data.DataRelation relation, bool childFirst) { this._relation = relation; if (childFirst) { this._childFirst = -1; } else { this._childFirst = 1; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] private global::System.Data.DataRow GetRoot(global::System.Data.DataRow row, out int distance) { global::System.Diagnostics.Debug.Assert((row != null)); global::System.Data.DataRow root = row; distance = 0; global::System.Collections.Generic.IDictionary<global::System.Data.DataRow, global::System.Data.DataRow> traversedRows = new global::System.Collections.Generic.Dictionary<global::System.Data.DataRow, global::System.Data.DataRow>(); traversedRows[row] = row; global::System.Data.DataRow parent = row.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default); for ( ; ((parent != null) && (traversedRows.ContainsKey(parent) == false)); ) { distance = (distance + 1); root = parent; traversedRows[parent] = parent; parent = parent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Default); } if ((distance == 0)) { traversedRows.Clear(); traversedRows[row] = row; parent = row.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original); for ( ; ((parent != null) && (traversedRows.ContainsKey(parent) == false)); ) { distance = (distance + 1); root = parent; traversedRows[parent] = parent; parent = parent.GetParentRow(this._relation, global::System.Data.DataRowVersion.Original); } } return root; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")] public int Compare(global::System.Data.DataRow row1, global::System.Data.DataRow row2) { if (object.ReferenceEquals(row1, row2)) { return 0; } if ((row1 == null)) { return -1; } if ((row2 == null)) { return 1; } int distance1 = 0; global::System.Data.DataRow root1 = this.GetRoot(row1, out distance1); int distance2 = 0; global::System.Data.DataRow root2 = this.GetRoot(row2, out distance2); if (object.ReferenceEquals(root1, root2)) { return (this._childFirst * distance1.CompareTo(distance2)); } else { global::System.Diagnostics.Debug.Assert(((root1.Table != null) && (root2.Table != null))); if ((root1.Table.Rows.IndexOf(root1) < root2.Table.Rows.IndexOf(root2))) { return -1; } else { return 1; } } } } } } #pragma warning restore 1591
60.597576
517
0.599324
[ "Apache-2.0" ]
NasirAziz/NoorInternationalMobileShop
BaarDanaTraderPOS/DataSet1.Designer.cs
99,988
C#
using System; using System.Collections.Generic; namespace Sg4Mvc.ModelUnbinders; public class ModelUnbinderProviders { private readonly List<IModelUnbinderProvider> _unbinderProviders = new List<IModelUnbinderProvider>(); public virtual void Add(IModelUnbinderProvider unbinderProvider) { _unbinderProviders.Add(unbinderProvider); } public virtual IModelUnbinder FindUnbinderFor(Type type) { foreach (var unbinderProvider in _unbinderProviders) { var result = unbinderProvider.GetUnbinder(type); if (result != null) { return result; } } return null; } public virtual void Clear() { _unbinderProviders.Clear(); } }
24.83871
106
0.649351
[ "Apache-2.0" ]
MarkFl12/R4MVC
src/Sg4Mvc/ModelUnbinders/ModelUnbinderProviders.cs
772
C#
using System.Threading.Tasks; using OrchardCore.ContentManagement; namespace OrchardCore.ContentLocalization.Handlers { public abstract class ContentLocalizationPartHandlerBase<TPart> : IContentLocalizationPartHandler where TPart : ContentPart, new() { async Task IContentLocalizationPartHandler.LocalizingAsync(LocalizationContentContext context, ContentPart part) { if (part is TPart tpart) { await LocalizingAsync(context, tpart); } } async Task IContentLocalizationPartHandler.LocalizedAsync(LocalizationContentContext context, ContentPart part) { if (part is TPart tpart) { await LocalizedAsync(context, tpart); } } public virtual Task LocalizingAsync(LocalizationContentContext context, TPart part) => Task.CompletedTask; public virtual Task LocalizedAsync(LocalizationContentContext context, TPart part) => Task.CompletedTask; } }
37.777778
134
0.689216
[ "BSD-3-Clause" ]
1051324354/OrchardCore
src/OrchardCore/OrchardCore.ContentLocalization.Abstractions/Handlers/ContentLocalizationPartHandlerBase.cs
1,020
C#
using System; namespace _04.TransportPrice { class Program { static void Main(string[] args) { const double TaxiStartPrice = 0.70; const double TaxiDaylyRate = 0.79; const double TaxiNightRate = 0.90; const double BussPrice = 0.09; const double TrainPrice = 0.06; const int BussMinDistance = 20; const int TrainMinDistance = 100; int km = int.Parse(Console.ReadLine()); string time = Console.ReadLine().ToLower(); if (km < 20) { if (time == "day") { Console.WriteLine($"{(km * TaxiDaylyRate + TaxiStartPrice):f2}"); } else if (time == "night") { Console.WriteLine($"{(km * TaxiNightRate + TaxiStartPrice):f2}"); } } if (km >= BussMinDistance && km < TrainMinDistance) { Console.WriteLine($"{(km * BussPrice):f2}"); } if (km >= TrainMinDistance) { Console.WriteLine($"{(km * TrainPrice):f2}"); } } } }
26.369565
85
0.456719
[ "MIT" ]
anidz/softuni-cs-fundamentals
ConditionalStatementsMore Exercises/04.TransportPrice/Program.cs
1,215
C#
using System.Collections.Generic; namespace Manager.Core.Types { public interface IPagedFilter<TResult, in TQuery> where TQuery : IQuery { PagedResult<TResult> Filter(IEnumerable<TResult> values, TQuery query); } }
26.222222
79
0.728814
[ "MIT" ]
PiotrKantorowicz1/ScheduleManager
src/Manager.Core/Types/IPagedFilter.cs
238
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview { using Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="AzureSynapseScanRulesetPropertiesAutoGenerated" /// /> /// </summary> public partial class AzureSynapseScanRulesetPropertiesAutoGeneratedTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="AzureSynapseScanRulesetPropertiesAutoGenerated" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="AzureSynapseScanRulesetPropertiesAutoGenerated" /> type, /// otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="AzureSynapseScanRulesetPropertiesAutoGenerated" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="AzureSynapseScanRulesetPropertiesAutoGenerated" /// />.</param> /// <returns> /// an instance of <see cref="AzureSynapseScanRulesetPropertiesAutoGenerated" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IAzureSynapseScanRulesetPropertiesAutoGenerated ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Models.Api20211001Preview.IAzureSynapseScanRulesetPropertiesAutoGenerated).IsAssignableFrom(type)) { return sourceValue; } try { return AzureSynapseScanRulesetPropertiesAutoGenerated.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return AzureSynapseScanRulesetPropertiesAutoGenerated.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return AzureSynapseScanRulesetPropertiesAutoGenerated.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
53.573333
253
0.607267
[ "MIT" ]
Agazoth/azure-powershell
src/Purview/Purviewdata.Autorest/generated/api/Models/Api20211001Preview/AzureSynapseScanRulesetPropertiesAutoGenerated.TypeConverter.cs
7,887
C#
namespace GreenHouse.Core.GraphQl.requestHelpers { public class PagedRequest { public int Take { get; set; } = 100; public int Offset { get; set; } } }
20
48
0.611111
[ "MIT" ]
GagiuFilip1/GreenHouse.WebApi
GreenHouse.WebApi.Core/GraphQl/requestHelpers/PagedRequest.cs
180
C#
namespace Be.Vlaanderen.Basisregisters.Shaperon { using System; using System.Globalization; using System.IO; public class DbaseNullableInt16 : DbaseFieldValue { public static readonly DbaseIntegerDigits MaximumIntegerDigits = DbaseInt16.MaximumIntegerDigits; private short? _value; public DbaseNullableInt16(DbaseField field, short? value = null) : base(field) { if (field == null) throw new ArgumentNullException(nameof(field)); if (field.FieldType != DbaseFieldType.Number && field.FieldType != DbaseFieldType.Float) throw new ArgumentException( $"The field {field.Name}'s type must be either number or float to use it as a short integer field.", nameof(field)); if (field.DecimalCount.ToInt32() != 0) throw new ArgumentException( $"The number field {field.Name}'s decimal count must be 0 to use it as a short integer field.", nameof(field)); Value = value; } public bool AcceptsValue(short? value) { if (value.HasValue) return DbaseInt16.FormatAsString(value.Value).Length <= Field.Length.ToInt32(); return true; } public short? Value { get => _value; set { if (value.HasValue) { var length = DbaseInt16.FormatAsString(value.Value).Length; if (length > Field.Length.ToInt32()) throw new FormatException( $"The value length {length} of field {Field.Name} is greater than its field length {Field.Length}."); } _value = value; } } public override void Reset() => _value = default; public override void Read(BinaryReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Value = reader.ReadAsNullableInt16(Field); } public override void Write(BinaryWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); writer.WriteAsNullableInt16(Field, Value); } public override void Accept(IDbaseFieldValueVisitor visitor) => (visitor as ITypedDbaseFieldValueVisitor)?.Visit(this); } }
32.371795
129
0.561188
[ "MIT" ]
Informatievlaanderen/shaperon
src/Be.Vlaanderen.Basisregisters.Shaperon/DbaseNullableInt16.cs
2,525
C#
using System.Web; using ServiceStack.Host.Handlers; namespace ServiceStack { public class PredefinedRoutesFeature : IPlugin { public void Register(IAppHost appHost) { appHost.CatchAllHandlers.Add(ProcessRequest); } public IHttpHandler ProcessRequest(string httpMethod, string pathInfo, string filePath) { var pathParts = pathInfo.TrimStart('/').Split('/'); if (pathParts.Length == 0) return null; return GetHandlerForPathParts(pathParts); } private static IHttpHandler GetHandlerForPathParts(string[] pathParts) { var pathController = pathParts[0].ToLower(); if (pathParts.Length == 1) { #if !NETSTANDARD1_6 if (pathController == "soap11") return new Soap11MessageReplyHttpHandler(); if (pathController == "soap12") return new Soap12MessageReplyHttpHandler(); #endif return null; } var pathAction = pathParts[1].ToLower(); var requestName = pathParts.Length > 2 ? pathParts[2] : null; var isReply = pathAction == "reply"; var isOneWay = pathAction == "oneway"; switch (pathController) { case "json": if (isReply) return new JsonReplyHandler { RequestName = requestName }; if (isOneWay) return new JsonOneWayHandler { RequestName = requestName }; break; case "xml": if (isReply) return new XmlReplyHandler { RequestName = requestName }; if (isOneWay) return new XmlOneWayHandler { RequestName = requestName }; break; case "jsv": if (isReply) return new JsvReplyHandler { RequestName = requestName }; if (isOneWay) return new JsvOneWayHandler { RequestName = requestName }; break; default: string contentType; if (HostContext.ContentTypes.ContentTypeFormats.TryGetValue(pathController, out contentType)) { var feature = contentType.ToFeature(); if (feature == Feature.None) feature = Feature.CustomFormat; if (isReply) return new GenericHandler(contentType, RequestAttributes.Reply, feature) { RequestName = requestName, }; if (isOneWay) return new GenericHandler(contentType, RequestAttributes.OneWay, feature) { RequestName = requestName, }; } break; } return null; } } }
37.755814
114
0.469972
[ "Apache-2.0" ]
BruceCowan-AI/ServiceStack
src/ServiceStack/PredefinedRoutesFeature.cs
3,164
C#
using Stencil.Forms.Base; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Stencil.Forms.Presentation.Shells.Tablet { public partial class TabletMenuShellPage : BaseContentPage, IShellView { public TabletMenuShellPage() : base(nameof(TabletMenuShellPage)) { InitializeComponent(); } public View MenuContent { get { return vwMenu.Content; } set { vwMenu.Content = value; } } public View ViewContent { get { return vwContent.Content; } set { vwContent.Content = value; } } } }
19.609756
74
0.46393
[ "MIT" ]
wmansfield/stencil.v2
mobile/Stencil.Forms/Platforms/Common/Presentation/Shells/Tablet/TabletMenuShellPage.xaml.cs
806
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.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Runtime.InteropServices; using System.Windows.Forms.VisualStyles; using static Interop; namespace System.Windows.Forms { public class DataGridViewComboBoxCell : DataGridViewCell { private static readonly int PropComboBoxCellDataSource = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellDisplayMember = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellValueMember = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellItems = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellDropDownWidth = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellMaxDropDownItems = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellEditingComboBox = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellValueMemberProp = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellDisplayMemberProp = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellDataManager = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellColumnTemplate = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellFlatStyle = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellDisplayStyle = PropertyStore.CreateKey(); private static readonly int PropComboBoxCellDisplayStyleForCurrentCellOnly = PropertyStore.CreateKey(); private const byte DATAGRIDVIEWCOMBOBOXCELL_margin = 3; private const byte DATAGRIDVIEWCOMBOBOXCELL_nonXPTriangleHeight = 4; private const byte DATAGRIDVIEWCOMBOBOXCELL_nonXPTriangleWidth = 7; private const byte DATAGRIDVIEWCOMBOBOXCELL_horizontalTextMarginLeft = 0; private const byte DATAGRIDVIEWCOMBOBOXCELL_verticalTextMarginTopWithWrapping = 0; private const byte DATAGRIDVIEWCOMBOBOXCELL_verticalTextMarginTopWithoutWrapping = 1; private const byte DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick = 0x01; private const byte DATAGRIDVIEWCOMBOBOXCELL_sorted = 0x02; private const byte DATAGRIDVIEWCOMBOBOXCELL_createItemsFromDataSource = 0x04; private const byte DATAGRIDVIEWCOMBOBOXCELL_autoComplete = 0x08; private const byte DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp = 0x10; private const byte DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp = 0x20; internal const int DATAGRIDVIEWCOMBOBOXCELL_defaultMaxDropDownItems = 8; private static readonly Type defaultFormattedValueType = typeof(string); private static readonly Type defaultEditType = typeof(DataGridViewComboBoxEditingControl); private static readonly Type defaultValueType = typeof(object); private static readonly Type cellType = typeof(DataGridViewComboBoxCell); private byte flags; // see DATAGRIDVIEWCOMBOBOXCELL_ consts above private static bool mouseInDropDownButtonBounds = false; private static int cachedDropDownWidth = -1; // Autosizing changed for VS // We need to make ItemFromComboBoxDataSource as fast as possible because ItemFromComboBoxDataSource is getting called a lot // during AutoSize. To do that we keep a copy of the key and the value. //private object keyUsedDuringAutoSize = null; //private object valueUsedDuringAutoSize = null; private static bool isScalingInitialized = false; private static readonly int OFFSET_2PIXELS = 2; private static int offset2X = OFFSET_2PIXELS; private static int offset2Y = OFFSET_2PIXELS; private static byte nonXPTriangleHeight = DATAGRIDVIEWCOMBOBOXCELL_nonXPTriangleHeight; private static byte nonXPTriangleWidth = DATAGRIDVIEWCOMBOBOXCELL_nonXPTriangleWidth; public DataGridViewComboBoxCell() { flags = DATAGRIDVIEWCOMBOBOXCELL_autoComplete; if (!isScalingInitialized) { if (DpiHelper.IsScalingRequired) { offset2X = DpiHelper.LogicalToDeviceUnitsX(OFFSET_2PIXELS); offset2Y = DpiHelper.LogicalToDeviceUnitsY(OFFSET_2PIXELS); nonXPTriangleWidth = (byte)DpiHelper.LogicalToDeviceUnitsX(DATAGRIDVIEWCOMBOBOXCELL_nonXPTriangleWidth); nonXPTriangleHeight = (byte)DpiHelper.LogicalToDeviceUnitsY(DATAGRIDVIEWCOMBOBOXCELL_nonXPTriangleHeight); } isScalingInitialized = true; } } /// <summary> /// Creates a new AccessibleObject for this DataGridViewComboBoxCell instance. /// The AccessibleObject instance returned by this method supports ControlType UIA property. /// </summary> /// <returns> /// AccessibleObject for this DataGridViewComboBoxCell instance. /// </returns> protected override AccessibleObject CreateAccessibilityInstance() { return new DataGridViewComboBoxCellAccessibleObject(this); } [DefaultValue(true)] public virtual bool AutoComplete { get { return ((flags & DATAGRIDVIEWCOMBOBOXCELL_autoComplete) != 0x00); } set { //CheckNoSharedCell(); if (value != AutoComplete) { if (value) { flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_autoComplete; } else { flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_autoComplete); } if (OwnsEditingComboBox(RowIndex)) { if (value) { EditingComboBox.AutoCompleteSource = AutoCompleteSource.ListItems; EditingComboBox.AutoCompleteMode = AutoCompleteMode.Append; } else { EditingComboBox.AutoCompleteMode = AutoCompleteMode.None; EditingComboBox.AutoCompleteSource = AutoCompleteSource.None; } } } } } private CurrencyManager DataManager { get { return GetDataManager(DataGridView); } set { if (value != null || Properties.ContainsObject(PropComboBoxCellDataManager)) { Properties.SetObject(PropComboBoxCellDataManager, value); } } } public virtual object DataSource { get { return Properties.GetObject(PropComboBoxCellDataSource); } set { //CheckNoSharedCell(); // Same check as for ListControl's DataSource if (value != null && !(value is IList || value is IListSource)) { throw new ArgumentException(SR.BadDataSourceForComplexBinding); } if (DataSource != value) { // Invalidate the currency manager DataManager = null; UnwireDataSource(); Properties.SetObject(PropComboBoxCellDataSource, value); WireDataSource(value); // Invalidate existing Items collection CreateItemsFromDataSource = true; cachedDropDownWidth = -1; try { InitializeDisplayMemberPropertyDescriptor(DisplayMember); } catch (Exception exception) { if (ClientUtils.IsCriticalException(exception)) { throw; } Debug.Assert(DisplayMember != null && DisplayMember.Length > 0); DisplayMemberInternal = null; } try { InitializeValueMemberPropertyDescriptor(ValueMember); } catch (Exception exception) { if (ClientUtils.IsCriticalException(exception)) { throw; } Debug.Assert(ValueMember != null && ValueMember.Length > 0); ValueMemberInternal = null; } if (value == null) { DisplayMemberInternal = null; ValueMemberInternal = null; } if (OwnsEditingComboBox(RowIndex)) { EditingComboBox.DataSource = value; InitializeComboBoxText(); } else { OnCommonChange(); } } } } [DefaultValue("")] public virtual string DisplayMember { get { object displayMember = Properties.GetObject(PropComboBoxCellDisplayMember); if (displayMember == null) { return string.Empty; } else { return (string)displayMember; } } set { //CheckNoSharedCell(); DisplayMemberInternal = value; if (OwnsEditingComboBox(RowIndex)) { EditingComboBox.DisplayMember = value; InitializeComboBoxText(); } else { OnCommonChange(); } } } private string DisplayMemberInternal { set { InitializeDisplayMemberPropertyDescriptor(value); if ((value != null && value.Length > 0) || Properties.ContainsObject(PropComboBoxCellDisplayMember)) { Properties.SetObject(PropComboBoxCellDisplayMember, value); } } } private PropertyDescriptor DisplayMemberProperty { get { return (PropertyDescriptor)Properties.GetObject(PropComboBoxCellDisplayMemberProp); } set { if (value != null || Properties.ContainsObject(PropComboBoxCellDisplayMemberProp)) { Properties.SetObject(PropComboBoxCellDisplayMemberProp, value); } } } [DefaultValue(DataGridViewComboBoxDisplayStyle.DropDownButton)] public DataGridViewComboBoxDisplayStyle DisplayStyle { get { int displayStyle = Properties.GetInteger(PropComboBoxCellDisplayStyle, out bool found); if (found) { return (DataGridViewComboBoxDisplayStyle)displayStyle; } return DataGridViewComboBoxDisplayStyle.DropDownButton; } set { // Sequential enum. Valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)DataGridViewComboBoxDisplayStyle.ComboBox, (int)DataGridViewComboBoxDisplayStyle.Nothing)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DataGridViewComboBoxDisplayStyle)); } if (value != DisplayStyle) { Properties.SetInteger(PropComboBoxCellDisplayStyle, (int)value); if (DataGridView != null) { if (RowIndex != -1) { DataGridView.InvalidateCell(this); } else { DataGridView.InvalidateColumnInternal(ColumnIndex); } } } } } internal DataGridViewComboBoxDisplayStyle DisplayStyleInternal { set { Debug.Assert(value >= DataGridViewComboBoxDisplayStyle.ComboBox && value <= DataGridViewComboBoxDisplayStyle.Nothing); if (value != DisplayStyle) { Properties.SetInteger(PropComboBoxCellDisplayStyle, (int)value); } } } [DefaultValue(false)] public bool DisplayStyleForCurrentCellOnly { get { int displayStyleForCurrentCellOnly = Properties.GetInteger(PropComboBoxCellDisplayStyleForCurrentCellOnly, out bool found); if (found) { return displayStyleForCurrentCellOnly == 0 ? false : true; } return false; } set { if (value != DisplayStyleForCurrentCellOnly) { Properties.SetInteger(PropComboBoxCellDisplayStyleForCurrentCellOnly, value ? 1 : 0); if (DataGridView != null) { if (RowIndex != -1) { DataGridView.InvalidateCell(this); } else { DataGridView.InvalidateColumnInternal(ColumnIndex); } } } } } internal bool DisplayStyleForCurrentCellOnlyInternal { set { if (value != DisplayStyleForCurrentCellOnly) { Properties.SetInteger(PropComboBoxCellDisplayStyleForCurrentCellOnly, value ? 1 : 0); } } } private Type DisplayType { get { if (DisplayMemberProperty != null) { return DisplayMemberProperty.PropertyType; } else if (ValueMemberProperty != null) { return ValueMemberProperty.PropertyType; } else { return defaultFormattedValueType; } } } private TypeConverter DisplayTypeConverter { get { if (DataGridView != null) { return DataGridView.GetCachedTypeConverter(DisplayType); } else { return TypeDescriptor.GetConverter(DisplayType); } } } [DefaultValue(1)] public virtual int DropDownWidth { get { int dropDownWidth = Properties.GetInteger(PropComboBoxCellDropDownWidth, out bool found); return found ? dropDownWidth : 1; } set { //CheckNoSharedCell(); if (value < 1) { throw new ArgumentOutOfRangeException(nameof(DropDownWidth), value, string.Format(SR.DataGridViewComboBoxCell_DropDownWidthOutOfRange, 1)); } Properties.SetInteger(PropComboBoxCellDropDownWidth, (int)value); if (OwnsEditingComboBox(RowIndex)) { EditingComboBox.DropDownWidth = value; } } } private DataGridViewComboBoxEditingControl EditingComboBox { get { return (DataGridViewComboBoxEditingControl)Properties.GetObject(PropComboBoxCellEditingComboBox); } set { if (value != null || Properties.ContainsObject(PropComboBoxCellEditingComboBox)) { Properties.SetObject(PropComboBoxCellEditingComboBox, value); } } } public override Type EditType { get { return defaultEditType; } } [DefaultValue(FlatStyle.Standard)] public FlatStyle FlatStyle { get { int flatStyle = Properties.GetInteger(PropComboBoxCellFlatStyle, out bool found); if (found) { return (FlatStyle)flatStyle; } return FlatStyle.Standard; } set { // Sequential enum. Valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FlatStyle)); } if (value != FlatStyle) { Properties.SetInteger(PropComboBoxCellFlatStyle, (int)value); OnCommonChange(); } } } internal FlatStyle FlatStyleInternal { set { Debug.Assert(value >= FlatStyle.Flat && value <= FlatStyle.System); if (value != FlatStyle) { Properties.SetInteger(PropComboBoxCellFlatStyle, (int)value); } } } public override Type FormattedValueType { get { return defaultFormattedValueType; } } internal bool HasItems { get { return Properties.ContainsObject(PropComboBoxCellItems) && Properties.GetObject(PropComboBoxCellItems) != null; } } [Browsable(false)] public virtual ObjectCollection Items { get { return GetItems(DataGridView); } } [DefaultValue(DATAGRIDVIEWCOMBOBOXCELL_defaultMaxDropDownItems)] public virtual int MaxDropDownItems { get { int maxDropDownItems = Properties.GetInteger(PropComboBoxCellMaxDropDownItems, out bool found); if (found) { return maxDropDownItems; } return DATAGRIDVIEWCOMBOBOXCELL_defaultMaxDropDownItems; } set { //CheckNoSharedCell(); if (value < 1 || value > 100) { throw new ArgumentOutOfRangeException(nameof(MaxDropDownItems), value, string.Format(SR.DataGridViewComboBoxCell_MaxDropDownItemsOutOfRange, 1, 100)); } Properties.SetInteger(PropComboBoxCellMaxDropDownItems, (int)value); if (OwnsEditingComboBox(RowIndex)) { EditingComboBox.MaxDropDownItems = value; } } } private bool PaintXPThemes { get { bool paintFlat = FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup; return !paintFlat && DataGridView.ApplyVisualStylesToInnerCells; } } private static bool PostXPThemesExist { get { return VisualStyleRenderer.IsElementDefined(VisualStyleElement.ComboBox.ReadOnlyButton.Normal); } } [DefaultValue(false)] public virtual bool Sorted { get { return ((flags & DATAGRIDVIEWCOMBOBOXCELL_sorted) != 0x00); } set { //CheckNoSharedCell(); if (value != Sorted) { if (value) { if (DataSource == null) { Items.SortInternal(); } else { throw new ArgumentException(SR.ComboBoxSortWithDataSource); } flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_sorted; } else { flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_sorted); } if (OwnsEditingComboBox(RowIndex)) { EditingComboBox.Sorted = value; } } } } internal DataGridViewComboBoxColumn TemplateComboBoxColumn { get { return (DataGridViewComboBoxColumn)Properties.GetObject(PropComboBoxCellColumnTemplate); } set { Properties.SetObject(PropComboBoxCellColumnTemplate, value); } } [DefaultValue("")] public virtual string ValueMember { get { object valueMember = Properties.GetObject(PropComboBoxCellValueMember); if (valueMember == null) { return string.Empty; } else { return (string)valueMember; } } set { //CheckNoSharedCell(); ValueMemberInternal = value; if (OwnsEditingComboBox(RowIndex)) { EditingComboBox.ValueMember = value; InitializeComboBoxText(); } else { OnCommonChange(); } } } private string ValueMemberInternal { set { InitializeValueMemberPropertyDescriptor(value); if ((value != null && value.Length > 0) || Properties.ContainsObject(PropComboBoxCellValueMember)) { Properties.SetObject(PropComboBoxCellValueMember, value); } } } private PropertyDescriptor ValueMemberProperty { get { return (PropertyDescriptor)Properties.GetObject(PropComboBoxCellValueMemberProp); } set { if (value != null || Properties.ContainsObject(PropComboBoxCellValueMemberProp)) { Properties.SetObject(PropComboBoxCellValueMemberProp, value); } } } public override Type ValueType { get { if (ValueMemberProperty != null) { return ValueMemberProperty.PropertyType; } else if (DisplayMemberProperty != null) { return DisplayMemberProperty.PropertyType; } else { Type baseValueType = base.ValueType; if (baseValueType != null) { return baseValueType; } return defaultValueType; } } } // Called when the row that owns the editing control gets unshared. internal override void CacheEditingControl() { EditingComboBox = DataGridView.EditingControl as DataGridViewComboBoxEditingControl; } private void CheckDropDownList(int x, int y, int rowIndex) { Debug.Assert(EditingComboBox != null); DataGridViewAdvancedBorderStyle dgvabsPlaceholder = new DataGridViewAdvancedBorderStyle(), dgvabsEffective; dgvabsEffective = AdjustCellBorderStyle(DataGridView.AdvancedCellBorderStyle, dgvabsPlaceholder, false /*singleVerticalBorderAdded*/, false /*singleHorizontalBorderAdded*/, false /*isFirstDisplayedColumn*/, false /*isFirstDisplayedRow*/); DataGridViewCellStyle cellStyle = GetInheritedStyle(null, rowIndex, false /*includeColors*/); Rectangle borderAndPaddingWidths = BorderWidths(dgvabsEffective); borderAndPaddingWidths.X += cellStyle.Padding.Left; borderAndPaddingWidths.Y += cellStyle.Padding.Top; borderAndPaddingWidths.Width += cellStyle.Padding.Right; borderAndPaddingWidths.Height += cellStyle.Padding.Bottom; Size size = GetSize(rowIndex); Size adjustedSize = new Size(size.Width - borderAndPaddingWidths.X - borderAndPaddingWidths.Width, size.Height - borderAndPaddingWidths.Y - borderAndPaddingWidths.Height); int dropHeight; using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) { dropHeight = Math.Min(GetDropDownButtonHeight(g, cellStyle), adjustedSize.Height - 2); } int dropWidth = Math.Min(SystemInformation.HorizontalScrollBarThumbWidth, adjustedSize.Width - 2 * DATAGRIDVIEWCOMBOBOXCELL_margin - 1); if (dropHeight > 0 && dropWidth > 0 && y >= borderAndPaddingWidths.Y + 1 && y <= borderAndPaddingWidths.Y + 1 + dropHeight) { if (DataGridView.RightToLeftInternal) { if (x >= borderAndPaddingWidths.X + 1 && x <= borderAndPaddingWidths.X + dropWidth + 1) { EditingComboBox.DroppedDown = true; } } else { if (x >= size.Width - borderAndPaddingWidths.Width - dropWidth - 1 && x <= size.Width - borderAndPaddingWidths.Width - 1) { EditingComboBox.DroppedDown = true; } } } } private void CheckNoDataSource() { if (DataSource != null) { throw new ArgumentException(SR.DataSourceLocksItems); } } private void ComboBox_DropDown(object sender, EventArgs e) { Debug.Assert(DataGridView != null); Debug.Assert(EditingComboBox != null); ComboBox comboBox = EditingComboBox; if (OwningColumn is DataGridViewComboBoxColumn owningComboBoxColumn) { DataGridViewAutoSizeColumnMode autoSizeColumnMode = owningComboBoxColumn.GetInheritedAutoSizeMode(DataGridView); if (autoSizeColumnMode != DataGridViewAutoSizeColumnMode.ColumnHeader && autoSizeColumnMode != DataGridViewAutoSizeColumnMode.Fill && autoSizeColumnMode != DataGridViewAutoSizeColumnMode.None) { if (DropDownWidth == 1) { // Owning combobox column is autosized based on inner cells. // Resize the dropdown list based on the max width of the items. if (cachedDropDownWidth == -1) { int maxPreferredWidth = -1; if ((HasItems || CreateItemsFromDataSource) && Items.Count > 0) { foreach (object item in Items) { Size preferredSize = TextRenderer.MeasureText(comboBox.GetItemText(item), comboBox.Font); if (preferredSize.Width > maxPreferredWidth) { maxPreferredWidth = preferredSize.Width; } } } cachedDropDownWidth = maxPreferredWidth + 2 + SystemInformation.VerticalScrollBarWidth; } Debug.Assert(cachedDropDownWidth >= 1); UnsafeNativeMethods.SendMessage(new HandleRef(comboBox, comboBox.Handle), NativeMethods.CB_SETDROPPEDWIDTH, cachedDropDownWidth, 0); } } else { // The dropdown width may have been previously adjusted to the items because of the owning column autosized. // The dropdown width needs to be realigned to the DropDownWidth property value. int dropDownWidth = unchecked((int)(long)UnsafeNativeMethods.SendMessage(new HandleRef(comboBox, comboBox.Handle), NativeMethods.CB_GETDROPPEDWIDTH, 0, 0)); if (dropDownWidth != DropDownWidth) { UnsafeNativeMethods.SendMessage(new HandleRef(comboBox, comboBox.Handle), NativeMethods.CB_SETDROPPEDWIDTH, DropDownWidth, 0); } } } } public override object Clone() { DataGridViewComboBoxCell dataGridViewCell; Type thisType = GetType(); if (thisType == cellType) //performance improvement { dataGridViewCell = new DataGridViewComboBoxCell(); } else { // dataGridViewCell = (DataGridViewComboBoxCell)System.Activator.CreateInstance(thisType); } base.CloneInternal(dataGridViewCell); dataGridViewCell.DropDownWidth = DropDownWidth; dataGridViewCell.MaxDropDownItems = MaxDropDownItems; dataGridViewCell.CreateItemsFromDataSource = false; dataGridViewCell.DataSource = DataSource; dataGridViewCell.DisplayMember = DisplayMember; dataGridViewCell.ValueMember = ValueMember; if (HasItems && DataSource == null && Items.Count > 0) { dataGridViewCell.Items.AddRangeInternal(Items.InnerArray.ToArray()); } dataGridViewCell.AutoComplete = AutoComplete; dataGridViewCell.Sorted = Sorted; dataGridViewCell.FlatStyleInternal = FlatStyle; dataGridViewCell.DisplayStyleInternal = DisplayStyle; dataGridViewCell.DisplayStyleForCurrentCellOnlyInternal = DisplayStyleForCurrentCellOnly; return dataGridViewCell; } private bool CreateItemsFromDataSource { get { return ((flags & DATAGRIDVIEWCOMBOBOXCELL_createItemsFromDataSource) != 0x00); } set { if (value) { flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_createItemsFromDataSource; } else { flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_createItemsFromDataSource); } } } private void DataSource_Disposed(object sender, EventArgs e) { Debug.Assert(sender == DataSource, "How can we get dispose notification from anything other than our DataSource?"); DataSource = null; } private void DataSource_Initialized(object sender, EventArgs e) { Debug.Assert(sender == DataSource); Debug.Assert(DataSource is ISupportInitializeNotification); Debug.Assert((flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) != 0x00); // Unhook the Initialized event. if (DataSource is ISupportInitializeNotification dsInit) { dsInit.Initialized -= new EventHandler(DataSource_Initialized); } // The wait is over: DataSource is initialized. flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp); // Check the DisplayMember and ValueMember values - will throw if values don't match existing fields. InitializeDisplayMemberPropertyDescriptor(DisplayMember); InitializeValueMemberPropertyDescriptor(ValueMember); } public override void DetachEditingControl() { DataGridView dgv = DataGridView; if (dgv == null || dgv.EditingControl == null) { throw new InvalidOperationException(); } if (EditingComboBox != null && (flags & DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp) != 0x00) { EditingComboBox.DropDown -= new EventHandler(ComboBox_DropDown); flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp); } EditingComboBox = null; base.DetachEditingControl(); } protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex) { if (cellStyle == null) { throw new ArgumentNullException(nameof(cellStyle)); } if (DataGridView == null || rowIndex < 0 || OwningColumn == null) { return Rectangle.Empty; } object value = GetValue(rowIndex); object formattedValue = GetEditedFormattedValue(value, rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting); ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle contentBounds = PaintPrivate(graphics, cellBounds, cellBounds, rowIndex, cellState, formattedValue, null /*errorText*/, // contentBounds is independent of errorText cellStyle, dgvabsEffective, out Rectangle dropDownButtonRect, // not used DataGridViewPaintParts.ContentForeground, true /*computeContentBounds*/, false /*computeErrorIconBounds*/, false /*computeDropDownButtonRect*/, false /*paint*/); #if DEBUG Rectangle contentBoundsDebug = PaintPrivate(graphics, cellBounds, cellBounds, rowIndex, cellState, formattedValue, GetErrorText(rowIndex), cellStyle, dgvabsEffective, out dropDownButtonRect, // not used DataGridViewPaintParts.ContentForeground, true /*computeContentBounds*/, false /*computeErrorIconBounds*/, false /*computeDropDownButtonRect*/, false /*paint*/); Debug.Assert(contentBoundsDebug.Equals(contentBounds)); #endif return contentBounds; } private CurrencyManager GetDataManager(DataGridView dataGridView) { CurrencyManager cm = (CurrencyManager)Properties.GetObject(PropComboBoxCellDataManager); if (cm == null && DataSource != null && dataGridView != null && dataGridView.BindingContext != null && !(DataSource == Convert.DBNull)) { if (DataSource is ISupportInitializeNotification dsInit && !dsInit.IsInitialized) { if ((flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) == 0x00) { dsInit.Initialized += new EventHandler(DataSource_Initialized); flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp; } } else { cm = (CurrencyManager)dataGridView.BindingContext[DataSource]; DataManager = cm; } } return cm; } private protected override string GetDefaultToolTipText() { if (string.IsNullOrEmpty(Value?.ToString()?.Trim(' ')) || Value is DBNull) { return SR.DefaultDataGridViewComboBoxCellTollTipText; } return null; } private int GetDropDownButtonHeight(Graphics graphics, DataGridViewCellStyle cellStyle) { int adjustment = 4; if (PaintXPThemes) { if (PostXPThemesExist) { adjustment = 8; } else { adjustment = 6; } } return DataGridViewCell.MeasureTextHeight(graphics, " ", cellStyle.Font, int.MaxValue, TextFormatFlags.Default) + adjustment; } protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex) { if (cellStyle == null) { throw new ArgumentNullException(nameof(cellStyle)); } if (DataGridView == null || rowIndex < 0 || OwningColumn == null || !DataGridView.ShowCellErrors || string.IsNullOrEmpty(GetErrorText(rowIndex))) { return Rectangle.Empty; } object value = GetValue(rowIndex); object formattedValue = GetEditedFormattedValue(value, rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting); ComputeBorderStyleCellStateAndCellBounds(rowIndex, out DataGridViewAdvancedBorderStyle dgvabsEffective, out DataGridViewElementStates cellState, out Rectangle cellBounds); Rectangle errorIconBounds = PaintPrivate(graphics, cellBounds, cellBounds, rowIndex, cellState, formattedValue, GetErrorText(rowIndex), cellStyle, dgvabsEffective, out Rectangle dropDownButtonRect, // not used DataGridViewPaintParts.ContentForeground, false /*computeContentBounds*/, true /*computeErrorBounds*/, false /*computeDropDownButtonRect*/, false /*paint*/); #if DEBUG Rectangle errorIconBoundsDebug = PaintPrivate(graphics, cellBounds, cellBounds, rowIndex, cellState, formattedValue, GetErrorText(rowIndex), cellStyle, dgvabsEffective, out dropDownButtonRect, // not used DataGridViewPaintParts.ContentForeground, false /*computeContentBounds*/, true /*computeErrorBounds*/, false /*computeDropDownButtonRect*/, false /*paint*/); Debug.Assert(errorIconBoundsDebug.Equals(errorIconBounds)); #endif return errorIconBounds; } protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { if (valueTypeConverter == null) { if (ValueMemberProperty != null) { valueTypeConverter = ValueMemberProperty.Converter; } else if (DisplayMemberProperty != null) { valueTypeConverter = DisplayMemberProperty.Converter; } } if (value == null || ((ValueType != null && !ValueType.IsAssignableFrom(value.GetType())) && value != System.DBNull.Value)) { // Do not raise the DataError event if the value is null and the row is the 'new row'. if (value == null /* && ((this.DataGridView != null && rowIndex == this.DataGridView.NewRowIndex) || this.Items.Count == 0)*/) { // Debug.Assert(rowIndex != -1 || this.Items.Count == 0); return base.GetFormattedValue(null, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context); } if (DataGridView != null) { DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs( new FormatException(SR.DataGridViewComboBoxCell_InvalidValue), ColumnIndex, rowIndex, context); RaiseDataError(dgvdee); if (dgvdee.ThrowException) { throw dgvdee.Exception; } } return base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context); } string strValue = value as string; if ((DataManager != null && (ValueMemberProperty != null || DisplayMemberProperty != null)) || !string.IsNullOrEmpty(ValueMember) || !string.IsNullOrEmpty(DisplayMember)) { if (!LookupDisplayValue(rowIndex, value, out object displayValue)) { if (value == System.DBNull.Value) { displayValue = System.DBNull.Value; } else if (strValue != null && string.IsNullOrEmpty(strValue) && DisplayType == typeof(string)) { displayValue = string.Empty; } else if (DataGridView != null) { DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs( new ArgumentException(SR.DataGridViewComboBoxCell_InvalidValue), ColumnIndex, rowIndex, context); RaiseDataError(dgvdee); if (dgvdee.ThrowException) { throw dgvdee.Exception; } if (OwnsEditingComboBox(rowIndex)) { ((IDataGridViewEditingControl)EditingComboBox).EditingControlValueChanged = true; DataGridView.NotifyCurrentCellDirty(true); } } } return base.GetFormattedValue(displayValue, rowIndex, ref cellStyle, DisplayTypeConverter, formattedValueTypeConverter, context); } else { if (!Items.Contains(value) && value != System.DBNull.Value && (!(value is string) || !string.IsNullOrEmpty(strValue))) { if (DataGridView != null) { DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs( new ArgumentException(SR.DataGridViewComboBoxCell_InvalidValue), ColumnIndex, rowIndex, context); RaiseDataError(dgvdee); if (dgvdee.ThrowException) { throw dgvdee.Exception; } } if (Items.Count > 0) { value = Items[0]; } else { value = string.Empty; } } return base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context); } } internal string GetItemDisplayText(object item) { object displayValue = GetItemDisplayValue(item); return (displayValue != null) ? Convert.ToString(displayValue, CultureInfo.CurrentCulture) : string.Empty; } internal object GetItemDisplayValue(object item) { Debug.Assert(item != null); bool displayValueSet = false; object displayValue = null; if (DisplayMemberProperty != null) { displayValue = DisplayMemberProperty.GetValue(item); displayValueSet = true; } else if (ValueMemberProperty != null) { displayValue = ValueMemberProperty.GetValue(item); displayValueSet = true; } else if (!string.IsNullOrEmpty(DisplayMember)) { PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(DisplayMember, true /*caseInsensitive*/); if (propDesc != null) { displayValue = propDesc.GetValue(item); displayValueSet = true; } } else if (!string.IsNullOrEmpty(ValueMember)) { PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(ValueMember, true /*caseInsensitive*/); if (propDesc != null) { displayValue = propDesc.GetValue(item); displayValueSet = true; } } if (!displayValueSet) { displayValue = item; } return displayValue; } internal ObjectCollection GetItems(DataGridView dataGridView) { ObjectCollection items = (ObjectCollection)Properties.GetObject(PropComboBoxCellItems); if (items == null) { items = new ObjectCollection(this); Properties.SetObject(PropComboBoxCellItems, items); } if (CreateItemsFromDataSource) { items.ClearInternal(); CurrencyManager dataManager = GetDataManager(dataGridView); if (dataManager != null && dataManager.Count != -1) { object[] newItems = new object[dataManager.Count]; for (int i = 0; i < newItems.Length; i++) { newItems[i] = dataManager[i]; } items.AddRangeInternal(newItems); } // Do not clear the CreateItemsFromDataSource flag when the data source has not been initialized yet if (dataManager != null || (flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) == 0x00) { CreateItemsFromDataSource = false; } } return items; } internal object GetItemValue(object item) { bool valueSet = false; object value = null; if (ValueMemberProperty != null) { value = ValueMemberProperty.GetValue(item); valueSet = true; } else if (DisplayMemberProperty != null) { value = DisplayMemberProperty.GetValue(item); valueSet = true; } else if (!string.IsNullOrEmpty(ValueMember)) { PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(ValueMember, true /*caseInsensitive*/); if (propDesc != null) { value = propDesc.GetValue(item); valueSet = true; } } if (!valueSet && !string.IsNullOrEmpty(DisplayMember)) { PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(DisplayMember, true /*caseInsensitive*/); if (propDesc != null) { value = propDesc.GetValue(item); valueSet = true; } } if (!valueSet) { value = item; } return value; } protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize) { if (DataGridView == null) { return new Size(-1, -1); } if (cellStyle == null) { throw new ArgumentNullException(nameof(cellStyle)); } Size preferredSize = Size.Empty; DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize); Rectangle borderWidthsRect = StdBorderWidths; int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal; int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical; TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); /* Changing design of DGVComboBoxCell.GetPreferredSize for performance reasons. * Old design required looking through each combo item string formattedValue; if (freeDimension == DataGridViewFreeDimension.Height) { formattedValue = GetFormattedValue(rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.PreferredSize) as string; if (formattedValue != null) { preferredSize = new Size(0, DataGridViewCell.MeasureTextSize(graphics, formattedValue, cellStyle.Font, flags).Height); } else { preferredSize = new Size(DataGridViewCell.MeasureTextSize(graphics, " ", cellStyle.Font, flags).Height, 0); } } else { if ((this.HasItems || this.CreateItemsFromDataSource) && this.Items.Count > 0) { int maxPreferredWidth = -1; try { foreach (object item in this.Items) { this.valueUsedDuringAutoSize = item; this.keyUsedDuringAutoSize = GetItemValue(item); formattedValue = GetFormattedValue(this.keyUsedDuringAutoSize, rowIndex, ref cellStyle, null, null, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.PreferredSize) as string; if (formattedValue != null) { preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedValue, cellStyle.Font, flags); } else { preferredSize = DataGridViewCell.MeasureTextSize(graphics, " ", cellStyle.Font, flags); } if (preferredSize.Width > maxPreferredWidth) { maxPreferredWidth = preferredSize.Width; } } } finally { this.keyUsedDuringAutoSize = null; this.valueUsedDuringAutoSize = null; } preferredSize.Width = maxPreferredWidth; } else { formattedValue = GetFormattedValue(rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.PreferredSize) as string; if (formattedValue != null) { preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedValue, cellStyle.Font, flags); } else { preferredSize = DataGridViewCell.MeasureTextSize(graphics, " ", cellStyle.Font, flags); } } if (freeDimension == DataGridViewFreeDimension.Width) { preferredSize.Height = 0; } } */ string formattedValue = GetFormattedValue(rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting | DataGridViewDataErrorContexts.PreferredSize) as string; if (!string.IsNullOrEmpty(formattedValue)) { preferredSize = DataGridViewCell.MeasureTextSize(graphics, formattedValue, cellStyle.Font, flags); } else { preferredSize = DataGridViewCell.MeasureTextSize(graphics, " ", cellStyle.Font, flags); } if (freeDimension == DataGridViewFreeDimension.Height) { preferredSize.Width = 0; } else if (freeDimension == DataGridViewFreeDimension.Width) { preferredSize.Height = 0; } if (freeDimension != DataGridViewFreeDimension.Height) { preferredSize.Width += SystemInformation.HorizontalScrollBarThumbWidth + 1 + 2 * DATAGRIDVIEWCOMBOBOXCELL_margin + borderAndPaddingWidths; if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + SystemInformation.HorizontalScrollBarThumbWidth + 1 + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth); } } if (freeDimension != DataGridViewFreeDimension.Width) { if (FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup) { preferredSize.Height += 6; } else { preferredSize.Height += 8; } preferredSize.Height += borderAndPaddingHeights; if (DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight); } } return preferredSize; } private void InitializeComboBoxText() { Debug.Assert(EditingComboBox != null); ((IDataGridViewEditingControl)EditingComboBox).EditingControlValueChanged = false; int rowIndex = ((IDataGridViewEditingControl)EditingComboBox).EditingControlRowIndex; Debug.Assert(rowIndex > -1); DataGridViewCellStyle dataGridViewCellStyle = GetInheritedStyle(null, rowIndex, false); EditingComboBox.Text = (string)GetFormattedValue(GetValue(rowIndex), rowIndex, ref dataGridViewCellStyle, null, null, DataGridViewDataErrorContexts.Formatting); } public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { Debug.Assert(DataGridView != null && DataGridView.EditingPanel != null && DataGridView.EditingControl != null); Debug.Assert(!ReadOnly); base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); if (DataGridView.EditingControl is ComboBox comboBox) { // Use the selection backcolor for the editing panel when the cell is selected if ((GetInheritedState(rowIndex) & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) { DataGridView.EditingPanel.BackColor = dataGridViewCellStyle.SelectionBackColor; } // We need the comboBox to be parented by a control which has a handle or else the native ComboBox ends up // w/ its parentHwnd pointing to the WinFormsParkingWindow. IntPtr h; if (comboBox.ParentInternal != null) { h = comboBox.ParentInternal.Handle; } h = comboBox.Handle; // make sure that assigning the DataSource property does not assert. comboBox.DropDownStyle = ComboBoxStyle.DropDownList; comboBox.FormattingEnabled = true; comboBox.MaxDropDownItems = MaxDropDownItems; comboBox.DropDownWidth = DropDownWidth; comboBox.DataSource = null; comboBox.ValueMember = null; comboBox.Items.Clear(); /* Don't set the position inside the currency manager blindly to 0 because it may be the case that the DataGridView and the DataGridViewComboBoxCell share the same DataManager. Then setting the position on the DataManager will also set the position on the DataGridView. And this causes problems when changing position inside the DataGridView. if (this.DataManager != null && this.DataManager.Count > 0) { this.DataManager.Position = 0; } */ comboBox.DataSource = DataSource; comboBox.DisplayMember = DisplayMember; comboBox.ValueMember = ValueMember; if (HasItems && DataSource == null && Items.Count > 0) { comboBox.Items.AddRange(Items.InnerArray.ToArray()); } comboBox.Sorted = Sorted; comboBox.FlatStyle = FlatStyle; if (AutoComplete) { comboBox.AutoCompleteSource = AutoCompleteSource.ListItems; comboBox.AutoCompleteMode = AutoCompleteMode.Append; } else { comboBox.AutoCompleteMode = AutoCompleteMode.None; comboBox.AutoCompleteSource = AutoCompleteSource.None; } if (!(initialFormattedValue is string initialFormattedValueStr)) { initialFormattedValueStr = string.Empty; } comboBox.Text = initialFormattedValueStr; if ((flags & DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp) == 0x00) { comboBox.DropDown += new EventHandler(ComboBox_DropDown); flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_dropDownHookedUp; } cachedDropDownWidth = -1; EditingComboBox = DataGridView.EditingControl as DataGridViewComboBoxEditingControl; if (GetHeight(rowIndex) > 21) { Rectangle rectBottomSection = DataGridView.GetCellDisplayRectangle(ColumnIndex, rowIndex, true); rectBottomSection.Y += 21; rectBottomSection.Height -= 21; DataGridView.Invalidate(rectBottomSection); } } } private void InitializeDisplayMemberPropertyDescriptor(string displayMember) { if (DataManager != null) { if (string.IsNullOrEmpty(displayMember)) { DisplayMemberProperty = null; } else { BindingMemberInfo displayBindingMember = new BindingMemberInfo(displayMember); // make the DataManager point to the sublist inside this.DataSource DataManager = DataGridView.BindingContext[DataSource, displayBindingMember.BindingPath] as CurrencyManager; PropertyDescriptorCollection props = DataManager.GetItemProperties(); PropertyDescriptor displayMemberProperty = props.Find(displayBindingMember.BindingField, true); if (displayMemberProperty == null) { throw new ArgumentException(string.Format(SR.DataGridViewComboBoxCell_FieldNotFound, displayMember)); } else { DisplayMemberProperty = displayMemberProperty; } } } } private void InitializeValueMemberPropertyDescriptor(string valueMember) { if (DataManager != null) { if (string.IsNullOrEmpty(valueMember)) { ValueMemberProperty = null; } else { BindingMemberInfo valueBindingMember = new BindingMemberInfo(valueMember); // make the DataManager point to the sublist inside this.DataSource DataManager = DataGridView.BindingContext[DataSource, valueBindingMember.BindingPath] as CurrencyManager; PropertyDescriptorCollection props = DataManager.GetItemProperties(); PropertyDescriptor valueMemberProperty = props.Find(valueBindingMember.BindingField, true); if (valueMemberProperty == null) { throw new ArgumentException(string.Format(SR.DataGridViewComboBoxCell_FieldNotFound, valueMember)); } else { ValueMemberProperty = valueMemberProperty; } } } } /// <summary> /// Find the item in the ComboBox currency manager for the current cell /// This can be horribly inefficient and it uses reflection which makes it expensive /// - ripe for optimization /// </summary> private object ItemFromComboBoxDataSource(PropertyDescriptor property, object key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } //if (key == this.keyUsedDuringAutoSize) //{ // return this.valueUsedDuringAutoSize; //} Debug.Assert(property != null); Debug.Assert(DataManager != null); object item = null; //If the data source is a bindinglist use that as it's probably more efficient if ((DataManager.List is IBindingList) && ((IBindingList)DataManager.List).SupportsSearching) { int index = ((IBindingList)DataManager.List).Find(property, key); if (index != -1) { item = DataManager.List[index]; } } else { //Otherwise walk across the items looking for the item we want for (int i = 0; i < DataManager.List.Count; i++) { object itemTmp = DataManager.List[i]; object value = property.GetValue(itemTmp); if (key.Equals(value)) { item = itemTmp; break; } } } return item; } private object ItemFromComboBoxItems(int rowIndex, string field, object key) { Debug.Assert(!string.IsNullOrEmpty(field)); object item = null; if (OwnsEditingComboBox(rowIndex)) { // It is likely that the item looked for is the selected item. item = EditingComboBox.SelectedItem; object displayValue = null; PropertyDescriptor propDesc = TypeDescriptor.GetProperties(item).Find(field, true /*caseInsensitive*/); if (propDesc != null) { displayValue = propDesc.GetValue(item); } if (displayValue == null || !displayValue.Equals(key)) { // No, the selected item is not looked for. item = null; // Need to loop through all the items } } if (item == null) { foreach (object itemCandidate in Items) { object displayValue = null; PropertyDescriptor propDesc = TypeDescriptor.GetProperties(itemCandidate).Find(field, true /*caseInsensitive*/); if (propDesc != null) { displayValue = propDesc.GetValue(itemCandidate); } if (displayValue != null && displayValue.Equals(key)) { // Found the item. item = itemCandidate; break; } } } if (item == null) { // The provided field could be wrong - try to match the key against an actual item if (OwnsEditingComboBox(rowIndex)) { // It is likely that the item looked for is the selected item. item = EditingComboBox.SelectedItem; if (item == null || !item.Equals(key)) { item = null; } } if (item == null && Items.Contains(key)) { item = key; } } return item; } public override bool KeyEntersEditMode(KeyEventArgs e) { if (((char.IsLetterOrDigit((char)e.KeyCode) && !(e.KeyCode >= Keys.F1 && e.KeyCode <= Keys.F24)) || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.Divide) || (e.KeyCode >= Keys.OemSemicolon && e.KeyCode <= Keys.Oem102) || (e.KeyCode == Keys.Space && !e.Shift) || (e.KeyCode == Keys.F4) || ((e.KeyCode == Keys.Down || e.KeyCode == Keys.Up) && e.Alt)) && (!e.Alt || (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up)) && !e.Control) { return true; } return base.KeyEntersEditMode(e); } /// <summary> /// Lookup the display text for the given value. /// /// We use the value and ValueMember to look up the item in the /// ComboBox datasource. We then use DisplayMember to get the /// text to display. /// </summary> private bool LookupDisplayValue(int rowIndex, object value, out object displayValue) { Debug.Assert(value != null); Debug.Assert(ValueMemberProperty != null || DisplayMemberProperty != null || !string.IsNullOrEmpty(ValueMember) || !string.IsNullOrEmpty(DisplayMember)); object item = null; if (DisplayMemberProperty != null || ValueMemberProperty != null) { //Now look up the item in the Combobox datasource - this can be horribly inefficient //and it uses reflection which makes it expensive - ripe for optimization item = ItemFromComboBoxDataSource(ValueMemberProperty ?? DisplayMemberProperty, value); } else { //Find the item in the Items collection based on the provided ValueMember or DisplayMember item = ItemFromComboBoxItems(rowIndex, string.IsNullOrEmpty(ValueMember) ? DisplayMember : ValueMember, value); } if (item == null) { displayValue = null; return false; } //Now we've got the item for the value - we can get the display text using the DisplayMember // DisplayMember & ValueMember may be null in which case we will use the item itself displayValue = GetItemDisplayValue(item); return true; } /// <summary> /// Lookup the value for the given display value. /// /// We use the display value and DisplayMember to look up the item in the /// ComboBox datasource. We then use ValueMember to get the value. /// </summary> private bool LookupValue(object formattedValue, out object value) { if (formattedValue == null) { value = null; return true; } Debug.Assert(DisplayMemberProperty != null || ValueMemberProperty != null || !string.IsNullOrEmpty(DisplayMember) || !string.IsNullOrEmpty(ValueMember)); object item = null; if (DisplayMemberProperty != null || ValueMemberProperty != null) { //Now look up the item in the DataGridViewComboboxCell datasource - this can be horribly inefficient //and it uses reflection which makes it expensive - ripe for optimization item = ItemFromComboBoxDataSource(DisplayMemberProperty ?? ValueMemberProperty, formattedValue); } else { //Find the item in the Items collection based on the provided DisplayMember or ValueMember item = ItemFromComboBoxItems(RowIndex, string.IsNullOrEmpty(DisplayMember) ? ValueMember : DisplayMember, formattedValue); } if (item == null) { value = null; return false; } //Now we've got the item for the value - we can get the value using the ValueMember value = GetItemValue(item); return true; } protected override void OnDataGridViewChanged() { if (DataGridView != null) { // Will throw an error if DataGridView is set and a member is invalid InitializeDisplayMemberPropertyDescriptor(DisplayMember); InitializeValueMemberPropertyDescriptor(ValueMember); } base.OnDataGridViewChanged(); } protected override void OnEnter(int rowIndex, bool throughMouseClick) { if (DataGridView == null) { return; } if (throughMouseClick && DataGridView.EditMode != DataGridViewEditMode.EditOnEnter) { flags |= (byte)DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick; } } private void OnItemsCollectionChanged() { if (TemplateComboBoxColumn != null) { Debug.Assert(TemplateComboBoxColumn.CellTemplate == this); TemplateComboBoxColumn.OnItemsCollectionChanged(); } cachedDropDownWidth = -1; if (OwnsEditingComboBox(RowIndex)) { InitializeComboBoxText(); } else { OnCommonChange(); } } protected override void OnLeave(int rowIndex, bool throughMouseClick) { if (DataGridView == null) { return; } flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick); } protected override void OnMouseClick(DataGridViewCellMouseEventArgs e) { if (DataGridView == null) { return; } Debug.Assert(e.ColumnIndex == ColumnIndex); Point ptCurrentCell = DataGridView.CurrentCellAddress; if (ptCurrentCell.X == e.ColumnIndex && ptCurrentCell.Y == e.RowIndex) { if ((flags & DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick) != 0x00) { flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_ignoreNextMouseClick); } else if ((EditingComboBox == null || !EditingComboBox.DroppedDown) && DataGridView.EditMode != DataGridViewEditMode.EditProgrammatically && DataGridView.BeginEdit(true /*selectAll*/)) { if (EditingComboBox != null && DisplayStyle != DataGridViewComboBoxDisplayStyle.Nothing) { CheckDropDownList(e.X, e.Y, e.RowIndex); } } } } protected override void OnMouseEnter(int rowIndex) { if (DataGridView == null) { return; } if (DisplayStyle == DataGridViewComboBoxDisplayStyle.ComboBox && FlatStyle == FlatStyle.Popup) { DataGridView.InvalidateCell(ColumnIndex, rowIndex); } base.OnMouseEnter(rowIndex); } protected override void OnMouseLeave(int rowIndex) { if (DataGridView == null) { return; } if (mouseInDropDownButtonBounds) { mouseInDropDownButtonBounds = false; if (ColumnIndex >= 0 && rowIndex >= 0 && (FlatStyle == FlatStyle.Standard || FlatStyle == FlatStyle.System) && DataGridView.ApplyVisualStylesToInnerCells) { DataGridView.InvalidateCell(ColumnIndex, rowIndex); } } if (DisplayStyle == DataGridViewComboBoxDisplayStyle.ComboBox && FlatStyle == FlatStyle.Popup) { DataGridView.InvalidateCell(ColumnIndex, rowIndex); } base.OnMouseEnter(rowIndex); } protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) { if (DataGridView == null) { return; } if ((FlatStyle == FlatStyle.Standard || FlatStyle == FlatStyle.System) && DataGridView.ApplyVisualStylesToInnerCells) { int rowIndex = e.RowIndex; DataGridViewCellStyle cellStyle = GetInheritedStyle(null, rowIndex, false /*includeColors*/); // get the border style bool singleVerticalBorderAdded = !DataGridView.RowHeadersVisible && DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single; bool singleHorizontalBorderAdded = !DataGridView.ColumnHeadersVisible && DataGridView.AdvancedCellBorderStyle.All == DataGridViewAdvancedCellBorderStyle.Single; bool isFirstDisplayedRow = rowIndex == DataGridView.FirstDisplayedScrollingRowIndex; bool isFirstDisplayedColumn = OwningColumn.Index == DataGridView.FirstDisplayedColumnIndex; bool isFirstDisplayedScrollingColumn = OwningColumn.Index == DataGridView.FirstDisplayedScrollingColumnIndex; DataGridViewAdvancedBorderStyle dgvabsEffective, dgvabsPlaceholder; dgvabsPlaceholder = new DataGridViewAdvancedBorderStyle(); dgvabsEffective = AdjustCellBorderStyle(DataGridView.AdvancedCellBorderStyle, dgvabsPlaceholder, singleVerticalBorderAdded, singleHorizontalBorderAdded, isFirstDisplayedRow, isFirstDisplayedColumn); Rectangle cellBounds = DataGridView.GetCellDisplayRectangle(OwningColumn.Index, rowIndex, false /*cutOverflow*/); Rectangle cutoffCellBounds = cellBounds; if (isFirstDisplayedScrollingColumn) { cellBounds.X -= DataGridView.FirstDisplayedScrollingColumnHiddenWidth; cellBounds.Width += DataGridView.FirstDisplayedScrollingColumnHiddenWidth; } DataGridViewElementStates rowState = DataGridView.Rows.GetRowState(rowIndex); DataGridViewElementStates cellState = CellStateFromColumnRowStates(rowState); cellState |= State; Rectangle dropDownButtonRect; using (Graphics g = WindowsFormsUtils.CreateMeasurementGraphics()) { PaintPrivate(g, cellBounds, cellBounds, rowIndex, cellState, null /*formattedValue*/, // dropDownButtonRect is independent of formattedValue null /*errorText*/, // dropDownButtonRect is independent of errorText cellStyle, dgvabsEffective, out dropDownButtonRect, DataGridViewPaintParts.ContentForeground, false /*computeContentBounds*/, false /*computeErrorIconBounds*/, true /*computeDropDownButtonRect*/, false /*paint*/); } bool newMouseInDropDownButtonBounds = dropDownButtonRect.Contains(DataGridView.PointToClient(Control.MousePosition)); if (newMouseInDropDownButtonBounds != mouseInDropDownButtonBounds) { mouseInDropDownButtonBounds = newMouseInDropDownButtonBounds; DataGridView.InvalidateCell(e.ColumnIndex, rowIndex); } } base.OnMouseMove(e); } private bool OwnsEditingComboBox(int rowIndex) { return rowIndex != -1 && EditingComboBox != null && rowIndex == ((IDataGridViewEditingControl)EditingComboBox).EditingControlRowIndex; } protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { if (cellStyle == null) { throw new ArgumentNullException(nameof(cellStyle)); } PaintPrivate(graphics, clipBounds, cellBounds, rowIndex, elementState, formattedValue, errorText, cellStyle, advancedBorderStyle, out Rectangle dropDownButtonRect, // not used paintParts, false /*computeContentBounds*/, false /*computeErrorIconBounds*/, false /*computeDropDownButtonRect*/, true /*paint*/); } // PaintPrivate is used in four places that need to duplicate the paint code: // 1. DataGridViewCell::Paint method // 2. DataGridViewCell::GetContentBounds // 3. DataGridViewCell::GetErrorIconBounds // 4. DataGridViewCell::OnMouseMove - to compute the dropDownButtonRect // // if computeContentBounds is true then PaintPrivate returns the contentBounds // else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds // else it returns Rectangle.Empty; // // PaintPrivate uses the computeDropDownButtonRect to determine if it should compute the dropDownButtonRect private Rectangle PaintPrivate(Graphics g, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, out Rectangle dropDownButtonRect, DataGridViewPaintParts paintParts, bool computeContentBounds, bool computeErrorIconBounds, bool computeDropDownButtonRect, bool paint) { // Parameter checking. // One bit and one bit only should be turned on Debug.Assert(paint || computeContentBounds || computeErrorIconBounds || computeDropDownButtonRect); Debug.Assert(!paint || !computeContentBounds || !computeErrorIconBounds || !computeDropDownButtonRect); Debug.Assert(!paint || !computeContentBounds || !computeDropDownButtonRect || !computeErrorIconBounds); Debug.Assert(!computeContentBounds || !computeErrorIconBounds || !paint || !computeDropDownButtonRect); Debug.Assert(!computeContentBounds || !computeErrorIconBounds || !computeDropDownButtonRect || !paint); Debug.Assert(!computeErrorIconBounds || !paint || !computeContentBounds || !computeDropDownButtonRect); Debug.Assert(!computeErrorIconBounds || !paint || !computeDropDownButtonRect || !computeContentBounds); Debug.Assert(cellStyle != null); Rectangle resultBounds = Rectangle.Empty; dropDownButtonRect = Rectangle.Empty; bool paintFlat = FlatStyle == FlatStyle.Flat || FlatStyle == FlatStyle.Popup; bool paintPopup = FlatStyle == FlatStyle.Popup && DataGridView.MouseEnteredCellAddress.Y == rowIndex && DataGridView.MouseEnteredCellAddress.X == ColumnIndex; bool paintXPThemes = !paintFlat && DataGridView.ApplyVisualStylesToInnerCells; bool paintPostXPThemes = paintXPThemes && PostXPThemesExist; ComboBoxState comboBoxState = ComboBoxState.Normal; if (DataGridView.MouseEnteredCellAddress.Y == rowIndex && DataGridView.MouseEnteredCellAddress.X == ColumnIndex && mouseInDropDownButtonBounds) { comboBoxState = ComboBoxState.Hot; } if (paint && DataGridViewCell.PaintBorder(paintParts)) { PaintBorder(g, clipBounds, cellBounds, cellStyle, advancedBorderStyle); } Rectangle borderWidths = BorderWidths(advancedBorderStyle); Rectangle valBounds = cellBounds; valBounds.Offset(borderWidths.X, borderWidths.Y); valBounds.Width -= borderWidths.Right; valBounds.Height -= borderWidths.Bottom; SolidBrush br; Point ptCurrentCell = DataGridView.CurrentCellAddress; bool cellCurrent = ptCurrentCell.X == ColumnIndex && ptCurrentCell.Y == rowIndex; bool cellEdited = cellCurrent && DataGridView.EditingControl != null; bool cellSelected = (elementState & DataGridViewElementStates.Selected) != 0; bool drawComboBox = DisplayStyle == DataGridViewComboBoxDisplayStyle.ComboBox && ((DisplayStyleForCurrentCellOnly && cellCurrent) || !DisplayStyleForCurrentCellOnly); bool drawDropDownButton = DisplayStyle != DataGridViewComboBoxDisplayStyle.Nothing && ((DisplayStyleForCurrentCellOnly && cellCurrent) || !DisplayStyleForCurrentCellOnly); if (DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected && !cellEdited) { br = DataGridView.GetCachedBrush(cellStyle.SelectionBackColor); } else { br = DataGridView.GetCachedBrush(cellStyle.BackColor); } if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255 && valBounds.Width > 0 && valBounds.Height > 0) { DataGridViewCell.PaintPadding(g, valBounds, cellStyle, br, DataGridView.RightToLeftInternal); } if (cellStyle.Padding != Padding.Empty) { if (DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } else { valBounds.Offset(cellStyle.Padding.Left, cellStyle.Padding.Top); } valBounds.Width -= cellStyle.Padding.Horizontal; valBounds.Height -= cellStyle.Padding.Vertical; } if (paint && valBounds.Width > 0 && valBounds.Height > 0) { if (paintXPThemes && drawComboBox) { if (paintPostXPThemes && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255) { g.FillRectangle(br, valBounds.Left, valBounds.Top, valBounds.Width, valBounds.Height); } if (DataGridViewCell.PaintContentBackground(paintParts)) { if (paintPostXPThemes) { DataGridViewComboBoxCellRenderer.DrawBorder(g, valBounds); } else { DataGridViewComboBoxCellRenderer.DrawTextBox(g, valBounds, comboBoxState); } } if (!paintPostXPThemes && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255 && valBounds.Width > 2 && valBounds.Height > 2) { g.FillRectangle(br, valBounds.Left + 1, valBounds.Top + 1, valBounds.Width - 2, valBounds.Height - 2); } } else if (DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255) { if (paintPostXPThemes && drawDropDownButton && !drawComboBox) { g.DrawRectangle(SystemPens.ControlLightLight, new Rectangle(valBounds.X, valBounds.Y, valBounds.Width - 1, valBounds.Height - 1)); } else { g.FillRectangle(br, valBounds.Left, valBounds.Top, valBounds.Width, valBounds.Height); } } } int dropWidth = Math.Min(SystemInformation.HorizontalScrollBarThumbWidth, valBounds.Width - 2 * DATAGRIDVIEWCOMBOBOXCELL_margin - 1); if (!cellEdited) { int dropHeight; if (paintXPThemes || paintFlat) { dropHeight = Math.Min(GetDropDownButtonHeight(g, cellStyle), paintPostXPThemes ? valBounds.Height : valBounds.Height - 2); } else { dropHeight = Math.Min(GetDropDownButtonHeight(g, cellStyle), valBounds.Height - 4); } if (dropWidth > 0 && dropHeight > 0) { Rectangle dropRect; if (paintXPThemes || paintFlat) { if (paintPostXPThemes) { dropRect = new Rectangle(DataGridView.RightToLeftInternal ? valBounds.Left : valBounds.Right - dropWidth, valBounds.Top, dropWidth, dropHeight); } else { dropRect = new Rectangle(DataGridView.RightToLeftInternal ? valBounds.Left + 1 : valBounds.Right - dropWidth - 1, valBounds.Top + 1, dropWidth, dropHeight); } } else { dropRect = new Rectangle(DataGridView.RightToLeftInternal ? valBounds.Left + 2 : valBounds.Right - dropWidth - 2, valBounds.Top + 2, dropWidth, dropHeight); } if (paintPostXPThemes && drawDropDownButton && !drawComboBox) { dropDownButtonRect = valBounds; } else { dropDownButtonRect = dropRect; } if (paint && DataGridViewCell.PaintContentBackground(paintParts)) { if (drawDropDownButton) { if (paintFlat) { g.FillRectangle(SystemBrushes.Control, dropRect); } else if (paintXPThemes) { if (paintPostXPThemes) { if (drawComboBox) { DataGridViewComboBoxCellRenderer.DrawDropDownButton(g, dropRect, comboBoxState, DataGridView.RightToLeftInternal); } else { DataGridViewComboBoxCellRenderer.DrawReadOnlyButton(g, valBounds, comboBoxState); DataGridViewComboBoxCellRenderer.DrawDropDownButton(g, dropRect, ComboBoxState.Normal); } if (SystemInformation.HighContrast) { // In the case of ComboBox style, background is not filled in, // in the case of DrawReadOnlyButton uses theming API to render CP_READONLY COMBOBOX part that renders the background, // this API does not have "selected" state, thus always uses BackColor br = DataGridView.GetCachedBrush(cellStyle.BackColor); } } else { DataGridViewComboBoxCellRenderer.DrawDropDownButton(g, dropRect, comboBoxState); } } else { g.FillRectangle(SystemBrushes.Control, dropRect); } } if (!paintFlat && !paintXPThemes && (drawComboBox || drawDropDownButton)) { // border painting is ripped from button renderer Color color = SystemColors.Control; Color buttonShadow; Color buttonShadowDark; Color buttonFace = color; Color highlight; bool stockColor = color.ToKnownColor() == SystemColors.Control.ToKnownColor(); bool highContrast = SystemInformation.HighContrast; if (color == SystemColors.Control) { buttonShadow = SystemColors.ControlDark; buttonShadowDark = SystemColors.ControlDarkDark; highlight = SystemColors.ControlLightLight; } else { buttonShadow = ControlPaint.Dark(color); highlight = ControlPaint.LightLight(color); if (highContrast) { buttonShadowDark = ControlPaint.LightLight(color); } else { buttonShadowDark = ControlPaint.DarkDark(color); } } buttonShadow = g.GetNearestColor(buttonShadow); buttonShadowDark = g.GetNearestColor(buttonShadowDark); buttonFace = g.GetNearestColor(buttonFace); highlight = g.GetNearestColor(highlight); // top + left Pen pen; if (stockColor) { if (SystemInformation.HighContrast) { pen = SystemPens.ControlLight; } else { pen = SystemPens.Control; } } else { pen = new Pen(highlight); } if (drawDropDownButton) { g.DrawLine(pen, dropRect.X, dropRect.Y, dropRect.X + dropRect.Width - 1, dropRect.Y); g.DrawLine(pen, dropRect.X, dropRect.Y, dropRect.X, dropRect.Y + dropRect.Height - 1); } // the bounds around the combobox control if (drawComboBox) { g.DrawLine(pen, valBounds.X, valBounds.Y + valBounds.Height - 1, valBounds.X + valBounds.Width - 1, valBounds.Y + valBounds.Height - 1); g.DrawLine(pen, valBounds.X + valBounds.Width - 1, valBounds.Y, valBounds.X + valBounds.Width - 1, valBounds.Y + valBounds.Height - 1); } // bottom + right if (stockColor) { pen = SystemPens.ControlDarkDark; } else { pen.Color = buttonShadowDark; } if (drawDropDownButton) { g.DrawLine(pen, dropRect.X, dropRect.Y + dropRect.Height - 1, dropRect.X + dropRect.Width - 1, dropRect.Y + dropRect.Height - 1); g.DrawLine(pen, dropRect.X + dropRect.Width - 1, dropRect.Y, dropRect.X + dropRect.Width - 1, dropRect.Y + dropRect.Height - 1); } // the bounds around the combobox control if (drawComboBox) { g.DrawLine(pen, valBounds.X, valBounds.Y, valBounds.X + valBounds.Width - 2, valBounds.Y); g.DrawLine(pen, valBounds.X, valBounds.Y, valBounds.X, valBounds.Y + valBounds.Height - 1); } // Top + Left inset if (stockColor) { pen = SystemPens.ControlLightLight; } else { pen.Color = buttonFace; } if (drawDropDownButton) { g.DrawLine(pen, dropRect.X + 1, dropRect.Y + 1, dropRect.X + dropRect.Width - 2, dropRect.Y + 1); g.DrawLine(pen, dropRect.X + 1, dropRect.Y + 1, dropRect.X + 1, dropRect.Y + dropRect.Height - 2); } // Bottom + Right inset if (stockColor) { pen = SystemPens.ControlDark; } else { pen.Color = buttonShadow; } if (drawDropDownButton) { g.DrawLine(pen, dropRect.X + 1, dropRect.Y + dropRect.Height - 2, dropRect.X + dropRect.Width - 2, dropRect.Y + dropRect.Height - 2); g.DrawLine(pen, dropRect.X + dropRect.Width - 2, dropRect.Y + 1, dropRect.X + dropRect.Width - 2, dropRect.Y + dropRect.Height - 2); } if (!stockColor) { pen.Dispose(); } } if (dropWidth >= 5 && dropHeight >= 3 && drawDropDownButton) { if (paintFlat) { Point middle = new Point(dropRect.Left + dropRect.Width / 2, dropRect.Top + dropRect.Height / 2); // if the width is odd - favor pushing it over one pixel right. middle.X += (dropRect.Width % 2); // if the height is odd - favor pushing it over one pixel down. middle.Y += (dropRect.Height % 2); g.FillPolygon(SystemBrushes.ControlText, new Point[] { new Point(middle.X - offset2X, middle.Y - 1), new Point(middle.X + offset2X + 1, middle.Y - 1), new Point(middle.X, middle.Y + offset2Y) }); } else if (!paintXPThemes) { // XPThemes already painted the drop down button // the down arrow looks better when it's fatten up by a pixel dropRect.X--; dropRect.Width++; Point middle = new Point(dropRect.Left + (dropRect.Width - 1) / 2, dropRect.Top + (dropRect.Height + nonXPTriangleHeight) / 2); // if the width is event - favor pushing it over one pixel right. middle.X += ((dropRect.Width + 1) % 2); // if the height is odd - favor pushing it over one pixel down. middle.Y += (dropRect.Height % 2); Point pt1 = new Point(middle.X - (nonXPTriangleWidth - 1) / 2, middle.Y - nonXPTriangleHeight); Point pt2 = new Point(middle.X + (nonXPTriangleWidth - 1) / 2, middle.Y - nonXPTriangleHeight); g.FillPolygon(SystemBrushes.ControlText, new Point[] { pt1, pt2, middle }); // quirk in GDI+ : if we dont draw the line below then the top right most pixel of the DropDown triangle will not paint // Would think that g.FillPolygon would have painted that... g.DrawLine(SystemPens.ControlText, pt1.X, pt1.Y, pt2.X, pt2.Y); // slim down the drop rect dropRect.X++; dropRect.Width--; } } if (paintPopup && drawComboBox) { // draw a dark border around the dropdown rect if we are in popup mode dropRect.Y--; dropRect.Height++; g.DrawRectangle(SystemPens.ControlDark, dropRect); } } } } Rectangle errorBounds = valBounds; Rectangle textBounds = Rectangle.Inflate(valBounds, -2, -2); if (paintPostXPThemes) { if (!DataGridView.RightToLeftInternal) { textBounds.X--; } textBounds.Width++; } if (drawDropDownButton) { if (paintXPThemes || paintFlat) { errorBounds.Width -= dropWidth; textBounds.Width -= dropWidth; if (DataGridView.RightToLeftInternal) { errorBounds.X += dropWidth; textBounds.X += dropWidth; } } else { errorBounds.Width -= dropWidth + 1; textBounds.Width -= dropWidth + 1; if (DataGridView.RightToLeftInternal) { errorBounds.X += dropWidth + 1; textBounds.X += dropWidth + 1; } } } if (textBounds.Width > 1 && textBounds.Height > 1) { if (cellCurrent && !cellEdited && DataGridViewCell.PaintFocus(paintParts) && DataGridView.ShowFocusCues && DataGridView.Focused && paint) { // Draw focus rectangle if (paintFlat) { Rectangle focusBounds = textBounds; if (!DataGridView.RightToLeftInternal) { focusBounds.X--; } focusBounds.Width++; focusBounds.Y--; focusBounds.Height += 2; ControlPaint.DrawFocusRectangle(g, focusBounds, Color.Empty, br.Color); } else if (paintPostXPThemes) { Rectangle focusBounds = textBounds; focusBounds.X++; focusBounds.Width -= 2; focusBounds.Y++; focusBounds.Height -= 2; if (focusBounds.Width > 0 && focusBounds.Height > 0) { ControlPaint.DrawFocusRectangle(g, focusBounds, Color.Empty, br.Color); } } else { ControlPaint.DrawFocusRectangle(g, textBounds, Color.Empty, br.Color); } } if (paintPopup) { valBounds.Width--; valBounds.Height--; if (!cellEdited && paint && DataGridViewCell.PaintContentBackground(paintParts) && drawComboBox) { g.DrawRectangle(SystemPens.ControlDark, valBounds); } } if (formattedValue is string formattedString) { // Font independent margins int verticalTextMarginTop = cellStyle.WrapMode == DataGridViewTriState.True ? DATAGRIDVIEWCOMBOBOXCELL_verticalTextMarginTopWithWrapping : DATAGRIDVIEWCOMBOBOXCELL_verticalTextMarginTopWithoutWrapping; if (DataGridView.RightToLeftInternal) { textBounds.Offset(DATAGRIDVIEWCOMBOBOXCELL_horizontalTextMarginLeft, verticalTextMarginTop); textBounds.Width += 2 - DATAGRIDVIEWCOMBOBOXCELL_horizontalTextMarginLeft; } else { textBounds.Offset(DATAGRIDVIEWCOMBOBOXCELL_horizontalTextMarginLeft - 1, verticalTextMarginTop); textBounds.Width += 1 - DATAGRIDVIEWCOMBOBOXCELL_horizontalTextMarginLeft; } textBounds.Height -= verticalTextMarginTop; if (textBounds.Width > 0 && textBounds.Height > 0) { TextFormatFlags flags = DataGridViewUtilities.ComputeTextFormatFlagsForCellStyleAlignment(DataGridView.RightToLeftInternal, cellStyle.Alignment, cellStyle.WrapMode); if (!cellEdited && paint) { if (DataGridViewCell.PaintContentForeground(paintParts)) { if ((flags & TextFormatFlags.SingleLine) != 0) { flags |= TextFormatFlags.EndEllipsis; } Color textColor; if (paintPostXPThemes && (drawDropDownButton || drawComboBox)) { textColor = DataGridViewComboBoxCellRenderer.VisualStyleRenderer.GetColor(ColorProperty.TextColor); } else { textColor = cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor; } TextRenderer.DrawText(g, formattedString, cellStyle.Font, textBounds, textColor, flags); } } else if (computeContentBounds) { resultBounds = DataGridViewUtilities.GetTextBounds(textBounds, formattedString, flags, cellStyle); } } } if (DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts)) { PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, errorBounds, errorText); if (cellEdited) { return Rectangle.Empty; } } } if (computeErrorIconBounds) { if (!string.IsNullOrEmpty(errorText)) { resultBounds = ComputeErrorIconBounds(errorBounds); } else { resultBounds = Rectangle.Empty; } } return resultBounds; } public override object ParseFormattedValue(object formattedValue, DataGridViewCellStyle cellStyle, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter) { if (valueTypeConverter == null) { if (ValueMemberProperty != null) { valueTypeConverter = ValueMemberProperty.Converter; } else if (DisplayMemberProperty != null) { valueTypeConverter = DisplayMemberProperty.Converter; } } // Find the item given its display value if ((DataManager != null && (DisplayMemberProperty != null || ValueMemberProperty != null)) || !string.IsNullOrEmpty(DisplayMember) || !string.IsNullOrEmpty(ValueMember)) { object value = ParseFormattedValueInternal(DisplayType, formattedValue, cellStyle, formattedValueTypeConverter, DisplayTypeConverter); object originalValue = value; if (!LookupValue(originalValue, out value)) { if (originalValue == System.DBNull.Value) { value = System.DBNull.Value; } else { throw new FormatException(string.Format(CultureInfo.CurrentCulture, SR.Formatter_CantConvert, value, DisplayType)); } } return value; } else { return ParseFormattedValueInternal(ValueType, formattedValue, cellStyle, formattedValueTypeConverter, valueTypeConverter); } } /// <summary> /// Gets the row Index and column Index of the cell. /// </summary> public override string ToString() { return "DataGridViewComboBoxCell { ColumnIndex=" + ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; } private void UnwireDataSource() { if (DataSource is IComponent component) { component.Disposed -= new EventHandler(DataSource_Disposed); } if (DataSource is ISupportInitializeNotification dsInit && (flags & DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp) != 0x00) { // If we previously hooked the data source's ISupportInitializeNotification // Initialized event, then unhook it now (we don't always hook this event, // only if we needed to because the data source was previously uninitialized) dsInit.Initialized -= new EventHandler(DataSource_Initialized); flags = (byte)(flags & ~DATAGRIDVIEWCOMBOBOXCELL_dataSourceInitializedHookedUp); } } private void WireDataSource(object dataSource) { // If the source is a component, then hook the Disposed event, // so we know when the component is deleted from the form if (dataSource is IComponent component) { component.Disposed += new EventHandler(DataSource_Disposed); } } /// <summary> /// A collection that stores objects. /// </summary> [ListBindable(false)] public class ObjectCollection : IList { private readonly DataGridViewComboBoxCell owner; private ArrayList items; private IComparer comparer; public ObjectCollection(DataGridViewComboBoxCell owner) { Debug.Assert(owner != null); this.owner = owner; } private IComparer Comparer { get { if (comparer == null) { comparer = new ItemComparer(owner); } return comparer; } } /// <summary> /// Retrieves the number of items. /// </summary> public int Count { get { return InnerArray.Count; } } /// <summary> /// Internal access to the actual data store. /// </summary> internal ArrayList InnerArray { get { if (items == null) { items = new ArrayList(); } return items; } } object ICollection.SyncRoot { get { return this; } } bool ICollection.IsSynchronized { get { return false; } } bool IList.IsFixedSize { get { return false; } } public bool IsReadOnly { get { return false; } } /// <summary> /// Adds an item to the collection. For an unsorted combo box, the item is /// added to the end of the existing list of items. For a sorted combo box, /// the item is inserted into the list according to its sorted position. /// The item's ToString() method is called to obtain the string that is /// displayed in the combo box. /// </summary> public int Add(object item) { //this.owner.CheckNoSharedCell(); owner.CheckNoDataSource(); if (item == null) { throw new ArgumentNullException(nameof(item)); } int index = InnerArray.Add(item); bool success = false; if (owner.Sorted) { try { InnerArray.Sort(Comparer); index = InnerArray.IndexOf(item); success = true; } finally { if (!success) { InnerArray.Remove(item); } } } owner.OnItemsCollectionChanged(); return index; } int IList.Add(object item) { return Add(item); } public void AddRange(params object[] items) { //this.owner.CheckNoSharedCell(); owner.CheckNoDataSource(); AddRangeInternal((ICollection)items); owner.OnItemsCollectionChanged(); } public void AddRange(ObjectCollection value) { //this.owner.CheckNoSharedCell(); owner.CheckNoDataSource(); AddRangeInternal((ICollection)value); owner.OnItemsCollectionChanged(); } /// <summary> /// Add range that bypasses the data source check. /// </summary> internal void AddRangeInternal(ICollection items) { if (items == null) { throw new ArgumentNullException(nameof(items)); } foreach (object item in items) { if (item == null) { throw new InvalidOperationException(SR.InvalidNullItemInCollection); } } // Add everything to the collection first, then sort InnerArray.AddRange(items); if (owner.Sorted) { InnerArray.Sort(Comparer); } } internal void SortInternal() { InnerArray.Sort(Comparer); } /// <summary> /// Retrieves the item with the specified index. /// </summary> public virtual object this[int index] { get { if (index < 0 || index >= InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } return InnerArray[index]; } set { //this.owner.CheckNoSharedCell(); owner.CheckNoDataSource(); if (index < 0 || index >= InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } InnerArray[index] = value ?? throw new ArgumentNullException(nameof(value)); owner.OnItemsCollectionChanged(); } } /// <summary> /// Removes all items from the collection. /// </summary> public void Clear() { if (InnerArray.Count > 0) { //this.owner.CheckNoSharedCell(); owner.CheckNoDataSource(); InnerArray.Clear(); owner.OnItemsCollectionChanged(); } } internal void ClearInternal() { InnerArray.Clear(); } public bool Contains(object value) { return IndexOf(value) != -1; } /// <summary> /// Copies the DataGridViewComboBoxCell Items collection to a destination array. /// </summary> public void CopyTo(object[] destination, int arrayIndex) { int count = InnerArray.Count; for (int i = 0; i < count; i++) { destination[i + arrayIndex] = InnerArray[i]; } } void ICollection.CopyTo(Array destination, int index) { int count = InnerArray.Count; for (int i = 0; i < count; i++) { destination.SetValue(InnerArray[i], i + index); } } /// <summary> /// Returns an enumerator for the DataGridViewComboBoxCell Items collection. /// </summary> public IEnumerator GetEnumerator() { return InnerArray.GetEnumerator(); } public int IndexOf(object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return InnerArray.IndexOf(value); } /// <summary> /// Adds an item to the collection. For an unsorted combo box, the item is /// added to the end of the existing list of items. For a sorted combo box, /// the item is inserted into the list according to its sorted position. /// The item's toString() method is called to obtain the string that is /// displayed in the combo box. /// </summary> public void Insert(int index, object item) { //this.owner.CheckNoSharedCell(); owner.CheckNoDataSource(); if (item == null) { throw new ArgumentNullException(nameof(item)); } if (index < 0 || index > InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), nameof(index))); } // If the combo box is sorted, then just treat this like an add // because we are going to twiddle the index anyway. if (owner.Sorted) { Add(item); } else { InnerArray.Insert(index, item); owner.OnItemsCollectionChanged(); } } /// <summary> /// Removes the given item from the collection, provided that it is /// actually in the list. /// </summary> public void Remove(object value) { int index = InnerArray.IndexOf(value); if (index != -1) { RemoveAt(index); } } /// <summary> /// Removes an item from the collection at the given index. /// </summary> public void RemoveAt(int index) { //this.owner.CheckNoSharedCell(); owner.CheckNoDataSource(); if (index < 0 || index >= InnerArray.Count) { throw new ArgumentOutOfRangeException(nameof(index), index, string.Format(SR.InvalidArgument, nameof(index), index)); } InnerArray.RemoveAt(index); owner.OnItemsCollectionChanged(); } } // end ObjectCollection private sealed class ItemComparer : IComparer { private readonly DataGridViewComboBoxCell dataGridViewComboBoxCell; public ItemComparer(DataGridViewComboBoxCell dataGridViewComboBoxCell) { this.dataGridViewComboBoxCell = dataGridViewComboBoxCell; } public int Compare(object item1, object item2) { if (item1 == null) { if (item2 == null) { return 0; //both null, then they are equal } return -1; //item1 is null, but item2 is valid (greater) } if (item2 == null) { return 1; //item2 is null, so item 1 is greater } string itemName1 = dataGridViewComboBoxCell.GetItemDisplayText(item1); string itemName2 = dataGridViewComboBoxCell.GetItemDisplayText(item2); CompareInfo compInfo = Application.CurrentCulture.CompareInfo; return compInfo.Compare(itemName1, itemName2, CompareOptions.StringSort); } } private class DataGridViewComboBoxCellRenderer { [ThreadStatic] private static VisualStyleRenderer visualStyleRenderer; private static readonly VisualStyleElement ComboBoxBorder = VisualStyleElement.ComboBox.Border.Normal; private static readonly VisualStyleElement ComboBoxDropDownButtonRight = VisualStyleElement.ComboBox.DropDownButtonRight.Normal; private static readonly VisualStyleElement ComboBoxDropDownButtonLeft = VisualStyleElement.ComboBox.DropDownButtonLeft.Normal; private static readonly VisualStyleElement ComboBoxReadOnlyButton = VisualStyleElement.ComboBox.ReadOnlyButton.Normal; private DataGridViewComboBoxCellRenderer() { } public static VisualStyleRenderer VisualStyleRenderer { get { if (visualStyleRenderer == null) { visualStyleRenderer = new VisualStyleRenderer(ComboBoxReadOnlyButton); } return visualStyleRenderer; } } public static void DrawTextBox(Graphics g, Rectangle bounds, ComboBoxState state) { ComboBoxRenderer.DrawTextBox(g, bounds, state); } public static void DrawDropDownButton(Graphics g, Rectangle bounds, ComboBoxState state) { ComboBoxRenderer.DrawDropDownButton(g, bounds, state); } // Post theming functions public static void DrawBorder(Graphics g, Rectangle bounds) { if (visualStyleRenderer == null) { visualStyleRenderer = new VisualStyleRenderer(ComboBoxBorder); } else { visualStyleRenderer.SetParameters(ComboBoxBorder.ClassName, ComboBoxBorder.Part, ComboBoxBorder.State); } visualStyleRenderer.DrawBackground(g, bounds); } public static void DrawDropDownButton(Graphics g, Rectangle bounds, ComboBoxState state, bool rightToLeft) { if (rightToLeft) { if (visualStyleRenderer == null) { visualStyleRenderer = new VisualStyleRenderer(ComboBoxDropDownButtonLeft.ClassName, ComboBoxDropDownButtonLeft.Part, (int)state); } else { visualStyleRenderer.SetParameters(ComboBoxDropDownButtonLeft.ClassName, ComboBoxDropDownButtonLeft.Part, (int)state); } } else { if (visualStyleRenderer == null) { visualStyleRenderer = new VisualStyleRenderer(ComboBoxDropDownButtonRight.ClassName, ComboBoxDropDownButtonRight.Part, (int)state); } else { visualStyleRenderer.SetParameters(ComboBoxDropDownButtonRight.ClassName, ComboBoxDropDownButtonRight.Part, (int)state); } } visualStyleRenderer.DrawBackground(g, bounds); } public static void DrawReadOnlyButton(Graphics g, Rectangle bounds, ComboBoxState state) { if (visualStyleRenderer == null) { visualStyleRenderer = new VisualStyleRenderer(ComboBoxReadOnlyButton.ClassName, ComboBoxReadOnlyButton.Part, (int)state); } else { visualStyleRenderer.SetParameters(ComboBoxReadOnlyButton.ClassName, ComboBoxReadOnlyButton.Part, (int)state); } visualStyleRenderer.DrawBackground(g, bounds); } } protected class DataGridViewComboBoxCellAccessibleObject : DataGridViewCellAccessibleObject { public DataGridViewComboBoxCellAccessibleObject(DataGridViewCell owner) : base(owner) { } internal override bool IsIAccessibleExSupported() => true; internal override object GetPropertyValue(UiaCore.UIA propertyID) { switch (propertyID) { case UiaCore.UIA.ControlTypePropertyId: return UiaCore.UIA.ComboBoxControlTypeId; case UiaCore.UIA.IsExpandCollapsePatternAvailablePropertyId: return IsPatternSupported(UiaCore.UIA.ExpandCollapsePatternId); } return base.GetPropertyValue(propertyID); } internal override bool IsPatternSupported(UiaCore.UIA patternId) { if (patternId == UiaCore.UIA.ExpandCollapsePatternId) { return true; } return base.IsPatternSupported(patternId); } internal override UiaCore.ExpandCollapseState ExpandCollapseState { get { DataGridViewComboBoxEditingControl comboBox = Owner.Properties.GetObject(PropComboBoxCellEditingComboBox) as DataGridViewComboBoxEditingControl; if (comboBox != null) { return comboBox.DroppedDown ? UiaCore.ExpandCollapseState.Expanded : UiaCore.ExpandCollapseState.Collapsed; } return UiaCore.ExpandCollapseState.Collapsed; } } } } }
41.886924
226
0.496456
[ "MIT" ]
AArnott/winforms
src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewComboBoxCell.cs
132,616
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace SNSPushNotification.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new SNSPushNotification.App()); app.RegisterForRemoteNotifications(); return base.FinishedLaunching(app, options); } public override void RegisteredForRemoteNotifications(UIApplication application, NSData token) { var deviceToken = token.Description.Replace("<", "").Replace(">", "").Replace(" ", ""); if (!string.IsNullOrEmpty(deviceToken)) { SNSUtils.RegisterDevice(SNSUtils.Platform.IOS, deviceToken); } } public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error) { Console.WriteLine(@"Failed to register for remote notification {0}", error.Description); } } }
36.632653
109
0.662396
[ "Apache-2.0" ]
Doug-AWS/aws-sdk-net-samples
XamarinSamples/SNS/SNSPushNotification/SNSPushNotification.iOS/AppDelegate.cs
1,797
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.AVS.Latest { [Obsolete(@"The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-native:avs:getCluster'.")] public static class GetCluster { /// <summary> /// A cluster resource /// Latest API Version: 2020-03-20. /// </summary> public static Task<GetClusterResult> InvokeAsync(GetClusterArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetClusterResult>("azure-native:avs/latest:getCluster", args ?? new GetClusterArgs(), options.WithVersion()); } public sealed class GetClusterArgs : Pulumi.InvokeArgs { /// <summary> /// Name of the cluster in the private cloud /// </summary> [Input("clusterName", required: true)] public string ClusterName { get; set; } = null!; /// <summary> /// Name of the private cloud /// </summary> [Input("privateCloudName", required: true)] public string PrivateCloudName { get; set; } = null!; /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetClusterArgs() { } } [OutputType] public sealed class GetClusterResult { /// <summary> /// The identity /// </summary> public readonly int ClusterId; /// <summary> /// The cluster size /// </summary> public readonly int ClusterSize; /// <summary> /// The hosts /// </summary> public readonly ImmutableArray<string> Hosts; /// <summary> /// Resource ID. /// </summary> public readonly string Id; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// The state of the cluster provisioning /// </summary> public readonly string ProvisioningState; /// <summary> /// The cluster SKU /// </summary> public readonly Outputs.SkuResponse Sku; /// <summary> /// Resource type. /// </summary> public readonly string Type; [OutputConstructor] private GetClusterResult( int clusterId, int clusterSize, ImmutableArray<string> hosts, string id, string name, string provisioningState, Outputs.SkuResponse sku, string type) { ClusterId = clusterId; ClusterSize = clusterSize; Hosts = hosts; Id = id; Name = name; ProvisioningState = provisioningState; Sku = sku; Type = type; } } }
28.486957
163
0.562576
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/AVS/Latest/GetCluster.cs
3,276
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace HuntingModel.Localization { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class ValidationRes { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal ValidationRes() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HuntingModel.Localization.ValidationRes", typeof(ValidationRes).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Field must be number. /// </summary> public static string VALIDATION_DOUBLE { get { return ResourceManager.GetString("VALIDATION_DOUBLE", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Field &quot;{0}&quot; can be at most {1} characters long. /// </summary> public static string VALIDATION_MAX_LENGTH { get { return ResourceManager.GetString("VALIDATION_MAX_LENGTH", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This field must be a whole number. /// </summary> public static string VALIDATION_NUMBER { get { return ResourceManager.GetString("VALIDATION_NUMBER", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Passwords does not match. /// </summary> public static string VALIDATION_PASSWORD_CONFIRM { get { return ResourceManager.GetString("VALIDATION_PASSWORD_CONFIRM", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Password must have {1} - {2} characters. /// </summary> public static string VALIDATION_PASSWORD_LENGTH { get { return ResourceManager.GetString("VALIDATION_PASSWORD_LENGTH", resourceCulture); } } /// <summary> /// Looks up a localized string similar to This field is required. /// </summary> public static string VALIDATION_REQUIRED { get { return ResourceManager.GetString("VALIDATION_REQUIRED", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Field must have {2} - {1} characters. /// </summary> public static string VALIDATION_STRING_LENGTH { get { return ResourceManager.GetString("VALIDATION_STRING_LENGTH", resourceCulture); } } } }
40.244094
188
0.584426
[ "MIT" ]
jirikoud/HuntingTerritory
HuntingModel/Localization/ValidationRes.Designer.cs
5,113
C#
using System; using Topshelf; namespace Neo4jManager.Host { public static class ServiceFactory { public static Topshelf.Host CreateHost(ServiceControl serviceControl, Action<Topshelf.Host> callback = null) { var host = HostFactory.New(c => { c.Service<ServiceControl>(service => { service.ConstructUsing(() => serviceControl); service.WhenStarted((s, h) => s.Start(h)); service.WhenStopped((s, h) => s.Stop(h)); }); c.RunAsLocalSystem(); c.SetDescription("Provides a Web API to manage Neo4j instances"); c.SetDisplayName("Neo4jManager"); c.SetServiceName("Neo4jManager"); c.EnablePauseAndContinue(); c.EnableServiceRecovery(r => { r.RestartService(1); }); }); callback?.Invoke(host); return host; } } }
28.828571
116
0.519326
[ "MIT" ]
barnardos-au/Neo4jManager
src/Neo4jManager.Host/ServiceFactory.cs
1,009
C#
namespace LegendaryClient.Controls { /// <summary> /// Interaction logic for SmallChampionItem.xaml /// </summary> public partial class SmallChampionItem { public SmallChampionItem() { InitializeComponent(); } } }
21.384615
56
0.586331
[ "BSD-2-Clause" ]
nongnoobjung/Legendary-Garena
LegendaryClient/ReplayElements/SmallChampionItem.xaml.cs
280
C#
using System; using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Work.Models { /// <summary> /// <para>表示 [POST] /cgi-bin/checkin/getcheckinoption 接口的响应。</para> /// </summary> public class CgibinCheckinGetCheckinOptionResponse : WechatWorkResponse { public static class Types { public class CheckinOption { public static class Types { public class CheckinGroup { public static class Types { public class CheckinDate { /// <summary> /// 获取或设置工作日序号列表。 /// </summary> [Newtonsoft.Json.JsonProperty("workdays")] [System.Text.Json.Serialization.JsonPropertyName("workdays")] public int[] WorkdayList { get; set; } = default!; /// <summary> /// 获取或设置工作日上下班打卡时间列表。 /// </summary> [Newtonsoft.Json.JsonProperty("checkintime")] [System.Text.Json.Serialization.JsonPropertyName("checkintime")] public CheckinTime[] CheckinTimeList { get; set; } = default!; /// <summary> /// 获取或设置是否下班不需要打卡。 /// </summary> [Newtonsoft.Json.JsonProperty("noneed_offwork")] [System.Text.Json.Serialization.JsonPropertyName("noneed_offwork")] public bool IsNoNeedOffWork { get; set; } /// <summary> /// 获取或设置弹性时间(单位:毫秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("flex_time")] [System.Text.Json.Serialization.JsonPropertyName("flex_time")] public int FlexTime { get; set; } /// <summary> /// 获取或设置允许迟到时间(单位:毫秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("flex_on_duty_time")] [System.Text.Json.Serialization.JsonPropertyName("flex_on_duty_time")] public int FlexOnDutyTime { get; set; } /// <summary> /// 获取或设置允许早退时间(单位:毫秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("flex_off_duty_time")] [System.Text.Json.Serialization.JsonPropertyName("flex_off_duty_time")] public int FlexOffDutyTime { get; set; } /// <summary> /// 获取或设置提前打卡时间限制(单位:毫秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("limit_aheadtime")] [System.Text.Json.Serialization.JsonPropertyName("limit_aheadtime")] public int LimitAheadTime { get; set; } } public class CheckinTime { /// <summary> /// 获取或设置上班时间距当天零点的秒数。 /// </summary> [Newtonsoft.Json.JsonProperty("work_sec")] [System.Text.Json.Serialization.JsonPropertyName("work_sec")] public int OnWorkTime { get; set; } /// <summary> /// 获取或设置下班时间距当天零点的秒数。 /// </summary> [Newtonsoft.Json.JsonProperty("off_work_sec")] [System.Text.Json.Serialization.JsonPropertyName("off_work_sec")] public int OffWorkTime { get; set; } /// <summary> /// 获取或设置提醒上班时间距当天零点的秒数。 /// </summary> [Newtonsoft.Json.JsonProperty("remind_work_sec")] [System.Text.Json.Serialization.JsonPropertyName("remind_work_sec")] public int RemindOnWorkTime { get; set; } /// <summary> /// 获取或设置提醒下班时间距当天零点的秒数。 /// </summary> [Newtonsoft.Json.JsonProperty("remind_off_work_sec")] [System.Text.Json.Serialization.JsonPropertyName("remind_off_work_sec")] public int RemindOffWorkTime { get; set; } } public class SpecialCheckinDate { /// <summary> /// 获取或设置特殊日期时间戳。 /// </summary> [Newtonsoft.Json.JsonProperty("timestamp")] [System.Text.Json.Serialization.JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// <summary> /// 获取或设置特殊日期上下班打卡时间列表。 /// </summary> [Newtonsoft.Json.JsonProperty("checkintime")] [System.Text.Json.Serialization.JsonPropertyName("checkintime")] public CheckinTime[] CheckinTimeList { get; set; } = default!; /// <summary> /// 获取或设置特殊日期备注。 /// </summary> [Newtonsoft.Json.JsonProperty("notes")] [System.Text.Json.Serialization.JsonPropertyName("notes")] public string Notes { get; set; } = default!; } public class WiFiMac { /// <summary> /// 获取或设置 Wi-Fi 打卡地点名称。 /// </summary> [Newtonsoft.Json.JsonProperty("wifiname")] [System.Text.Json.Serialization.JsonPropertyName("wifiname")] public string Name { get; set; } = default!; /// <summary> /// 获取或设置 Wi-Fi 打卡地点 MAC 地址或 BSSID。 /// </summary> [Newtonsoft.Json.JsonProperty("wifimac")] [System.Text.Json.Serialization.JsonPropertyName("wifimac")] public string Mac { get; set; } = default!; } public class Location { /// <summary> /// 获取或设置位置打卡地点名称。 /// </summary> [Newtonsoft.Json.JsonProperty("loc_title")] [System.Text.Json.Serialization.JsonPropertyName("loc_title")] public string Title { get; set; } = default!; /// <summary> /// 获取或设置位置打卡地点详情。 /// </summary> [Newtonsoft.Json.JsonProperty("loc_detail")] [System.Text.Json.Serialization.JsonPropertyName("loc_detail")] public string Detail { get; set; } = default!; /// <summary> /// 获取或设置位置打卡地点经度。 /// </summary> [Newtonsoft.Json.JsonProperty("lng")] [System.Text.Json.Serialization.JsonPropertyName("lng")] public double Longitude { get; set; } /// <summary> /// 获取或设置位置打卡地点纬度。 /// </summary> [Newtonsoft.Json.JsonProperty("lat")] [System.Text.Json.Serialization.JsonPropertyName("lat")] public double Latitude { get; set; } /// <summary> /// 获取或设置允许打卡范围(单位:米)。 /// </summary> [Newtonsoft.Json.JsonProperty("distance")] [System.Text.Json.Serialization.JsonPropertyName("distance")] public int Distance { get; set; } } public class Schedule { public static class Types { public class TimeSection : CheckinTime { /// <summary> /// 获取或设置时段 ID。 /// </summary> [Newtonsoft.Json.JsonProperty("time_id")] [System.Text.Json.Serialization.JsonPropertyName("time_id")] public int TimeSectionId { get; set; } /// <summary> /// 获取或设置是否允许休息。 /// </summary> [Newtonsoft.Json.JsonProperty("allow_rest")] [System.Text.Json.Serialization.JsonPropertyName("allow_rest")] public bool AllowRest { get; set; } /// <summary> /// 获取或设置休息开始时间距当天零点的秒数。 /// </summary> [Newtonsoft.Json.JsonProperty("rest_begin_time")] [System.Text.Json.Serialization.JsonPropertyName("rest_begin_time")] public int RestBeginTime { get; set; } /// <summary> /// 获取或设置休息结束时间距当天零点的秒数。 /// </summary> [Newtonsoft.Json.JsonProperty("rest_end_time")] [System.Text.Json.Serialization.JsonPropertyName("rest_end_time")] public int RestEndTime { get; set; } } public class LateRule { /// <summary> /// 获取或设置是否允许超时下班。 /// </summary> [Newtonsoft.Json.JsonProperty("allow_offwork_after_time")] [System.Text.Json.Serialization.JsonPropertyName("allow_offwork_after_time")] public bool AllowOffWorkAfterTime { get; set; } /// <summary> /// 获取或设置迟到规则列表。 /// </summary> [Newtonsoft.Json.JsonProperty("timerules")] [System.Text.Json.Serialization.JsonPropertyName("timerules")] public TimeRule[] TimeRuleList { get; set; } = default!; } public class TimeRule { /// <summary> /// 获取或设置晚走的时间距离最晚一个下班的时间(单位:秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("offwork_after_time")] [System.Text.Json.Serialization.JsonPropertyName("offwork_after_time")] public int OffWorkAfterTime { get; set; } /// <summary> /// 获取或设置第二天第一个班次允许迟到的弹性时间(单位:秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("onwork_flex_time")] [System.Text.Json.Serialization.JsonPropertyName("onwork_flex_time")] public int OnWorkFlexTime { get; set; } } } /// <summary> /// 获取或设置排班 ID。 /// </summary> [Newtonsoft.Json.JsonProperty("schedule_id")] [System.Text.Json.Serialization.JsonPropertyName("schedule_id")] public int ScheduleId { get; set; } /// <summary> /// 获取或设置排班名称。 /// </summary> [Newtonsoft.Json.JsonProperty("schedule_name")] [System.Text.Json.Serialization.JsonPropertyName("schedule_name")] public string Name { get; set; } = default!; /// <summary> /// 获取或设置班次上下班时段列表。 /// </summary> [Newtonsoft.Json.JsonProperty("time_section")] [System.Text.Json.Serialization.JsonPropertyName("time_section")] public Types.TimeSection[] TimeSectionList { get; set; } = default!; /// <summary> /// 获取或设置是否下班不需要打卡。 /// </summary> [Newtonsoft.Json.JsonProperty("noneed_offwork")] [System.Text.Json.Serialization.JsonPropertyName("noneed_offwork")] public bool IsNoNeedOffWork { get; set; } /// <summary> /// 获取或设置提前打卡时间限制(单位:毫秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("limit_aheadtime")] [System.Text.Json.Serialization.JsonPropertyName("limit_aheadtime")] public int LimitAheadTime { get; set; } /// <summary> /// 获取或设置下班延迟打卡时间限制(单位:毫秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("limit_offtime")] [System.Text.Json.Serialization.JsonPropertyName("limit_offtime")] public int LimitOffTime { get; set; } /// <summary> /// 获取或设置是否允许弹性时间。 /// </summary> [Newtonsoft.Json.JsonProperty("allow_flex")] [System.Text.Json.Serialization.JsonPropertyName("allow_flex")] public bool AllowFlex { get; set; } /// <summary> /// 获取或设置允许迟到时间(单位:毫秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("flex_on_duty_time")] [System.Text.Json.Serialization.JsonPropertyName("flex_on_duty_time")] public int FlexOnDutyTime { get; set; } /// <summary> /// 获取或设置允许早退时间(单位:毫秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("flex_off_duty_time")] [System.Text.Json.Serialization.JsonPropertyName("flex_off_duty_time")] public int FlexOffDutyTime { get; set; } /// <summary> /// 获取或设置最早可打卡时间限制(单位:毫秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("max_allow_arrive_early")] [System.Text.Json.Serialization.JsonPropertyName("max_allow_arrive_early")] public int MaxAllowArriveEarly { get; set; } /// <summary> /// 获取或设置最晚可打卡时间限制(单位:毫秒)。 /// </summary> [Newtonsoft.Json.JsonProperty("max_allow_arrive_late")] [System.Text.Json.Serialization.JsonPropertyName("max_allow_arrive_late")] public int MaxAllowArriveLate { get; set; } /// <summary> /// 获取或设置晚走晚到时间规则信息。 /// </summary> [Newtonsoft.Json.JsonProperty("late_rule")] [System.Text.Json.Serialization.JsonPropertyName("late_rule")] public Types.LateRule? LateRule { get; set; } } } /// <summary> /// 获取或设置打卡规则 ID。 /// </summary> [Newtonsoft.Json.JsonProperty("groupid")] [System.Text.Json.Serialization.JsonPropertyName("groupid")] public int GroupId { get; set; } /// <summary> /// 获取或设置打卡规则类型。 /// </summary> [Newtonsoft.Json.JsonProperty("grouptype")] [System.Text.Json.Serialization.JsonPropertyName("grouptype")] public int GroupType { get; set; } /// <summary> /// 获取或设置打卡规则名称。 /// </summary> [Newtonsoft.Json.JsonProperty("groupname")] [System.Text.Json.Serialization.JsonPropertyName("groupname")] public string Name { get; set; } = default!; /// <summary> /// 获取或设置是否同步法定节假日。 /// </summary> [Newtonsoft.Json.JsonProperty("sync_holidays")] [System.Text.Json.Serialization.JsonPropertyName("sync_holidays")] public bool IsSyncHolidays { get; set; } /// <summary> /// 获取或设置是否打卡必须拍照。 /// </summary> [Newtonsoft.Json.JsonProperty("need_photo")] [System.Text.Json.Serialization.JsonPropertyName("need_photo")] public bool RequirePhoto { get; set; } /// <summary> /// 获取或设置是否备注时允许上传本地图片。 /// </summary> [Newtonsoft.Json.JsonProperty("note_can_use_local_pic")] [System.Text.Json.Serialization.JsonPropertyName("note_can_use_local_pic")] public bool AllowNotesUseLocalPicture { get; set; } /// <summary> /// 获取或设置是否非工作日允许打卡。 /// </summary> [Newtonsoft.Json.JsonProperty("allow_checkin_offworkday")] [System.Text.Json.Serialization.JsonPropertyName("allow_checkin_offworkday")] public bool AllowCheckinNonWorkday { get; set; } /// <summary> /// 获取或设置是否允许提交补卡申请。 /// </summary> [Newtonsoft.Json.JsonProperty("allow_apply_offworkday")] [System.Text.Json.Serialization.JsonPropertyName("allow_apply_offworkday")] public bool AllowApplyOffWorkday { get; set; } /// <summary> /// 获取或设置打卡时间配置列表。 /// </summary> [Newtonsoft.Json.JsonProperty("checkindate")] [System.Text.Json.Serialization.JsonPropertyName("checkindate")] public Types.CheckinDate[] CheckinDateList { get; set; } = default!; /// <summary> /// 获取或设置特殊日期必须打卡日期列表。 /// </summary> [Newtonsoft.Json.JsonProperty("spe_workdays")] [System.Text.Json.Serialization.JsonPropertyName("spe_workdays")] public Types.SpecialCheckinDate[]? SpecialCheckinDateList { get; set; } /// <summary> /// 获取或设置特殊日期不用打卡日期列表。 /// </summary> [Newtonsoft.Json.JsonProperty("spe_offdays")] [System.Text.Json.Serialization.JsonPropertyName("spe_offdays")] public Types.SpecialCheckinDate[]? SpecialNonCheckinDateList { get; set; } /// <summary> /// 获取或设置 Wi-Fi 打卡地点列表。 /// </summary> [Newtonsoft.Json.JsonProperty("wifimac_infos")] [System.Text.Json.Serialization.JsonPropertyName("wifimac_infos")] public Types.WiFiMac[]? WiFiMacList { get; set; } /// <summary> /// 获取或设置位置打卡地点列表。 /// </summary> [Newtonsoft.Json.JsonProperty("loc_infos")] [System.Text.Json.Serialization.JsonPropertyName("loc_infos")] public Types.Location[]? LocationList { get; set; } /// <summary> /// 获取或设置排班列表。 /// </summary> [Newtonsoft.Json.JsonProperty("schedulelist")] [System.Text.Json.Serialization.JsonPropertyName("schedulelist")] public Types.Schedule[]? ScheduleList { get; set; } } } /// <summary> /// 获取或设置成员账号。 /// </summary> [Newtonsoft.Json.JsonProperty("userid")] [System.Text.Json.Serialization.JsonPropertyName("userid")] public string UserId { get; set; } = default!; /// <summary> /// 获取或设置打卡规则信息。 /// </summary> [Newtonsoft.Json.JsonProperty("group")] [System.Text.Json.Serialization.JsonPropertyName("group")] public Types.CheckinGroup CheckinGroup { get; set; } = default!; } } /// <summary> /// 获取或设置打卡规则列表。 /// </summary> [Newtonsoft.Json.JsonProperty("info")] [System.Text.Json.Serialization.JsonPropertyName("info")] public Types.CheckinOption[] CheckinOptionList { get; set; } = default!; } }
53.237581
117
0.386425
[ "MIT" ]
KimMeng2015/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Work/Models/CgibinCheckin/CgibinCheckinGetCheckinOptionResponse.cs
26,511
C#
#nullable disable namespace Amazon.CodeBuild { public class SourceAuth { public string Type { get; set; } public string Resource { get; set; } } }
15.75
45
0.571429
[ "MIT" ]
JTOne123/Amazon
src/Amazon.CodeBuild/Models/SourceAuth.cs
191
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace P251_Party_Planner_3 { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
21.772727
66
0.565762
[ "MIT" ]
kysgithub/HeadFirstInCSharp
HeadFirstInCSharp/Ch06/P251-Party Planner 3.0/Program.cs
501
C#
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace Abraks.Data.Migrations { public partial class CreateIdentitySchema : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), PasswordHash = table.Column<string>(nullable: true), SecurityStamp = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), TwoFactorEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), LockoutEnabled = table.Column<bool>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), RoleId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), UserId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(maxLength: 128, nullable: false), ProviderKey = table.Column<string>(maxLength: 128, nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(maxLength: 128, nullable: false), Name = table.Column<string>(maxLength: 128, nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true, filter: "[NormalizedName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true, filter: "[NormalizedUserName] IS NOT NULL"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
43.063348
122
0.498266
[ "MIT" ]
Ceappie/Abraks
Abraks.Data/Migrations/00000000000000_CreateIdentitySchema.cs
9,519
C#
// -- FILE ------------------------------------------------------------------ // name : TimePeriodCollectionTest.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.02.18 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // ------------------------------------------------------------------------ using System; using TimePeriod.Enums; using TimePeriod.Interfaces; using Xunit; namespace TimePeriod.Tests { public sealed class TimePeriodCollectionTest : TestUnitBase { public TimePeriodCollectionTest() { startTestData = ClockProxy.Clock.Now; endTestData = startTestData.Add( durationTesData ); timeRangeTestData = new TimeRangePeriodRelationTestData( startTestData, endTestData, offsetTestData ); } // TimePeriodCollectionTest [Trait("Category", "TimePeriodCollection")] [Fact] public void DefaultConstructorTest() { TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal(0, timePeriods.Count); Assert.False( timePeriods.HasStart ); Assert.False( timePeriods.HasEnd ); Assert.False( timePeriods.IsReadOnly ); } // DefaultConstructorTest [Trait("Category", "TimePeriodCollection")] [Fact] public void CopyConstructorTest() { TimePeriodCollection timePeriods = new TimePeriodCollection( timeRangeTestData.AllPeriods ); Assert.Equal<int>( timePeriods.Count, timeRangeTestData.AllPeriods.Count ); Assert.True( timePeriods.HasStart ); Assert.True( timePeriods.HasEnd ); Assert.False( timePeriods.IsReadOnly ); } // CopyConstructorTest [Trait("Category", "TimePeriodCollection")] [Fact] public void CountTest() { TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal(0, timePeriods.Count); timePeriods.AddAll( timeRangeTestData.AllPeriods ); Assert.Equal<int>( timePeriods.Count, timeRangeTestData.AllPeriods.Count ); timePeriods.Clear(); Assert.Equal(0, timePeriods.Count); } // CountTest [Trait("Category", "TimePeriodCollection")] [Fact] public void ItemIndexTest() { TimePeriodCollection timePeriods = new TimePeriodCollection(); SchoolDay schoolDay = new SchoolDay(); timePeriods.AddAll( schoolDay ); Assert.Equal( timePeriods[ 0 ], schoolDay.Lesson1 ); Assert.Equal( timePeriods[ 1 ], schoolDay.Break1 ); Assert.Equal( timePeriods[ 2 ], schoolDay.Lesson2 ); Assert.Equal( timePeriods[ 3 ], schoolDay.Break2 ); Assert.Equal( timePeriods[ 4 ], schoolDay.Lesson3 ); Assert.Equal( timePeriods[ 5 ], schoolDay.Break3 ); Assert.Equal( timePeriods[ 6 ], schoolDay.Lesson4 ); } // ItemIndexTest [Trait("Category", "TimePeriodCollection")] [Fact] public void IsAnytimeTest() { DateTime now = ClockProxy.Clock.Now; TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.True( timePeriods.IsAnytime ); timePeriods.Add( TimeRange.Anytime ); Assert.True( timePeriods.IsAnytime ); timePeriods.Clear(); Assert.True( timePeriods.IsAnytime ); timePeriods.Add( new TimeRange( TimeSpec.MinPeriodDate, now ) ); Assert.False( timePeriods.IsAnytime ); timePeriods.Add( new TimeRange( now, TimeSpec.MaxPeriodDate ) ); Assert.True( timePeriods.IsAnytime ); timePeriods.Clear(); Assert.True( timePeriods.IsAnytime ); } // IsAnytimeTest [Trait("Category", "TimePeriodCollection")] [Fact] public void IsMomentTest() { DateTime now = ClockProxy.Clock.Now; TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.False( timePeriods.IsMoment ); timePeriods.Add( TimeRange.Anytime ); Assert.False( timePeriods.IsMoment ); timePeriods.Clear(); Assert.False( timePeriods.IsMoment ); timePeriods.Add( new TimeRange( now ) ); Assert.True( timePeriods.IsMoment ); timePeriods.Add( new TimeRange( now ) ); Assert.True( timePeriods.IsMoment ); timePeriods.Clear(); Assert.True( timePeriods.IsAnytime ); } // IsMomentTest [Trait("Category", "TimePeriodCollection")] [Fact] public void HasStartTest() { TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.False( timePeriods.HasStart ); timePeriods.Add( new TimeBlock( TimeSpec.MinPeriodDate, Duration.Hour ) ); Assert.False( timePeriods.HasStart ); timePeriods.Clear(); timePeriods.Add( new TimeBlock( ClockProxy.Clock.Now, Duration.Hour ) ); Assert.True( timePeriods.HasStart ); } // HasStartTest [Trait("Category", "TimePeriodCollection")] [Fact] public void StartTest() { DateTime now = ClockProxy.Clock.Now; TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal( timePeriods.Start, TimeSpec.MinPeriodDate ); timePeriods.Add( new TimeBlock( now, Duration.Hour ) ); Assert.Equal<DateTime>( timePeriods.Start, now ); timePeriods.Clear(); Assert.Equal( timePeriods.Start, TimeSpec.MinPeriodDate ); } // StartTest [Trait("Category", "TimePeriodCollection")] [Fact] public void StartMoveTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection( schoolDay ); timePeriods.Start = now.AddHours( 0 ); Assert.Equal<DateTime>( timePeriods.Start, now ); timePeriods.Start = now.AddHours( 1 ); Assert.Equal<DateTime>( timePeriods.Start, now.AddHours( 1 ) ); timePeriods.Start = now.AddHours( -1 ); Assert.Equal<DateTime>( timePeriods.Start, now.AddHours( -1 ) ); } // StartMoveTest [Trait("Category", "TimePeriodCollection")] [Fact] public void SortByTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection(); // start timePeriods.Add( schoolDay.Lesson4 ); timePeriods.Add( schoolDay.Break3 ); timePeriods.Add( schoolDay.Lesson3 ); timePeriods.Add( schoolDay.Break2 ); timePeriods.Add( schoolDay.Lesson2 ); timePeriods.Add( schoolDay.Break1 ); timePeriods.Add( schoolDay.Lesson1 ); timePeriods.SortBy( TimePeriodStartComparer.Comparer ); Assert.Equal( timePeriods[ 0 ], schoolDay.Lesson1 ); Assert.Equal( timePeriods[ 1 ], schoolDay.Break1 ); Assert.Equal( timePeriods[ 2 ], schoolDay.Lesson2 ); Assert.Equal( timePeriods[ 3 ], schoolDay.Break2 ); Assert.Equal( timePeriods[ 4 ], schoolDay.Lesson3 ); Assert.Equal( timePeriods[ 5 ], schoolDay.Break3 ); Assert.Equal( timePeriods[ 6 ], schoolDay.Lesson4 ); timePeriods.SortReverseBy( TimePeriodStartComparer.Comparer ); Assert.Equal( timePeriods[ 0 ], schoolDay.Lesson4 ); Assert.Equal( timePeriods[ 1 ], schoolDay.Break3 ); Assert.Equal( timePeriods[ 2 ], schoolDay.Lesson3 ); Assert.Equal( timePeriods[ 3 ], schoolDay.Break2 ); Assert.Equal( timePeriods[ 4 ], schoolDay.Lesson2 ); Assert.Equal( timePeriods[ 5 ], schoolDay.Break1 ); Assert.Equal( timePeriods[ 6 ], schoolDay.Lesson1 ); // end timePeriods.Clear(); timePeriods.AddAll( schoolDay ); timePeriods.SortReverseBy( TimePeriodEndComparer.Comparer ); Assert.Equal( timePeriods[ 0 ], schoolDay.Lesson4 ); Assert.Equal( timePeriods[ 1 ], schoolDay.Break3 ); Assert.Equal( timePeriods[ 2 ], schoolDay.Lesson3 ); Assert.Equal( timePeriods[ 3 ], schoolDay.Break2 ); Assert.Equal( timePeriods[ 4 ], schoolDay.Lesson2 ); Assert.Equal( timePeriods[ 5 ], schoolDay.Break1 ); Assert.Equal( timePeriods[ 6 ], schoolDay.Lesson1 ); timePeriods.SortBy( TimePeriodEndComparer.Comparer ); Assert.Equal( timePeriods[ 0 ], schoolDay.Lesson1 ); Assert.Equal( timePeriods[ 1 ], schoolDay.Break1 ); Assert.Equal( timePeriods[ 2 ], schoolDay.Lesson2 ); Assert.Equal( timePeriods[ 3 ], schoolDay.Break2 ); Assert.Equal( timePeriods[ 4 ], schoolDay.Lesson3 ); Assert.Equal( timePeriods[ 5 ], schoolDay.Break3 ); Assert.Equal( timePeriods[ 6 ], schoolDay.Lesson4 ); // duration timePeriods.Clear(); TimeSpan oneHour = new TimeSpan( 1, 0, 0 ); TimeSpan twoHours = new TimeSpan( 2, 0, 0 ); TimeSpan threeHours = new TimeSpan( 3, 0, 0 ); TimeSpan fourHours = new TimeSpan( 4, 0, 0 ); timePeriods.Add( new TimeRange( now, oneHour ) ); timePeriods.Add( new TimeRange( now, twoHours ) ); timePeriods.Add( new TimeRange( now, threeHours ) ); timePeriods.Add( new TimeRange( now, fourHours ) ); timePeriods.SortReverseBy( TimePeriodDurationComparer.Comparer ); Assert.Equal( fourHours, timePeriods[ 0 ].Duration ); Assert.Equal( threeHours, timePeriods[ 1 ].Duration ); Assert.Equal( twoHours, timePeriods[ 2 ].Duration ); Assert.Equal( oneHour, timePeriods[ 3 ].Duration ); timePeriods.SortBy( TimePeriodDurationComparer.Comparer ); Assert.Equal( oneHour, timePeriods[ 0 ].Duration ); Assert.Equal( twoHours, timePeriods[ 1 ].Duration ); Assert.Equal( threeHours, timePeriods[ 2 ].Duration ); Assert.Equal( fourHours, timePeriods[ 3 ].Duration ); } // SortByTest [Trait("Category", "TimePeriodCollection")] [Fact] public void SortByStartTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection(); timePeriods.Add( schoolDay.Lesson4 ); timePeriods.Add( schoolDay.Break3 ); timePeriods.Add( schoolDay.Lesson3 ); timePeriods.Add( schoolDay.Break2 ); timePeriods.Add( schoolDay.Lesson2 ); timePeriods.Add( schoolDay.Break1 ); timePeriods.Add( schoolDay.Lesson1 ); timePeriods.SortByStart( ListSortDirection.Descending ); Assert.Equal( timePeriods[ 0 ], schoolDay.Lesson4 ); Assert.Equal( timePeriods[ 1 ], schoolDay.Break3 ); Assert.Equal( timePeriods[ 2 ], schoolDay.Lesson3 ); Assert.Equal( timePeriods[ 3 ], schoolDay.Break2 ); Assert.Equal( timePeriods[ 4 ], schoolDay.Lesson2 ); Assert.Equal( timePeriods[ 5 ], schoolDay.Break1 ); Assert.Equal( timePeriods[ 6 ], schoolDay.Lesson1 ); timePeriods.SortByStart(); Assert.Equal( timePeriods[ 0 ], schoolDay.Lesson1 ); Assert.Equal( timePeriods[ 1 ], schoolDay.Break1 ); Assert.Equal( timePeriods[ 2 ], schoolDay.Lesson2 ); Assert.Equal( timePeriods[ 3 ], schoolDay.Break2 ); Assert.Equal( timePeriods[ 4 ], schoolDay.Lesson3 ); Assert.Equal( timePeriods[ 5 ], schoolDay.Break3 ); Assert.Equal( timePeriods[ 6 ], schoolDay.Lesson4 ); } // SortByStartTest [Trait("Category", "TimePeriodCollection")] [Fact] public void SortByEndTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection(); timePeriods.AddAll( schoolDay ); timePeriods.SortByEnd( ListSortDirection.Descending ); Assert.Equal( timePeriods[ 0 ], schoolDay.Lesson4 ); Assert.Equal( timePeriods[ 1 ], schoolDay.Break3 ); Assert.Equal( timePeriods[ 2 ], schoolDay.Lesson3 ); Assert.Equal( timePeriods[ 3 ], schoolDay.Break2 ); Assert.Equal( timePeriods[ 4 ], schoolDay.Lesson2 ); Assert.Equal( timePeriods[ 5 ], schoolDay.Break1 ); Assert.Equal( timePeriods[ 6 ], schoolDay.Lesson1 ); timePeriods.SortByEnd(); Assert.Equal( timePeriods[ 0 ], schoolDay.Lesson1 ); Assert.Equal( timePeriods[ 1 ], schoolDay.Break1 ); Assert.Equal( timePeriods[ 2 ], schoolDay.Lesson2 ); Assert.Equal( timePeriods[ 3 ], schoolDay.Break2 ); Assert.Equal( timePeriods[ 4 ], schoolDay.Lesson3 ); Assert.Equal( timePeriods[ 5 ], schoolDay.Break3 ); Assert.Equal( timePeriods[ 6 ], schoolDay.Lesson4 ); } // SortByEndTest [Trait("Category", "TimePeriodCollection")] [Fact] public void SortByDurationTest() { DateTime now = ClockProxy.Clock.Now; TimePeriodCollection timePeriods = new TimePeriodCollection(); TimeSpan oneHour = new TimeSpan( 1, 0, 0 ); TimeSpan twoHours = new TimeSpan( 2, 0, 0 ); TimeSpan threeHours = new TimeSpan( 3, 0, 0 ); TimeSpan fourHours = new TimeSpan( 4, 0, 0 ); timePeriods.Add( new TimeRange( now, oneHour ) ); timePeriods.Add( new TimeRange( now, twoHours ) ); timePeriods.Add( new TimeRange( now, threeHours ) ); timePeriods.Add( new TimeRange( now, fourHours ) ); timePeriods.SortByDuration( ListSortDirection.Descending ); Assert.Equal( fourHours, timePeriods[ 0 ].Duration ); Assert.Equal( threeHours, timePeriods[ 1 ].Duration ); Assert.Equal( twoHours, timePeriods[ 2 ].Duration ); Assert.Equal( oneHour, timePeriods[ 3 ].Duration ); timePeriods.SortByDuration(); Assert.Equal( oneHour, timePeriods[ 0 ].Duration ); Assert.Equal( twoHours, timePeriods[ 1 ].Duration ); Assert.Equal( threeHours, timePeriods[ 2 ].Duration ); Assert.Equal( fourHours, timePeriods[ 3 ].Duration ); } // SortByDurationTest [Trait("Category", "TimePeriodCollection")] [Fact] public void InsidePeriodsTimePeriodTest() { DateTime now = ClockProxy.Clock.Now; TimeRange timeRange1 = new TimeRange( new DateTime( now.Year, now.Month, 8 ), new DateTime( now.Year, now.Month, 18 ) ); TimeRange timeRange2 = new TimeRange( new DateTime( now.Year, now.Month, 10 ), new DateTime( now.Year, now.Month, 11 ) ); TimeRange timeRange3 = new TimeRange( new DateTime( now.Year, now.Month, 13 ), new DateTime( now.Year, now.Month, 15 ) ); TimeRange timeRange4 = new TimeRange( new DateTime( now.Year, now.Month, 9 ), new DateTime( now.Year, now.Month, 13 ) ); TimeRange timeRange5 = new TimeRange( new DateTime( now.Year, now.Month, 15 ), new DateTime( now.Year, now.Month, 17 ) ); TimePeriodCollection timePeriods = new TimePeriodCollection(); timePeriods.Add( timeRange1 ); timePeriods.Add( timeRange2 ); timePeriods.Add( timeRange3 ); timePeriods.Add( timeRange4 ); timePeriods.Add( timeRange5 ); Assert.Equal(5, timePeriods.InsidePeriods( timeRange1 ).Count); Assert.Equal(1, timePeriods.InsidePeriods( timeRange2 ).Count); Assert.Equal(1, timePeriods.InsidePeriods( timeRange3 ).Count); Assert.Equal(2, timePeriods.InsidePeriods( timeRange4 ).Count); Assert.Equal(1, timePeriods.InsidePeriods( timeRange5 ).Count); ITimeRange test1 = timeRange1.Copy( new TimeSpan( 100, 0, 0, 0 ).Negate() ); ITimePeriodCollection insidePeriods1 = timePeriods.InsidePeriods( test1 ); Assert.Equal(0, insidePeriods1.Count); ITimeRange test2 = timeRange1.Copy( new TimeSpan( 100, 0, 0, 0 ) ); ITimePeriodCollection insidePeriods2 = timePeriods.InsidePeriods( test2 ); Assert.Equal(0, insidePeriods2.Count); TimeRange test3 = new TimeRange( new DateTime( now.Year, now.Month, 9 ), new DateTime( now.Year, now.Month, 11 ) ); ITimePeriodCollection insidePeriods3 = timePeriods.InsidePeriods( test3 ); Assert.Equal(1, insidePeriods3.Count); TimeRange test4 = new TimeRange( new DateTime( now.Year, now.Month, 14 ), new DateTime( now.Year, now.Month, 17 ) ); ITimePeriodCollection insidePeriods4 = timePeriods.InsidePeriods( test4 ); Assert.Equal(1, insidePeriods4.Count); } // InsidePeriodsTimePeriodTest [Trait("Category", "TimePeriodCollection")] [Fact] public void OverlapPeriodsTest() { DateTime now = ClockProxy.Clock.Now; TimeRange timeRange1 = new TimeRange( new DateTime( now.Year, now.Month, 8 ), new DateTime( now.Year, now.Month, 18 ) ); TimeRange timeRange2 = new TimeRange( new DateTime( now.Year, now.Month, 10 ), new DateTime( now.Year, now.Month, 11 ) ); TimeRange timeRange3 = new TimeRange( new DateTime( now.Year, now.Month, 13 ), new DateTime( now.Year, now.Month, 15 ) ); TimeRange timeRange4 = new TimeRange( new DateTime( now.Year, now.Month, 9 ), new DateTime( now.Year, now.Month, 13 ) ); TimeRange timeRange5 = new TimeRange( new DateTime( now.Year, now.Month, 15 ), new DateTime( now.Year, now.Month, 17 ) ); TimePeriodCollection timePeriods = new TimePeriodCollection(); timePeriods.Add( timeRange1 ); timePeriods.Add( timeRange2 ); timePeriods.Add( timeRange3 ); timePeriods.Add( timeRange4 ); timePeriods.Add( timeRange5 ); Assert.Equal(5, timePeriods.OverlapPeriods( timeRange1 ).Count); Assert.Equal(3, timePeriods.OverlapPeriods( timeRange2 ).Count); Assert.Equal(2, timePeriods.OverlapPeriods( timeRange3 ).Count); Assert.Equal(3, timePeriods.OverlapPeriods( timeRange4 ).Count); Assert.Equal(2, timePeriods.OverlapPeriods( timeRange5 ).Count); ITimeRange test1 = timeRange1.Copy( new TimeSpan( 100, 0, 0, 0 ).Negate() ); ITimePeriodCollection insidePeriods1 = timePeriods.OverlapPeriods( test1 ); Assert.Equal(0, insidePeriods1.Count); ITimeRange test2 = timeRange1.Copy( new TimeSpan( 100, 0, 0, 0 ) ); ITimePeriodCollection insidePeriods2 = timePeriods.OverlapPeriods( test2 ); Assert.Equal(0, insidePeriods2.Count); TimeRange test3 = new TimeRange( new DateTime( now.Year, now.Month, 9 ), new DateTime( now.Year, now.Month, 11 ) ); ITimePeriodCollection insidePeriods3 = timePeriods.OverlapPeriods( test3 ); Assert.Equal(3, insidePeriods3.Count); TimeRange test4 = new TimeRange( new DateTime( now.Year, now.Month, 14 ), new DateTime( now.Year, now.Month, 17 ) ); ITimePeriodCollection insidePeriods4 = timePeriods.OverlapPeriods( test4 ); Assert.Equal(3, insidePeriods4.Count); } // OverlapPeriodsTest [Trait("Category", "TimePeriodCollection")] [Fact] public void IntersectionPeriodsDateTimeTest() { DateTime now = ClockProxy.Clock.Now; TimeRange timeRange1 = new TimeRange( new DateTime( now.Year, now.Month, 8 ), new DateTime( now.Year, now.Month, 18 ) ); TimeRange timeRange2 = new TimeRange( new DateTime( now.Year, now.Month, 10 ), new DateTime( now.Year, now.Month, 11 ) ); TimeRange timeRange3 = new TimeRange( new DateTime( now.Year, now.Month, 13 ), new DateTime( now.Year, now.Month, 15 ) ); TimeRange timeRange4 = new TimeRange( new DateTime( now.Year, now.Month, 9 ), new DateTime( now.Year, now.Month, 14 ) ); TimeRange timeRange5 = new TimeRange( new DateTime( now.Year, now.Month, 16 ), new DateTime( now.Year, now.Month, 17 ) ); TimePeriodCollection timePeriods = new TimePeriodCollection(); timePeriods.Add( timeRange1 ); timePeriods.Add( timeRange2 ); timePeriods.Add( timeRange3 ); timePeriods.Add( timeRange4 ); timePeriods.Add( timeRange5 ); Assert.Equal(1, timePeriods.IntersectionPeriods( timeRange1.Start ).Count); Assert.Equal(1, timePeriods.IntersectionPeriods( timeRange1.End ).Count); Assert.Equal(3, timePeriods.IntersectionPeriods( timeRange2.Start ).Count); Assert.Equal(3, timePeriods.IntersectionPeriods( timeRange2.End ).Count); Assert.Equal(3, timePeriods.IntersectionPeriods( timeRange3.Start ).Count); Assert.Equal(2, timePeriods.IntersectionPeriods( timeRange3.End ).Count); Assert.Equal(2, timePeriods.IntersectionPeriods( timeRange4.Start ).Count); Assert.Equal(3, timePeriods.IntersectionPeriods( timeRange4.End ).Count); Assert.Equal(2, timePeriods.IntersectionPeriods( timeRange5.Start ).Count); Assert.Equal(2, timePeriods.IntersectionPeriods( timeRange5.End ).Count); DateTime test1 = timeRange1.Start.AddMilliseconds( -1 ); ITimePeriodCollection insidePeriods1 = timePeriods.IntersectionPeriods( test1 ); Assert.Equal(0, insidePeriods1.Count); DateTime test2 = timeRange1.End.AddMilliseconds( 1 ); ITimePeriodCollection insidePeriods2 = timePeriods.IntersectionPeriods( test2 ); Assert.Equal(0, insidePeriods2.Count); DateTime test3 = new DateTime( now.Year, now.Month, 12 ); ITimePeriodCollection insidePeriods3 = timePeriods.IntersectionPeriods( test3 ); Assert.Equal(2, insidePeriods3.Count); DateTime test4 = new DateTime( now.Year, now.Month, 14 ); ITimePeriodCollection insidePeriods4 = timePeriods.IntersectionPeriods( test4 ); Assert.Equal(3, insidePeriods4.Count); } // IntersectionPeriodsDateTimeTest [Trait("Category", "TimePeriodCollection")] [Fact] public void RelationPeriodsTest() { DateTime now = ClockProxy.Clock.Now; TimeRange timeRange1 = new TimeRange( new DateTime( now.Year, now.Month, 8 ), new DateTime( now.Year, now.Month, 18 ) ); TimeRange timeRange2 = new TimeRange( new DateTime( now.Year, now.Month, 10 ), new DateTime( now.Year, now.Month, 11 ) ); TimeRange timeRange3 = new TimeRange( new DateTime( now.Year, now.Month, 13 ), new DateTime( now.Year, now.Month, 15 ) ); TimeRange timeRange4 = new TimeRange( new DateTime( now.Year, now.Month, 9 ), new DateTime( now.Year, now.Month, 14 ) ); TimeRange timeRange5 = new TimeRange( new DateTime( now.Year, now.Month, 16 ), new DateTime( now.Year, now.Month, 17 ) ); TimePeriodCollection timePeriods = new TimePeriodCollection(); timePeriods.Add( timeRange1 ); timePeriods.Add( timeRange2 ); timePeriods.Add( timeRange3 ); timePeriods.Add( timeRange4 ); timePeriods.Add( timeRange5 ); Assert.Equal(1, timePeriods.RelationPeriods( timeRange1, PeriodRelation.ExactMatch ).Count); Assert.Equal(1, timePeriods.RelationPeriods( timeRange2, PeriodRelation.ExactMatch ).Count); Assert.Equal(1, timePeriods.RelationPeriods( timeRange3, PeriodRelation.ExactMatch ).Count); Assert.Equal(1, timePeriods.RelationPeriods( timeRange4, PeriodRelation.ExactMatch ).Count); Assert.Equal(1, timePeriods.RelationPeriods( timeRange5, PeriodRelation.ExactMatch ).Count); // all Assert.Equal(5, timePeriods.RelationPeriods( new TimeRange( new DateTime( now.Year, now.Month, 7 ), new DateTime( now.Year, now.Month, 19 ) ), PeriodRelation.Enclosing ).Count); // timerange3 Assert.Equal(1, timePeriods.RelationPeriods( new TimeRange( new DateTime( now.Year, now.Month, 11 ), new DateTime( now.Year, now.Month, 16 ) ), PeriodRelation.Enclosing ).Count); } // RelationPeriodsTest [Trait("Category", "TimePeriodCollection")] [Fact] public void IntersectionPeriodsTimePeriodTest() { DateTime now = ClockProxy.Clock.Now; TimeRange timeRange1 = new TimeRange( new DateTime( now.Year, now.Month, 8 ), new DateTime( now.Year, now.Month, 18 ) ); TimeRange timeRange2 = new TimeRange( new DateTime( now.Year, now.Month, 10 ), new DateTime( now.Year, now.Month, 11 ) ); TimeRange timeRange3 = new TimeRange( new DateTime( now.Year, now.Month, 13 ), new DateTime( now.Year, now.Month, 15 ) ); TimeRange timeRange4 = new TimeRange( new DateTime( now.Year, now.Month, 9 ), new DateTime( now.Year, now.Month, 13 ) ); TimeRange timeRange5 = new TimeRange( new DateTime( now.Year, now.Month, 15 ), new DateTime( now.Year, now.Month, 17 ) ); TimePeriodCollection timePeriods = new TimePeriodCollection(); timePeriods.Add( timeRange1 ); timePeriods.Add( timeRange2 ); timePeriods.Add( timeRange3 ); timePeriods.Add( timeRange4 ); timePeriods.Add( timeRange5 ); Assert.Equal(5, timePeriods.IntersectionPeriods( timeRange1 ).Count); Assert.Equal(3, timePeriods.IntersectionPeriods( timeRange2 ).Count); Assert.Equal(4, timePeriods.IntersectionPeriods( timeRange3 ).Count); Assert.Equal(4, timePeriods.IntersectionPeriods( timeRange4 ).Count); Assert.Equal(3, timePeriods.IntersectionPeriods( timeRange5 ).Count); ITimeRange test1 = timeRange1.Copy( new TimeSpan( 100, 0, 0, 0 ).Negate() ); ITimePeriodCollection insidePeriods1 = timePeriods.IntersectionPeriods( test1 ); Assert.Equal(0, insidePeriods1.Count); ITimeRange test2 = timeRange1.Copy( new TimeSpan( 100, 0, 0, 0 ) ); ITimePeriodCollection insidePeriods2 = timePeriods.IntersectionPeriods( test2 ); Assert.Equal(0, insidePeriods2.Count); TimeRange test3 = new TimeRange( new DateTime( now.Year, now.Month, 9 ), new DateTime( now.Year, now.Month, 11 ) ); ITimePeriodCollection insidePeriods3 = timePeriods.IntersectionPeriods( test3 ); Assert.Equal(3, insidePeriods3.Count); TimeRange test4 = new TimeRange( new DateTime( now.Year, now.Month, 14 ), new DateTime( now.Year, now.Month, 17 ) ); ITimePeriodCollection insidePeriods4 = timePeriods.IntersectionPeriods( test4 ); Assert.Equal(3, insidePeriods4.Count); } // IntersectionPeriodsTimePeriodTest [Trait("Category", "TimePeriodCollection")] [Fact] public void HasEndTest() { DateTime now = ClockProxy.Clock.Now; TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.False( timePeriods.HasEnd ); timePeriods.Add( new TimeBlock( Duration.Hour, TimeSpec.MaxPeriodDate ) ); Assert.False( timePeriods.HasEnd ); timePeriods.Clear(); timePeriods.Add( new TimeBlock( now, Duration.Hour ) ); Assert.True( timePeriods.HasEnd ); } // HasEndTest [Trait("Category", "TimePeriodCollection")] [Fact] public void EndTest() { DateTime now = ClockProxy.Clock.Now; TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal( timePeriods.End, TimeSpec.MaxPeriodDate ); timePeriods.Add( new TimeBlock( Duration.Hour, now ) ); Assert.Equal<DateTime>( timePeriods.End, now ); timePeriods.Clear(); Assert.Equal( timePeriods.End, TimeSpec.MaxPeriodDate ); } // EndTest [Trait("Category", "TimePeriodCollection")] [Fact] public void EndMoveTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection( schoolDay ); DateTime end = schoolDay.End; timePeriods.End = end.AddHours( 0 ); Assert.Equal<DateTime>( timePeriods.End, end ); timePeriods.End = end.AddHours( 1 ); Assert.Equal<DateTime>( timePeriods.End, end.AddHours( 1 ) ); timePeriods.End = end.AddHours( -1 ); Assert.Equal<DateTime>( timePeriods.End, end.AddHours( -1 ) ); } // EndMoveTest [Trait("Category", "TimePeriodCollection")] [Fact] public void DurationTest() { TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal( timePeriods.Duration, TimeSpec.MaxPeriodDuration ); TimeSpan duration = Duration.Hour; timePeriods.Add( new TimeBlock( ClockProxy.Clock.Now, duration ) ); Assert.Equal<TimeSpan>( timePeriods.Duration, duration ); } // DurationTest [Trait("Category", "TimePeriodCollection")] [Fact] public void TotalDurationTest() { DateTime now = ClockProxy.Clock.Now; TimeRange timeRange1 = new TimeRange( new DateTime( now.Year, now.Month, 8 ), new DateTime( now.Year, now.Month, 18 ) ); TimeRange timeRange2 = new TimeRange( new DateTime( now.Year, now.Month, 10 ), new DateTime( now.Year, now.Month, 11 ) ); TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal<TimeSpan>( timePeriods.TotalDuration, TimeSpan.Zero ); timePeriods.Add( timeRange1 ); Assert.Equal( timePeriods.TotalDuration, timeRange1.End.Subtract( timeRange1.Start ) ); Assert.Equal( timePeriods.TotalDuration, timeRange1.Duration ); timePeriods.Add( timeRange2 ); Assert.Equal( timePeriods.TotalDuration, timeRange1.End.Subtract( timeRange1.Start ). Add( timeRange2.End.Subtract( timeRange2.Start ) ) ); Assert.Equal( timePeriods.TotalDuration, timeRange1.Duration.Add( timeRange2.Duration ) ); } // TotalDurationTest /* [Trait("Category", "TimePeriodCollection")] [Fact] public void TotalDaylightDurationTest() { DateTime dstStart = new DateTime( 2014, 3, 30, 2, 0, 0 ).AddHours( 1 ); DateTime dstEnd = new DateTime( 2014, 10, 26, 3, 0, 0 ).AddHours( -1 ); TimeRange timeRange1 = new TimeRange( dstStart.AddHours( -2 ), dstStart.AddHours( 2 ) ); TimeRange timeRange2 = new TimeRange( dstEnd.AddHours( -2 ), dstEnd.AddHours( 2 ) ); TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById( "Central Europe Standard Time" ); TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal( timePeriods.GetTotalDaylightDuration( timeZone ), TimeSpan.Zero ); timePeriods.Add( timeRange1 ); Assert.Equal( timePeriods.GetTotalDaylightDuration( timeZone ), timeRange1.GetDaylightDuration( timeZone ) ); timePeriods.Add( timeRange2 ); Assert.Equal( timePeriods.GetTotalDaylightDuration( timeZone ), timeRange1.GetDaylightDuration( timeZone ). Add( timeRange2.GetDaylightDuration( timeZone ) ) ); } // TotalDaylightDurationTest */ [Trait("Category", "TimePeriodCollection")] [Fact] public void MoveTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection( schoolDay ); DateTime startDate = schoolDay.Start; DateTime endDate = schoolDay.End; TimeSpan startDuration = timePeriods.Duration; TimeSpan duration = Duration.Hour; timePeriods.Move( duration ); Assert.Equal<DateTime>( timePeriods.Start, startDate.Add( duration ) ); Assert.Equal<DateTime>( timePeriods.End, endDate.Add( duration ) ); Assert.Equal<TimeSpan>( timePeriods.Duration, startDuration ); } // MoveTest [Trait("Category", "TimePeriodCollection")] [Fact] public void AddTest() { TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal(0, timePeriods.Count); timePeriods.Add( new TimeRange() ); Assert.Equal(1, timePeriods.Count); timePeriods.Add( new TimeRange() ); Assert.Equal(2, timePeriods.Count); timePeriods.Clear(); Assert.Equal(0, timePeriods.Count); } // AddTest [Trait("Category", "TimePeriodCollection")] [Fact] public void ContainsPeriodTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection( schoolDay ); TimeRange timeRange = new TimeRange( schoolDay.Lesson1.Start, schoolDay.Lesson1.End ); Assert.False( timePeriods.Contains( timeRange ) ); Assert.True( timePeriods.ContainsPeriod( timeRange ) ); timePeriods.Add( timeRange ); Assert.True( timePeriods.Contains( timeRange ) ); Assert.True( timePeriods.ContainsPeriod( timeRange ) ); } // ContainsPeriodTest [Trait("Category", "TimePeriodCollection")] [Fact] public void AddAllTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal(0, timePeriods.Count); timePeriods.AddAll( schoolDay ); Assert.Equal( timePeriods.Count, schoolDay.Count ); timePeriods.Clear(); Assert.Equal(0, timePeriods.Count); } // AddAllTest [Trait("Category", "TimePeriodCollection")] [Fact] public void InsertTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal(0, timePeriods.Count); timePeriods.Add( schoolDay.Lesson1 ); Assert.Equal(1, timePeriods.Count); timePeriods.Add( schoolDay.Lesson3 ); Assert.Equal(2, timePeriods.Count); timePeriods.Add( schoolDay.Lesson4 ); Assert.Equal(3, timePeriods.Count); // between Assert.Equal( timePeriods[ 1 ], schoolDay.Lesson3 ); timePeriods.Insert( 1, schoolDay.Lesson2 ); Assert.Equal( timePeriods[ 1 ], schoolDay.Lesson2 ); // first Assert.Equal( timePeriods[ 0 ], schoolDay.Lesson1 ); timePeriods.Insert( 0, schoolDay.Break1 ); Assert.Equal( timePeriods[ 0 ], schoolDay.Break1 ); // last Assert.Equal( timePeriods[ timePeriods.Count - 1 ], schoolDay.Lesson4 ); timePeriods.Insert( timePeriods.Count, schoolDay.Break3 ); Assert.Equal( timePeriods[ timePeriods.Count - 1 ], schoolDay.Break3 ); } // InsertTest [Trait("Category", "TimePeriodCollection")] [Fact] public void ContainsTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.False( timePeriods.Contains( schoolDay.Lesson1 ) ); timePeriods.Add( schoolDay.Lesson1 ); Assert.True( timePeriods.Contains( schoolDay.Lesson1 ) ); timePeriods.Remove( schoolDay.Lesson1 ); Assert.False( timePeriods.Contains( schoolDay.Lesson1 ) ); } // ContainsTest [Trait("Category", "TimePeriodCollection")] [Fact] public void IndexOfTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal<int>( timePeriods.IndexOf( new TimeRange() ), -1 ); Assert.Equal<int>( timePeriods.IndexOf( new TimeBlock() ), -1 ); timePeriods.AddAll( schoolDay ); Assert.Equal(0, timePeriods.IndexOf( schoolDay.Lesson1 )); Assert.Equal(1, timePeriods.IndexOf( schoolDay.Break1 )); Assert.Equal(2, timePeriods.IndexOf( schoolDay.Lesson2 )); Assert.Equal(3, timePeriods.IndexOf( schoolDay.Break2 )); Assert.Equal(4, timePeriods.IndexOf( schoolDay.Lesson3 )); Assert.Equal(5, timePeriods.IndexOf( schoolDay.Break3 )); Assert.Equal(6, timePeriods.IndexOf( schoolDay.Lesson4 )); timePeriods.Remove( schoolDay.Lesson1 ); Assert.Equal<int>( timePeriods.IndexOf( schoolDay.Lesson1 ), -1 ); } // IndexOfTest [Trait("Category", "TimePeriodCollection")] [Fact] public void CopyToTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection( schoolDay ); ITimePeriod[] array = new ITimePeriod[ schoolDay.Count ]; timePeriods.CopyTo( array, 0 ); Assert.Equal( array[ 0 ], schoolDay.Lesson1 ); Assert.Equal( array[ 1 ], schoolDay.Break1 ); Assert.Equal( array[ 2 ], schoolDay.Lesson2 ); Assert.Equal( array[ 3 ], schoolDay.Break2 ); Assert.Equal( array[ 4 ], schoolDay.Lesson3 ); Assert.Equal( array[ 5 ], schoolDay.Break3 ); Assert.Equal( array[ 6 ], schoolDay.Lesson4 ); } // CopyToTest [Trait("Category", "TimePeriodCollection")] [Fact] public void ClearTest() { TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.Equal(0, timePeriods.Count); timePeriods.Clear(); Assert.Equal(0, timePeriods.Count); timePeriods.AddAll( new SchoolDay() ); Assert.Equal(7, timePeriods.Count); timePeriods.Clear(); Assert.Equal(0, timePeriods.Count); } // ClearTest [Trait("Category", "TimePeriodCollection")] [Fact] public void RemoveTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection(); Assert.False( timePeriods.Contains( schoolDay.Lesson1 ) ); timePeriods.Add( schoolDay.Lesson1 ); Assert.True( timePeriods.Contains( schoolDay.Lesson1 ) ); timePeriods.Remove( schoolDay.Lesson1 ); Assert.False( timePeriods.Contains( schoolDay.Lesson1 ) ); } // RemoveTest [Trait("Category", "TimePeriodCollection")] [Fact] public void RemoveAtTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection( schoolDay ); // inside Assert.Equal( timePeriods[ 2 ], schoolDay.Lesson2 ); timePeriods.RemoveAt( 2 ); Assert.Equal( timePeriods[ 2 ], schoolDay.Break2 ); // first Assert.Equal( timePeriods[ 0 ], schoolDay.Lesson1 ); timePeriods.RemoveAt( 0 ); Assert.Equal( timePeriods[ 0 ], schoolDay.Break1 ); // last Assert.Equal( timePeriods[ timePeriods.Count - 1 ], schoolDay.Lesson4 ); timePeriods.RemoveAt( timePeriods.Count - 1 ); Assert.Equal( timePeriods[ timePeriods.Count - 1 ], schoolDay.Break3 ); } // RemoveAtTest [Trait("Category", "TimePeriodCollection")] [Fact] public void IsSamePeriodTest() { DateTime now = ClockProxy.Clock.Now; SchoolDay schoolDay = new SchoolDay( now ); TimePeriodCollection timePeriods = new TimePeriodCollection( schoolDay ); Assert.True( timePeriods.IsSamePeriod( timePeriods ) ); Assert.True( timePeriods.IsSamePeriod( schoolDay ) ); Assert.True( schoolDay.IsSamePeriod( schoolDay ) ); Assert.True( schoolDay.IsSamePeriod( timePeriods ) ); Assert.False( timePeriods.IsSamePeriod( TimeBlock.Anytime ) ); Assert.False( schoolDay.IsSamePeriod( TimeBlock.Anytime ) ); timePeriods.RemoveAt( 0 ); Assert.False( timePeriods.IsSamePeriod( schoolDay ) ); } // IsSamePeriodTest [Trait("Category", "TimePeriodCollection")] [Fact] public void HasInsideTest() { DateTime now = ClockProxy.Clock.Now; TimeSpan offset = Duration.Second; TimeRangePeriodRelationTestData testData = new TimeRangePeriodRelationTestData( now, now.AddHours( 1 ), offset ); TimePeriodCollection timePeriods = new TimePeriodCollection(); timePeriods.Add( testData.Reference ); Assert.False( timePeriods.HasInside( testData.Before ) ); Assert.False( timePeriods.HasInside( testData.StartTouching ) ); Assert.False( timePeriods.HasInside( testData.StartInside ) ); Assert.False( timePeriods.HasInside( testData.InsideStartTouching ) ); Assert.True( timePeriods.HasInside( testData.EnclosingStartTouching ) ); Assert.True( timePeriods.HasInside( testData.Enclosing ) ); Assert.True( timePeriods.HasInside( testData.EnclosingEndTouching ) ); Assert.True( timePeriods.HasInside( testData.ExactMatch ) ); Assert.False( timePeriods.HasInside( testData.Inside ) ); Assert.False( timePeriods.HasInside( testData.InsideEndTouching ) ); Assert.False( timePeriods.HasInside( testData.EndInside ) ); Assert.False( timePeriods.HasInside( testData.EndTouching ) ); Assert.False( timePeriods.HasInside( testData.After ) ); } // HasInsideTest [Trait("Category", "TimePeriodCollection")] [Fact] public void IntersectsWithTest() { DateTime now = ClockProxy.Clock.Now; TimeSpan offset = Duration.Second; TimeRangePeriodRelationTestData testData = new TimeRangePeriodRelationTestData( now, now.AddHours( 1 ), offset ); TimePeriodCollection timePeriods = new TimePeriodCollection(); timePeriods.Add( testData.Reference ); Assert.False( timePeriods.IntersectsWith( testData.Before ) ); Assert.True( timePeriods.IntersectsWith( testData.StartTouching ) ); Assert.True( timePeriods.IntersectsWith( testData.StartInside ) ); Assert.True( timePeriods.IntersectsWith( testData.InsideStartTouching ) ); Assert.True( timePeriods.IntersectsWith( testData.EnclosingStartTouching ) ); Assert.True( timePeriods.IntersectsWith( testData.Enclosing ) ); Assert.True( timePeriods.IntersectsWith( testData.EnclosingEndTouching ) ); Assert.True( timePeriods.IntersectsWith( testData.ExactMatch ) ); Assert.True( timePeriods.IntersectsWith( testData.Inside ) ); Assert.True( timePeriods.IntersectsWith( testData.InsideEndTouching ) ); Assert.True( timePeriods.IntersectsWith( testData.EndInside ) ); Assert.True( timePeriods.IntersectsWith( testData.EndTouching ) ); Assert.False( timePeriods.IntersectsWith( testData.After ) ); } // IntersectsWithTest [Trait("Category", "TimePeriodCollection")] [Fact] public void OverlapsWithTest() { DateTime now = ClockProxy.Clock.Now; TimeSpan offset = Duration.Second; TimeRangePeriodRelationTestData testData = new TimeRangePeriodRelationTestData( now, now.AddHours( 1 ), offset ); TimePeriodCollection timePeriods = new TimePeriodCollection(); timePeriods.Add( testData.Reference ); Assert.False( timePeriods.OverlapsWith( testData.Before ) ); Assert.False( timePeriods.OverlapsWith( testData.StartTouching ) ); Assert.True( timePeriods.OverlapsWith( testData.StartInside ) ); Assert.True( timePeriods.OverlapsWith( testData.InsideStartTouching ) ); Assert.True( timePeriods.OverlapsWith( testData.EnclosingStartTouching ) ); Assert.True( timePeriods.OverlapsWith( testData.Enclosing ) ); Assert.True( timePeriods.OverlapsWith( testData.EnclosingEndTouching ) ); Assert.True( timePeriods.OverlapsWith( testData.ExactMatch ) ); Assert.True( timePeriods.OverlapsWith( testData.Inside ) ); Assert.True( timePeriods.OverlapsWith( testData.InsideEndTouching ) ); Assert.True( timePeriods.OverlapsWith( testData.EndInside ) ); Assert.False( timePeriods.OverlapsWith( testData.EndTouching ) ); Assert.False( timePeriods.OverlapsWith( testData.After ) ); } // OverlapsWithTest [Trait("Category", "TimePeriodCollection")] [Fact] public void GetRelationTest() { DateTime now = ClockProxy.Clock.Now; TimeSpan offset = Duration.Second; TimeRangePeriodRelationTestData testData = new TimeRangePeriodRelationTestData( now, now.AddHours( 1 ), offset ); TimePeriodCollection timePeriods = new TimePeriodCollection(); timePeriods.Add( testData.Reference ); Assert.Equal(PeriodRelation.Before, timePeriods.GetRelation( testData.Before )); Assert.Equal(PeriodRelation.StartTouching, timePeriods.GetRelation( testData.StartTouching )); Assert.Equal(PeriodRelation.StartInside, timePeriods.GetRelation( testData.StartInside )); Assert.Equal(PeriodRelation.InsideStartTouching, timePeriods.GetRelation( testData.InsideStartTouching )); Assert.Equal(PeriodRelation.EnclosingStartTouching, timePeriods.GetRelation( testData.EnclosingStartTouching )); Assert.Equal(PeriodRelation.Enclosing, timePeriods.GetRelation( testData.Enclosing )); Assert.Equal(PeriodRelation.EnclosingEndTouching, timePeriods.GetRelation( testData.EnclosingEndTouching )); Assert.Equal(PeriodRelation.ExactMatch, timePeriods.GetRelation( testData.ExactMatch )); Assert.Equal(PeriodRelation.Inside, timePeriods.GetRelation( testData.Inside )); Assert.Equal(PeriodRelation.InsideEndTouching, timePeriods.GetRelation( testData.InsideEndTouching )); Assert.Equal(PeriodRelation.EndInside, timePeriods.GetRelation( testData.EndInside )); Assert.Equal(PeriodRelation.EndTouching, timePeriods.GetRelation( testData.EndTouching )); Assert.Equal(PeriodRelation.After, timePeriods.GetRelation( testData.After )); } // GetRelationTest // members private readonly TimeSpan durationTesData = Duration.Hour; private readonly DateTime startTestData; private readonly DateTime endTestData; private readonly TimeSpan offsetTestData = Duration.Millisecond; private readonly TimeRangePeriodRelationTestData timeRangeTestData; } // class TimePeriodCollectionTest } // namespace Itenso.TimePeriodTests // -- EOF -------------------------------------------------------------------
41.661945
182
0.692747
[ "MIT" ]
JeroenMX/TimePeriod
src/TimePeriodTests/TimePeriodCollectionTest.cs
44,120
C#
using System; using System.Collections.Generic; namespace EZOper.NetSiteUtilities.AopApi { /// <summary> /// AOP API: alipay.open.public.message.custom.send /// </summary> public class AlipayOpenPublicMessageCustomSendRequest : IAopRequest<AlipayOpenPublicMessageCustomSendResponse> { /// <summary> /// 异步单发消息 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.open.public.message.custom.send"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.436364
114
0.605508
[ "MIT" ]
erikzhouxin/CSharpSolution
NetSiteUtilities/AopApi/Request/AlipayOpenPublicMessageCustomSendRequest.cs
2,590
C#
using System; using System.Collections.Generic; using Perpetuum.Accounting.Characters; namespace Perpetuum.Services.Social { internal class FriendInfo { public readonly Character character; public SocialState socialState; public string note; public DateTime lastStateUpdate; public FriendInfo(Character character, SocialState socialState) { this.character = character; this.socialState = socialState; } public IDictionary<string, object> ToDictionary() { return new Dictionary<string, object> { {"characterId", character.Id}, {"socialState", (int) socialState}, {"note", note}, {"lastStateUpdate", lastStateUpdate} }; } public override string ToString() { return $"Character: {character}, SocialState: {socialState}, Note: {note}, LastStateUpdate {lastStateUpdate}"; } } }
28.666667
122
0.588178
[ "MIT" ]
LoyalServant/PerpetuumServerCore
Perpetuum/Services/Social/FriendInfo.cs
1,034
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Irony.Interpreter { public static class Util { public static string SafeFormat(this string template, params object[] args) { if (args == null || args.Length == 0) return template; try { template = string.Format(template, args); } catch (Exception ex) { template = template + "(message formatting failed: " + ex.Message + " Args: " + string.Join(",", args) + ")"; } return template; }//method public static void Check(bool condition, string messageTemplate, params object[] args) { if (condition) return; throw new Exception(messageTemplate.SafeFormat(args)); } }//class }
27.625
125
0.553167
[ "MIT" ]
Hyperspaces/Hyperspace.DotLua
src/Irony.Interpreter/Utilities/Util.cs
886
C#
namespace TaxiDinamica.Web.ViewModels.Partners { using System.Collections.Generic; public class PartnersOwnerViewModel { public IEnumerable<PartnersOwnerViewModel> Partners { get; set; } } }
21.6
73
0.726852
[ "MIT" ]
jarvandev/cero-filas
src/Web/TaxiDinamica.Web.ViewModels/Partners/PartnersOwnerViewModel.cs
216
C#
using Domain.Models; using System.Collections.Generic; namespace Domain { /// <summary> /// A repository managing data access for Customer, Order, Store, and Inventory objects. /// </summary> public interface IBurgerRepo { /// <summary> /// Get all stores with deferred execution. /// </summary> /// <returns>The collection of stores</returns> IEnumerable<Store> GetStores(string search = null); /// <summary> /// Get a store by ID. /// </summary> /// <returns>The store</returns> Store GetStoreById(int storeId); void AddStore(Store store); void DeleteStore(int storeId); void UpdateStore(Store store); /// <summary> /// Add a customer. /// </summary> /// <param name="cust">The customer</param> void AddCustomer(Customer cust); Customer GetCustomerByFullName(string firstName, string lastName); /// <summary> /// Delete a customer by ID. Any orders associated to it will also be deleted. /// </summary> /// <param int="custId">The ID of the customer</param> void DeleteCustomer(int custId); /// <summary> /// Update a customer's info. /// </summary> /// <param name="cust">The customer with changed values</param> void UpdateCustomer(Customer cust); /// <summary> /// Get a customer by ID. /// </summary> /// <param int="custId">The ID of the customer</param> Customer GetCustomerById(int custId); /// <summary> /// Add an order and associate it with a restaurant and customer. /// </summary> /// <param name="order">The order</param> /// <param int="storeId">The store's Id #</param> /// <param int="custId">The customer's Id #</param> void AddOrder(OrderHistory order); /// <summary> /// Delete a review by ID. /// </summary> /// <param name="reviewId">The ID of the review</param> void DeleteOrder(int orderId); /// <summary> /// Update an order. /// </summary> /// <param name="order">The order with changed values</param> void UpdateOrder(OrderHistory order); /// <summary> /// Get all orders according to customer Id. /// </summary> /// <param name="custId">The ID of the customer</param> /// <returns>The collection of restaurants</returns> IEnumerable<OrderHistory> OrderHistoryByCustomerId(int custId); /// <summary> /// Get all orders according to store Id. /// </summary> /// <param name="storeId">The ID of the store</param> /// <returns>The collection of restaurants</returns> IEnumerable<OrderHistory> OrderHistoryByStoreId(int storeId); void DecrementInventory(string product, int storeId); IEnumerable<Domain.Models.Inventory> DisplayMenu(int storeId); void BeginOrder(Domain.Models.CurrentOrder order); void AddStoreToOrder(Domain.Models.CurrentOrder order); void AddToOrder(int orderId, int prodId); Domain.Models.CurrentOrder GetCurrentOrder(); void RemoveCurrentOrder(); /// <summary> /// Persist changes to the data source. /// </summary> void Save(); } }
31.090909
92
0.583918
[ "MIT" ]
2002-feb24-net/pauls-project1
Domain/IBurgerRepo.cs
3,422
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataTools.Graphs.EdgeWeightedUndirectedGraph { /// <summary> /// The Edge class represents a weighted edge in an edge weighted graph. /// Each edge consists of 2 integers (naming the 2 vertices) and a double-value weight. /// </summary> public class Edge : IComparable<Edge> { // A vertex. private int v; // The other vertex. private int w; /// <summary> /// The weight of this edge. /// </summary> public double Weight { get; private set; } /// <summary> /// Initializes an edge between vertex v and vertex w of the given weight. /// </summary> /// <param name="v">A vertex of this edge.</param> /// <param name="w">The other vertex of this edge.</param> /// <param name="weight">The weight of this edge.</param> public Edge(int v, int w, double weight) { if (v < 0 || w < 0) throw new ArgumentOutOfRangeException("Vertex name must be a non-negative integer."); if (double.IsNaN(weight)) throw new ArgumentException("Weight is NaN."); this.v = v; this.w = w; Weight = weight; } /// <summary> /// Returns either end-point of this edge. /// </summary> /// <returns>Either end-point of this edge.</returns> public int Either() { return v; } /// <summary> /// Returns the end-point of this edge that is different from the given vertex. /// </summary> /// <param name="v">One end-point of this edge.</param> /// <returns>The end-point of this edge that is different from the given vertex.</returns> public int Other(int v) { if (v == this.v) return w; else if (v == w) return this.v; else throw new ArgumentOutOfRangeException("Illegal end-point."); } /// <summary> /// Compare 2 edges by weight. /// </summary> /// <param name="that">The other edge.</param> /// <returns> /// A negative integer, 0, or positive integer depending on whether the weight of this is less than, /// equal to, or greater than the argument edge. /// </returns> public int CompareTo(Edge that) { double epsilon = 1E-4; if (Weight - that.Weight < epsilon) return -1; else if (Weight - that.Weight > epsilon) return 1; else return 0; } /// <summary> /// Returns a string representation of this edge. /// </summary> /// <returns>T string representation of this edge.</returns> public override string ToString() { return string.Format("{0}-{1} {2:F5}", v, w, Weight); } } }
32.702128
108
0.534483
[ "MIT" ]
D15190304050/CSharpConsole2017
DataTools/Graphs/EdgeWeightedGraph/Edge.cs
3,076
C#
using Nucleus.Maths; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Nucleus.Results.Deprecated { /// <summary> /// Results storage table for nodes, keyed by result type /// </summary> [Serializable] public class NodeResults : ModelObjectResults<NodeResultTypes, Interval> { #region Constructors #if !JS /// <summary> /// Deserialisation constructor /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected NodeResults(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif /// <summary> /// Initialises a new empty NodeResults dictionary /// </summary> public NodeResults() : base() { } #endregion } }
25.027778
105
0.642619
[ "MIT" ]
escooo/Nucleus
Nucleus/Nucleus/Deprecated/NodeResults.cs
903
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GoL { public class Cell : ICell { public int X { get; set; } public int Y { get; set; } public Cell(int x, int y) { X = x; Y = y; } public override bool Equals(object other) { Cell cell = other as Cell; return cell != null && cell.X == X && cell.Y == Y; } public override int GetHashCode() { return X ^ Y; } public List<ICell> getNeighbours() { List<ICell> neighbours = new List<ICell>(); for (int x = X - 1; x <= X + 1; x++) { for (int y = Y - 1; y <= Y + 1; y++) { if (x == X && y == Y) { continue; } neighbours.Add(new Cell(x, y)); } } return neighbours; } } }
22.145833
62
0.38476
[ "MIT" ]
pezia/game-of-life-c-sharp
GoLImpl/Cell.cs
1,065
C#
using System; using Xamarin.Forms; namespace ShapesDemos { public class SpiralRunnerDemoPage : SpiralDemoPage { public SpiralRunnerDemoPage() { polyline.StrokeDashArray.Add(4); polyline.StrokeDashArray.Add(2); double total = polyline.StrokeDashArray[0] + polyline.StrokeDashArray[1]; Device.StartTimer(TimeSpan.FromMilliseconds(15), () => { double secs = DateTime.Now.TimeOfDay.TotalSeconds; polyline.StrokeDashOffset = total * (secs % 1); return true; }); } } }
25.958333
85
0.577849
[ "Apache-2.0" ]
15217711253/xamarin-forms-samples
UserInterface/ShapesDemos/ShapesDemos/Views/SpiralRunnerDemoPage.cs
625
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("UblLarsen.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("UblLarsen.Test")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [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("9229579d-d480-4165-99c9-3b5caf50ab11")] // 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.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.305556
84
0.751269
[ "Unlicense" ]
Gammern/ubllarsen
UblLarsen/UblLarsen.IntegrationV2_0.Test/Properties/AssemblyInfo.cs
1,382
C#
// // CFException.cs: Convert CFError into an CFException // // Authors: Mono Team // // Copyright (C) 2009 Novell, Inc // Copyright 2012 Xamarin Inc. // // 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.Runtime.InteropServices; using Foundation; using ObjCRuntime; namespace CoreFoundation { public static class CFErrorDomain { public static readonly NSString Cocoa; public static readonly NSString Mach; public static readonly NSString OSStatus; public static readonly NSString Posix; static CFErrorDomain () { var handle = Libraries.CoreFoundation.Handle; Cocoa = Dlfcn.GetStringConstant (handle, "kCFErrorDomainCocoa"); Mach = Dlfcn.GetStringConstant (handle, "kCFErrorDomainMach"); OSStatus = Dlfcn.GetStringConstant (handle, "kCFErrorDomainOSStatus"); Posix = Dlfcn.GetStringConstant (handle, "kCFErrorDomainPosix"); } } public static class CFExceptionDataKey { public static readonly NSString Description; public static readonly NSString LocalizedDescription; public static readonly NSString LocalizedFailureReason; public static readonly NSString LocalizedRecoverySuggestion; public static readonly NSString UnderlyingError; static CFExceptionDataKey () { var handle = Libraries.CoreFoundation.Handle; Description = Dlfcn.GetStringConstant (handle, "kCFErrorDescriptionKey"); LocalizedDescription = Dlfcn.GetStringConstant (handle, "kCFErrorLocalizedDescriptionKey"); LocalizedFailureReason = Dlfcn.GetStringConstant (handle, "kCFErrorLocalizedFailureReasonKey"); LocalizedRecoverySuggestion = Dlfcn.GetStringConstant (handle, "kCFErrorLocalizedRecoverySuggestionKey"); UnderlyingError = Dlfcn.GetStringConstant (handle, "kCFErrorUnderlyingErrorKey"); } } public class CFException : Exception { public CFException (string description, NSString domain, nint code, string failureReason, string recoverySuggestion) : base (description) { Code = code; Domain = domain; FailureReason = failureReason; RecoverySuggestion = recoverySuggestion; } public static CFException FromCFError (IntPtr cfErrorHandle) { return FromCFError (cfErrorHandle, true); } public static CFException FromCFError (IntPtr cfErrorHandle, bool release) { if (cfErrorHandle == IntPtr.Zero) throw new ArgumentNullException (nameof (cfErrorHandle)); var e = new CFException ( CFString.FromHandle (CFErrorCopyDescription (cfErrorHandle), releaseHandle: true), (NSString) Runtime.GetNSObject (CFErrorGetDomain (cfErrorHandle)), CFErrorGetCode (cfErrorHandle), CFString.FromHandle (CFErrorCopyFailureReason (cfErrorHandle), releaseHandle: true), CFString.FromHandle (CFErrorCopyRecoverySuggestion (cfErrorHandle), releaseHandle: true)); var cfUserInfo = CFErrorCopyUserInfo (cfErrorHandle); if (cfUserInfo != IntPtr.Zero) { using (var userInfo = new NSDictionary (cfUserInfo)) { foreach (var i in userInfo) e.Data.Add (i.Key?.ToString (), i.Value?.ToString ()); } } if (release) CFObject.CFRelease (cfErrorHandle); return e; } public nint Code {get; private set;} public NSString Domain {get; private set;} public string FailureReason {get; private set;} public string RecoverySuggestion {get; private set;} [DllImport (Constants.CoreFoundationLibrary)] static extern IntPtr CFErrorCopyDescription (IntPtr err); [DllImport (Constants.CoreFoundationLibrary)] static extern IntPtr CFErrorCopyFailureReason (IntPtr err); [DllImport (Constants.CoreFoundationLibrary)] static extern IntPtr CFErrorCopyRecoverySuggestion (IntPtr err); [DllImport (Constants.CoreFoundationLibrary)] static extern IntPtr CFErrorCopyUserInfo (IntPtr err); [DllImport (Constants.CoreFoundationLibrary)] static extern nint CFErrorGetCode (IntPtr err); [DllImport (Constants.CoreFoundationLibrary)] static extern IntPtr CFErrorGetDomain (IntPtr err); } }
37.080292
118
0.751378
[ "BSD-3-Clause" ]
Therzok/xamarin-macios
src/CoreFoundation/CFException.cs
5,080
C#
using System.Collections.Generic; using Essensoft.AspNetCore.Payment.Alipay.Response; namespace Essensoft.AspNetCore.Payment.Alipay.Request { /// <summary> /// AOP API: alipay.open.mini.version.gray.cancel /// </summary> public class AlipayOpenMiniVersionGrayCancelRequest : IAlipayRequest<AlipayOpenMiniVersionGrayCancelResponse> { /// <summary> /// 小程序结束灰度 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return returnUrl; } public void SetTerminalType(string terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return terminalType; } public void SetTerminalInfo(string terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return terminalInfo; } public void SetProdCode(string prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return prodCode; } public string GetApiName() { return "alipay.open.mini.version.gray.cancel"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.891892
113
0.585596
[ "MIT" ]
AkonCoder/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayOpenMiniVersionGrayCancelRequest.cs
2,666
C#
// Copyright 2021 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.SecurityCenter.V1.Snippets { using Google.Cloud.SecurityCenter.V1; using Google.Protobuf.WellKnownTypes; using System.Threading.Tasks; public sealed partial class GeneratedSecurityCenterClientStandaloneSnippets { /// <summary>Snippet for SetFindingStateAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task SetFindingStateResourceNamesAsync() { // Create client SecurityCenterClient securityCenterClient = await SecurityCenterClient.CreateAsync(); // Initialize request argument(s) FindingName name = FindingName.FromOrganizationSourceFinding("[ORGANIZATION]", "[SOURCE]", "[FINDING]"); Finding.Types.State state = Finding.Types.State.Unspecified; Timestamp startTime = new Timestamp(); // Make the request Finding response = await securityCenterClient.SetFindingStateAsync(name, state, startTime); } } }
41.581395
116
0.700783
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/securitycenter/v1/google-cloud-securitycenter-v1-csharp/Google.Cloud.SecurityCenter.V1.StandaloneSnippets/SecurityCenterClient.SetFindingStateResourceNamesAsyncSnippet.g.cs
1,788
C#
using System; using System.Text; using System.Collections.Generic; namespace Altazion.Api.Data { ///<summary> ///Objet de données PubliciteData ///</summary> public class PubliciteData { ///<summary> ///Obtient ou définit la valeur EstValide ///</summary> public bool EstValide{ get; set; } ///<summary> ///Obtient ou définit la valeur Guid ///</summary> public Guid Guid{ get; set; } ///<summary> ///Obtient ou définit la valeur DateDebut ///</summary> public DateTime DateDebut{ get; set; } ///<summary> ///Obtient ou définit la valeur DateFin ///</summary> public DateTime DateFin{ get; set; } ///<summary> ///Obtient ou définit la valeur Libelle ///</summary> public string Libelle{ get; set; } ///<summary> ///Obtient ou définit la valeur TypeOpe ///</summary> public string TypeOpe{ get; set; } ///<summary> ///Obtient ou définit la valeur Items ///</summary> public PubliciteItem[] Items{ get; set; } } }
20.061224
43
0.650051
[ "MIT" ]
altazion/altazion-sdk-csharp
SdkCSharpSources/Altazion.Api/Data/CommercialOpeCommControllerPubliciteData.cs
993
C#
using ApplicationCore.Entities.PostAggregate; using Ardalis.Specification; namespace ApplicationCore.Specifications { public class PostWithCommentsSpecification : Specification<Post> { public PostWithCommentsSpecification(int postId) { Query .Where(p => p.Id == postId) .Include(p => p.Comments); } } }
25.6
68
0.630208
[ "MIT" ]
aslamovyura/api-on-endpoints
ApplicationCore/Specifications/PostWithCommentsSpecification.cs
386
C#
namespace Windows.UI.Xaml.Controls; public class NavigationViewBackRequestedEventArgs { }
15.166667
49
0.846154
[ "MIT" ]
ljcollins25/Codeground
src/UnoApp/UnoDecompile/Uno.UI/Windows.UI.Xaml.Controls/NavigationViewBackRequestedEve.cs
91
C#
using System.Xml; using EppLib.Entities; namespace EppLib.Extensions.Nominet.Notifications { public class ReferralAcceptNotification : PollResponse { public DomainCreateResult DomainCreateResult { get; set; } public ReferralAcceptNotification(string xml) : base(xml) { } public ReferralAcceptNotification(byte[] bytes) : base(bytes) { } protected override void ProcessDataNode(XmlDocument doc, XmlNamespaceManager namespaces) { base.ProcessDataNode(doc, namespaces); namespaces.AddNamespace("domain", "urn:ietf:params:xml:ns:domain-1.0"); var domainCreateDataNode = doc.SelectSingleNode("/ns:epp/ns:response/ns:resData/domain:creData", namespaces); if (domainCreateDataNode != null) { var domainRes = new DomainCreateResponse(domainCreateDataNode.OuterXml); DomainCreateResult = domainRes.DomainCreateResult; } } } }
30.857143
112
0.765046
[ "Apache-2.0" ]
CodeMakerInc/EppLib.NET
EppLib/Extensions/Nominet/Notifications/ReferralAcceptNotification.cs
866
C#
using System.Collections.Generic; using NGitLab.Models; namespace NGitLab { public interface IIssueClient { IEnumerable<Issue> All(); IEnumerable<Issue> AllInState(IssueState state); IEnumerable<Issue> Get(string title, IssueState state); Issue Get(int id); /// <summary> /// Get a list of all project issues /// </summary> IEnumerable<Issue> Owned(); /// <summary> /// Get a list of issues for the specified project. /// </summary> IEnumerable<Issue> ForProject(int projectId); Issue Create(IssueCreate issue); Issue Delete(int issueIid); Issue Update(int issueId, IssueUpdate issue); IssueTimeTrack TimeEstimateSet(int issueId, string duration); IssueTimeTrack TimeEstimateReset(int issueId); IssueTimeTrack TimeSpentAdd(int issueId, string duration); IssueTimeTrack TimeSpentReset(int issueId); IssueTimeTrack TimeStats(int issueId); Issue ChangeMilestone(int issueIid, int milestoneId); Issue ReopenIssue(int issueIid); Issue CloseIssue(int issueIid); } }
25.106383
69
0.642373
[ "MIT" ]
Duffylo/NGitLabPlus
NGitLab/NGitLab/IIssueClient.cs
1,182
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileOpenerAPI { public class FileOpenerServiceMain { FileOpenerService service; public FileOpenerServiceMain() { service = new FileOpenerService(); } public IT_TeamPointMainScreenInteractor.FileOpenerAPI GetFileOpenerAPI() { return service as IT_TeamPointMainScreenInteractor.FileOpenerAPI; } } }
23.5
80
0.68472
[ "MIT" ]
ITB-Github/ITB_IT
FileOpenerAPI/FileOpenerServiceMain.cs
519
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Fund : Form { public Fund() { InitializeComponent(); } //Code to ensure the user checks only one option begins here private void Chkfirst_CheckedChanged(object sender, EventArgs e) { if (chkfirst.Checked) { chkFidelity.Enabled = false; chkDiamond.Enabled = false; chkUba.Enabled = false; chkZenith.Enabled = false; chkUnion.Enabled = false; } else { chkFidelity.Enabled = true; chkDiamond.Enabled = true; chkUba.Enabled = true; chkZenith.Enabled = true; chkUnion.Enabled = true; } } private void ChkFidelity_CheckedChanged(object sender, EventArgs e) { if (chkFidelity.Checked) { chkfirst.Enabled = false; chkDiamond.Enabled = false; chkUba.Enabled = false; chkZenith.Enabled = false; chkUnion.Enabled = false; } else { chkfirst.Enabled = true; chkDiamond.Enabled = true; chkUba.Enabled = true; chkUnion.Enabled = true; chkZenith.Enabled = true; } } private void ChkZenith_CheckedChanged(object sender, EventArgs e) { if (chkZenith.Checked) { chkfirst.Enabled = false; chkFidelity.Enabled = false; chkDiamond.Enabled = false; chkUba.Enabled = false; chkUnion.Enabled = false; } else { chkfirst.Enabled = true; chkFidelity.Enabled = true; chkDiamond.Enabled = true; chkUba.Enabled = true; chkUnion.Enabled = true; } } private void ChkDiamond_CheckedChanged(object sender, EventArgs e) { if (chkDiamond.Checked) { chkfirst.Enabled = false; chkFidelity.Enabled = false; chkZenith.Enabled = false; chkUba.Enabled = false; chkUnion.Enabled = false; } else { chkfirst.Enabled = true; chkFidelity.Enabled = true; chkUba.Enabled = true; chkUnion.Enabled = true; chkZenith.Enabled = true; } } private void ChkUnion_CheckedChanged(object sender, EventArgs e) { if (chkUnion.Checked) { chkfirst.Enabled = false ; chkFidelity.Enabled = false; chkUba.Enabled = false; chkZenith.Enabled = false; chkDiamond.Enabled = false; } else { chkfirst.Enabled = true; chkFidelity.Enabled = true; chkZenith.Enabled = true; chkDiamond.Enabled = true; chkUba.Enabled = true; } } private void ChkUba_CheckedChanged(object sender, EventArgs e) { if (chkUba.Checked) { chkUnion.Enabled = false; chkfirst.Enabled = false; chkFidelity.Enabled = false; chkDiamond.Enabled = false; chkZenith.Enabled = false; } else { chkUnion.Enabled = true; chkfirst.Enabled = true; chkFidelity.Enabled = true; chkDiamond.Enabled = true; chkZenith.Enabled = true; } }//end of code to ensure that the user checks onlyt one option UInt64 acNo = 0;//variable to hold recievers account number double amount = 0;//variable to hold amount to be transfered public double balance; private void BtnFundClear_Click(object sender, EventArgs e) { lblDisplay.Text = "";//clllears the display } private void BtnOk_Click(object sender, EventArgs e) { if (chkDiamond.Checked || chkfirst.Checked || chkfirst.Checked || chkUba.Checked || chkUnion.Checked || chkZenith.Checked) { try { if (acNo == 0) { MessageBox.Show("Enter Reciepient's Account Number"); btnOk.Visible = false; btnOk2.Visible = true; } if (acNo != 0) { amount = Convert.ToUInt64(lblDisplay.Text); btnOk.Visible = false; btnOk2.Visible = true; if (acNo > 0 && amount != 0 && amount <= balance) { MessageBox.Show(amount + " Has been transfered to " + acNo + " Successfully"); btnOk2.Visible = false; btnOk.Visible = true; } //reset Account number and Amount to enable user perform another operation instantly acNo = 0; amount = 0; } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } else { MessageBox.Show("Please Select a Bank"); } lblDisplay.Text = "";//clears the display } private void BtnfundCancel_Click(object sender, EventArgs e) { //confirms the user intends to cancel a transaction var message = MessageBox.Show("Do you want to Cancel Transaction?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (message == DialogResult.Yes) { lblDisplay.Text = ""; Form1 form = new Form1(); form.ShowDialog(); this.Close(); } } private void BtnOk2_Click(object sender, EventArgs e) { try { if (acNo == 0) { acNo = Convert.ToUInt64(lblDisplay.Text); btnOk2.Visible = false; btnOk.Visible = true; MessageBox.Show("Please enter Amount"); } } catch (Exception a) { MessageBox.Show(a.Message.ToString()); } lblDisplay.Text = ""; } private void Numbers(object sender, EventArgs e)//Gets the Numbers to display { Button number = (Button)sender; lblDisplay.Text += number.Text; } } }
32.373913
141
0.46159
[ "MIT" ]
PopeFrancisOgbonna/ATM
WindowsFormsApp1/Fund.cs
7,448
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Shapes; using Timer = System.Timers.Timer; namespace TerraLauncher.Controls.Terraria { public class TerrariaWindow : ContentControl { static TerrariaWindow() { DefaultStyleKeyProperty.OverrideMetadata(typeof(TerrariaWindow), new FrameworkPropertyMetadata(typeof(TerrariaWindow))); } bool resizing = false; public TerrariaWindow() { } protected override void OnRender(DrawingContext d) { DrawCropped.DrawFrame(d, CroppedFrames.WindowFrame, ActualWidth, ActualHeight); base.OnRender(d); } private void OnDragWindow(object sender, MouseButtonEventArgs e) { Window.GetWindow(this).DragMove(); } private void OnCloseWindow(object sender, MouseButtonEventArgs e) { Sounds.PlayClose(); Window.GetWindow(this).Close(); } private void OnMinimizeWindow(object sender, MouseButtonEventArgs e) { Sounds.PlayClose(); Window.GetWindow(this).WindowState = WindowState.Minimized; } public override void OnApplyTemplate() { ((TerrariaButton)GetTemplateChild("closeButton")).MouseUp += OnCloseWindow; ((TerrariaButton)GetTemplateChild("minimizeButton")).MouseUp += OnMinimizeWindow; ((Grid)GetTemplateChild("titleBar")).MouseLeftButtonDown += OnDragWindow; Grid grid = (Grid)GetTemplateChild("windowGrid"); foreach (var child in grid.Children) { Rectangle rect = child as Rectangle; if (rect != null && rect.Name.EndsWith("SizeGrip")) { rect.MouseLeftButtonDown += OnResizeBegin; rect.MouseLeftButtonUp += OnResizeEnd; rect.MouseMove += OnResizeMove; } } } private void OnResizeBegin(object sender, MouseButtonEventArgs e) { Rectangle senderRect = sender as Rectangle; if (senderRect != null) { resizing = true; senderRect.CaptureMouse(); } } private void OnResizeEnd(object sender, MouseButtonEventArgs e) { Rectangle senderRect = sender as Rectangle; if (senderRect != null) { resizing = false; ; senderRect.ReleaseMouseCapture(); } } private void OnResizeMove(object sender, MouseEventArgs e) { if (resizing) { Rectangle senderRect = sender as Rectangle; Window mainWindow = senderRect.Tag as Window; if (senderRect != null) { double width = e.GetPosition(mainWindow).X; double height = e.GetPosition(mainWindow).Y; senderRect.CaptureMouse(); if (senderRect.Name.ToLower().Contains("right")) { width += 5; if (width > 0) mainWindow.Width = width; } if (senderRect.Name.ToLower().Contains("left")) { width -= 5; double width2 = mainWindow.MinWidth - (mainWindow.Width - width); if (width2 > 0) width -= width2; mainWindow.Left += width; width = mainWindow.Width - width; if (width > 0) { mainWindow.Width = width; } } if (senderRect.Name.ToLower().Contains("bottom")) { height += 5; if (height > 0) mainWindow.Height = height; } if (senderRect.Name.ToLower().Contains("top")) { height -= 5; double height2 = mainWindow.MinHeight - (mainWindow.Height - height); if (height2 > 0) height -= height2; mainWindow.Top += height; height = mainWindow.Height - height; if (height > 0) { mainWindow.Height = height; } } } } } } }
29.860656
84
0.682679
[ "MIT" ]
trigger-death/TerraLauncher
TerraLauncher/Controls/Terraria/TerrariaWindow.cs
3,645
C#
namespace SoftUni.Models { using System.Collections.Generic; using System; public partial class Project { public Project() { EmployeesProjects = new HashSet<EmployeeProject>(); } public int ProjectId { get; set; } public string Name { get; set; } public string Description { get; set; } public DateTime StartDate { get; set; } public DateTime? EndDate { get; set; } public virtual ICollection<EmployeeProject> EmployeesProjects { get; set; } } }
26.333333
83
0.605787
[ "MIT" ]
AntoniyaIvanova/SoftUni
C#/C# DB/Entity Framework Core/03. ENTITY FRAMEWORK INTRODUCTION/EntityFrameworkIntro/SoftUni/Models/Project.cs
555
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Security.Principal; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using HunterPie.Core; using HunterPie.Core.Definitions; using HunterPie.Core.Integrations.DataExporter; using HunterPie.GUI; using HunterPie.GUIControls; using HunterPie.GUIControls.Custom_Controls; using HunterPie.Plugins; using Debugger = HunterPie.Logger.Debugger; using PluginDisplay = HunterPie.GUIControls.Plugins; using HunterPie.Core.Input; // HunterPie using HunterPie.Memory; using Presence = HunterPie.Core.Integrations.Discord.Presence; using Process = System.Diagnostics.Process; using ProcessStartInfo = System.Diagnostics.ProcessStartInfo; using System.Threading.Tasks; using System.Net.Http; using HunterPie.Core.Craft; using Newtonsoft.Json; using System.Diagnostics; namespace HunterPie { /// <summary> /// HunterPie main window logic; /// </summary> public partial class Hunterpie : Window { // TODO: Refactor all this messy code // Classes TrayIcon TrayIcon; readonly Game MonsterHunter = new Game(); Presence Discord; Overlay GameOverlay; readonly Exporter dataExporter = new Exporter(); PluginManager pluginManager = new PluginManager(); bool OfflineMode = false; bool IsUpdating = true; // HunterPie version public const string HUNTERPIE_VERSION = "1.0.3.98"; private readonly List<int> registeredHotkeys = new List<int>(); // Helpers public bool IsPlayerLoggedOn { get => (bool)GetValue(IsPlayerLoggedOnProperty); set => SetValue(IsPlayerLoggedOnProperty, value); } public static readonly DependencyProperty IsPlayerLoggedOnProperty = DependencyProperty.Register("IsPlayerLoggedOn", typeof(bool), typeof(Hunterpie)); public Visibility AdministratorIconVisibility { get => (Visibility)GetValue(AdministratorIconVisibilityProperty); set => SetValue(AdministratorIconVisibilityProperty, value); } public static readonly DependencyProperty AdministratorIconVisibilityProperty = DependencyProperty.Register("AdministratorIconVisibility", typeof(Visibility), typeof(Hunterpie)); public string Version { get => (string)GetValue(VersionProperty); set => SetValue(VersionProperty, value); } public static readonly DependencyProperty VersionProperty = DependencyProperty.Register("Version", typeof(string), typeof(Hunterpie)); public bool IsDragging { get { return (bool)GetValue(IsDraggingProperty); } set { SetValue(IsDraggingProperty, value); } } public static readonly DependencyProperty IsDraggingProperty = DependencyProperty.Register("IsDragging", typeof(bool), typeof(Hunterpie)); public Hunterpie() { if (CheckIfItsRunningFromWinrar()) { MessageBox.Show("You must extract HunterPie files before running it, otherwise it will most likely crash due to missing files or not save your settings.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); Close(); return; } CheckIfHunterPieOpen(); AppDomain.CurrentDomain.UnhandledException += ExceptionLogger; IsPlayerLoggedOn = false; SetDPIAwareness(); Buffers.Initialize(1024); Buffers.Add<byte>(64); // Initialize debugger and player config Debugger.InitializeDebugger(); UserSettings.InitializePlayerConfig(); // Initialize localization GStrings.InitStrings(UserSettings.PlayerConfig.HunterPie.Language); // Load custom theme and console colors LoadCustomTheme(); LoadOverwriteTheme(); Debugger.LoadNewColors(); AdministratorIconVisibility = IsRunningAsAdmin() ? Visibility.Visible : Visibility.Collapsed; Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; InitializeComponent(); WindowBlur.SetIsEnabled(this, true); } private bool IsRunningAsAdmin() { var winIdentity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(winIdentity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } private void LoadData() { MonsterData.LoadMonsterData(); AbnormalityData.LoadAbnormalityData(); Recipes.LoadRecipes(); } private void CheckIfHunterPieOpen() { // Block new instances of HunterPie if there's one already running Process instance = Process.GetCurrentProcess(); IEnumerable<Process> processes = Process.GetProcessesByName("HunterPie").Where(p => p.Id != instance.Id); foreach (Process p in processes) p.Kill(); } private void SetDPIAwareness() { if (Environment.OSVersion.Version >= new Version(6, 3, 0)) { if (Environment.OSVersion.Version >= new Version(10, 0, 15063)) { WindowsHelper.SetProcessDpiAwarenessContext((int)WindowsHelper.DPI_AWARENESS_CONTEXT.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); } else { WindowsHelper.SetProcessDpiAwareness(WindowsHelper.PROCESS_DPI_AWARENESS.PROCESS_PER_MONITOR_DPI_AWARE); } } else { WindowsHelper.SetProcessDPIAware(); } } #region AUTO UPDATE private bool StartUpdateProcess() { if (!File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Update.exe"))) return false; Process UpdateProcess = new Process(); UpdateProcess.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Update.exe"); UpdateProcess.StartInfo.Arguments = $"version={HUNTERPIE_VERSION} branch={UserSettings.PlayerConfig.HunterPie.Update.Branch}"; UpdateProcess.Start(); return true; } private bool CheckIfUpdateEnableAndStart() { if (UserSettings.PlayerConfig.HunterPie.Update.Enabled) { bool justUpdated = false; bool latestVersion = false; string[] args = Environment.GetCommandLineArgs(); foreach (string argument in args) { if (argument.StartsWith("justUpdated")) { string parsed = ParseArgs(argument); justUpdated = parsed == "True"; } if (argument.StartsWith("latestVersion")) { string parsed = ParseArgs(argument); latestVersion = parsed == "True"; } if (argument.StartsWith("offlineMode")) { OfflineMode = ParseArgs(argument) == "True"; } } if (justUpdated) { OpenChangelog(); return true; } if (latestVersion) { return true; } Debugger.Log("Updating updater.exe"); // This will update Update.exe AutoUpdate au = new AutoUpdate(UserSettings.PlayerConfig.HunterPie.Update.Branch); au.Instance.DownloadFileCompleted += OnUpdaterDownloadComplete; OfflineMode = au.offlineMode; if (!au.CheckAutoUpdate() && !au.offlineMode) { HandleUpdaterUpdate(); } else { return true; } Hide(); return false; } else { Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_AUTOUPDATE_DISABLED_WARN']")); return true; } } private void OnUpdaterDownloadComplete(object sender, AsyncCompletedEventArgs e) { if (e.Error != null) { Debugger.Error(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_UPDATE_ERROR']")); Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_OFFLINEMODE_WARN']")); OfflineMode = true; return; } else { Debugger.Error(e.Error); } HandleUpdaterUpdate(); } private void HandleUpdaterUpdate() { bool StartUpdate = StartUpdateProcess(); if (StartUpdate) { Close(); } else { MessageBox.Show("Update.exe not found! Skipping auto-update...", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } private string ParseArgs(string arg) { try { return arg.Split('=')[1]; } catch { return ""; } } #endregion #region HOT KEYS private void SetHotKeys() { string[] hotkeys = { UserSettings.PlayerConfig.Overlay.ToggleOverlayKeybind, UserSettings.PlayerConfig.Overlay.MonstersComponent.SwitchMonsterBarModeHotkey, UserSettings.PlayerConfig.Overlay.ToggleDesignKeybind }; Action[] callbacks = { ToggleOverlayCallback, SwitchMonsterBarModeCallback, ToggleDesignModeCallback }; for (int i = 0; i < hotkeys.Length; i++) { string hotkey = hotkeys[i]; Action callback = callbacks[i]; if (hotkey == "None") { continue; } int id = Hotkey.Register(hotkey, callback); if (id > 0) { registeredHotkeys.Add(id); } else { Debugger.Error("Failed to register hotkey"); } } } private void RemoveHotKeys() { foreach (int id in registeredHotkeys) { Hotkey.Unregister(id); } registeredHotkeys.Clear(); } private void ToggleOverlayCallback() { if (GameOverlay == null) { return; } UserSettings.PlayerConfig.Overlay.Enabled = !UserSettings.PlayerConfig.Overlay.Enabled; UserSettings.SaveNewConfig(); } private void SwitchMonsterBarModeCallback() { if (GameOverlay == null) { return; } UserSettings.PlayerConfig.Overlay.MonstersComponent.ShowMonsterBarMode = UserSettings.PlayerConfig.Overlay.MonstersComponent.ShowMonsterBarMode + 1 >= 5 ? (byte)0 : (byte)(UserSettings.PlayerConfig.Overlay.MonstersComponent.ShowMonsterBarMode + 1); UserSettings.SaveNewConfig(); } private void ToggleDesignModeCallback() { GameOverlay?.ToggleDesignMode(); } private void ConvertOldHotkeyToNew(int Key) { if (Key == 0) return; UserSettings.PlayerConfig.Overlay.ToggleDesignKeybind = KeyboardHookHelper.GetKeyboardKeyByID(Key).ToString(); UserSettings.PlayerConfig.Overlay.ToggleDesignModeKey = 0; } #endregion #region TRAY ICON private void InitializeTrayIcon() { TrayIcon = new TrayIcon(); // Tray icon itself TrayIcon.NotifyIcon.BalloonTipTitle = "HunterPie"; TrayIcon.NotifyIcon.Text = "HunterPie"; TrayIcon.NotifyIcon.Icon = Properties.Resources.LOGO_HunterPie; TrayIcon.NotifyIcon.Visible = true; TrayIcon.NotifyIcon.MouseDoubleClick += OnTrayIconClick; // Menu items System.Windows.Forms.MenuItem ExitItem = new System.Windows.Forms.MenuItem() { Text = "Close" }; ExitItem.Click += OnTrayIconExitClick; System.Windows.Forms.MenuItem SettingsItem = new System.Windows.Forms.MenuItem() { Text = "Settings" }; SettingsItem.Click += OnTrayIconSettingsClick; TrayIcon.ContextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { SettingsItem, ExitItem }); } private void OnTrayIconSettingsClick(object sender, EventArgs e) { Show(); WindowState = WindowState.Normal; Focus(); OpenSettings(); } private void OnTrayIconExitClick(object sender, EventArgs e) => Close(); private void OnTrayIconClick(object sender, EventArgs e) { Show(); WindowState = WindowState.Normal; Focus(); } #endregion // Why are people running HunterPie before extracting the files?????????????????????? private bool CheckIfItsRunningFromWinrar() { string path = AppDomain.CurrentDomain.BaseDirectory; return path.Contains("AppData\\Local\\Temp\\"); } private void LoadCustomTheme() { if (UserSettings.PlayerConfig.HunterPie.Theme == null || UserSettings.PlayerConfig.HunterPie.Theme == "Default") return; if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Themes"))) { Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Themes")); } if (!File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"Themes/{UserSettings.PlayerConfig.HunterPie.Theme}"))) { Debugger.Error(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_THEME_NOT_FOUND_ERROR']".Replace("{THEME_NAME}", UserSettings.PlayerConfig.HunterPie.Theme))); return; } try { using (FileStream stream = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"Themes/{UserSettings.PlayerConfig.HunterPie.Theme}"), FileMode.Open)) { XamlReader reader = new XamlReader(); ResourceDictionary ThemeDictionary = (ResourceDictionary)reader.LoadAsync(stream); Application.Current.Resources.MergedDictionaries.Add(ThemeDictionary); Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_THEME_LOAD_WARN']")); } } catch (Exception err) { Debugger.Error($"{GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_THEME_NOT_LOAD_ERROR']")}\n{err}"); } } private void LoadOverwriteTheme() { try { using (FileStream stream = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"HunterPie.Resources/UI/Overwrite.xaml"), FileMode.Open)) { XamlReader reader = new XamlReader(); ResourceDictionary res = (ResourceDictionary)reader.LoadAsync(stream); Application.Current.Resources.MergedDictionaries.Add(res); } } catch (Exception err) { Debugger.Error(err); } } private void ExceptionLogger(object sender, UnhandledExceptionEventArgs e) { File.WriteAllText("crashes.txt", e.ExceptionObject.ToString()); if (UserSettings.PlayerConfig.HunterPie.Debug.SendCrashFileToDev) { const string HunterPieCrashesWebhook = "https://discordapp.com/api/webhooks/756301992930050129/sTbp4PmjYZMlGGT0IYIhYtTiVw9hpaqwjo-n1Aawl2omWfnV-SD3NpH691xm4TleJ2p-"; // Also try to send the crash error to my webhook so I can fix it using (var httpClient = new HttpClient()) { using (var req = new HttpRequestMessage(new HttpMethod("POST"), HunterPieCrashesWebhook)) { using (var content = new MultipartFormDataContent()) { content.Add(new StringContent(""), "username"); content.Add(new StringContent($"```Exception type: {e.ExceptionObject.GetType()}\n-----------------------------------\nBranch: {UserSettings.PlayerConfig.HunterPie.Update.Branch}\nVersion: {FileVersionInfo.GetVersionInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "HunterPie.exe")).FileVersion}\nGAME BUILD VERSION: {Game.Version}\nHunterPie elapsed time: {DateTime.UtcNow - Process.GetCurrentProcess().StartTime.ToUniversalTime()}```"), "content"); content.Add(new StringContent(e.ExceptionObject.ToString()), "file", "crashes.txt"); req.Content = content; httpClient.SendAsync(req).Wait(); } } } } Debugger.WriteStacktrace(); } private void StartEverything() { SetAnimationsFramerate(); HookEvents(); Kernel.StartScanning(); // Scans game memory if (UserSettings.PlayerConfig.HunterPie.StartHunterPieMinimized) { WindowState = WindowState.Minimized; Hide(); } else { Show(); } } private void SetAnimationsFramerate() => Timeline.DesiredFrameRateProperty.OverrideMetadata(typeof(Timeline), new FrameworkPropertyMetadata { DefaultValue = Math.Min(60, Math.Max(1, UserSettings.PlayerConfig.Overlay.DesiredAnimationFrameRate)) }); #region Game & Client Events private void HookEvents() { // Kernel events Kernel.OnGameStart += OnGameStart; Kernel.OnGameClosed += OnGameClose; // Settings UserSettings.OnSettingsUpdate += SendToOverlay; } private void UnhookEvents() { // Debug AppDomain.CurrentDomain.UnhandledException -= ExceptionLogger; // Kernel events Kernel.OnGameStart -= OnGameStart; Kernel.OnGameClosed -= OnGameClose; // Settings UserSettings.OnSettingsUpdate -= SendToOverlay; } public void SendToOverlay(object source, EventArgs e) { GameOverlay?.GlobalSettingsEventHandler(source, e); Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle, new Action(() => { // Only shows notification if HunterPie is visible if (IsVisible) { CNotification notification = new CNotification() { Text = GStrings.GetLocalizationByXPath("/Notifications/String[@ID='STATIC_SETTINGS_LOAD']"), FirstButtonVisibility = Visibility.Collapsed, SecondButtonVisibility = Visibility.Collapsed, NIcon = FindResource("ICON_CHECKED") as ImageSource, ShowTime = 11 }; NotificationsPanel.Children.Add(notification); notification.ShowNotification(); } Settings.RefreshSettingsUI(); })); } private void HookGameEvents() { // Game events MonsterHunter.Player.OnZoneChange += OnZoneChange; MonsterHunter.Player.OnCharacterLogin += OnLogin; MonsterHunter.Player.OnCharacterLogout += OnLogout; MonsterHunter.Player.OnSessionChange += OnSessionChange; MonsterHunter.Player.OnClassChange += OnClassChange; } private void UnhookGameEvents() { MonsterHunter.Player.OnZoneChange -= OnZoneChange; MonsterHunter.Player.OnCharacterLogin -= OnLogin; MonsterHunter.Player.OnCharacterLogout -= OnLogout; MonsterHunter.Player.OnSessionChange -= OnSessionChange; MonsterHunter.Player.OnClassChange -= OnClassChange; } private void ExportGameData() { if (MonsterHunter.Player.ZoneID != 0) { string sSession = MonsterHunter.Player.SteamID != 0 ? $"steam://joinlobby/582010/{MonsterHunter.Player.SteamSession}/{MonsterHunter.Player.SteamID}" : ""; Data playerData = new Data { Name = MonsterHunter.Player.Name, HR = MonsterHunter.Player.Level, MR = MonsterHunter.Player.MasterRank, BuildURL = Honey.LinkStructureBuilder(MonsterHunter.Player.GetPlayerGear()), Session = MonsterHunter.Player.SessionID, SteamSession = sSession, Playtime = MonsterHunter.Player.PlayTime, WeaponName = MonsterHunter.Player.WeaponName }; dataExporter.ExportData(playerData); } } private void OnSessionChange(object source, EventArgs args) { Debugger.Log($"SESSION: {MonsterHunter.Player.SessionID}"); // Writes the session ID to a Sessions.txt if (!string.IsNullOrEmpty(MonsterHunter.Player.SessionID) && MonsterHunter.Player.IsLoggedOn) { ExportGameData(); // Because some people don't give permissions to write to files zzzzz try { File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Sessions.txt"), MonsterHunter.Player.SessionID); } catch { Debugger.Error("Missing permissions to write to files."); } } } public void OnZoneChange(object source, EventArgs e) { if (MonsterHunter.Player.IsLoggedOn) { Debugger.Debug($"ZoneID: {MonsterHunter.Player.ZoneID}"); ExportGameData(); } } public void OnLogin(object source, EventArgs e) { Debugger.Log($"Logged on {MonsterHunter.Player.Name}"); Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => { IsPlayerLoggedOn = true; })); ExportGameData(); } public void OnLogout(object source, EventArgs e) => Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Render, new Action(() => { IsPlayerLoggedOn = false; })); private void OnClassChange(object source, EventArgs args) => ExportGameData(); public void OnGameStart(object source, EventArgs e) { // Set HunterPie hotkeys SetHotKeys(); // Create game instances MonsterHunter.CreateInstances(); // Hook game events HookGameEvents(); // Set game context and load the modules PluginManager.ctx = MonsterHunter; if (pluginManager.IsReady) { pluginManager.LoadPlugins(); } else { pluginManager.QueueLoad = true; } // Creates new overlay Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => { if (GameOverlay == null) { GameOverlay = new Overlay(MonsterHunter); GameOverlay.HookEvents(); UserSettings.TriggerSettingsEvent(); } })); // Loads memory map if (Address.LoadMemoryMap(Kernel.GameVersion) || Kernel.GameVersion == Address.GAME_VERSION) { Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_MAP_LOAD']").Replace("{HunterPie_Map}", $"'MonsterHunterWorld.{Kernel.GameVersion}.map'")); } else { Debugger.Error(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_GAME_VERSION_UNSUPPORTED']").Replace("{GAME_VERSION}", $"{Kernel.GameVersion}")); return; } // Starts scanning MonsterHunter.StartScanning(); // Initializes rich presence if (Discord is null) { Discord = new Presence(MonsterHunter); if (OfflineMode) Discord.SetOfflineMode(); Discord.StartRPC(); } } public void OnGameClose(object source, EventArgs e) { // Remove global hotkeys RemoveHotKeys(); UnhookGameEvents(); pluginManager?.UnloadPlugins(); Discord?.Dispose(); Discord = null; MonsterHunter?.StopScanning(); Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => { GameOverlay?.Dispose(); GameOverlay = null; })); MonsterHunter?.DestroyInstances(); if (UserSettings.PlayerConfig.HunterPie.Options.CloseWhenGameCloses) { Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() => { Close(); })); } } #endregion #region Sub Windows /* Open sub windows */ private void OpenDebugger() { SwitchButtonOn(BUTTON_CONSOLE); SwitchButtonOff(BUTTON_CHANGELOG); SwitchButtonOff(BUTTON_SETTINGS); SwitchButtonOff(BUTTON_PLUGINS); ConsolePanel.Children.Clear(); ConsolePanel.Children.Add(Debugger.Instance); } private void OpenSettings() { SwitchButtonOff(BUTTON_CONSOLE); SwitchButtonOff(BUTTON_CHANGELOG); SwitchButtonOn(BUTTON_SETTINGS); SwitchButtonOff(BUTTON_PLUGINS); ConsolePanel.Children.Clear(); ConsolePanel.Children.Add(Settings.Instance); Settings.RefreshSettingsUI(); } private void OpenPlugins() { SwitchButtonOff(BUTTON_CONSOLE); SwitchButtonOff(BUTTON_CHANGELOG); SwitchButtonOff(BUTTON_SETTINGS); SwitchButtonOn(BUTTON_PLUGINS); ConsolePanel.Children.Clear(); ConsolePanel.Children.Add(PluginDisplay.Instance); } private void OpenChangelog() { SwitchButtonOff(BUTTON_CONSOLE); SwitchButtonOn(BUTTON_CHANGELOG); SwitchButtonOff(BUTTON_SETTINGS); SwitchButtonOff(BUTTON_PLUGINS); ConsolePanel.Children.Clear(); ConsolePanel.Children.Add(Changelog.Instance); } #endregion #region Animations private void SwitchButtonOn(StackPanel buttonActive) { Border ButtonBorder = (Border)buttonActive.Children[0]; ButtonBorder.SetValue(BorderThicknessProperty, new Thickness(4, 0, 0, 0)); } private void SwitchButtonOff(StackPanel buttonActive) { Border ButtonBorder = (Border)buttonActive.Children[0]; ButtonBorder.SetValue(BorderThicknessProperty, new Thickness(0, 0, 0, 0)); } #endregion #region WINDOW EVENTS private void OnWindowInitialized(object sender, EventArgs e) { Hide(); Width = UserSettings.PlayerConfig.HunterPie.Width; Height = UserSettings.PlayerConfig.HunterPie.Height; Top = UserSettings.PlayerConfig.HunterPie.PosY; Left = UserSettings.PlayerConfig.HunterPie.PosX; OpenDebugger(); // Initialize everything under this line if (!CheckIfUpdateEnableAndStart()) return; // Convert the old HotKey to the new one ConvertOldHotkeyToNew(UserSettings.PlayerConfig.Overlay.ToggleDesignModeKey); IsUpdating = false; InitializeTrayIcon(); // Update version text Version = GStrings.GetLocalizationByXPath("/Console/String[@ID='CONSOLE_VERSION']").Replace("{HunterPie_Version}", HUNTERPIE_VERSION).Replace("{HunterPie_Branch}", UserSettings.PlayerConfig.HunterPie.Update.Branch); // Initializes the Hotkey API Hotkey.Load(); // Support message :) ShowSupportMessage(); // Initializes the rest of HunterPie LoadData(); Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_HUNTERPIE_INITIALIZED']")); StartEverything(); Task.Factory.StartNew(async () => { await pluginManager.PreloadPlugins(); Dispatcher.Invoke(() => { PluginDisplay.Instance.InitializePluginDisplayer(PluginManager.packages); }); }); } private void OnCloseWindowButtonClick(object sender, MouseButtonEventArgs e) { // X button function; bool ExitConfirmation = MessageBox.Show(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_QUIT']"), "HunterPie", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes; if (ExitConfirmation) Close(); } private void OnWindowDrag(object sender, MouseButtonEventArgs e) { if (WindowState == WindowState.Maximized) { var point = PointToScreen(e.MouseDevice.GetPosition(this)); if (point.X <= RestoreBounds.Width / 2) Left = 0; else if (point.X >= RestoreBounds.Width) Left = point.X - (RestoreBounds.Width - (ActualWidth - point.X)); else { Left = point.X - (RestoreBounds.Width / 2); } Top = point.Y - (((FrameworkElement)sender).ActualWidth / 2); WindowState = WindowState.Normal; } // When top bar is held by LMB DragMove(); } private void OnMinimizeButtonClick(object sender, MouseButtonEventArgs e) { if (UserSettings.PlayerConfig.HunterPie.MinimizeToSystemTray) { WindowState = WindowState.Minimized; Hide(); } else { WindowState = WindowState.Minimized; } } private void OnWindowClosing(object sender, CancelEventArgs e) { Hide(); Debugger.WriteStacktrace(); pluginManager?.UnloadPlugins(); UserSettings.PlayerConfig.HunterPie.PosX = Left; UserSettings.PlayerConfig.HunterPie.PosY = Top; if (!IsUpdating) UserSettings.SaveNewConfig(); Debugger.DumpLog(); // Dispose tray icon if (TrayIcon != null) { TrayIcon.NotifyIcon.Click -= OnTrayIconClick; TrayIcon.ContextMenu.MenuItems[0].Click -= OnTrayIconSettingsClick; TrayIcon.ContextMenu.MenuItems[1].Click -= OnTrayIconExitClick; TrayIcon.Dispose(); } // Dispose stuff & stop scanning threads GameOverlay?.Dispose(); if (MonsterHunter.IsActive) MonsterHunter?.StopScanning(); Discord?.Dispose(); Kernel.StopScanning(); UserSettings.RemoveFileWatcher(); Settings.Instance?.UninstallKeyboardHook(); // Unhook events if (MonsterHunter.Player != null) UnhookGameEvents(); UnhookEvents(); Hotkey.Unload(); } private void OnGithubButtonClick(object sender, MouseButtonEventArgs e) => Process.Start("https://github.com/Haato3o/HunterPie"); private void OnConsoleButtonClick(object sender, MouseButtonEventArgs e) => OpenDebugger(); private void OnSettingsButtonClick(object sender, MouseButtonEventArgs e) => OpenSettings(); private void OnPluginsButtonClick(object sender, MouseButtonEventArgs e) => OpenPlugins(); private void OnChangelogButtonClick(object sender, MouseButtonEventArgs e) => OpenChangelog(); private void OnUploadBuildButtonClick(object sender, MouseButtonEventArgs e) { CNotification notification = new CNotification() { Text = GStrings.GetLocalizationByXPath("/Notifications/String[@ID='MESSAGE_BUILD_UPLOADED']"), NIcon = FindResource("ICON_BUILD") as ImageSource, FirstButtonImage = FindResource("ICON_COPY") as ImageSource, FirstButtonText = GStrings.GetLocalizationByXPath("/Settings/String[@ID='STATIC_COPYCLIPBOARD']"), FirstButtonVisibility = Visibility.Visible, SecondButtonImage = FindResource("ICON_LINK") as ImageSource, SecondButtonText = GStrings.GetLocalizationByXPath("/Notifications/String[@ID='STATIC_OPENDEFAULTBROWSER']"), SecondButtonVisibility = Visibility.Visible, Callback1 = new Action(() => { string BuildLink = Honey.LinkStructureBuilder(MonsterHunter.Player.GetPlayerGear(), true); Clipboard.SetData(DataFormats.Text, BuildLink); }), Callback2 = new Action(() => { string BuildLink = Honey.LinkStructureBuilder(MonsterHunter.Player.GetPlayerGear(), true); Process.Start(BuildLink); }), ShowTime = 11 }; NotificationsPanel.Children.Add(notification); notification.ShowNotification(); } private void OnExportGearButtonClick(object sender, MouseButtonEventArgs e) { // Task, so it doesnt freeze the UI Task.Factory.StartNew(() => { sItem[] decoration = MonsterHunter.Player.GetDecorationsFromStorage(); sGear[] gears = MonsterHunter.Player.GetGearFromStorage(); string exported = Honey.ExportDecorationsToHoney(decoration, gears); if (dataExporter.ExportCustomData("Decorations-HoneyHuntersWorld.txt", exported)) { Debugger.Warn("Exported decorations to ./DataExport/Decorations-HoneyHuntersWorld.txt!"); } else { Debugger.Error("Failed to export decorations. Make sure HunterPie has permission to create/write to files."); } exported = Honey.ExportCharmsToHoney(gears); if (dataExporter.ExportCustomData("Charms-HoneyHuntersWorld.txt", exported)) { Debugger.Warn("Exported charms to ./DataExport/Charms-HoneyHuntersWorld.txt!"); } else { Debugger.Error("Failed to export charms. Make sure HunterPie has permission to create/write to files."); } Dispatcher.Invoke(() => { CNotification notification = new CNotification() { NIcon = FindResource("ICON_DECORATION") as ImageSource, Text = GStrings.GetLocalizationByXPath("/Notifications/String[@ID='MESSAGE_GEAR_EXPORTED']"), FirstButtonImage = FindResource("ICON_LINK") as ImageSource, FirstButtonText = GStrings.GetLocalizationByXPath("/Notifications/String[@ID='STATIC_OPENFOLDER']"), FirstButtonVisibility = Visibility.Visible, SecondButtonVisibility = Visibility.Collapsed, ShowTime = 11, Callback1 = new Action(() => { Process.Start(dataExporter.ExportPath); }) }; NotificationsPanel.Children.Add(notification); notification.ShowNotification(); }); }); } private void OnDiscordButtonClick(object sender, MouseButtonEventArgs e) => Process.Start("https://discord.gg/5pdDq4Q"); private void OnLaunchGameButtonClick(object sender, RoutedEventArgs e) => LaunchGame(); private void LaunchGame() { try { ProcessStartInfo GameStartInfo = new ProcessStartInfo { FileName = "steam://run/582010", Arguments = UserSettings.PlayerConfig.HunterPie.Launch.LaunchArgs, UseShellExecute = true }; Process.Start(GameStartInfo); } catch (Exception err) { Debugger.Error($"{GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_LAUNCH_ERROR']")}\n{err}"); } } private void OnWindowSizeChange(object sender, SizeChangedEventArgs e) { UserSettings.PlayerConfig.HunterPie.Width = (float)e.NewSize.Width; UserSettings.PlayerConfig.HunterPie.Height = (float)e.NewSize.Height; } private void Reload() { // Welp Process.Start(Application.ResourceAssembly.Location, "latestVersion=True"); Application.Current.Shutdown(); } private void OnKeyDown(object sender, KeyEventArgs e) { Key key = (e.Key == Key.System ? e.SystemKey : e.Key); if (key == Key.LeftShift || key == Key.RightShift || key == Key.LeftCtrl || key == Key.RightCtrl || key == Key.LeftAlt || key == Key.RightAlt || key == Key.LWin || key == Key.RWin) { return; } if ((Keyboard.Modifiers & ModifierKeys.Control) != 0 && e.Key == Key.R) { Reload(); } } #endregion #region Helpers public static Version ParseVersion(string version) { return new Version(version); } private void ShowSupportMessage() { CNotification notification = new CNotification() { Text = "Do you like HunterPie and want to support its development? Consider donating!", NIcon = FindResource("LOGO_HunterPie") as ImageSource, FirstButtonImage = FindResource("ICON_PAYPAL") as ImageSource, FirstButtonText = "PayPal", FirstButtonVisibility = Visibility.Visible, SecondButtonImage = FindResource("ICON_PATREON") as ImageSource, SecondButtonText = "Patreon", SecondButtonVisibility = Visibility.Visible, Callback1 = new Action(() => { Process.Start("https://server.hunterpie.me/donate"); }), Callback2 = new Action(() => { Process.Start("https://www.patreon.com/HunterPie"); }), ShowTime = 20 }; NotificationsPanel.Children.Add(notification); notification.ShowNotification(); } #endregion private async void window_Drop(object sender, DragEventArgs e) { IsDragging = false; string modulejson = ((string[])e.Data.GetData("FileName"))?.FirstOrDefault(); string moduleContent; bool isOnline = false; if (modulejson is null) { isOnline = true; modulejson = e.Data.GetData("UnicodeText") as string; } if (!modulejson.ToLower().EndsWith("module.json")) { return; } if (isOnline) { if (!modulejson.StartsWith("http")) { modulejson = $"https://{modulejson}"; } moduleContent = await PluginUpdate.ReadOnlineModuleJson(modulejson); } else { moduleContent = File.ReadAllText(modulejson); } PluginInformation moduleInformation = JsonConvert.DeserializeObject<PluginInformation>(moduleContent); if (moduleInformation is null || string.IsNullOrEmpty(moduleInformation?.Name)) { Debugger.Log("Invalid module.json!"); return; } string modPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules", moduleInformation.Name); if (!Directory.Exists(modPath)) { Directory.CreateDirectory(modPath); } File.WriteAllText(Path.Combine(modPath, "module.json"), JsonConvert.SerializeObject(moduleInformation, Formatting.Indented)); if (PluginUpdate.PluginSupportsUpdate(moduleInformation)) { if (await PluginUpdate.UpdateAllFiles(moduleInformation, modPath)) { Debugger.Module($"Installed {moduleInformation.Name}!"); } else { Debugger.Error($"Failed to install {moduleInformation.Name}."); } } else { Debugger.Error(GStrings.GetLocalizationByXPath("/Console/String[@ID='ERROR_PLUGIN_AUTO_UPDATE']")); } CNotification notification = new CNotification() { Text = GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_PLUGIN_INSTALLED']").Replace("{name}", moduleInformation.Name), NIcon = FindResource("ICON_PLUGIN") as ImageSource, FirstButtonVisibility = Visibility.Collapsed, SecondButtonVisibility = Visibility.Collapsed, ShowTime = 5 }; NotificationsPanel.Children.Add(notification); notification.ShowNotification(); } private void window_DragEnter(object sender, DragEventArgs e) { IsDragging = true; } private void window_DragLeave(object sender, DragEventArgs e) { IsDragging = false; } } }
38.15671
486
0.563318
[ "MIT" ]
amadare42/HunterPie
HunterPie/Hunterpie.xaml.cs
44,073
C#
//----------------------------------------------------------------------- // <copyright file="AugmentedImageExampleController.cs" company="Google"> // // Copyright 2018 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore.Examples.AugmentedImage { using System.Collections.Generic; using System.Runtime.InteropServices; using GoogleARCore; using UnityEngine; using UnityEngine.UI; /// <summary> /// Controller for AugmentedImage example. /// </summary> /// <remarks> /// In this sample, we assume all images are static or moving slowly with /// a large occupation of the screen. If the target is actively moving, /// we recommend to check <see cref="AugmentedImage.TrackingMethod"/> and /// render only when the tracking method equals to /// <see cref="AugmentedImageTrackingMethod"/>.<c>FullTracking</c>. /// See details in <a href="https://developers.google.com/ar/develop/c/augmented-images/"> /// Recognize and Augment Images</a> /// </remarks> public class AugmentedImageExampleController : MonoBehaviour { /// <summary> /// A prefab for visualizing an AugmentedImage. /// </summary> public AugmentedImageVisualizer AugmentedImageVisualizerPrefab; /// <summary> /// The overlay containing the fit to scan user guide. /// </summary> public GameObject FitToScanOverlay; private Dictionary<int, AugmentedImageVisualizer> m_Visualizers = new Dictionary<int, AugmentedImageVisualizer>(); private List<AugmentedImage> m_TempAugmentedImages = new List<AugmentedImage>(); /// <summary> /// The Unity Awake() method. /// </summary> public void Awake() { // Enable ARCore to target 60fps camera capture frame rate on supported devices. // Note, Application.targetFrameRate is ignored when QualitySettings.vSyncCount != 0. Application.targetFrameRate = 60; } /// <summary> /// The Unity Update method. /// </summary> public void Update() { // Exit the app when the 'back' button is pressed. if (Input.GetKey(KeyCode.Escape)) { Application.Quit(); } // Only allow the screen to sleep when not tracking. if (Session.Status != SessionStatus.Tracking) { Screen.sleepTimeout = SleepTimeout.SystemSetting; } else { Screen.sleepTimeout = SleepTimeout.NeverSleep; } // Get updated augmented images for this frame. Session.GetTrackables<AugmentedImage>( m_TempAugmentedImages, TrackableQueryFilter.Updated); // Create visualizers and anchors for updated augmented images that are tracking and do // not previously have a visualizer. Remove visualizers for stopped images. foreach (var image in m_TempAugmentedImages) { AugmentedImageVisualizer visualizer = null; m_Visualizers.TryGetValue(image.DatabaseIndex, out visualizer); if (image.TrackingState == TrackingState.Tracking && visualizer == null) { // Create an anchor to ensure that ARCore keeps tracking this augmented image. Anchor anchor = image.CreateAnchor(image.CenterPose); visualizer = (AugmentedImageVisualizer)Instantiate( AugmentedImageVisualizerPrefab, anchor.transform); visualizer.Image = image; m_Visualizers.Add(image.DatabaseIndex, visualizer); } else if (image.TrackingState == TrackingState.Stopped && visualizer != null) { m_Visualizers.Remove(image.DatabaseIndex); GameObject.Destroy(visualizer.gameObject); } } // Show the fit-to-scan overlay if there are no images that are Tracking. foreach (var visualizer in m_Visualizers.Values) { if (visualizer.Image.TrackingState == TrackingState.Tracking) { FitToScanOverlay.SetActive(false); return; } } FitToScanOverlay.SetActive(true); } } }
39.79845
99
0.593689
[ "Apache-2.0" ]
ARtSSt/ARCore
Assets/GoogleARCore/Examples/AugmentedImage/Scripts/AugmentedImageExampleController.cs
5,134
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AntSimulation { class Ant : GameObject { private Nest nest; private bool hasFood = false; public Ant(Nest nest) { this.nest = nest; } public override void UpdateOn(World world) { if (hasFood) { Color = Color.Red; ReleasePheromone(world); MoveToNest(world); } else { Color = Color.Blue; Wander(world); if (!CheckFood(world)) { CheckPheromone(world); } } } private void Wander(World world) { Forward(world.Random(1, 5)); Turn(world.Random(-25, 25)); } private bool CheckFood(World world) { IEnumerable<GameObject> food = FindNear<Food>(world, 15); if (food.Any()) { GameObject f = food.Where(each => each.Position.Equals(Position)).FirstOrDefault(); if (f != null) { hasFood = true; world.Remove(f); } else { LookTo(food.First().Position); Wander(world); } return true; } return false; } private void CheckPheromone(World world) { PointF? strongestPoint = null; double strongestIntensity = 0; IEnumerable<Pheromone> nearPheromones = FindNear<Pheromone>(world, 10); foreach (Pheromone p in nearPheromones.Where(p => p.Intensity > 5)) { if (p.Intensity > strongestIntensity) { strongestIntensity = p.Intensity; strongestPoint = p.Position; } } if (strongestPoint.HasValue) { LookTo(strongestPoint.Value); Wander(world); } } private void ReleasePheromone(World world) { Pheromone.SpawnOn(world, Position, world.Dist(Position, world.Center) * 1.5); } private void MoveToNest(World world) { LookTo(nest.Position); Wander(world); if (Position.Equals(nest.Position)) { hasFood = false; } } private IEnumerable<T> FindNear<T>(World world, float radius) where T : GameObject { List<T> result = new List<T>(); for (float x = Position.X - radius; x <= Position.X + radius; x++) { for (float y = Position.Y - radius; y <= Position.Y + radius; y++) { result.AddRange(world .GameObjectsNear(new PointF(x, y)) .Select(t => t as T) .Where(t => t != null)); } } return result; } } }
27.588235
99
0.442888
[ "MIT" ]
RichoM/TO2021
Ejercicios/AntSimulation/AntSimulation/Ants/Ant.cs
3,285
C#
using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using ESFA.DC.ILR.ValidationService.Interface; namespace ESFA.DC.ILR.ValidationService.Stubs { public class ContextMessageStringProviderService : IMessageStreamProviderService { private readonly IPreValidationContext _validationContext; public ContextMessageStringProviderService(IPreValidationContext validationContext) { _validationContext = validationContext; } public async Task<Stream> Provide(CancellationToken cancellationToken) { return new MemoryStream(Encoding.UTF8.GetBytes(_validationContext.Input)); } } }
29.375
91
0.740426
[ "MIT" ]
sampanu/DC-ILR-1819-ValidationService
src/ESFA.DC.ILR.ValidationService.AcceptanceTests/Stubs/ContextMessageStringProviderService.cs
707
C#
namespace CompatibilityChecker.Library { using System.Collections.Immutable; using System.Reflection.Metadata; public struct ArrayShapeSignature { private readonly BlobReader reader; public ArrayShapeSignature(BlobReader blobReader) { reader = blobReader; } public int Rank { get { return reader.ReadCompressedInteger(); } } public ImmutableArray<int> Lengths { get { var reader = this.reader; // rank reader.ReadCompressedInteger(); // sizes int numSizes = reader.ReadCompressedInteger(); var builder = ImmutableArray.CreateBuilder<int>(numSizes); for (int i = 0; i < numSizes; i++) { builder.Add(reader.ReadCompressedInteger()); } return builder.ToImmutable(); } } public ImmutableArray<int> LowerBounds { get { var reader = this.reader; // rank reader.ReadCompressedInteger(); // sizes int numSizes = reader.ReadCompressedInteger(); for (int i = 0; i < numSizes; i++) { reader.ReadCompressedInteger(); } // bounds int numBounds = reader.ReadCompressedInteger(); var builder = ImmutableArray.CreateBuilder<int>(numBounds); for (int i = 0; i < numBounds; i++) { builder.Add(reader.ReadCompressedSignedInteger()); } return builder.ToImmutable(); } } public BlobReader Skip() { var reader = this.reader; // rank reader.ReadCompressedInteger(); // sizes int numSizes = reader.ReadCompressedInteger(); for (int i = 0; i < numSizes; i++) { reader.ReadCompressedInteger(); } // bounds int numBounds = reader.ReadCompressedInteger(); for (int i = 0; i < numBounds; i++) { reader.ReadCompressedSignedInteger(); } return reader; } } }
25.649485
75
0.459405
[ "Apache-2.0" ]
EraYaN/dotnet-compatibility
CompatibilityChecker.Library/ArrayShapeSignature.cs
2,488
C#
using UniLife.Server.Middleware.Wrappers; using UniLife.Shared.Dto.Definitions; using System.Threading.Tasks; namespace UniLife.Server.Managers { public interface IDonemManager { Task<ApiResponse> Get(); Task<ApiResponse> Get(int id); Task<ApiResponse> Create(DonemDto donemDto); Task<ApiResponse> Update(DonemDto donemDto); Task<ApiResponse> Delete(int id); Task<ApiResponse> Current(); Task<ApiResponse> CreateNewDonemWithTakvim(DonemDto donemDto); } }
29.166667
70
0.702857
[ "MIT" ]
ahmetsekmen/UniLife
src/UniLife.Server/Managers/IDonemManager.cs
527
C#
using System.Collections.Generic; namespace Frapper.ViewModel.Messages { public class MessageTemplate { public string Subject { get; set; } public string Body { get; set; } public string ToAddress { get; set; } public IEnumerable<string> Bcc { get; set; } public IEnumerable<string> Cc { get; set; } } }
27.461538
52
0.630252
[ "MIT" ]
Ramasagar/Frapper
Frapper.Web/Frapper.ViewModel/Messages/MessageTemplate.cs
359
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { #pragma warning disable CS8618 [JsiiByValue(fqn: "aws.Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchSingleQueryArgument")] public class Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchSingleQueryArgument : aws.IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchSingleQueryArgument { [JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}", isOverride: true)] public string Name { get; set; } } }
39.1
293
0.789003
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementAndStatementStatementByteMatchStatementFieldToMatchSingleQueryArgument.cs
782
C#
 using System.Diagnostics; namespace KihonEngine.Studio.Helpers { public static class ExternalResources { public const string DocumentationUrl = "https://github.com/nico65535/KihonEngine/blob/main/doc/kihon-engine-studio.md"; public static void Navigate(string url) { // for .NET Core you need to add UseShellExecute = true // see https://docs.microsoft.com/dotnet/api/system.diagnostics.processstartinfo.useshellexecute#property-value Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); } } }
33
127
0.685185
[ "MIT" ]
nico65535/KihonEngine
source/KihonEngine.Studio/Helpers/ExternalResources.cs
596
C#
/* * Copyright (c) 2012 Stephen A. Pratt * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("cai-nmbuild")] [assembly: AssemblyDescription("Design-time navigation mesh build extensions.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("critterai.org")] [assembly: AssemblyProduct("CAINav")] [assembly: AssemblyCopyright("Copyright © Stephen Pratt 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.4.0.0")] [assembly: AssemblyFileVersion("0.4.0.0")]
43.974359
80
0.763848
[ "MIT" ]
bluesky7290/NFrame_unity3d_nav
source/build/assemblyInfo/cai-nmbuild.cs
1,718
C#
using System; namespace TinyPngApi.Areas.HelpPage { /// <summary> /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. /// </summary> public class TextSample { public TextSample(string text) { if (text == null) { throw new ArgumentNullException("text"); } Text = text; } public string Text { get; private set; } public override bool Equals(object obj) { TextSample other = obj as TextSample; return other != null && Text == other.Text; } public override int GetHashCode() { return Text.GetHashCode(); } public override string ToString() { return Text; } } }
23.945946
140
0.532731
[ "Apache-2.0" ]
ahmadaghazadeh/TinyPngApi
src/TinyPngApi/Areas/HelpPage/SampleGeneration/TextSample.cs
886
C#
// Copyright 2017-2020 Elringus (Artyom Sovetnikov). All Rights Reserved. #if UNITY_GOOGLE_DRIVE_AVAILABLE using System.Collections.Generic; using System.Linq; using UniRx.Async; using UnityGoogleDrive; namespace Naninovel { public class GoogleDriveResourceLocator<TResource> : LocateResourcesRunner<TResource> where TResource : UnityEngine.Object { public readonly string RootPath; private IRawConverter<TResource> converter; public GoogleDriveResourceLocator (IResourceProvider provider, string rootPath, string resourcesPath, IRawConverter<TResource> converter) : base (provider, resourcesPath) { RootPath = rootPath; this.converter = converter; } public override async UniTask RunAsync () { var result = new List<string>(); // 1. Find all the files by path. var fullPath = PathUtils.Combine(RootPath, Path) + "/"; var files = await Helpers.FindFilesByPathAsync(fullPath, fields: new List<string> { "files(name, mimeType)" }); // 2. Filter the results by representations (MIME types). var reprToFileMap = new Dictionary<RawDataRepresentation, List<UnityGoogleDrive.Data.File>>(); foreach (var representation in converter.Representations) reprToFileMap.Add(representation, files.Where(f => f.MimeType == representation.MimeType).ToList()); // 3. Create resources using located files. foreach (var reprToFile in reprToFileMap) { foreach (var file in reprToFile.Value) { var fileName = string.IsNullOrEmpty(reprToFile.Key.Extension) ? file.Name : file.Name.GetBeforeLast("."); var filePath = string.IsNullOrEmpty(Path) ? fileName : string.Concat(Path, '/', fileName); result.Add(filePath); } } SetResult(result); } } } #endif
36.214286
125
0.629191
[ "MIT" ]
BSK-Baesick/Partita
Assets/Naninovel/Runtime/Common/ResourceProvider/GoogleDriveResourceLocator.cs
2,030
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 DotNetNuke.Web.Mvp { using System; [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")] public abstract class WebServiceView : WebServiceViewBase {} }
36.923077
149
0.741667
[ "MIT" ]
Acidburn0zzz/Dnn.Platform
DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs
482
C#
using System; using System.Collections.Generic; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework; using System.Diagnostics; using Microsoft.Xna.Framework.Graphics; using NuclearWinter.Xna; #if !FNA using OSKey = System.Windows.Forms.Keys; #endif namespace NuclearWinter.UI { /* * A Screen handles passing on user input, updating and drawing * a bunch of widgets */ public class Screen { //---------------------------------------------------------------------- public NuclearGame Game { get; private set; } public bool IsActive; public Style Style { get; private set; } public int Width { get; private set; } public int Height { get; private set; } public Rectangle Bounds { get { return new Rectangle(0, 0, Width, Height); } } public Group Root { get; private set; } public Widget FocusedWidget { get; private set; } bool mbHasActivatedFocusedWidget; Widget mClickedWidget; int miClickedWidgetMouseButton; public Widget HoveredWidget { get; private set; } Point mPreviousMouseHitPoint; int miIgnoreClickFrames; //---------------------------------------------------------------------- public Screen(NuclearWinter.NuclearGame game, Style style, int width, int height) { Game = game; Style = style; Width = width; Height = height; Root = new Group(this); } //---------------------------------------------------------------------- public void Resize(int width, int height) { Width = width; Height = height; Root.DoLayout(Bounds); // This will prevent accidental clicks when maximizing the window miIgnoreClickFrames = 3; } //---------------------------------------------------------------------- public void HandleInput() { //------------------------------------------------------------------ // Make sure we don't hold references to orphaned widgets if (FocusedWidget != null && FocusedWidget.IsOrphan) { FocusedWidget = null; mbHasActivatedFocusedWidget = false; } if (HoveredWidget != null && HoveredWidget.IsOrphan) { Game.SetCursor(MouseCursor.Default); HoveredWidget = null; } if (mClickedWidget != null && mClickedWidget.IsOrphan) mClickedWidget = null; //------------------------------------------------------------------ Point mouseHitPoint = new Point( (int)(Game.InputMgr.MouseState.X / Resolution.ScaleFactor), (int)((Game.InputMgr.MouseState.Y - Game.GraphicsDevice.Viewport.Y) / Resolution.ScaleFactor) ); if (!IsActive) { if (HoveredWidget != null) { HoveredWidget.OnMouseOut(mouseHitPoint); HoveredWidget = null; } if (mClickedWidget != null) { mClickedWidget.OnMouseUp(mouseHitPoint, miClickedWidgetMouseButton); mClickedWidget = null; } return; } //------------------------------------------------------------------ // Mouse buttons bool bHasMouseEvent = false; if (miIgnoreClickFrames == 0) { for (int iButton = 0; iButton < 3; iButton++) { if (Game.InputMgr.WasMouseButtonJustPressed(iButton)) { bHasMouseEvent = true; if (mClickedWidget == null) { miClickedWidgetMouseButton = iButton; Widget hitWidget = null; if (FocusedWidget != null) { hitWidget = FocusedWidget.HitTest(mouseHitPoint); } if (hitWidget == null) { hitWidget = Root.HitTest(mouseHitPoint); } while (hitWidget != null && !hitWidget.OnMouseDown(mouseHitPoint, iButton)) { hitWidget = hitWidget.Parent; } mClickedWidget = hitWidget; } } } if (Game.InputMgr.WasMouseJustDoubleClicked()) { bHasMouseEvent = true; Widget widget = FocusedWidget == null ? null : FocusedWidget.HitTest(mouseHitPoint); if (widget != null) { bool bPressed; switch (Game.InputMgr.PrimaryMouseButton) { case 0: bPressed = Game.InputMgr.MouseState.LeftButton == ButtonState.Pressed; break; case 2: bPressed = Game.InputMgr.MouseState.RightButton == ButtonState.Pressed; break; default: throw new NotSupportedException(); } if (bPressed) { mClickedWidget = widget; miClickedWidgetMouseButton = Game.InputMgr.PrimaryMouseButton; } if (widget.OnMouseDoubleClick(mouseHitPoint)) { miIgnoreClickFrames = 3; } } } } else { miIgnoreClickFrames--; } for (int iButton = 0; iButton < 3; iButton++) { if (Game.InputMgr.WasMouseButtonJustReleased(iButton)) { bHasMouseEvent = true; if (mClickedWidget != null && iButton == miClickedWidgetMouseButton) { mClickedWidget.OnMouseUp(mouseHitPoint, iButton); mClickedWidget = null; } } } if (!bHasMouseEvent) { if (mouseHitPoint != mPreviousMouseHitPoint) { if (mClickedWidget == null) { // old code only checked focused widget for mouse hit which meant you would not get // Widget.OnMouseEnter and Widget.OnMMouseOut events on other widgets than the focussed var hoveredWidget = Root.HitTest(mouseHitPoint); if (hoveredWidget != null && hoveredWidget == HoveredWidget) { HoveredWidget.OnMouseMove(mouseHitPoint); } else { // cache previously hoveed widget and set the new hovered widget // before call OnMouseOut or else any handler that checks for // Widget.IsHovered will get an old result var previousHoveredWidget = this.HoveredWidget; this.HoveredWidget = hoveredWidget; if (previousHoveredWidget != null) { previousHoveredWidget.OnMouseOut(mouseHitPoint); } if (HoveredWidget != null) { HoveredWidget.OnMouseEnter(mouseHitPoint); } } } else { mClickedWidget.OnMouseMove(mouseHitPoint); } } } // Mouse wheel int iWheelDelta = Game.InputMgr.GetMouseWheelDelta(); if (iWheelDelta != 0) { Widget hoveredWidget = (FocusedWidget == null ? null : FocusedWidget.HitTest(mouseHitPoint)) ?? Root.HitTest(mouseHitPoint); if (hoveredWidget != null) { hoveredWidget.OnMouseWheel(mouseHitPoint, iWheelDelta); } } mPreviousMouseHitPoint = mouseHitPoint; //------------------------------------------------------------------ // Keyboard if (FocusedWidget != null) { foreach (char character in Game.InputMgr.EnteredText) { FocusedWidget.OnTextEntered(character); } if (Game.InputMgr.JustPressedOSKeys.Contains(OSKey.Enter) || Game.InputMgr.JustPressedOSKeys.Contains(OSKey.Return) || Game.InputMgr.JustPressedOSKeys.Contains(OSKey.Space)) { if (FocusedWidget.OnActivateDown()) { mbHasActivatedFocusedWidget = true; } } else if (Game.InputMgr.JustReleasedOSKeys.Contains(OSKey.Enter) || Game.InputMgr.JustReleasedOSKeys.Contains(OSKey.Return) || Game.InputMgr.JustReleasedOSKeys.Contains(OSKey.Space)) { if (mbHasActivatedFocusedWidget) { FocusedWidget.OnActivateUp(); mbHasActivatedFocusedWidget = false; } } if (Game.InputMgr.WasKeyJustPressed(Keys.Left)) FocusedWidget.OnPadMove(UI.Direction.Left); if (Game.InputMgr.WasKeyJustPressed(Keys.Right)) FocusedWidget.OnPadMove(UI.Direction.Right); if (Game.InputMgr.WasKeyJustPressed(Keys.Up)) FocusedWidget.OnPadMove(UI.Direction.Up); if (Game.InputMgr.WasKeyJustPressed(Keys.Down)) FocusedWidget.OnPadMove(UI.Direction.Down); foreach (Keys key in Game.InputMgr.JustPressedKeys) { FocusedWidget.OnKeyPress(key); } foreach (var key in Game.InputMgr.JustPressedOSKeys) { FocusedWidget.OnOSKeyPress(key); } } } //---------------------------------------------------------------------- public void Update(float elapsedTime) { Root.DoLayout(new Rectangle(0, 0, Width, Height)); Root.Update(elapsedTime); } //---------------------------------------------------------------------- public void Focus(Widget widget) { Debug.Assert(widget.Screen == this); mbHasActivatedFocusedWidget = false; if (FocusedWidget != null && FocusedWidget != widget) { FocusedWidget.OnBlur(); } if (FocusedWidget != widget) { FocusedWidget = widget; FocusedWidget.OnFocus(); } } //---------------------------------------------------------------------- public void DrawBox(Texture2D texture, Rectangle extents, int cornerSize, Color color) { // Corners Game.SpriteBatch.Draw(texture, new Rectangle(extents.Left, extents.Top, cornerSize, cornerSize), new Rectangle(0, 0, cornerSize, cornerSize), color); Game.SpriteBatch.Draw(texture, new Rectangle(extents.Right - cornerSize, extents.Top, cornerSize, cornerSize), new Rectangle(texture.Width - cornerSize, 0, cornerSize, cornerSize), color); Game.SpriteBatch.Draw(texture, new Rectangle(extents.Left, extents.Bottom - cornerSize, cornerSize, cornerSize), new Rectangle(0, texture.Height - cornerSize, cornerSize, cornerSize), color); Game.SpriteBatch.Draw(texture, new Rectangle(extents.Right - cornerSize, extents.Bottom - cornerSize, cornerSize, cornerSize), new Rectangle(texture.Width - cornerSize, texture.Height - cornerSize, cornerSize, cornerSize), color); // Content Game.SpriteBatch.Draw(texture, new Rectangle(extents.Left + cornerSize, extents.Top + cornerSize, extents.Width - cornerSize * 2, extents.Height - cornerSize * 2), new Rectangle(cornerSize, cornerSize, texture.Width - cornerSize * 2, texture.Height - cornerSize * 2), color); // Border top / bottom Game.SpriteBatch.Draw(texture, new Rectangle(extents.Left + cornerSize, extents.Top, extents.Width - cornerSize * 2, cornerSize), new Rectangle(cornerSize, 0, texture.Width - cornerSize * 2, cornerSize), color); Game.SpriteBatch.Draw(texture, new Rectangle(extents.Left + cornerSize, extents.Bottom - cornerSize, extents.Width - cornerSize * 2, cornerSize), new Rectangle(cornerSize, texture.Height - cornerSize, texture.Width - cornerSize * 2, cornerSize), color); // Border left / right Game.SpriteBatch.Draw(texture, new Rectangle(extents.Left, extents.Top + cornerSize, cornerSize, extents.Height - cornerSize * 2), new Rectangle(0, cornerSize, cornerSize, texture.Height - cornerSize * 2), color); Game.SpriteBatch.Draw(texture, new Rectangle(extents.Right - cornerSize, extents.Top + cornerSize, cornerSize, extents.Height - cornerSize * 2), new Rectangle(texture.Width - cornerSize, cornerSize, cornerSize, texture.Height - cornerSize * 2), color); } //---------------------------------------------------------------------- Stack<Rectangle> mlScissorRects = new Stack<Rectangle>(); Rectangle TransformRect(Rectangle rectangle, Matrix matrix) { Vector2 vMin = new Vector2(rectangle.X, rectangle.Y); Vector2 vMax = new Vector2(rectangle.Right, rectangle.Bottom); vMin = Vector2.Transform(vMin, matrix); vMax = Vector2.Transform(vMax, matrix); Rectangle bounds = new Rectangle( (int)vMin.X, (int)vMin.Y, (int)(vMax.X - vMin.X), (int)(vMax.Y - vMin.Y) ); return bounds; } public void PushScissorRectangle(Rectangle scissorRectangle) { Rectangle rect = TransformRect(scissorRectangle, Game.SpriteMatrix); rect.Offset(0, NuclearWinter.Resolution.Viewport.Y); Rectangle parentRect = ScissorRectangle; Rectangle newRect = parentRect.Clip(rect).Clip(Game.GraphicsDevice.Viewport.Bounds); SuspendBatch(); mlScissorRects.Push(newRect); ResumeBatch(); } public void PopScissorRectangle() { SuspendBatch(); mlScissorRects.Pop(); ResumeBatch(); } public void DoScissorRectangle(Rectangle scissorRectangle, Action action) { try { this.PushScissorRectangle(scissorRectangle); action(); } finally { this.PopScissorRectangle(); } } public Rectangle ScissorRectangle { get { return mlScissorRects.Count > 0 ? mlScissorRects.Peek() : Game.GraphicsDevice.Viewport.Bounds; } } //---------------------------------------------------------------------- public void Draw() { Game.SpriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, Game.SpriteMatrix); Root.Draw(); if (FocusedWidget != null && IsActive) { FocusedWidget.DrawFocused(); } if (HoveredWidget != null && IsActive) { HoveredWidget.DrawHovered(); } Game.SpriteBatch.End(); Debug.Assert(mlScissorRects.Count == 0, "Unbalanced calls to PushScissorRectangles"); } //---------------------------------------------------------------------- public void SuspendBatch() { Game.SpriteBatch.End(); Game.GraphicsDevice.RasterizerState = RasterizerState.CullNone; } //---------------------------------------------------------------------- public void ResumeBatch() { Game.GraphicsDevice.RasterizerState = Game.ScissorRasterizerState; if (mlScissorRects.Count > 0) { var rect = mlScissorRects.Peek(); if (rect.Width > 0 && rect.Height > 0) { Game.GraphicsDevice.ScissorRectangle = rect; } Game.SpriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, Game.ScissorRasterizerState, null, Game.SpriteMatrix); } else { Game.SpriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, Game.SpriteMatrix); } } } }
40.349666
288
0.466854
[ "MIT" ]
robintheilade/nuclearwinter4monogame
NuclearWinter/UI/Screen.cs
18,119
C#
using System; using Xunit; using System.IO; using Lab03WordGuessGame; using static Lab03WordGuessGame.Program; namespace XUnitTestLab03WordGuessGame { public class UnitTest1 { /// <summary> /// makes sure the dummy text file "wordTest.txt" does not exist /// yet by deleting any known instance of it ///Simple test to create a text file with the word "Something" ///by using method being tested ///then checks to see if that file actually exists ///thus proven that the method ///exist /// </summary> [Fact] public void FileCanBeCreated() { File.Delete("wordTest.txt"); AddWordstoFile("wordTest.txt", "Something"); Assert.True(File.Exists("wordTest.txt")); } /// <summary> /// Tests if file can be updated with custom method /// creates file "wordTestUpdate.txt" /// updates it 5 times by add text "Something" /// this means text file should contain 5 lines /// counts number of lines until it does not equal null /// expects count to be 5 /// </summary> [Fact] public void FileCanBeUpdated() { int count = 0; File.Delete("wordTestUpdate.txt"); for (int i = 0; i < 5; i++) { AddWordstoFile("wordTestUpdate.txt", "Something"); } using (StreamReader sr = File.OpenText("wordTestUpdate.txt")) { while (sr.ReadLine() != null) { count++; } } Assert.Equal(5, count); } /// <summary> ///makes sure the dummy text file "wordTestDelete.txt" does not exist /// yet by deleting any known instance of it ///create a text file with the word "Something" ///by using the add method ///then runs DeleteWordFile method to test that file ///can be deleted by removing the word ///then checks to see if that file doesn't exists /// </summary> [Fact] public void FileCanBeDeleted() { File.Delete("wordTestDelete.txt"); AddWordstoFile("wordTestDelete.txt", "Something"); DeleteWordFile("wordTestDelete.txt"); Assert.False(File.Exists("wordTestDelete.txt")); } /// <summary> /// creates string variable "testWord" /// Makes sure wordAdd.txt doesn't exist /// creates wordAdd.txt with the first word of "Something" /// using AddWordstoFile method /// uses same method to add the second word of "Something Cool" /// reads the linr of the text file /// assign that value to "testWord" /// verifies the method works if the testWord is equal to /// "Something", the first word to be added to test file. /// verifies the method words if the testWord is equal to /// "Something Cool", the second word to be added to test file. /// </summary> [Theory] [InlineData("Something", 1)] [InlineData("Something Cool", 2)] public void WordsCanBeAdded(string expected, int input) { string testWord = ""; File.Delete("wordAdd.txt"); AddWordstoFile("wordAdd.txt", "Something"); AddWordstoFile("wordAdd.txt", "Something Cool"); using (StreamReader sr = File.OpenText("wordAdd.txt")) { for (int i = 0; i < input; i++) { testWord = sr.ReadLine(); } } Assert.Equal(expected, testWord); } /// <summary> /// Test adds two words to dummy text file /// then tests the DeleteWords method to successfully delete /// the second line by specifying that word exactly /// then when streamreader tries to read the second line /// the expected value should be null /// file is verified to be updated /// </summary> [Fact] public void WordsCanBeDeleted() { string testWord = ""; File.Delete("wordDelete.txt"); AddWordstoFile("wordDelete.txt", "Something"); AddWordstoFile("wordDelete.txt", "Something Cool"); DeleteWords("wordDelete.txt", "Something Cool"); using (StreamReader sr = File.OpenText("wordDelete.txt")) { for (int i = 0; i < 2; i++) { testWord = sr.ReadLine(); } } Assert.Null(testWord); } /// <summary> /// this tests adds five dummy words to a text file tested called /// "wordRetriveFile.txt" /// Then it tests the method that retrieves the word on each /// line by specifying what line its on /// </summary> /// <param name="expected">what the test outcome expects</param> /// <param name="input">selects what line of the text /// file to output</param> [Theory] [InlineData("Something", 1)] [InlineData("Nothing", 2)] [InlineData("Everything", 3)] [InlineData("Always", 4)] [InlineData("Never", 5)] public void CanGetAllWords(string expected, int input) { File.Delete("wordRetrieveFile.txt"); AddWordstoFile("wordRetrieveFile.txt", "Something"); AddWordstoFile("wordRetrieveFile.txt", "Nothing"); AddWordstoFile("wordRetrieveFile.txt", "Everything"); AddWordstoFile("wordRetrieveFile.txt", "Always"); AddWordstoFile("wordRetrieveFile.txt", "Never"); Assert.Equal(expected, GetActualWord(input, "wordRetrieveFile.txt")); } /// <summary> /// checks if method can match user guess letter to the answer word /// and replaces the testCharacterArray with said letter /// initital testCharacterArray is filled with '-' /// if input is 'a', and as the answer array has an 'a' /// in the zero index, the '-' in the zero index of /// testCharacterArray should be replaced with 'a' /// </summary> [Fact] public void DetectLetterInAnswer() { char input = 'a'; char[] testCharacterArray = { '-', '-', '-', '-', '-', '-' }; char[] answer = { 'a', 'b', 'd', 'e', 'f', 'g' }; CompareGuess(answer, input, testCharacterArray); Assert.Equal('a', testCharacterArray[0]); } /// <summary> /// if the array to be displayed matches the answer /// array, returns true for win /// </summary> [Fact] public void GameIsWonTest() { char[] answerArray = { 'a', 'b', 'c' }; char[] inputCharArray = { 'a', 'b', 'c' }; Assert.True(DidWinGame(inputCharArray, answerArray)); } /// <summary> /// if array doesn't match answer, returns false /// for win /// </summary> [Fact] public void GameIsNotWonTest() { char[] answerArray = { 'a', 'b', 'c' }; char[] inputCharArray = { 'a', 'e', 'c' }; Assert.False(DidWinGame(inputCharArray, answerArray)); } } }
34.171875
75
0.612254
[ "MIT" ]
nguyenvinh2/Hangman-for-C-Sharp
XUnitTestLab03WordGuessGame/UnitTest1.cs
6,561
C#
using Newtonsoft.Json; namespace FreeAgentSniper.Models { public class GetTokenResponse { [JsonProperty("access_token")] public string AccessToken { get; set; } [JsonProperty("refresh_token")] public string RefreshToken { get; set; } [JsonProperty("expires_in")] public int ExpiresIn { get; set; } [JsonProperty("token_type")] public string TokenType { get; set; } } }
24.421053
48
0.601293
[ "MIT" ]
jmbledsoe/FreeAgentSniper
src/Models/GetTokenResponse.cs
464
C#
using System; using System.Collections.Generic; using Hl7.Fhir.Introspection; using Hl7.Fhir.Validation; using System.Linq; using System.Runtime.Serialization; using Hl7.Fhir.Utility; /* Copyright (c) 2011+, HL7, 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. * Neither the name of HL7 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. */ #pragma warning disable 1591 // suppress XML summary warnings // // Generated for FHIR v3.0.2 // namespace Hl7.Fhir.Model { /// <summary> /// A reply to an appointment request for a patient and/or practitioner(s), such as a confirmation or rejection /// </summary> [FhirType("AppointmentResponse", IsResource=true)] [DataContract] public partial class AppointmentResponse : Hl7.Fhir.Model.DomainResource, System.ComponentModel.INotifyPropertyChanged { [NotMapped] public override ResourceType ResourceType { get { return ResourceType.AppointmentResponse; } } [NotMapped] public override string TypeName { get { return "AppointmentResponse"; } } /// <summary> /// External Ids for this item /// </summary> [FhirElement("identifier", InSummary=true, Order=90)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Identifier> Identifier { get { if(_Identifier==null) _Identifier = new List<Hl7.Fhir.Model.Identifier>(); return _Identifier; } set { _Identifier = value; OnPropertyChanged("Identifier"); } } private List<Hl7.Fhir.Model.Identifier> _Identifier; /// <summary> /// Appointment this response relates to /// </summary> [FhirElement("appointment", InSummary=true, Order=100)] [CLSCompliant(false)] [References("Appointment")] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.ResourceReference Appointment { get { return _Appointment; } set { _Appointment = value; OnPropertyChanged("Appointment"); } } private Hl7.Fhir.Model.ResourceReference _Appointment; /// <summary> /// Time from appointment, or requested new start time /// </summary> [FhirElement("start", Order=110)] [DataMember] public Hl7.Fhir.Model.Instant StartElement { get { return _StartElement; } set { _StartElement = value; OnPropertyChanged("StartElement"); } } private Hl7.Fhir.Model.Instant _StartElement; /// <summary> /// Time from appointment, or requested new start time /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public DateTimeOffset? Start { get { return StartElement != null ? StartElement.Value : null; } set { if (!value.HasValue) StartElement = null; else StartElement = new Hl7.Fhir.Model.Instant(value); OnPropertyChanged("Start"); } } /// <summary> /// Time from appointment, or requested new end time /// </summary> [FhirElement("end", Order=120)] [DataMember] public Hl7.Fhir.Model.Instant EndElement { get { return _EndElement; } set { _EndElement = value; OnPropertyChanged("EndElement"); } } private Hl7.Fhir.Model.Instant _EndElement; /// <summary> /// Time from appointment, or requested new end time /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public DateTimeOffset? End { get { return EndElement != null ? EndElement.Value : null; } set { if (!value.HasValue) EndElement = null; else EndElement = new Hl7.Fhir.Model.Instant(value); OnPropertyChanged("End"); } } /// <summary> /// Role of participant in the appointment /// </summary> [FhirElement("participantType", InSummary=true, Order=130)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.CodeableConcept> ParticipantType { get { if(_ParticipantType==null) _ParticipantType = new List<Hl7.Fhir.Model.CodeableConcept>(); return _ParticipantType; } set { _ParticipantType = value; OnPropertyChanged("ParticipantType"); } } private List<Hl7.Fhir.Model.CodeableConcept> _ParticipantType; /// <summary> /// Person, Location/HealthcareService or Device /// </summary> [FhirElement("actor", InSummary=true, Order=140)] [CLSCompliant(false)] [References("Patient","Practitioner","RelatedPerson","Device","HealthcareService","Location")] [DataMember] public Hl7.Fhir.Model.ResourceReference Actor { get { return _Actor; } set { _Actor = value; OnPropertyChanged("Actor"); } } private Hl7.Fhir.Model.ResourceReference _Actor; /// <summary> /// accepted | declined | tentative | in-process | completed | needs-action | entered-in-error /// </summary> [FhirElement("participantStatus", InSummary=true, Order=150)] [Cardinality(Min=1,Max=1)] [DataMember] public Code<Hl7.Fhir.Model.ParticipationStatus> ParticipantStatusElement { get { return _ParticipantStatusElement; } set { _ParticipantStatusElement = value; OnPropertyChanged("ParticipantStatusElement"); } } private Code<Hl7.Fhir.Model.ParticipationStatus> _ParticipantStatusElement; /// <summary> /// accepted | declined | tentative | in-process | completed | needs-action | entered-in-error /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public Hl7.Fhir.Model.ParticipationStatus? ParticipantStatus { get { return ParticipantStatusElement != null ? ParticipantStatusElement.Value : null; } set { if (!value.HasValue) ParticipantStatusElement = null; else ParticipantStatusElement = new Code<Hl7.Fhir.Model.ParticipationStatus>(value); OnPropertyChanged("ParticipantStatus"); } } /// <summary> /// Additional comments /// </summary> [FhirElement("comment", Order=160)] [DataMember] public Hl7.Fhir.Model.FhirString CommentElement { get { return _CommentElement; } set { _CommentElement = value; OnPropertyChanged("CommentElement"); } } private Hl7.Fhir.Model.FhirString _CommentElement; /// <summary> /// Additional comments /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Comment { get { return CommentElement != null ? CommentElement.Value : null; } set { if (value == null) CommentElement = null; else CommentElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Comment"); } } public static ElementDefinition.ConstraintComponent AppointmentResponse_APR_1 = new ElementDefinition.ConstraintComponent() { Expression = "participantType.exists() or actor.exists()", Key = "apr-1", Severity = ElementDefinition.ConstraintSeverity.Warning, Human = "Either the participantType or actor must be specified", Xpath = "(exists(f:participantType) or exists(f:actor))" }; public override void AddDefaultConstraints() { base.AddDefaultConstraints(); InvariantConstraints.Add(AppointmentResponse_APR_1); } public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as AppointmentResponse; if (dest != null) { base.CopyTo(dest); if(Identifier != null) dest.Identifier = new List<Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy()); if(Appointment != null) dest.Appointment = (Hl7.Fhir.Model.ResourceReference)Appointment.DeepCopy(); if(StartElement != null) dest.StartElement = (Hl7.Fhir.Model.Instant)StartElement.DeepCopy(); if(EndElement != null) dest.EndElement = (Hl7.Fhir.Model.Instant)EndElement.DeepCopy(); if(ParticipantType != null) dest.ParticipantType = new List<Hl7.Fhir.Model.CodeableConcept>(ParticipantType.DeepCopy()); if(Actor != null) dest.Actor = (Hl7.Fhir.Model.ResourceReference)Actor.DeepCopy(); if(ParticipantStatusElement != null) dest.ParticipantStatusElement = (Code<Hl7.Fhir.Model.ParticipationStatus>)ParticipantStatusElement.DeepCopy(); if(CommentElement != null) dest.CommentElement = (Hl7.Fhir.Model.FhirString)CommentElement.DeepCopy(); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new AppointmentResponse()); } public override bool Matches(IDeepComparable other) { var otherT = other as AppointmentResponse; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Identifier, otherT.Identifier)) return false; if( !DeepComparable.Matches(Appointment, otherT.Appointment)) return false; if( !DeepComparable.Matches(StartElement, otherT.StartElement)) return false; if( !DeepComparable.Matches(EndElement, otherT.EndElement)) return false; if( !DeepComparable.Matches(ParticipantType, otherT.ParticipantType)) return false; if( !DeepComparable.Matches(Actor, otherT.Actor)) return false; if( !DeepComparable.Matches(ParticipantStatusElement, otherT.ParticipantStatusElement)) return false; if( !DeepComparable.Matches(CommentElement, otherT.CommentElement)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as AppointmentResponse; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Identifier, otherT.Identifier)) return false; if( !DeepComparable.IsExactly(Appointment, otherT.Appointment)) return false; if( !DeepComparable.IsExactly(StartElement, otherT.StartElement)) return false; if( !DeepComparable.IsExactly(EndElement, otherT.EndElement)) return false; if( !DeepComparable.IsExactly(ParticipantType, otherT.ParticipantType)) return false; if( !DeepComparable.IsExactly(Actor, otherT.Actor)) return false; if( !DeepComparable.IsExactly(ParticipantStatusElement, otherT.ParticipantStatusElement)) return false; if( !DeepComparable.IsExactly(CommentElement, otherT.CommentElement)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; foreach (var elem in Identifier) { if (elem != null) yield return elem; } if (Appointment != null) yield return Appointment; if (StartElement != null) yield return StartElement; if (EndElement != null) yield return EndElement; foreach (var elem in ParticipantType) { if (elem != null) yield return elem; } if (Actor != null) yield return Actor; if (ParticipantStatusElement != null) yield return ParticipantStatusElement; if (CommentElement != null) yield return CommentElement; } } [NotMapped] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; foreach (var elem in Identifier) { if (elem != null) yield return new ElementValue("identifier", elem); } if (Appointment != null) yield return new ElementValue("appointment", Appointment); if (StartElement != null) yield return new ElementValue("start", StartElement); if (EndElement != null) yield return new ElementValue("end", EndElement); foreach (var elem in ParticipantType) { if (elem != null) yield return new ElementValue("participantType", elem); } if (Actor != null) yield return new ElementValue("actor", Actor); if (ParticipantStatusElement != null) yield return new ElementValue("participantStatus", ParticipantStatusElement); if (CommentElement != null) yield return new ElementValue("comment", CommentElement); } } } }
42.544199
163
0.616194
[ "BSD-3-Clause" ]
CASPA-Care/caspa-fhir-net-api
src/Hl7.Fhir.Core/Model/Generated/AppointmentResponse.cs
15,403
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; namespace GraphQL.EntityFramework { public static class ExpressionBuilder<T> { const string LIST_PROPERTY_PATTERN = @"\[(.*)\]"; #region Conditional List /// <summary> /// Build a predicate for a supplied list of where's (Grouped or not) /// </summary> public static Expression<Func<T, bool>> BuildPredicate(IEnumerable<WhereExpression> wheres) { var expressionBody = MakePredicateBody(wheres); var param = PropertyCache<T>.SourceParameter; return Expression.Lambda<Func<T, bool>>(expressionBody, param); } /// <summary> /// Makes the predicate body from the supplied parameter and list of where expressions /// </summary> private static Expression MakePredicateBody(IEnumerable<WhereExpression> wheres) { Expression? mainExpression = null; WhereExpression previousWhere = new(); // Iterate over wheres foreach (var where in wheres) { Expression nextExpression; // If there are grouped expressions if (@where.GroupedExpressions?.Length > 0) { // Recurse with new set of expression nextExpression = MakePredicateBody(where.GroupedExpressions); // If the whole group is to be negated if (where.Negate) { // Negate it nextExpression = NegateExpression(nextExpression); } } // Otherwise handle single expressions else { // Get the predicate body for the single expression nextExpression = MakePredicateBody(where.Path, where.Comparison, where.Value, where.Negate, where.Case); } // If this is the first where processed if (mainExpression == null) { // Assign to main expression mainExpression = nextExpression; } else { // Otherwise combine expression by specified connector or default (AND) if not provided mainExpression = CombineExpressions(previousWhere.Connector, mainExpression, nextExpression); } // Save the previous where so the connector can be retrieved previousWhere = where; } return mainExpression ?? Expression.Constant(false); } #endregion #region Conditional Single /// <summary> /// Create a single predicate for the single set of supplied conditional arguments /// </summary> public static Expression<Func<T, bool>> BuildPredicate(string path, Comparison comparison, string?[]? values) { return BuildPredicate(path, comparison, values, null); } /// <summary> /// Create a single predicate for the single set of supplied conditional arguments /// </summary> public static Expression<Func<T, bool>> BuildPredicate(string path, Comparison comparison, string?[]? values, StringComparison? stringComparison) { return BuildPredicate(path, comparison, values, false, stringComparison); } /// <summary> /// Create a single predicate for the single set of supplied conditional arguments /// </summary> public static Expression<Func<T, bool>> BuildPredicate(string path, Comparison comparison, string?[]? values, bool negate) { return BuildPredicate(path, comparison, values, negate, null); } /// <summary> /// Create a single predicate for the single set of supplied conditional arguments /// </summary> public static Expression<Func<T, bool>> BuildPredicate(string path, Comparison comparison, string?[]? values, bool negate, StringComparison? stringComparison) { var expressionBody = MakePredicateBody(path, comparison, values, negate, stringComparison); var param = PropertyCache<T>.SourceParameter; return Expression.Lambda<Func<T, bool>>(expressionBody, param); } /// <summary> /// Makes the predicate body from the single set of supplied conditional arguments /// </summary> static Expression MakePredicateBody(string path, Comparison comparison, string?[]? values, bool negate = false, StringComparison? stringComparison = null) { Expression expressionBody; // If path includes list property access if (HasListInPath(path)) { // Handle a list path expressionBody = ProcessList(path, comparison, values!, stringComparison); } // Otherwise linear property access else { // Just get expression expressionBody = GetExpression(path, comparison, values, stringComparison); } // If the expression should be negated if (negate) { // Not it expressionBody = NegateExpression(expressionBody); } return expressionBody; } #endregion #region Body Builders (Lol) /// <summary> /// Process a list based item inside the property path /// </summary> static Expression ProcessList(string path, Comparison comparison, string?[]? values, StringComparison? stringComparison = null) { // Get the path pertaining to individual list items var listPath = Regex.Match(path, LIST_PROPERTY_PATTERN).Groups[1].Value; // Remove the part of the path that leads into list item properties path = Regex.Replace(path, LIST_PROPERTY_PATTERN, ""); // Get the property on the current object up to the list member var property = PropertyCache<T>.GetProperty(path); // Get the list item type details var listItemType = property.PropertyType.GetGenericArguments().Single(); // Generate the predicate for the list item type var subPredicate = (Expression) typeof(ExpressionBuilder<>) .MakeGenericType(listItemType) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Single(m => m.Name == "BuildPredicate" && m.GetParameters().Length == 5) .Invoke(new object(), new object[] { listPath, comparison, values!, false, stringComparison! })!; // Generate a method info for the Any Enumerable Static Method var anyInfo = typeof(Enumerable) .GetMethods(BindingFlags.Static | BindingFlags.Public) .First(m => m.Name == "Any" && m.GetParameters().Length == 2) .MakeGenericMethod(listItemType); // Create Any Expression Call return Expression.Call(anyInfo, property.Left, subPredicate); } /// <summary> /// Build an expression from provided where parameters /// </summary> static Expression GetExpression(string path, Comparison comparison, string?[]? values, StringComparison? stringComparison = null) { var property = PropertyCache<T>.GetProperty(path); Expression expressionBody; if (property.PropertyType == typeof(string)) { switch (comparison) { case Comparison.NotIn: WhereValidator.ValidateString(comparison, stringComparison); expressionBody = NegateExpression(MakeStringIn(values!, property, stringComparison)); // Ensure expression is negated break; case Comparison.In: WhereValidator.ValidateString(comparison, stringComparison); expressionBody = MakeStringIn(values!, property, stringComparison); break; default: WhereValidator.ValidateSingleString(comparison, stringComparison); var value = values?.Single(); expressionBody = MakeStringComparison(comparison, value, property, stringComparison); break; } } else { switch (comparison) { case Comparison.NotIn: WhereValidator.ValidateObject(property.PropertyType, comparison, stringComparison); expressionBody = NegateExpression(MakeObjectIn(values!, property)); // Ensure expression is negated break; case Comparison.In: WhereValidator.ValidateObject(property.PropertyType, comparison, stringComparison); expressionBody = MakeObjectIn(values!, property); break; default: WhereValidator.ValidateSingleObject(property.PropertyType, comparison, null); var value = values?.Single(); var valueObject = TypeConverter.ConvertStringToType(value, property.PropertyType); expressionBody = MakeObjectComparison(comparison, valueObject, property); break; } } return expressionBody; } #endregion #region Operations /// <summary> /// Make Object List In Comparision /// </summary> static Expression MakeObjectIn(string[] values, Property<T> property) { // Attempt to convert the string values to the object type var objects = TypeConverter.ConvertStringsToList(values, property.PropertyType); // Make the object values a constant expression var constant = Expression.Constant(objects); // Build and return the expression body return Expression.Call(constant, property.ListContainsMethod!, property.Left); } /// <summary> /// Make String List In Comparison /// </summary> static Expression MakeStringIn(string[] values, Property<T> property, StringComparison? comparison) { MethodCallExpression equalsBody; // If string comparison not provided if (comparison == null) { // Do basic string compare equalsBody = Expression.Call(null, ReflectionCache.StringEqual, ExpressionCache.StringParam, property.Left); } // Otherwise else { // String comparison with comparison type value equalsBody = Expression.Call(null, ReflectionCache.StringEqualComparison, ExpressionCache.StringParam, property.Left, Expression.Constant(comparison)); } // Make lambda for comparing each string value against property value var itemEvaluate = Expression.Lambda<Func<string, bool>>(equalsBody, ExpressionCache.StringParam); // Build Expression body to check if any string values match the property value return Expression.Call(null, ReflectionCache.StringAny, Expression.Constant(values), itemEvaluate); } /// <summary> /// Make String based single value comparisons /// </summary> static Expression MakeStringComparison(Comparison comparison, string? value, Property<T> property, StringComparison? stringComparison) { var left = property.Left; var valueConstant = Expression.Constant(value, typeof(string)); var nullCheck = Expression.NotEqual(left, ExpressionCache.Null); if (stringComparison == null) { switch (comparison) { case Comparison.Equal: return Expression.Call(ReflectionCache.StringEqual, left, valueConstant); case Comparison.Like: return Expression.Call(null, ReflectionCache.StringLike, ExpressionCache.EfFunction, left, valueConstant); case Comparison.StartsWith: var startsWithExpression = Expression.Call(left, ReflectionCache.StringStartsWith, valueConstant); return Expression.AndAlso(nullCheck, startsWithExpression); case Comparison.EndsWith: var endsWithExpression = Expression.Call(left, ReflectionCache.StringEndsWith, valueConstant); return Expression.AndAlso(nullCheck, endsWithExpression); case Comparison.Contains: var indexOfExpression = Expression.Call(left, ReflectionCache.StringIndexOf, valueConstant); var notEqualExpression = Expression.NotEqual(indexOfExpression, ExpressionCache.NegativeOne); return Expression.AndAlso(nullCheck, notEqualExpression); } } else { var comparisonConstant = Expression.Constant(stringComparison, typeof(StringComparison)); switch (comparison) { case Comparison.Equal: return Expression.Call(ReflectionCache.StringEqualComparison, left, valueConstant, comparisonConstant); case Comparison.StartsWith: var startsWithExpression = Expression.Call(left, ReflectionCache.StringStartsWithComparison, valueConstant, comparisonConstant); return Expression.AndAlso(nullCheck, startsWithExpression); case Comparison.EndsWith: var endsWithExpression = Expression.Call(left, ReflectionCache.StringEndsWithComparison, valueConstant, comparisonConstant); return Expression.AndAlso(nullCheck, endsWithExpression); case Comparison.Contains: var indexOfExpression = Expression.Call(left, ReflectionCache.StringIndexOfComparison, valueConstant, comparisonConstant); var notEqualExpression = Expression.NotEqual(indexOfExpression, ExpressionCache.NegativeOne); return Expression.AndAlso(nullCheck, notEqualExpression); } } throw new($"Invalid comparison operator '{comparison}'."); } /// <summary> /// Make Object based single value comparisons /// </summary> static Expression MakeObjectComparison(Comparison comparison, object? value, Property<T> property) { var left = property.Left; var constant = Expression.Constant(value, left.Type); switch (comparison) { case Comparison.Equal: return Expression.MakeBinary(ExpressionType.Equal, left, constant); case Comparison.GreaterThan: return Expression.MakeBinary(ExpressionType.GreaterThan, left, constant); case Comparison.GreaterThanOrEqual: return Expression.MakeBinary(ExpressionType.GreaterThanOrEqual, left, constant); case Comparison.LessThan: return Expression.MakeBinary(ExpressionType.LessThan, left, constant); case Comparison.LessThanOrEqual: return Expression.MakeBinary(ExpressionType.LessThanOrEqual, left, constant); } throw new($"Invalid comparison operator '{comparison}'."); } #endregion #region Helpers /// <summary> /// Checks the path for matching list property marker /// </summary> private static bool HasListInPath(string path) { return Regex.IsMatch(path, LIST_PROPERTY_PATTERN); } /// <summary> /// Combine expressions by a specified binary operator /// </summary> static Expression CombineExpressions(Connector connector, Expression expr1, Expression expr2) { switch (connector) { case Connector.And: return Expression.AndAlso(expr1, expr2); case Connector.Or: return Expression.OrElse(expr1, expr2); } throw new($"Invalid connector operator '{connector}'."); } /// <summary> /// Negates a supplied expression /// </summary> static Expression NegateExpression(Expression expression) { return Expression.Not(expression); } #endregion } }
43.487437
167
0.583372
[ "MIT" ]
Intecpsp/GraphQL.EntityFramework
src/GraphQL.EntityFramework/Where/ExpressionBuilder.cs
17,310
C#
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http ://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using HandleUtils; using NDesk.Options; using System; using System.Collections.Generic; using System.Diagnostics; namespace CheckObjectManagerAccess { class Program { static bool _recursive = false; static bool _print_sddl = false; static bool _show_write_only = false; static HashSet<string> _walked = new HashSet<string>(); static NativeHandle _token; static uint _dir_rights = 0; static HashSet<string> _type_filter = new HashSet<string>(); static void ShowHelp(OptionSet p) { Console.WriteLine("Usage: CheckObjectManagerAccess [options] dir1 [dir2..dirN]"); Console.WriteLine(); Console.WriteLine("Options:"); p.WriteOptionDescriptions(Console.Out); } static Type GetTypeAccessRights(ObjectTypeInfo type) { switch (type.Name.ToLower()) { case "directory": return typeof(DirectoryAccessRights); case "event": return typeof(EventAccessRights); case "section": return typeof(SectionAccessRights); case "mutant": return typeof(MutantAccessRights); case "semaphore": return typeof(SemaphoreAccessRights); case "job": return typeof(JobObjectAccessRights); case "symboliclink": return typeof(SymbolicLinkAccessRights); default: throw new ArgumentException("Can't get type for access rights"); } } static string AccessMaskToString(ObjectTypeInfo type, uint granted_access) { if (type.HasFullPermission(granted_access)) { return "Full Permission"; } Object rights = Enum.ToObject(GetTypeAccessRights(type), granted_access & 0xFFFF); StandardAccessRights standard = (StandardAccessRights)(granted_access & 0x1F0000); return String.Join(", ", new string[] { standard.ToString(), rights.ToString() }); } static void CheckAccess(string path, byte[] sd, ObjectTypeInfo type) { try { if (_type_filter.Count > 0) { if (!_type_filter.Contains(type.Name.ToLower())) { return; } } if (sd.Length > 0) { uint granted_access = 0; if (_dir_rights != 0) { granted_access = NativeBridge.GetAllowedAccess(_token, type, (uint)_dir_rights, sd); } else { granted_access = NativeBridge.GetMaximumAccess(_token, type, sd); } if (granted_access != 0) { // As we can get all the righs for the key get maximum if (_dir_rights != 0) { granted_access = NativeBridge.GetMaximumAccess(_token, type, sd); } if (!_show_write_only || type.HasWritePermission(granted_access)) { Console.WriteLine("<{0}> {1} : {2:X08} {3}", type.Name, path, granted_access, AccessMaskToString(type, granted_access)); if (_print_sddl) { Console.WriteLine("{0}", NativeBridge.GetStringSecurityDescriptor(sd)); } } } } } catch (Exception) { } } static void DumpDirectory(ObjectDirectory dir) { if (_walked.Contains(dir.FullPath.ToLower())) { return; } _walked.Add(dir.FullPath.ToLower()); try { CheckAccess(dir.FullPath, dir.SecurityDescriptor, ObjectTypeInfo.GetTypeByName("Directory")); if (_recursive) { foreach (ObjectDirectoryEntry entry in dir.Entries) { try { if (entry.IsDirectory) { DumpDirectory(ObjectNamespace.OpenDirectory(entry.FullPath)); } else { CheckAccess(entry.FullPath, entry.SecurityDescriptor, ObjectTypeInfo.GetTypeByName(entry.TypeName)); } } catch (Exception ex) { Console.Error.WriteLine("Error opening {0} {1}", entry.FullPath, ex.Message); } } } } catch (Exception ex) { Console.Error.WriteLine("Error dumping directory {0} {1}", dir.FullPath, ex.Message); } } static uint ParseRight(string name, Type enumtype) { return (uint)Enum.Parse(enumtype, name, true); } static void Main(string[] args) { bool show_help = false; int pid = Process.GetCurrentProcess().Id; try { OptionSet opts = new OptionSet() { { "r", "Recursive tree directory listing", v => _recursive = v != null }, { "sddl", "Print full SDDL security descriptors", v => _print_sddl = v != null }, { "p|pid=", "Specify a PID of a process to impersonate when checking", v => pid = int.Parse(v.Trim()) }, { "w", "Show only write permissions granted", v => _show_write_only = v != null }, { "k=", String.Format("Filter on a specific directory right [{0}]", String.Join(",", Enum.GetNames(typeof(DirectoryAccessRights)))), v => _dir_rights |= ParseRight(v, typeof(DirectoryAccessRights)) }, { "s=", String.Format("Filter on a standard right [{0}]", String.Join(",", Enum.GetNames(typeof(StandardAccessRights)))), v => _dir_rights |= ParseRight(v, typeof(StandardAccessRights)) }, { "x=", "Specify a base path to exclude from recursive search", v => _walked.Add(v.ToLower()) }, { "t=", "Specify a type of object to include", v => _type_filter.Add(v.ToLower()) }, { "h|help", "show this message and exit", v => show_help = v != null }, }; List<string> paths = opts.Parse(args); if (show_help || (paths.Count == 0)) { ShowHelp(opts); } else { _token = NativeBridge.OpenProcessToken(pid); foreach (string path in paths) { ObjectDirectory dir = ObjectNamespace.OpenDirectory(path); DumpDirectory(dir); } } } catch (Exception e) { Console.WriteLine(e.Message); } } } }
39.913636
167
0.455301
[ "Apache-2.0" ]
GabberBaby/sandbox-attacksurface-analysis-tools
CheckObjectManagerAccess/Program.cs
8,783
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; namespace DirGen { /// <summary> /// メッセージを格納するイベント引数を提供します。 /// </summary> public class MessageEventArgs : EventArgs { /// <summary> /// メッセージを取得します。 /// </summary> public string Message { get; private set; } /// <summary> /// メッセージから<see cref="MessageEventArgs"/>クラスの新しいインスタンスを生成します。 /// </summary> /// <param name="mes">メッセージ</param> public MessageEventArgs( string mes ) { Message = mes; } } /// <summary> /// ディレクトリー構造の定義ファイルを読み込み、ディレクトリーを作成するジェネレータークラスを提供します。 /// </summary> public class DirectoryGenerator { /// <summary> /// 出力先のルートパスを表します。 /// </summary> private string targetRootPath; /// <summary> /// 出力先のパスに作成するルートフォルダー名を表します。 /// </summary> private string targetRootFolderName; /// <summary> /// ディレクトリー構造を表す、XMLツリーを表します。 /// </summary> private XElement directoryTree; /// <summary> /// トークンなどの展開後のディレクトリー構造を表す、XMLツリーを表します。 /// </summary> private XElement extractedDirectoryTree; /// <summary> /// トークンの辞書リストを表します。 /// </summary> private Dictionary<string, string[]> tokenListMap; /// <summary> /// アプリのパスを表します。 /// </summary> private static readonly string appPath = Directory.GetCurrentDirectory(); /// <summary> /// 定義ファイルが入っているパスを表します。 /// </summary> private string definitionFilePath; /// <summary> /// ファイル名で利用できない文字を認識するための正規表現を表します。 /// </summary> private static readonly Regex fileNameInvaildRecongnizer = new Regex( $"[{Regex.Escape( "\\/:*?\"<>|" )}]" ); /// <summary> /// 先頭に「$」が付いた名前をトークンとして認識するための正規表現を表します。 /// </summary> private static readonly Regex tokenRecongnizer = new Regex( @"(?<=^(\$))(.*)" ); /// <summary> /// 先頭に「$」が付いた名前をトークンではなく、「$」付きの名前として認識するための正規表現を表します。 /// </summary> private static readonly Regex antiTokenRecongnizer = new Regex( @"(?<=^(\\))(\$.*)" ); /// <summary> /// <see cref="DirectoryGenerator">クラスからメッセージを受け取った時に実行するイベントハンドラーです。 /// </summary> public EventHandler<MessageEventArgs> NotifyMessageRecieved; /// <summary> /// <see cref="DirectoryGenerator">クラスの新しいインスタンスを生成します。 /// </summary> public DirectoryGenerator() { } /// <summary> /// メッセージを発行します。 /// </summary> /// <param name="message">クラス利用側に送信するメッセージ</param> private void NotifyMessage( string message ) { NotifyMessageRecieved?.Invoke( this, new MessageEventArgs( message ) ); } /// <summary> /// ディレクトリー構造を定義したXMLファイルを読み込みます。 /// </summary> /// <param name="xmlPath">XMLファイルのパス</param> public void Load( string xmlPath ) { NotifyMessage( $"'{xmlPath}' をロードしています。" ); XElement xml = XElement.Load( xmlPath ); definitionFilePath = Path.GetDirectoryName( Path.GetFullPath( xmlPath ) ); NotifyMessage( $"ディレクトリーの構成を読み込んでいます。" ); directoryTree = new XElement( xml.Element( "directory" ) ); NotifyMessage( $"トークンを読み込んでいます。" ); // <tokens>ノードの<token>ノードのコレクションを取得します。 tokenListMap = xml.Element( "tokens" ).Elements( "token" ) .ToDictionary( // トークン(key属性値)をkeyに、 tkey => tkey.Attribute( "key" ).Value, // トークンから置き換える文字列群(<token_value>ノードのvalue属性値のコレクション)を値に設定します。 tval => tval.Elements( "token_value" ) .Select( tv => tv.Attribute( "value" ).Value ) .Distinct() .ToArray() ); NotifyMessage( $"出力先のパスを読み込んでいます。" ); // target_pathが未指定の場合、アプリのパスを設定します。 targetRootPath = directoryTree.Attribute( "target_path" )?.Value ?? definitionFilePath; // nameが未指定の場合、nullを設定します。 targetRootFolderName = directoryTree.Attribute( "name" )?.Value; NotifyMessage( $"'{xmlPath}' のロードを完了しました。" ); } /// <summary> /// ディレクトリー構造を解析し、トークンを展開します。 /// </summary> private void ExtractDirectoryTree() { NotifyMessage( $"ディレクトリー構成を解析しています。" ); // 展開後のディレクトリー構造のXMLオブジェクトを作成します。 extractedDirectoryTree = new XElement( directoryTree ); // extractedDirectoryTreeの参照をコピーし、カレントノードを作成します。 // ※カレントノード経由でXMLの内容を変更すると、extractedDirectoryTreeにも反映します。 var curNode = extractedDirectoryTree; // 子ノードを探索済みフラグを表します。 bool childNodeIsVisited = false; while( curNode != null ) { #region 子ノードの探索 // カレントノードにて、未探索の子ノードがあるかどうか判別します。 if( !childNodeIsVisited && curNode.HasElements ) { // 末っ子のノードにアクセスします。 while( true ) { // 子ノードを取得し、種類を判別します。 var childNode = curNode.FirstNode; // 子ノードが存在しない時、ループから抜けます。 if( childNode == null ) { break; } // 子ノードが要素の時、カレントノードに設定します。 else if( childNode is XElement ) { curNode = childNode as XElement; } // 子ノードが要素以外(コメントなど)の時、そのノードを削除します。 else { childNode.Remove(); } } continue; } // 子ノードを探索済みの場合、フラグをオフにします。 else if( childNodeIsVisited ) { // 直下のサブディレクトリー内のフォルダー名やファイル名が重複していないかチェックします。 if( curNode.Elements().GroupBy( node => node.Attribute( "name" ).Value ).Any( _ => _.Count() >= 2 ) ) { throw new Exception( $"'{curNode.Attribute( "name" ).Value}' フォルダーの中に、同じ名前のフォルダーまたはファイルが重複しています。" ); } childNodeIsVisited = false; } #endregion #region トークンの展開 var name = curNode.Attribute( "name" ); if( name?.Value != null ) { // name属性の値がトークンであるかどうか判別します。 if( tokenRecongnizer.IsMatch( name.Value ) ) { // 「$」以降の文字列を取り出します。 var token = tokenRecongnizer.Match( name.Value ).Value; // トークンのあるノードの参照をコピーします。 var tokenNode = curNode; // トークンが辞書に含まれているか判別します。 if( tokenListMap.ContainsKey( token ) ) { // トークンに登録されているフォルダー名・ファイル名を展開します。 foreach( var item in tokenListMap[token] ) { if( fileNameInvaildRecongnizer.IsMatch( item ) ) { throw new Exception( $"トークンに対応する名前 '{item}' に、ファイル名として使用できない文字( \\ / : * ? \" < > | )が含まれています。" ); } // 展開後の名前をname属性にしたノードを追加します。 curNode.AddAfterSelf( new XElement( tokenNode.Name, new XAttribute( "name", item ) ) ); // 追加したノードにアクセスします。 curNode = curNode.NextNode as XElement; // トークンノードに子ノードがあれば、追加したノードの子にコピーします。 if( tokenNode.HasElements ) { curNode.Add( tokenNode.Elements() ); } } } // トークンノードを削除します。 tokenNode.Remove(); } else { if( antiTokenRecongnizer.IsMatch( name.Value ) ) { // 先頭の「$」の前に付いている「\」を取り除きます。 name.Value = antiTokenRecongnizer.Match( name.Value ).Value; } if( fileNameInvaildRecongnizer.IsMatch( name.Value ) ) { throw new Exception( $"名前 '{name.Value}' に、ファイル名として使用できない文字( \\ / : * ? \" < > | )が含まれています。" ); } } } else { throw new Exception( $"{curNode.Name} ノードにname属性が存在しないか、属性名が無効です。" ); } #endregion #region 次のノードの探索 // 次のノードを判別します。 while( true ) { var nextNode = curNode.NextNode; // 次のノードが存在しない時、親のノードに戻ります。 if( nextNode == null ) { curNode = curNode.Parent; childNodeIsVisited = true; break; } // 次のノードが要素の時、カレントノードに設定します。 else if( nextNode is XElement ) { curNode = nextNode as XElement; break; } // 次のノードが要素以外(コメントなど)の時、そのノードを削除します。 else { nextNode.Remove(); } } #endregion } NotifyMessage( $"ディレクトリー構成の解析が完了しました。" ); } /// <summary> /// 展開後のディレクトリー構造からディレクトリーを作成します。 /// </summary> private void CreateDirectory() { try { NotifyMessage( $"ディレクトリーを作成しています。" ); // ディレクトリーの出力先パスが存在するかどうか判別します。 if( !Directory.Exists( targetRootPath ) ) { throw new Exception( $"出力先パス '{targetRootPath}' が存在しないか、ディレクトリー名が無効です。" ); } // ディレクトリーの出力先パスにカレントディレクトリーを移動します。 Directory.SetCurrentDirectory( targetRootPath ); // ルートフォルダーを作成するかどうか判別します。 if( targetRootFolderName != null ) { // ディレクトリーの出力先パスが既に存在するかどうか判別します。 if( Directory.Exists( targetRootFolderName ) ) { throw new Exception( $"ルートフォルダー '{targetRootFolderName}' は出力先パスに既に存在しています。削除してからやり直してください。" ); } // ルートフォルダーを作成し、カレントディレクトリーを移動します。 Directory.CreateDirectory( targetRootFolderName ); Directory.SetCurrentDirectory( targetRootFolderName ); } else { // 出力先パスにファイルやフォルダーが存在するかどうか判別します。 if( Directory.EnumerateDirectories( Directory.GetCurrentDirectory() ).Any() || Directory.EnumerateFiles( Directory.GetCurrentDirectory() ).Any() || Directory.EnumerateFileSystemEntries( Directory.GetCurrentDirectory() ).Any() ) { throw new Exception( $"出力先パス '{targetRootPath}' 内に別のファイルやフォルダーが存在しています。それらを削除するか、ディレクトリーを格納するルートフォルダーの作成を検討してください。" ); } } // SAXパーサーを使って、展開後のXMLツリーを読み込み、ディレクトリーを作成していきます。 using( var reader = XmlReader.Create( new StringReader( extractedDirectoryTree.ToString() ) ) ) { while( reader.Read() ) { switch( reader.NodeType ) { case XmlNodeType.Element: // 要素のノード // 現在のノードの子ノードから空であるかどうかの情報を取得します。 // ※ここで値を保持するのは、MoveToAttributeメソッドの実行後では、値を正しく取得できないからです。 var isEmptyElement = reader.IsEmptyElement; // 要素名を判別します。 var type = reader.Name; if( reader.MoveToAttribute( "name" ) ) { // フォルダー用のノードの時、name属性に指定した名前のフォルダーを作成し、カレントディレクトリーを移動します。 if( type == "folder" ) { var path = reader.Value; NotifyMessage( $"ディレクトリー '{path}' を作成しています。( 出力先 : {Directory.GetCurrentDirectory()} )" ); Directory.CreateDirectory( path ); Directory.SetCurrentDirectory( path ); // 子ノードが空の時、1つ親のフォルダーに移動します。 if( isEmptyElement ) { Directory.SetCurrentDirectory( "..\\" ); } } // ファイル用のノードの時、name属性に指定した名前のファイルをコピーします。 else if( type == "file" ) { var sourceFilePath = reader.Value; var targetFilePath = Path.GetFileName( sourceFilePath ); // 移動元のファイルのパスを生成します。 if( !Path.IsPathRooted( sourceFilePath ) ) { sourceFilePath = $"{definitionFilePath}\\{sourceFilePath}"; } NotifyMessage( $"ファイル '{targetFilePath}' をコピーしています。( 出力先 : {Directory.GetCurrentDirectory()} )" ); File.Copy( sourceFilePath, targetFilePath ); } } break; case XmlNodeType.EndElement: // 要素の終了ノード // フォルダー用ノードの時、1つ親のフォルダーに移動します。 if( reader.Name == "folder" ) { Directory.SetCurrentDirectory( "..\\" ); } break; } } } } finally { // アプリのパスにカレントディレクトリーを移動します。 Directory.SetCurrentDirectory( appPath ); } NotifyMessage( $"ディレクトリーの作成が完了しました。" ); } /// <summary> /// 読み込んだ定義ファイルに基づき、ディレクトリーを作成します。 /// </summary> public void GenerateDirectory() { ExtractDirectoryTree(); CreateDirectory(); } } }
29.625344
124
0.634834
[ "BSD-2-Clause" ]
Nia-TN1012/DirGen
DirGen/DirectoryGenerator.cs
15,286
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.data.dataservice.ad.offline /// </summary> public class AlipayDataDataserviceAdOfflineRequest : IAopRequest<AlipayDataDataserviceAdOfflineResponse> { /// <summary> /// 广告暂停API /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.data.dataservice.ad.offline"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.581818
108
0.605628
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Request/AlipayDataDataserviceAdOfflineRequest.cs
2,602
C#
using System; using System.Collections.Generic; using System.Data; using Paradigm.ORM.Data.Converters; using Paradigm.ORM.Data.Database; using Npgsql; using Paradigm.ORM.Data.Exceptions; namespace Paradigm.ORM.Data.PostgreSql { /// <summary> /// Provides a way to execute commands on a PostgreSQL Server Database. /// </summary> /// <seealso cref="IDatabaseCommand" /> internal partial class PostgreSqlDatabaseCommand : IDatabaseCommand { #region Properties /// <summary> /// Gets or sets the internal MySqlCommand instance. /// </summary> private NpgsqlCommand Command { get; set; } /// <summary> /// Gets or sets a reference to the current connection to the database. /// </summary> private PostgreSqlDatabaseConnector Connector { get; set; } /// <summary> /// Gets or sets the SQL statement, table name or stored procedure to execute /// at the data source. /// </summary> /// <returns> /// The SQL statement or stored procedure to execute. The default is an /// empty string. /// </returns> public string CommandText { get => this.Command.CommandText; set => this.Command.CommandText = value; } /// <summary> /// Gets or sets a value indicating how the CommandText /// property is to be interpreted. /// </summary> /// <returns> /// One of the <see cref="System.Data.CommandType" /> values. The default is Text. /// </returns> public CommandType CommandType { get => this.Command.CommandType; set => this.Command.CommandType = value; } /// <summary> /// Gets or sets the wait time before terminating the attempt to execute a command /// and generating an error. /// </summary> /// <returns> /// The time in seconds to wait for the command to execute. The default is 30 seconds. /// </returns> public int CommandTimeout { get => this.Command.CommandTimeout; set => this.Command.CommandTimeout = value; } /// <summary> /// Gets the array of parameters of this command instance. /// </summary> /// <returns> /// The parameters of the SQL statement or stored procedure. The default /// is an empty collection. /// </returns> public IEnumerable<IDbDataParameter> Parameters => this.Command.Parameters; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="PostgreSqlDatabaseCommand"/> class. /// </summary> /// <param name="command">The command.</param> /// <param name="connector">The database connector.</param> /// <exception cref="System.ArgumentNullException">command can not be null.</exception> /// <exception cref="System.ArgumentNullException">connector can not be null.</exception> internal PostgreSqlDatabaseCommand(NpgsqlCommand command, PostgreSqlDatabaseConnector connector) { this.Command = command ?? throw new ArgumentNullException(nameof(command), $"{nameof(command)} can not be null."); this.Connector = connector ?? throw new ArgumentNullException(nameof(connector), $"{nameof(connector)} can not be null."); } #endregion #region Public Methods /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this.Command?.Dispose(); this.Command = null; this.Connector = null; } /// <summary> /// Sends the CommandText to the <see cref="PostgreSqlDatabaseConnector" /> /// and builds a <see cref="PostgreSqlDatabaseReader" />. /// </summary> /// <returns> /// A database reader object. /// </returns> public IDatabaseReader ExecuteReader() { try { if (!this.Connector.IsOpen()) this.Connector.Open(); this.Command.Transaction = this.Connector.ActiveTransaction?.Transaction; this.Connector.LogProvider?.Info($"Execute Reader: {this.Command.CommandText}"); return new PostgreSqlDatabaseReader(this.Command.ExecuteReader()); } catch (Exception e) { this.Connector.LogProvider?.Error(e.Message); throw new DatabaseCommandException(this, e); } } /// <summary> /// Executes a SQL statement against the connection and returns the number /// of rows affected. /// </summary> /// <returns> /// The number of rows affected. /// </returns> public int ExecuteNonQuery() { try { if (!this.Connector.IsOpen()) this.Connector.Open(); this.Command.Transaction = this.Connector.ActiveTransaction?.Transaction; this.Connector.LogProvider?.Info($"Execute Non Query: {this.Command.CommandText}"); return this.Command.ExecuteNonQuery(); } catch (Exception e) { this.Connector.LogProvider?.Error(e.Message); throw new DatabaseCommandException(this, e); } } /// <summary> /// Executes the query, and returns the first column of the first row in the result /// set returned by the query. Additional columns or rows are ignored. /// </summary> /// <returns> /// The first column of the first row in the result set, or a null reference /// if the result set is empty. /// </returns> public object ExecuteScalar() { try { if (!this.Connector.IsOpen()) this.Connector.Open(); this.Command.Transaction = this.Connector.ActiveTransaction?.Transaction; this.Connector.LogProvider?.Info($"Execute Scalar: {this.Command.CommandText}"); return this.Command.ExecuteScalar(); } catch (Exception e) { this.Connector.LogProvider?.Error(e.Message); throw new DatabaseCommandException(this, e); } } /// <summary> /// Adds an existing parameter to the command. /// </summary> /// <param name="parameter">Parameter to add.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(IDataParameter parameter) { this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, Type type) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = DbTypeConverter.FromType(type) }; if (type == typeof(Nullable<>)) parameter.IsNullable = true; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="size">Parameter size.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, Type type, long size) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = DbTypeConverter.FromType(type), Size = (int)size }; if (type == typeof(Nullable<>)) parameter.IsNullable = true; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="precision">Parameter precision.</param> /// <param name="scale">Parameter scale.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, Type type, byte precision, byte scale) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = DbTypeConverter.FromType(type), Precision = precision, Scale = scale }; if (type == typeof(Nullable<>)) parameter.IsNullable = true; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="size">Parameter size.</param> /// <param name="precision">Parameter precision.</param> /// <param name="scale">Parameter scale.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, Type type, long size, byte precision, byte scale) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = DbTypeConverter.FromType(type), Size = (int)size, Precision = precision, Scale = scale }; if (type == typeof(Nullable<>)) parameter.IsNullable = true; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="size">Parameter size.</param> /// <param name="precision">Parameter precision.</param> /// <param name="scale">Parameter scale.</param> /// <param name="value">Parameter value</param> /// <returns> /// The reference of the parameter recently added. /// </returns> /// <exception cref="NotImplementedException"></exception> public IDataParameter AddParameter(string name, Type type, long size, byte precision, byte scale, object value) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = DbTypeConverter.FromType(type), Size = (int)size, Precision = precision, Scale = scale, Value = value ?? DBNull.Value }; if (type == typeof(Nullable<>)) parameter.IsNullable = true; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, DbType type) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = type }; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="isNullable">Indicates if the parameter is nullable.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, DbType type, bool isNullable) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = type, IsNullable = isNullable }; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="size">Parameter size.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, DbType type, long size) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = type, Size = (int)size }; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="size">Parameter size.</param> /// <param name="isNullable">Indicates if the parameter is nullable.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, DbType type, int size, bool isNullable) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = type, Size = size, IsNullable = isNullable }; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="precision">Parameter precision.</param> /// <param name="scale">Parameter scale.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, DbType type, byte precision, byte scale) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = type, Precision = precision, Scale = scale }; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="size">Parameter size.</param> /// <param name="precision">Parameter precision.</param> /// <param name="scale">Parameter scale.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, DbType type, long size, byte precision, byte scale) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = type, Size = (int)size, Precision = precision, Scale = scale }; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="precision">Parameter precision.</param> /// <param name="scale">Parameter scale.</param> /// <param name="isNullable">Indicates if the parameter is nullable.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, DbType type, byte precision, byte scale, bool isNullable) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = type, Precision = precision, Scale = scale, IsNullable = isNullable }; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="size">Parameter size.</param> /// <param name="precision">Parameter precision.</param> /// <param name="scale">Parameter scale.</param> /// <param name="isNullable">Indicates if the parameter is nullable.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, DbType type, long size, byte precision, byte scale, bool isNullable) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = type, Size = (int)size, Precision = precision, Scale = scale, IsNullable = isNullable }; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Adds a new parameter to the command. /// </summary> /// <param name="name">Parameter name.</param> /// <param name="type">Parameter type.</param> /// <param name="size">Parameter size.</param> /// <param name="precision">Parameter precision.</param> /// <param name="scale">Parameter scale.</param> /// <param name="isNullable">Indicates if the parameter is nullable.</param> /// <param name="value">Parameter value.</param> /// <returns> /// The reference of the parameter recently added. /// </returns> public IDataParameter AddParameter(string name, DbType type, long size, byte precision, byte scale, bool isNullable, object value) { var parameter = new NpgsqlParameter { ParameterName = name, DbType = type, Size = (int)size, Precision = precision, Scale = scale, IsNullable = isNullable, Value = value ?? DBNull.Value }; this.Command.Parameters.Add(parameter); return parameter; } /// <summary> /// Gets a parameter by index. /// </summary> /// <param name="index">Parameter index.</param> /// <returns> /// The reference of the parameter. /// </returns> public IDataParameter GetParameter(int index) { return this.Command.Parameters[index]; } /// <summary> /// Gets a parameter by name. /// </summary> /// <param name="name">Parameter name.</param> /// <returns> /// The reference of the parameter. /// </returns> public IDataParameter GetParameter(string name) { return this.Command.Parameters[name]; } /// <summary> /// Clears the parameters. /// </summary> public void ClearParameters() { this.Command.Parameters.Clear(); } #endregion } }
35.977509
138
0.539601
[ "MIT" ]
MiracleDevs/Paradigm.ORM
src/Paradigm.ORM.Data.PostgreSql/PostgreSqlDatabaseCommand.cs
20,795
C#
using Halcyon.HAL.Attributes; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using Threax.AspNetCore.Halcyon.Ext; using Threax.AspNetCore.UserBuilder.Entities; using Threax.AspNetCore.UserBuilder.Entities.Mvc; namespace DevApp.Controllers.Api { [Route("api/[controller]")] [ResponseCache(NoStore = true)] public class RolesController : RolesControllerBase<RoleAssignments, UserCollection> { public RolesController(IRoleManager roleManager, IHttpContextAccessor contextAccessor) : base(roleManager, contextAccessor) { } protected override UserCollection GetUserCollection(RolesQuery query, int total, IEnumerable<RoleAssignments> users) { return new UserCollection(query, total, users); } } [HalModel] [HalSelfActionLink(RolesControllerRels.ListUsers, typeof(RolesController))] [DeclareHalLink(PagedCollectionView<Object>.Rels.Next, RolesControllerRels.ListUsers, typeof(RolesController), ResponseOnly = true)] [DeclareHalLink(PagedCollectionView<Object>.Rels.Previous, RolesControllerRels.ListUsers, typeof(RolesController), ResponseOnly = true)] [DeclareHalLink(PagedCollectionView<Object>.Rels.First, RolesControllerRels.ListUsers, typeof(RolesController), ResponseOnly = true)] [DeclareHalLink(PagedCollectionView<Object>.Rels.Last, RolesControllerRels.ListUsers, typeof(RolesController), ResponseOnly = true)] public class UserCollection : UserCollectionBase<RoleAssignments> { public UserCollection(RolesQuery query, int total, IEnumerable<RoleAssignments> items) : base(query, total, items) { } } }
42.146341
140
0.755787
[ "Apache-2.0" ]
threax/AspNetCore.Swashbuckle.Convention
src/DevApp/Controllers/Api/RolesController.cs
1,730
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("GS.WeeklyReport.Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GS.WeeklyReport.Common")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("0d1cc52c-93c9-4ff3-85ca-716ea90fe45a")] // 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.297297
84
0.745942
[ "Apache-2.0" ]
Tyler-Wu/weekly
GS.WeeklyReport.Common/Properties/AssemblyInfo.cs
1,420
C#
#pragma checksum "..\..\..\..\..\Views\Data\MainData.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5D1A1845EA31868A158D7ED919374ABC110516F1" //------------------------------------------------------------------------------ // <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 Kindergarten.ViewModels.DataViewModels; using Kindergarten.Views.Data; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Controls.Ribbon; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace Kindergarten.Views.Data { /// <summary> /// MainData /// </summary> public partial class MainData : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector { private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.8.1.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/Kindergarten;component/views/data/maindata.xaml", System.UriKind.Relative); #line 1 "..\..\..\..\..\Views\Data\MainData.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.8.1.0")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal System.Delegate _CreateDelegate(System.Type delegateType, string handler) { return System.Delegate.CreateDelegate(delegateType, this, handler); } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.8.1.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { this._contentLoaded = true; } } }
42.2
143
0.680513
[ "Unlicense" ]
AlexanderAndrenko/Univer-programming--project-
Kindergarten/Kindergarten/obj/Debug/net472/Views/Data/MainData.g.i.cs
3,589
C#
using System; using System.Security.Principal; using System.Web; using System.Web.Hosting; namespace MongoDB.Messaging.Security { /// <summary> /// A class to get user information /// </summary> public static class UserHelper { private static string GetCurrentUserName() { if (!HostingEnvironment.IsHosted) return Environment.UserName; IPrincipal currentUser = null; HttpContext current = HttpContext.Current; if (current != null) currentUser = current.User; if ((currentUser != null)) return currentUser.Identity.Name; return Environment.UserName; } /// <summary> /// Gets the current logged in user name /// </summary> /// <returns>The current user name</returns> public static string Current() { string username = GetCurrentUserName(); string name = username; var parts = username.Split('\\'); if (parts.Length == 2) name = parts[1]; return name; } } }
25.304348
54
0.547251
[ "Apache-2.0" ]
IsaacSee/MongoDB.Messaging
Source/MongoDB.Messaging/Security/UserHelper.cs
1,166
C#
using System.Runtime.CompilerServices; using System.Xml; namespace System.Html.Speech { [Imported, Serializable] public partial class SpeechRecognitionEventInit : EventInit { public DocumentBase Emma { get; set; } public string Interpretation { get; set; } public int ResultIndex { get; set; } public object Results { get; set; } } }
13.642857
62
0.672775
[ "Apache-2.0" ]
Saltarelle/SaltarelleWeb
Web/Generated/Html/Speech/SpeechRecognitionEventInit.cs
384
C#
using System; using System.Collections.Generic; using System.Linq; using Autodesk.Revit.DB; using Objects.BuiltElements.Revit; using Speckle.Core.Models; using DB = Autodesk.Revit.DB; using Mesh = Objects.Geometry.Mesh; namespace Objects.Converter.Revit { public partial class ConverterRevit { public List<ApplicationPlaceholderObject> WallToNative(BuiltElements.Wall speckleWall) { if (speckleWall.baseLine == null) { throw new Speckle.Core.Logging.SpeckleException("Only line based Walls are currently supported."); } var revitWall = GetExistingElementByApplicationId(speckleWall.applicationId) as DB.Wall; var wallType = GetElementType<WallType>(speckleWall); Level level = null; var structural = false; var baseCurve = CurveToNative(speckleWall.baseLine).get_Item(0); if (speckleWall is RevitWall speckleRevitWall) { level = LevelToNative(speckleRevitWall.level); structural = speckleRevitWall.structural; } else { level = LevelToNative(LevelFromCurve(baseCurve)); } //if it's a new element, we don't need to update certain properties bool isUpdate = true; if (revitWall == null) { isUpdate = false; revitWall = DB.Wall.Create(Doc, baseCurve, level.Id, structural); } if (revitWall == null) { ConversionErrors.Add(new Exception($"Failed to create wall ${speckleWall.applicationId}.")); return null; } //is structural update TrySetParam(revitWall, BuiltInParameter.WALL_STRUCTURAL_SIGNIFICANT, structural); if (revitWall.WallType.Name != wallType.Name) { revitWall.ChangeTypeId(wallType.Id); } if (isUpdate) { //NOTE: updating an element location can be buggy if the baseline and level elevation don't match //Let's say the first time an element is created its base point/curve is @ 10m and the Level is @ 0m //the element will be created @ 0m //but when this element is updated (let's say with no changes), it will jump @ 10m (unless there is a level change)! //to avoid this behavior we're moving the base curve to match the level elevation var newz = baseCurve.GetEndPoint(0).Z; var offset = level.Elevation - newz; var newCurve = baseCurve; if (Math.Abs(offset) > 0.0164042) // level and curve are not at the same height { newCurve = baseCurve.CreateTransformed(Transform.CreateTranslation(new XYZ(0, 0, offset))); } ((LocationCurve)revitWall.Location).Curve = newCurve; TrySetParam(revitWall, BuiltInParameter.WALL_BASE_CONSTRAINT, level); } if (speckleWall is RevitWall spklRevitWall) { if (spklRevitWall.flipped != revitWall.Flipped) { revitWall.Flip(); } if (spklRevitWall.topLevel != null) { var topLevel = LevelToNative(spklRevitWall.topLevel); TrySetParam(revitWall, BuiltInParameter.WALL_HEIGHT_TYPE, topLevel); } else { TrySetParam(revitWall, BuiltInParameter.WALL_USER_HEIGHT_PARAM, speckleWall.height, speckleWall.units); } TrySetParam(revitWall, BuiltInParameter.WALL_BASE_OFFSET, spklRevitWall.baseOffset, speckleWall.units); TrySetParam(revitWall, BuiltInParameter.WALL_TOP_OFFSET, spklRevitWall.topOffset, speckleWall.units); } else // Set wall unconnected height. { TrySetParam(revitWall, BuiltInParameter.WALL_USER_HEIGHT_PARAM, speckleWall.height, speckleWall.units); } SetInstanceParameters(revitWall, speckleWall); var placeholders = new List<ApplicationPlaceholderObject>() { new ApplicationPlaceholderObject { applicationId = speckleWall.applicationId, ApplicationGeneratedId = revitWall.UniqueId, NativeObject = revitWall } }; var hostedElements = SetHostedElements(speckleWall, revitWall); placeholders.AddRange(hostedElements); return placeholders; } public Base WallToSpeckle(DB.Wall revitWall) { var baseGeometry = LocationToSpeckle(revitWall); if (baseGeometry is Geometry.Point) { return RevitElementToSpeckle(revitWall); } RevitWall speckleWall = new RevitWall(); speckleWall.family = revitWall.WallType.FamilyName.ToString(); speckleWall.type = revitWall.WallType.Name; speckleWall.baseLine = (ICurve)baseGeometry; speckleWall.level = ConvertAndCacheLevel(revitWall, BuiltInParameter.WALL_BASE_CONSTRAINT); speckleWall.topLevel = ConvertAndCacheLevel(revitWall, BuiltInParameter.WALL_HEIGHT_TYPE); speckleWall.height = GetParamValue<double>(revitWall, BuiltInParameter.WALL_USER_HEIGHT_PARAM); speckleWall.baseOffset = GetParamValue<double>(revitWall, BuiltInParameter.WALL_BASE_OFFSET); speckleWall.topOffset = GetParamValue<double>(revitWall, BuiltInParameter.WALL_TOP_OFFSET); speckleWall.structural = GetParamValue<bool>(revitWall, BuiltInParameter.WALL_STRUCTURAL_SIGNIFICANT); speckleWall.flipped = revitWall.Flipped; if (revitWall.CurtainGrid == null) { if ( revitWall.IsStackedWall ) { var wallMembers = revitWall.GetStackedWallMemberIds().Select(id => (Wall)Doc.GetElement(id)); speckleWall.elements = new List<Base>(); foreach ( var wall in wallMembers ) speckleWall.elements.Add(WallToSpeckle(wall)); } speckleWall.displayMesh = GetElementDisplayMesh(revitWall, new Options() {DetailLevel = ViewDetailLevel.Fine, ComputeReferences = false}); } else { // curtain walls have two meshes, one for panels and one for mullions // adding mullions as sub-elements so they can be correctly displayed in viewers etc (var panelsMesh, var mullionsMesh) = GetCurtainWallDisplayMesh(revitWall); speckleWall["renderMaterial"] = new Other.RenderMaterial() { opacity = 0.2, diffuse = System.Drawing.Color.AliceBlue.ToArgb() }; speckleWall.displayMesh = panelsMesh; var mullions = new Base { [ "@displayMesh" ] = mullionsMesh, [ "renderMaterial" ] = new Other.RenderMaterial() {diffuse = System.Drawing.Color.DarkGray.ToArgb()} }; speckleWall.elements = new List<Base> { mullions }; } GetAllRevitParamsAndIds(speckleWall, revitWall, new List<string> { "WALL_USER_HEIGHT_PARAM", "WALL_BASE_OFFSET", "WALL_TOP_OFFSET", "WALL_BASE_CONSTRAINT", "WALL_HEIGHT_TYPE", "WALL_STRUCTURAL_SIGNIFICANT" }); GetHostedElements(speckleWall, revitWall); return speckleWall; } private (Mesh, Mesh) GetCurtainWallDisplayMesh(DB.Wall wall) { var grid = wall.CurtainGrid; var meshPanels = new Mesh(); var meshMullions = new Mesh(); var solidPanels = new List<Solid>(); var solidMullions = new List<Solid>(); foreach (ElementId panelId in grid.GetPanelIds()) { solidPanels.AddRange(GetElementSolids(Doc.GetElement(panelId))); } foreach (ElementId mullionId in grid.GetMullionIds()) { solidMullions.AddRange(GetElementSolids(Doc.GetElement(mullionId))); } (meshPanels.faces, meshPanels.vertices) = GetFaceVertexArrFromSolids(solidPanels); (meshMullions.faces, meshMullions.vertices) = GetFaceVertexArrFromSolids(solidMullions); meshPanels.units = ModelUnits; meshMullions.units = ModelUnits; return (meshPanels, meshMullions); } } }
35.268182
136
0.67354
[ "Apache-2.0" ]
dtnaughton/speckle-sharp
Objects/Converters/ConverterRevit/ConverterRevitShared/Partial Classes/ConvertWall.cs
7,761
C#
using System.Linq; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.OData; using Microsoft.WindowsAzure.Mobile.Service; using AJTaskManagerServiceService.DataObjects; using AJTaskManagerServiceService.Models; namespace AJTaskManagerServiceService.Controllers { public class GroupController : TableController<Group> { protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); AJTaskManagerServiceContext context = new AJTaskManagerServiceContext(); DomainManager = new EntityDomainManager<Group>(context, Request, Services); } // GET tables/Group public IQueryable<Group> GetAllGroup() { return Query(); } // GET tables/Group/48D68C86-6EA6-4C25-AA33-223FC9A27959 public SingleResult<Group> GetGroup(string id) { return Lookup(id); } // PATCH tables/Group/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task<Group> PatchGroup(string id, Delta<Group> patch) { return UpdateAsync(id, patch); } // POST tables/Group public async Task<IHttpActionResult> PostGroup(Group item) { Group current = await InsertAsync(item); return CreatedAtRoute("Tables", new { id = current.Id }, current); } // DELETE tables/Group/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task DeleteGroup(string id) { return DeleteAsync(id); } } }
30.886792
87
0.651191
[ "Apache-2.0" ]
qbasko/AJTaskManager
AJTaskManagerService/AJTaskManagerServiceService/Controllers/GroupController.cs
1,639
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cus.Entities.Entities { public class Order_details { public int OrderID {get; set;} public int ProductID {get; set;} public decimal UnitPrice {get; set;} public object Quantity {get; set;} public object Discount {get; set;} } }
18.833333
38
0.731563
[ "Unlicense" ]
wugelis/Cus.WebForm
Cus.Entities/Entities/Order_details.cs
339
C#
// <copyright file="FhirUtils.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // </copyright> using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using static Microsoft.Health.Fhir.SpecManager.Models.FhirTypeBase; namespace Microsoft.Health.Fhir.SpecManager.Models { /// <summary>A fhir utilities.</summary> public abstract class FhirUtils { /// <summary>The RegEx remove duplicate lines.</summary> private const string _regexRemoveDuplicateLinesDefinition = "__+"; /// <summary>The RegEx remove duplicate lines.</summary> private static Regex _regexRemoveDuplicateLines = new Regex(_regexRemoveDuplicateLinesDefinition); /// <summary>Converts this object to a convention.</summary> /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception> /// <exception cref="ArgumentException"> Thrown when one or more arguments have unsupported or /// illegal values.</exception> /// <param name="name"> The value.</param> /// <param name="path"> Full pathname of the file.</param> /// <param name="convention"> The convention.</param> /// <param name="concatenatePath"> (Optional) True to concatenate path.</param> /// <param name="concatenationDelimiter">(Optional) The concatenation delimiter.</param> /// <returns>The given data converted to a string.</returns> public static string ToConvention( string name, string path, NamingConvention convention, bool concatenatePath = false, string concatenationDelimiter = "") { string value = name; if (concatenatePath && (!string.IsNullOrEmpty(path))) { value = path; } if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException(nameof(name)); } switch (convention) { case NamingConvention.FhirDotNotation: return value; case NamingConvention.PascalDotNotation: { string[] components = ToPascal(value.Split('.')); return string.Join(".", components); } case NamingConvention.PascalCase: { string[] components = ToPascal(value.Split('.')); return string.Join(concatenationDelimiter, components); } case NamingConvention.CamelCase: { string[] components = ToCamel(value.Split('.')); return string.Join(concatenationDelimiter, components); } case NamingConvention.UpperCase: { string[] components = ToUpperInvariant(value.Split('.')); return string.Join(concatenationDelimiter, components); } case NamingConvention.LowerCase: { string[] components = ToLowerInvariant(value.Split('.')); return string.Join(concatenationDelimiter, components); } case NamingConvention.None: default: throw new ArgumentException($"Invalid Naming Convention: {convention}"); } } /// <summary>Sanitized to convention.</summary> /// <param name="sanitized"> The sanitized.</param> /// <param name="convention">The convention.</param> /// <returns>A string.</returns> public static string SanitizedToConvention(string sanitized, NamingConvention convention) { if (string.IsNullOrEmpty(sanitized)) { throw new ArgumentNullException(nameof(sanitized)); } switch (convention) { case NamingConvention.FhirDotNotation: return sanitized.Replace('_', '.'); case NamingConvention.PascalDotNotation: { string[] components = ToPascal(sanitized.Split('_')); return string.Join(".", components); } case NamingConvention.PascalCase: { string[] components = ToPascal(sanitized.Split('_')); return string.Join(string.Empty, components); } case NamingConvention.CamelCase: { string[] components = ToCamel(sanitized.Split('_')); return string.Join(string.Empty, components); } case NamingConvention.UpperCase: { return sanitized.ToUpperInvariant(); } case NamingConvention.LowerCase: { return sanitized.ToLowerInvariant(); } case NamingConvention.None: default: throw new ArgumentException($"Invalid Naming Convention: {convention}"); } } /// <summary>Sanitize for quoted.</summary> /// <param name="input">The input.</param> /// <returns>A string.</returns> public static string SanitizeForQuoted(string input) { if (string.IsNullOrEmpty(input)) { return string.Empty; } input = input.Replace("\"", "\\\""); input = input.Replace("\r", "\\r"); input = input.Replace("\n", "\\n"); return input; } /// <summary>Sanitize for code.</summary> /// <param name="input"> The input.</param> /// <param name="reservedWords">The reserved words.</param> /// <param name="name"> [out] The sanitized name for the code.</param> /// <param name="value"> [out] The sanitized value for the code.</param> public static void SanitizeForCode( string input, HashSet<string> reservedWords, out string name, out string value) { if (string.IsNullOrEmpty(input)) { name = string.Empty; value = string.Empty; return; } name = input.Trim(); if (name.Contains(" ")) { name = name.Substring(0, name.IndexOf(' ')); } value = name; name = SanitizeForProperty(name, reservedWords); } /// <summary>Sanitize for value.</summary> /// <param name="input">The input.</param> /// <returns>A string.</returns> public static string SanitizeForValue(string input) { if (string.IsNullOrEmpty(input)) { return string.Empty; } string value = input.Trim(); value = value.Replace("\"", "\\\""); return value; } /// <summary>Requires alpha.</summary> /// <param name="value">The value.</param> /// <returns>True if it succeeds, false if it fails.</returns> private static bool RequiresAlpha(string value) { if (string.IsNullOrEmpty(value)) { return true; } if (value[0] == '_') { return true; } if (!char.IsLetter(value[0])) { return true; } return false; } /// <summary>Sanitize for property.</summary> /// <param name="value"> The value.</param> /// <param name="reservedWords">The reserved words.</param> /// <returns>A string.</returns> public static string SanitizeForProperty( string value, HashSet<string> reservedWords) { if (string.IsNullOrEmpty(value)) { return "NONE"; } if (value.StartsWith("http://hl7.org/fhir/", StringComparison.Ordinal)) { value = value.Substring(20); } StringBuilder sb = new StringBuilder(); int valueLen = value.Length; for (int i = 0; i < valueLen; i++) { char ch = value[i]; char second = (i + 1 < valueLen) ? value[i + 1] : '\0'; char third = (i + 2 < valueLen) ? value[i + 2] : '\0'; switch (ch) { case '.': if ((second == '.') && (third == '.')) { sb.Append("_ellipsis_"); i += 2; continue; } sb.Append('_'); break; case '’': case '\'': if (second == '\'') { sb.Append("_double_quote_"); i++; continue; } sb.Append("_quote_"); break; case '=': if (second == '=') { sb.Append("_double_equals_"); i++; continue; } sb.Append("_equals_"); break; case '!': if (second == '=') { sb.Append("_not_equals_"); i++; continue; } sb.Append("_not_"); break; case '<': if (second == '=') { sb.Append("_less_than_or_equals_"); i++; continue; } sb.Append("_less_than_"); break; case '>': if (second == '=') { sb.Append("_greater_than_or_equals_"); i++; continue; } sb.Append("_greater_than_"); break; case '…': sb.Append("_ellipsis_unicode_"); break; case '*': sb.Append("_asterisk_"); break; case '^': sb.Append("_power_"); break; case '#': sb.Append("_number_"); break; case '$': sb.Append("_dollar_"); break; case '%': sb.Append("_percent_"); break; case '&': sb.Append("_and_"); break; case '@': sb.Append("_at_"); break; case '+': sb.Append("_plus_"); break; case '{': sb.Append("_"); // sb.Append("_open_brace_"); break; case '}': sb.Append("_"); // sb.Append("_close_brace_"); break; case '[': sb.Append("_"); // sb.Append("_open_bracket_"); break; case ']': sb.Append("_"); // sb.Append("_close_bracket_"); break; case '(': sb.Append("_"); // sb.Append("_open_parenthesis_"); break; case ')': sb.Append("_"); // sb.Append("_close_parenthesis_"); break; case '\\': sb.Append("_"); // sb.Append("_backslash_"); break; case '/': if (i == 0) { sb.Append("Per"); } else { sb.Append("_"); // sb.Append("_slash_"); } break; case '|': sb.Append("_pipe_"); break; case ':': sb.Append("_"); // sb.Append("_colon_"); break; case ';': sb.Append("_"); // sb.Append("_semicolon_"); break; case ',': sb.Append("_"); // sb.Append("_comma_"); break; case '°': sb.Append("_degrees_"); break; case '?': sb.Append("_question_"); break; case '"': case '“': case '”': sb.Append("_quotation_"); break; case ' ': case '-': case '–': case '—': case '_': if (sb.Length != 0) { sb.Append('_'); } break; case '\r': case '\n': break; default: if (ch < 128) { sb.Append(ch); } break; } } value = sb.ToString(); // remove duplicate underscores caused by prior replacements value = _regexRemoveDuplicateLines.Replace(value, "_"); while (value.StartsWith("_", StringComparison.Ordinal)) { value = value.Substring(1); } while (value.EndsWith("_", StringComparison.Ordinal)) { value = value.Remove(value.Length - 1); } // need to check for all digits or underscores, or reserved word if (RequiresAlpha(value) || ((reservedWords != null) && reservedWords.Contains(value))) { if (value[0] == '_') { return $"VAL{value}"; } return $"VAL_{value}"; } return value; } } }
32.385396
116
0.39296
[ "MIT" ]
FirelyTeam/fhir-codegen
src/Microsoft.Health.Fhir.SpecManager/Models/FhirUtils.cs
15,981
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 OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Region.Framework.Scenes; using System.Collections; using System.Collections.Generic; using System.Text; namespace OpenSim.Region.UserStatistics { public class SimStatsAJAX : IStatsController { #region IStatsController Members public string ReportName { get { return ""; } } public Hashtable ProcessModel(Hashtable pParams) { List<Scene> m_scene = (List<Scene>)pParams["Scenes"]; Hashtable nh = new Hashtable(); nh.Add("hdata", m_scene); nh.Add("simstats", pParams["SimStats"]); return nh; } public string RenderView(Hashtable pModelResult) { StringBuilder output = new StringBuilder(); List<Scene> all_scenes = (List<Scene>) pModelResult["hdata"]; Dictionary<UUID, USimStatsData> sdatadic = (Dictionary<UUID,USimStatsData>)pModelResult["simstats"]; const string TableClass = "defaultr"; const string TRClass = "defaultr"; const string TDHeaderClass = "header"; const string TDDataClass = "content"; //const string TDDataClassRight = "contentright"; const string TDDataClassCenter = "contentcenter"; foreach (USimStatsData sdata in sdatadic.Values) { foreach (Scene sn in all_scenes) { if (sn.RegionInfo.RegionID == sdata.RegionId) { output.Append("<H2>"); output.Append(sn.RegionInfo.RegionName); output.Append("</H2>"); } } HTMLUtil.TABLE_O(ref output, TableClass); HTMLUtil.TR_O(ref output, TRClass); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("Dilatn"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("SimFPS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("PhysFPS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("AgntUp"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("RootAg"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("ChldAg"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("Prims"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("ATvPrm"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("AtvScr"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("ScrLPS"); HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); HTMLUtil.TR_O(ref output, TRClass); HTMLUtil.TD_O(ref output, TDDataClass); output.Append(sdata.TimeDilation); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClass); output.Append(sdata.SimFps); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.PhysicsFps); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.AgentUpdates); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.RootAgents); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.ChildAgents); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.TotalPrims); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.ActivePrims); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.ActiveScripts); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.ScriptLinesPerSecond); HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); HTMLUtil.TR_O(ref output, TRClass); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("FrmMS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("AgtMS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("PhysMS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("OthrMS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("ScrLPS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("OutPPS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("InPPS"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("NoAckKB"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("PndDWN"); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDHeaderClass); output.Append("PndUP"); HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); HTMLUtil.TR_O(ref output, TRClass); HTMLUtil.TD_O(ref output, TDDataClass); output.Append(sdata.TotalFrameTime); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClass); output.Append(sdata.AgentFrameTime); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.PhysicsFrameTime); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.OtherFrameTime); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.ScriptLinesPerSecond); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.OutPacketsPerSecond); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.InPacketsPerSecond); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.UnackedBytes); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.PendingDownloads); HTMLUtil.TD_C(ref output); HTMLUtil.TD_O(ref output, TDDataClassCenter); output.Append(sdata.PendingUploads); HTMLUtil.TD_C(ref output); HTMLUtil.TR_C(ref output); HTMLUtil.TABLE_C(ref output); } return output.ToString(); } /// <summary> /// Return stat information for all regions in the sim. Returns data of the form: /// <pre> /// {"REGIONNAME": { /// "region": "REGIONNAME", /// "timeDilation": "101", /// ... // the rest of the stat info /// }, /// ... // entries for each region /// } /// </pre> /// </summary> /// <param name="pModelResult"></param> /// <returns></returns> public string RenderJson(Hashtable pModelResult) { List<Scene> all_scenes = (List<Scene>) pModelResult["hdata"]; Dictionary<UUID, USimStatsData> sdatadic = (Dictionary<UUID,USimStatsData>)pModelResult["simstats"]; OSDMap allStatsInfo = new OpenMetaverse.StructuredData.OSDMap(); foreach (USimStatsData sdata in sdatadic.Values) { OSDMap statsInfo = new OpenMetaverse.StructuredData.OSDMap(); string regionName = "unknown"; foreach (Scene sn in all_scenes) { if (sn.RegionInfo.RegionID == sdata.RegionId) { regionName = sn.RegionInfo.RegionName; break; } } statsInfo.Add("region", new OSDString(regionName)); statsInfo.Add("timeDilation", new OSDString(sdata.TimeDilation.ToString())); statsInfo.Add("simFPS", new OSDString(sdata.SimFps.ToString())); statsInfo.Add("physicsFPS", new OSDString(sdata.PhysicsFps.ToString())); statsInfo.Add("agentUpdates", new OSDString(sdata.AgentUpdates.ToString())); statsInfo.Add("rootAgents", new OSDString(sdata.RootAgents.ToString())); statsInfo.Add("childAgents", new OSDString(sdata.ChildAgents.ToString())); statsInfo.Add("totalPrims", new OSDString(sdata.TotalPrims.ToString())); statsInfo.Add("activePrims", new OSDString(sdata.ActivePrims.ToString())); statsInfo.Add("activeScripts", new OSDString(sdata.ActiveScripts.ToString())); statsInfo.Add("scriptLinesPerSec", new OSDString(sdata.ScriptLinesPerSecond.ToString())); statsInfo.Add("totalFrameTime", new OSDString(sdata.TotalFrameTime.ToString())); statsInfo.Add("agentFrameTime", new OSDString(sdata.AgentFrameTime.ToString())); statsInfo.Add("physicsFrameTime", new OSDString(sdata.PhysicsFrameTime.ToString())); statsInfo.Add("otherFrameTime", new OSDString(sdata.OtherFrameTime.ToString())); statsInfo.Add("outPacketsPerSec", new OSDString(sdata.OutPacketsPerSecond.ToString())); statsInfo.Add("inPacketsPerSec", new OSDString(sdata.InPacketsPerSecond.ToString())); statsInfo.Add("unackedByptes", new OSDString(sdata.UnackedBytes.ToString())); statsInfo.Add("pendingDownloads", new OSDString(sdata.PendingDownloads.ToString())); statsInfo.Add("pendingUploads", new OSDString(sdata.PendingUploads.ToString())); allStatsInfo.Add(regionName, statsInfo); } return allStatsInfo.ToString(); } #endregion } }
47.623656
112
0.577632
[ "BSD-3-Clause" ]
Michelle-Argus/ArribasimExtract
OpenSim/Region/UserStatistics/SimStatsAJAX.cs
13,287
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace BotesPesqueros { static class Program { /// <summary> /// Punto de entrada principal para la aplicación. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
22.521739
65
0.617761
[ "MIT" ]
JoseLuisRojasAranda/Visual-Practicas
BotesPesqueros/BotesPesqueros/Program.cs
521
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Compute.Models; using Azure.ResourceManager.Resources; namespace Azure.ResourceManager.Compute { /// <summary> /// A class representing a collection of <see cref="VirtualMachineResource" /> and their operations. /// Each <see cref="VirtualMachineResource" /> in the collection will belong to the same instance of <see cref="ResourceGroupResource" />. /// To get a <see cref="VirtualMachineCollection" /> instance call the GetVirtualMachines method from an instance of <see cref="ResourceGroupResource" />. /// </summary> public partial class VirtualMachineCollection : ArmCollection, IEnumerable<VirtualMachineResource>, IAsyncEnumerable<VirtualMachineResource> { private readonly ClientDiagnostics _virtualMachineClientDiagnostics; private readonly VirtualMachinesRestOperations _virtualMachineRestClient; /// <summary> Initializes a new instance of the <see cref="VirtualMachineCollection"/> class for mocking. </summary> protected VirtualMachineCollection() { } /// <summary> Initializes a new instance of the <see cref="VirtualMachineCollection"/> class. </summary> /// <param name="client"> The client parameters to use in these operations. </param> /// <param name="id"> The identifier of the parent resource that is the target of operations. </param> internal VirtualMachineCollection(ArmClient client, ResourceIdentifier id) : base(client, id) { _virtualMachineClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Compute", VirtualMachineResource.ResourceType.Namespace, Diagnostics); TryGetApiVersion(VirtualMachineResource.ResourceType, out string virtualMachineApiVersion); _virtualMachineRestClient = new VirtualMachinesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, virtualMachineApiVersion); #if DEBUG ValidateResourceId(Id); #endif } internal static void ValidateResourceId(ResourceIdentifier id) { if (id.ResourceType != ResourceGroupResource.ResourceType) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceGroupResource.ResourceType), nameof(id)); } /// <summary> /// The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName} /// Operation Id: VirtualMachines_CreateOrUpdate /// </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="vmName"> The name of the virtual machine. </param> /// <param name="data"> Parameters supplied to the Create Virtual Machine operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="vmName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="vmName"/> or <paramref name="data"/> is null. </exception> public virtual async Task<ArmOperation<VirtualMachineResource>> CreateOrUpdateAsync(WaitUntil waitUntil, string vmName, VirtualMachineData data, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(vmName, nameof(vmName)); Argument.AssertNotNull(data, nameof(data)); using var scope = _virtualMachineClientDiagnostics.CreateScope("VirtualMachineCollection.CreateOrUpdate"); scope.Start(); try { var response = await _virtualMachineRestClient.CreateOrUpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, vmName, data, cancellationToken).ConfigureAwait(false); var operation = new ComputeArmOperation<VirtualMachineResource>(new VirtualMachineOperationSource(Client), _virtualMachineClientDiagnostics, Pipeline, _virtualMachineRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, vmName, data).Request, response, OperationFinalStateVia.Location); if (waitUntil == WaitUntil.Completed) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// The operation to create or update a virtual machine. Please note some properties can be set only during virtual machine creation. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName} /// Operation Id: VirtualMachines_CreateOrUpdate /// </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="vmName"> The name of the virtual machine. </param> /// <param name="data"> Parameters supplied to the Create Virtual Machine operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="vmName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="vmName"/> or <paramref name="data"/> is null. </exception> public virtual ArmOperation<VirtualMachineResource> CreateOrUpdate(WaitUntil waitUntil, string vmName, VirtualMachineData data, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(vmName, nameof(vmName)); Argument.AssertNotNull(data, nameof(data)); using var scope = _virtualMachineClientDiagnostics.CreateScope("VirtualMachineCollection.CreateOrUpdate"); scope.Start(); try { var response = _virtualMachineRestClient.CreateOrUpdate(Id.SubscriptionId, Id.ResourceGroupName, vmName, data, cancellationToken); var operation = new ComputeArmOperation<VirtualMachineResource>(new VirtualMachineOperationSource(Client), _virtualMachineClientDiagnostics, Pipeline, _virtualMachineRestClient.CreateCreateOrUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, vmName, data).Request, response, OperationFinalStateVia.Location); if (waitUntil == WaitUntil.Completed) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Retrieves information about the model view or the instance view of a virtual machine. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName} /// Operation Id: VirtualMachines_Get /// </summary> /// <param name="vmName"> The name of the virtual machine. </param> /// <param name="expand"> The expand expression to apply on the operation. &apos;InstanceView&apos; retrieves a snapshot of the runtime properties of the virtual machine that is managed by the platform and can change outside of control plane operations. &apos;UserData&apos; retrieves the UserData property as part of the VM model view that was provided by the user during the VM Create/Update operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="vmName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="vmName"/> is null. </exception> public virtual async Task<Response<VirtualMachineResource>> GetAsync(string vmName, InstanceViewTypes? expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(vmName, nameof(vmName)); using var scope = _virtualMachineClientDiagnostics.CreateScope("VirtualMachineCollection.Get"); scope.Start(); try { var response = await _virtualMachineRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, vmName, expand, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw new RequestFailedException(response.GetRawResponse()); return Response.FromValue(new VirtualMachineResource(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Retrieves information about the model view or the instance view of a virtual machine. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName} /// Operation Id: VirtualMachines_Get /// </summary> /// <param name="vmName"> The name of the virtual machine. </param> /// <param name="expand"> The expand expression to apply on the operation. &apos;InstanceView&apos; retrieves a snapshot of the runtime properties of the virtual machine that is managed by the platform and can change outside of control plane operations. &apos;UserData&apos; retrieves the UserData property as part of the VM model view that was provided by the user during the VM Create/Update operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="vmName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="vmName"/> is null. </exception> public virtual Response<VirtualMachineResource> Get(string vmName, InstanceViewTypes? expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(vmName, nameof(vmName)); using var scope = _virtualMachineClientDiagnostics.CreateScope("VirtualMachineCollection.Get"); scope.Start(); try { var response = _virtualMachineRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, vmName, expand, cancellationToken); if (response.Value == null) throw new RequestFailedException(response.GetRawResponse()); return Response.FromValue(new VirtualMachineResource(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Lists all of the virtual machines in the specified resource group. Use the nextLink property in the response to get the next page of virtual machines. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines /// Operation Id: VirtualMachines_List /// </summary> /// <param name="filter"> The system query option to filter VMs returned in the response. Allowed value is &apos;virtualMachineScaleSet/id&apos; eq /subscriptions/{subId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmssName}&apos;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="VirtualMachineResource" /> that may take multiple service requests to iterate over. </returns> public virtual AsyncPageable<VirtualMachineResource> GetAllAsync(string filter = null, CancellationToken cancellationToken = default) { async Task<Page<VirtualMachineResource>> FirstPageFunc(int? pageSizeHint) { using var scope = _virtualMachineClientDiagnostics.CreateScope("VirtualMachineCollection.GetAll"); scope.Start(); try { var response = await _virtualMachineRestClient.ListAsync(Id.SubscriptionId, Id.ResourceGroupName, filter, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new VirtualMachineResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<VirtualMachineResource>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _virtualMachineClientDiagnostics.CreateScope("VirtualMachineCollection.GetAll"); scope.Start(); try { var response = await _virtualMachineRestClient.ListNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, filter, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.Select(value => new VirtualMachineResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> /// Lists all of the virtual machines in the specified resource group. Use the nextLink property in the response to get the next page of virtual machines. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines /// Operation Id: VirtualMachines_List /// </summary> /// <param name="filter"> The system query option to filter VMs returned in the response. Allowed value is &apos;virtualMachineScaleSet/id&apos; eq /subscriptions/{subId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmssName}&apos;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="VirtualMachineResource" /> that may take multiple service requests to iterate over. </returns> public virtual Pageable<VirtualMachineResource> GetAll(string filter = null, CancellationToken cancellationToken = default) { Page<VirtualMachineResource> FirstPageFunc(int? pageSizeHint) { using var scope = _virtualMachineClientDiagnostics.CreateScope("VirtualMachineCollection.GetAll"); scope.Start(); try { var response = _virtualMachineRestClient.List(Id.SubscriptionId, Id.ResourceGroupName, filter, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new VirtualMachineResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<VirtualMachineResource> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _virtualMachineClientDiagnostics.CreateScope("VirtualMachineCollection.GetAll"); scope.Start(); try { var response = _virtualMachineRestClient.ListNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, filter, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.Select(value => new VirtualMachineResource(Client, value)), response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> /// Checks to see if the resource exists in azure. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName} /// Operation Id: VirtualMachines_Get /// </summary> /// <param name="vmName"> The name of the virtual machine. </param> /// <param name="expand"> The expand expression to apply on the operation. &apos;InstanceView&apos; retrieves a snapshot of the runtime properties of the virtual machine that is managed by the platform and can change outside of control plane operations. &apos;UserData&apos; retrieves the UserData property as part of the VM model view that was provided by the user during the VM Create/Update operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="vmName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="vmName"/> is null. </exception> public virtual async Task<Response<bool>> ExistsAsync(string vmName, InstanceViewTypes? expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(vmName, nameof(vmName)); using var scope = _virtualMachineClientDiagnostics.CreateScope("VirtualMachineCollection.Exists"); scope.Start(); try { var response = await _virtualMachineRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, vmName, expand, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Checks to see if the resource exists in azure. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName} /// Operation Id: VirtualMachines_Get /// </summary> /// <param name="vmName"> The name of the virtual machine. </param> /// <param name="expand"> The expand expression to apply on the operation. &apos;InstanceView&apos; retrieves a snapshot of the runtime properties of the virtual machine that is managed by the platform and can change outside of control plane operations. &apos;UserData&apos; retrieves the UserData property as part of the VM model view that was provided by the user during the VM Create/Update operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="vmName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="vmName"/> is null. </exception> public virtual Response<bool> Exists(string vmName, InstanceViewTypes? expand = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(vmName, nameof(vmName)); using var scope = _virtualMachineClientDiagnostics.CreateScope("VirtualMachineCollection.Exists"); scope.Start(); try { var response = _virtualMachineRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, vmName, expand, cancellationToken: cancellationToken); return Response.FromValue(response.Value != null, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } IEnumerator<VirtualMachineResource> IEnumerable<VirtualMachineResource>.GetEnumerator() { return GetAll().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetAll().GetEnumerator(); } IAsyncEnumerator<VirtualMachineResource> IAsyncEnumerable<VirtualMachineResource>.GetAsyncEnumerator(CancellationToken cancellationToken) { return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken); } } }
65.385965
488
0.676371
[ "MIT" ]
v-kaifazhang/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/VirtualMachineCollection.cs
22,362
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 System.Linq; using System.Numerics; using System.Threading; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Drawables; using osu.Game.Graphics.Containers; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Tests.Visual.UserInterface { public class TestSceneUpdateableBeatmapSetCover : OsuTestScene { [Test] public void TestLocal([Values] BeatmapSetCoverType coverType) { AddStep("setup cover", () => Child = new UpdateableOnlineBeatmapSetCover(coverType) { OnlineInfo = CreateAPIBeatmapSet(), RelativeSizeAxes = Axes.Both, Masking = true, }); AddUntilStep("wait for load", () => this.ChildrenOfType<OnlineBeatmapSetCover>().SingleOrDefault()?.IsLoaded ?? false); } [Test] public void TestUnloadAndReload() { OsuScrollContainer scroll = null; List<UpdateableOnlineBeatmapSetCover> covers = new List<UpdateableOnlineBeatmapSetCover>(); AddStep("setup covers", () => { var beatmapSet = CreateAPIBeatmapSet(); FillFlowContainer fillFlow; Child = scroll = new OsuScrollContainer { Size = new Vector2(500f), Child = fillFlow = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(10), Padding = new MarginPadding { Bottom = 550 } } }; var coverTypes = Enum.GetValues(typeof(BeatmapSetCoverType)) .Cast<BeatmapSetCoverType>() .ToList(); for (int i = 0; i < 25; i++) { var coverType = coverTypes[i % coverTypes.Count]; var cover = new UpdateableOnlineBeatmapSetCover(coverType) { OnlineInfo = beatmapSet, Height = 100, Masking = true, }; if (coverType == BeatmapSetCoverType.Cover) cover.Width = 500; else if (coverType == BeatmapSetCoverType.Card) cover.Width = 400; else if (coverType == BeatmapSetCoverType.List) cover.Size = new Vector2(100, 50); fillFlow.Add(cover); covers.Add(cover); } }); var loadedCovers = covers.Where(c => c.ChildrenOfType<OnlineBeatmapSetCover>().SingleOrDefault()?.IsLoaded ?? false); AddUntilStep("some loaded", () => loadedCovers.Any()); AddStep("scroll to end", () => scroll.ScrollToEnd()); AddUntilStep("all unloaded", () => !loadedCovers.Any()); } [Test] public void TestSetNullBeatmapWhileLoading() { TestUpdateableOnlineBeatmapSetCover updateableCover = null; AddStep("setup cover", () => Child = updateableCover = new TestUpdateableOnlineBeatmapSetCover { OnlineInfo = CreateAPIBeatmapSet(), RelativeSizeAxes = Axes.Both, Masking = true, }); AddStep("change model", () => updateableCover.OnlineInfo = null); AddWaitStep("wait some", 5); AddAssert("no cover added", () => !updateableCover.ChildrenOfType<DelayedLoadUnloadWrapper>().Any()); } [Test] public void TestCoverChangeOnNewBeatmap() { TestUpdateableOnlineBeatmapSetCover updateableCover = null; OnlineBeatmapSetCover initialCover = null; AddStep("setup cover", () => Child = updateableCover = new TestUpdateableOnlineBeatmapSetCover(0) { OnlineInfo = createBeatmapWithCover("https://assets.ppy.sh/beatmaps/1189904/covers/cover.jpg"), RelativeSizeAxes = Axes.Both, Masking = true, Alpha = 0.4f }); AddUntilStep("cover loaded", () => updateableCover.ChildrenOfType<OnlineBeatmapSetCover>().Any()); AddStep("store initial cover", () => initialCover = updateableCover.ChildrenOfType<OnlineBeatmapSetCover>().Single()); AddUntilStep("wait for fade complete", () => initialCover.Alpha == 1); AddStep("switch beatmap", () => updateableCover.OnlineInfo = createBeatmapWithCover("https://assets.ppy.sh/beatmaps/1079428/covers/cover.jpg")); AddUntilStep("new cover loaded", () => updateableCover.ChildrenOfType<OnlineBeatmapSetCover>().Except(new[] { initialCover }).Any()); } private static APIBeatmapSet createBeatmapWithCover(string coverUrl) => new APIBeatmapSet { Covers = new BeatmapSetOnlineCovers { Cover = coverUrl } }; private class TestUpdateableOnlineBeatmapSetCover : UpdateableOnlineBeatmapSetCover { private readonly int loadDelay; public TestUpdateableOnlineBeatmapSetCover(int loadDelay = 10000) { this.loadDelay = loadDelay; } protected override Drawable CreateDrawable(IBeatmapSetOnlineInfo model) { if (model == null) return null; return new TestOnlineBeatmapSetCover(model, loadDelay) { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fill, }; } } private class TestOnlineBeatmapSetCover : OnlineBeatmapSetCover { private readonly int loadDelay; public TestOnlineBeatmapSetCover(IBeatmapSetOnlineInfo set, int loadDelay) : base(set) { this.loadDelay = loadDelay; } [BackgroundDependencyLoader] private void load() { Thread.Sleep(loadDelay); } } } }
38.291209
146
0.538958
[ "MIT" ]
Azyyyyyy/osu
osu.Game.Tests/Visual/UserInterface/TestSceneUpdateableBeatmapSetCover.cs
6,788
C#
using System; using System.IO; namespace Socket.Quobject.EngineIoClientDotNet.Parser { public class ByteBuffer { private long _limit = 0; private readonly MemoryStream _memoryStream; public ByteBuffer(int length) { this._memoryStream = new MemoryStream(); this._memoryStream.SetLength((long) length); this._memoryStream.Capacity = length; this._limit = (long) length; } public static ByteBuffer Allocate(int length) { return new ByteBuffer(length); } internal void Put(byte[] buf) { this._memoryStream.Write(buf, 0, buf.Length); } internal byte[] Array() { return this._memoryStream.ToArray(); } internal static ByteBuffer Wrap(byte[] data) { ByteBuffer byteBuffer = new ByteBuffer(data.Length); byteBuffer.Put(data); return byteBuffer; } public int Capacity { get { return this._memoryStream.Capacity; } } internal byte Get(long index) { if (index > (long) this.Capacity) throw new IndexOutOfRangeException(); this._memoryStream.Position = index; return (byte) this._memoryStream.ReadByte(); } internal ByteBuffer Get(byte[] dst, int offset, int length) { this._memoryStream.Read(dst, offset, length); return this; } internal ByteBuffer Get(byte[] dst) { return this.Get(dst, 0, dst.Length); } internal void Position(long newPosition) { this._memoryStream.Position = newPosition; } internal void Limit(long newLimit) { this._limit = newLimit; if (this._memoryStream.Position <= newLimit) return; this._memoryStream.Position = newLimit; } internal long Remaining() { return this._limit - this._memoryStream.Position; } internal void Clear() { this.Position(0L); this.Limit((long) this.Capacity); } } }
21.369565
63
0.62411
[ "MIT" ]
EliseuPHP/MotionSensorUnity
Assets/Plugins/Socket/Quobject/EngineIoClientDotNet/Parser/ByteBuffer.cs
1,966
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum GroundType { Ground, Water } public class GroundTileData { public GroundType groundType = GroundType.Ground; public float primaryGrowth = 0f; public bool primaryGrowthComplete = false; public float secondaryGrowth = 0f; public bool secondaryGrowthComplete = false; public GroundTileData(GroundType type) { groundType = type; } public int AddGrowth(float growth) { //Primary Growth if (!primaryGrowthComplete) { primaryGrowth += growth; if (primaryGrowth >= 1f) { primaryGrowth = 1f; primaryGrowthComplete = true; return 1; } } else if(primaryGrowthComplete && !secondaryGrowthComplete) { secondaryGrowth += growth; if (secondaryGrowth >= 1f) { secondaryGrowth = 1f; secondaryGrowthComplete = true; return 2; } } return 0; } }
22.68
66
0.561728
[ "MIT" ]
KeithSwanger/a-field-of-flowers
Start From Nothing/Assets/Scripts/GroundTileData.cs
1,136
C#
// // ServiceOperationResultKind.cs // // Author: // Marek Habersack <grendel@twistedcode.net> // // Copyright (c) 2011 Novell, Inc // // 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.Data.Services.Providers; namespace System.Data.Services.Providers { public enum ServiceOperationResultKind { DirectValue = 0, Enumeration = 1, QueryWithMultipleResults = 2, QueryWithSingleResult = 3, Void = 4 } }
36
80
0.751355
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Data.Services/System.Data.Services.Providers/ServiceOperationResultKind.cs
1,478
C#
using FluentAssertions; using FluentAssertions.Execution; using Pubs.CoreDomain.Entities; using Pubs.UnitTests.Setup; using System.Collections.Generic; using System.Linq; using Xunit; namespace Pubs.UnitTests.Domain.Entities { public class AuthorTests : UnitTestBase { [Fact] public void property_update_succeeds() { var sut = new Author { Id = 25, FirstName = "Unit", LastName = "Test", AuthorCode = "ABC123456", Address = "123 Sesame St.", City = "Denver", State = "CO", ZipCode = "80123", PhoneNumber = "3038876688", Contract = true, AuthorTitles = new List<AuthorTitle>() { new AuthorTitle() { Id = 7 } } }; using (new AssertionScope()) { sut.Id.Should().Be(25); sut.FirstName.Should().Be("Unit"); sut.LastName.Should().Be("Test"); sut.AuthorCode.Should().Be("ABC123456"); sut.Address.Should().Be("123 Sesame St."); sut.City.Should().Be("Denver"); sut.State.Should().Be("CO"); sut.ZipCode.Should().Be("80123"); sut.PhoneNumber.Should().Be("3038876688"); sut.Contract.Should().BeTrue(); sut.AuthorTitles.FirstOrDefault(x => x.Id == 7).Should().NotBeNull(); } } } }
32.0625
87
0.495127
[ "MIT" ]
theMickster/pubs
tests/Pubs.UnitTests/Domain/Entities/AuthorTests.cs
1,541
C#
using UnityEngine; using System.Collections; /* * * バトルの管理をするスクリプト * */ public class BattleManager : MonoBehaviour { public CharaInfo charaInfo; // Use this for initialization void Start () { charaInfo = charaInfo.GetComponent<CharaInfo>(); } // Update is called once per frame void Update () { charaInfo.atk = 3; } }
14.08
56
0.664773
[ "MIT" ]
reverinu/reverinuBattleSystemProject
KawakenBattleSystem/Assets/Scripts/Manager/BattleManager.cs
382
C#