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; /* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace org.camunda.bpm.engine.impl.bpmn.behavior { //JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#: // import static org.camunda.bpm.engine.impl.bpmn.helper.CompensationUtil.SIGNAL_COMPENSATION_DONE; using BpmnExceptionHandler = org.camunda.bpm.engine.impl.bpmn.helper.BpmnExceptionHandler; using ErrorPropagationException = org.camunda.bpm.engine.impl.bpmn.helper.ErrorPropagationException; using EventType = org.camunda.bpm.engine.impl.@event.EventType; using EventSubscriptionEntity = org.camunda.bpm.engine.impl.persistence.entity.EventSubscriptionEntity; using ExecutionEntity = org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity; using PvmActivity = org.camunda.bpm.engine.impl.pvm.PvmActivity; using ActivityExecution = org.camunda.bpm.engine.impl.pvm.@delegate.ActivityExecution; using ActivityImpl = org.camunda.bpm.engine.impl.pvm.process.ActivityImpl; using PvmExecutionImpl = org.camunda.bpm.engine.impl.pvm.runtime.PvmExecutionImpl; /// <summary> /// Denotes an 'activity' in the sense of BPMN 2.0: /// a parent class for all tasks, subprocess and callActivity. /// /// @author Joram Barrez /// @author Daniel Meyer /// @author Thorben Lindhauer /// </summary> public class AbstractBpmnActivityBehavior : FlowNodeActivityBehavior { protected internal new static readonly BpmnBehaviorLogger LOG = ProcessEngineLogger.BPMN_BEHAVIOR_LOGGER; /// <summary> /// Subclasses that call leave() will first pass through this method, before /// the regular <seealso cref="FlowNodeActivityBehavior.leave(ActivityExecution)"/> is /// called. /// </summary> public override void doLeave(ActivityExecution execution) { PvmActivity currentActivity = execution.Activity; ActivityImpl compensationHandler = ((ActivityImpl) currentActivity).findCompensationHandler(); // subscription for compensation event subprocess is already created if (compensationHandler != null && !isCompensationEventSubprocess(compensationHandler)) { createCompensateEventSubscription(execution, compensationHandler); } base.doLeave(execution); } protected internal virtual bool isCompensationEventSubprocess(ActivityImpl activity) { return activity.CompensationHandler && activity.SubProcessScope && activity.TriggeredByEvent; } protected internal virtual void createCompensateEventSubscription(ActivityExecution execution, ActivityImpl compensationHandler) { // the compensate event subscription is created at subprocess or miBody of the the current activity PvmActivity currentActivity = execution.Activity; ActivityExecution scopeExecution = execution.findExecutionForFlowScope(currentActivity.FlowScope); EventSubscriptionEntity.createAndInsert((ExecutionEntity) scopeExecution, EventType.COMPENSATE, compensationHandler); } /// <summary> /// Takes an <seealso cref="ActivityExecution"/> and an <seealso cref="Callable"/> and wraps /// the call to the Callable with the proper error propagation. This method /// also makes sure that exceptions not caught by following activities in the /// process will be thrown and not propagated. /// </summary> /// <param name="execution"> </param> /// <param name="toExecute"> </param> /// <exception cref="Exception"> </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: protected void executeWithErrorPropagation(org.camunda.bpm.engine.impl.pvm.delegate.ActivityExecution execution, java.util.concurrent.Callable<Void> toExecute) throws Exception protected internal virtual void executeWithErrorPropagation(ActivityExecution execution, Callable<Void> toExecute) { string activityInstanceId = execution.ActivityInstanceId; try { toExecute.call(); } catch (Exception ex) { if (activityInstanceId.Equals(execution.ActivityInstanceId)) { try { BpmnExceptionHandler.propagateException(execution, ex); } catch (ErrorPropagationException) { // exception has been logged by thrower // re-throw the original exception so that it is logged // and set as cause of the failure throw ex; } } else { throw ex; } } } //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public void signal(org.camunda.bpm.engine.impl.pvm.delegate.ActivityExecution execution, String signalName, Object signalData) throws Exception public virtual void signal(ActivityExecution execution, string signalName, object signalData) { if (SIGNAL_COMPENSATION_DONE.Equals(signalName)) { signalCompensationDone(execution); } else { base.signal(execution, signalName, signalData); } } protected internal virtual void signalCompensationDone(ActivityExecution execution) { // default behavior is to join compensating executions and propagate the signal if all executions have compensated // only wait for non-event-scope executions cause a compensation event subprocess consume the compensation event and // do not have to compensate embedded subprocesses (which are still non-event-scope executions) if (((PvmExecutionImpl) execution).NonEventScopeExecutions.Count == 0) { if (execution.Parent != null) { ActivityExecution parent = execution.Parent; execution.remove(); parent.signal(SIGNAL_COMPENSATION_DONE, null); } } else { ((ExecutionEntity)execution).forceUpdate(); } } } }
39.092025
193
0.760986
[ "Apache-2.0" ]
luizfbicalho/Camunda.NET
camunda-bpm-platform-net/engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/behavior/AbstractBpmnActivityBehavior.cs
6,374
C#
namespace Umbraco.Cms.Infrastructure.Persistence.DatabaseModelDefinitions { public enum ModificationType { Create, Alter, Drop, Rename, Insert, Update, Delete } }
16.571429
74
0.573276
[ "MIT" ]
Ambertvu/Umbraco-CMS
src/Umbraco.Infrastructure/Persistence/DatabaseModelDefinitions/ModificationType.cs
234
C#
using System; namespace _04._Back_In_30_Minutes { public class Program { public static void Main() { var hours = int.Parse(Console.ReadLine()); var minutes = int.Parse(Console.ReadLine()); int allMinutes = (hours * 60) + minutes + 30; Console.WriteLine($"{allMinutes / 60 % 24}:{allMinutes % 60:d2}"); } } }
22
78
0.54798
[ "Apache-2.0" ]
vencislav-viktorov/VS-Console-App
Tech Module New one/01.IntroNBasicSyntax-Lab/04. Back In 30 Minutes/04. Back In 30 Minutes.cs
398
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography { public partial interface ICspAsymmetricAlgorithm { CspKeyContainerInfo CspKeyContainerInfo { get; } byte[] ExportCspBlob(bool includePrivateParameters); void ImportCspBlob(byte[] rawData); } }
31.384615
71
0.732843
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/ICspAsymmetricAlgorithm.cs
408
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BassClefStudio.UWP.OAuth.Services { public class GraphAuthenticationProvider : OAuthAuthenticationProvider { public static readonly string[] GraphBasicScopes = new string[] { "openid", "profile" }; public static readonly string[] MicrosoftToDoScopes = new string[] { "Tasks.ReadWrite", "Tasks.ReadWrite.Shared", "User.Read", "email", "offline_access" }; public GraphAuthenticationProvider(string clientId, params string[][] scopes) : base( "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", "https://login.microsoftonline.com/common/oauth2/v2.0/token", "https://login.microsoftonline.com/common/oauth2/nativeclient", clientId, scopes.SelectMany(s => s).ToArray(), "code", new string[] { "iss", "preferred_username" }, "https://graph.microsoft.com/v1.0/me/", "displayName", "userPrincipalName") { } } }
31.195122
85
0.563722
[ "MIT" ]
bassclefstudio/BassClefStudio.UWP
BassClefStudio.UWP.OAuth/Services/GraphAuthenticationProvider.cs
1,281
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* Require101.cs -- язык основного текста. */ #region Using directives using JetBrains.Annotations; using MoonSharp.Interpreter; #endregion namespace ManagedClient.Quality.Rules { /// <summary> /// Язык основного текста. /// </summary> [PublicAPI] [MoonSharpUserData] public sealed class Require101 : IrbisRule { #region Private members private IrbisMenu _menu; private void CheckField ( [NotNull] RecordField field ) { MustNotContainSubfields ( field ); if (!CheckForMenu(_menu, field.Text)) { AddDefect ( field, 10, "Поле 101 (язык основного текста) не из словаря" ); } } #endregion #region IrbisRule members /// <inheritdoc cref="IrbisRule.FieldSpec"/> public override string FieldSpec { get { return "101"; } } /// <inheritdoc cref="IrbisRule.CheckRecord"/> public override RuleReport CheckRecord ( RuleContext context ) { BeginCheck(context); RecordField[] fields = GetFields(); if (fields.Length == 0) { AddDefect ( "101", 10, "Не заполнено поле 101: Язык основного текста" ); } MustBeUniqueField ( fields ); _menu = CacheMenu("jz.mnu", _menu); foreach (RecordField field in fields) { CheckField(field); } return EndCheck(); } #endregion } }
22.98913
84
0.456738
[ "MIT" ]
amironov73/ManagedClient.3
ManagedClient/Quality/Rules/Require101.cs
2,223
C#
using System.Linq; using Avalonia.Controls.Generators; using Avalonia.Controls.Metadata; using Avalonia.Controls.Mixins; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Input; using Avalonia.LogicalTree; namespace Avalonia.Controls { /// <summary> /// An item in a <see cref="TreeView"/>. /// </summary> [TemplatePart("PART_Header", typeof(IControl))] [PseudoClasses(":pressed", ":selected")] public class TreeViewItem : HeaderedItemsControl, ISelectable { /// <summary> /// Defines the <see cref="IsExpanded"/> property. /// </summary> public static readonly DirectProperty<TreeViewItem, bool> IsExpandedProperty = AvaloniaProperty.RegisterDirect<TreeViewItem, bool>( nameof(IsExpanded), o => o.IsExpanded, (o, v) => o.IsExpanded = v); /// <summary> /// Defines the <see cref="IsSelected"/> property. /// </summary> public static readonly StyledProperty<bool> IsSelectedProperty = ListBoxItem.IsSelectedProperty.AddOwner<TreeViewItem>(); /// <summary> /// Defines the <see cref="Level"/> property. /// </summary> public static readonly DirectProperty<TreeViewItem, int> LevelProperty = AvaloniaProperty.RegisterDirect<TreeViewItem, int>( nameof(Level), o => o.Level); private static readonly ITemplate<IPanel> DefaultPanel = new FuncTemplate<IPanel>(() => new StackPanel()); private TreeView? _treeView; private IControl? _header; private bool _isExpanded; private int _level; /// <summary> /// Initializes static members of the <see cref="TreeViewItem"/> class. /// </summary> static TreeViewItem() { SelectableMixin.Attach<TreeViewItem>(IsSelectedProperty); PressedMixin.Attach<TreeViewItem>(); FocusableProperty.OverrideDefaultValue<TreeViewItem>(true); ItemsPanelProperty.OverrideDefaultValue<TreeViewItem>(DefaultPanel); ParentProperty.Changed.AddClassHandler<TreeViewItem>((o, e) => o.OnParentChanged(e)); RequestBringIntoViewEvent.AddClassHandler<TreeViewItem>((x, e) => x.OnRequestBringIntoView(e)); } /// <summary> /// Gets or sets a value indicating whether the item is expanded to show its children. /// </summary> public bool IsExpanded { get { return _isExpanded; } set { SetAndRaise(IsExpandedProperty, ref _isExpanded, value); } } /// <summary> /// Gets or sets the selection state of the item. /// </summary> public bool IsSelected { get { return GetValue(IsSelectedProperty); } set { SetValue(IsSelectedProperty, value); } } /// <summary> /// Gets the level/indentation of the item. /// </summary> public int Level { get { return _level; } private set { SetAndRaise(LevelProperty, ref _level, value); } } /// <summary> /// Gets the <see cref="ITreeItemContainerGenerator"/> for the tree view. /// </summary> public new ITreeItemContainerGenerator ItemContainerGenerator => (ITreeItemContainerGenerator)base.ItemContainerGenerator; /// <inheritdoc/> protected override IItemContainerGenerator CreateItemContainerGenerator() => CreateTreeItemContainerGenerator<TreeViewItem>(); /// <inheritdoc/> protected ITreeItemContainerGenerator CreateTreeItemContainerGenerator<TVItem>() where TVItem: TreeViewItem, new() { return new TreeItemContainerGenerator<TVItem>( this, TreeViewItem.HeaderProperty, TreeViewItem.ItemTemplateProperty, TreeViewItem.ItemsProperty, TreeViewItem.IsExpandedProperty); } /// <inheritdoc/> protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); _treeView = this.GetLogicalAncestors().OfType<TreeView>().FirstOrDefault(); Level = CalculateDistanceFromLogicalParent<TreeView>(this) - 1; ItemContainerGenerator.UpdateIndex(); if (ItemTemplate == null && _treeView?.ItemTemplate != null) { ItemTemplate = _treeView.ItemTemplate; } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); ItemContainerGenerator.UpdateIndex(); } protected virtual void OnRequestBringIntoView(RequestBringIntoViewEventArgs e) { if (e.TargetObject == this && _header != null) { var m = _header.TransformToVisual(this); if (m.HasValue) { var bounds = new Rect(_header.Bounds.Size); var rect = bounds.TransformToAABB(m.Value); e.TargetRect = rect; } } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { if (!e.Handled) { switch (e.Key) { case Key.Right: if (Items != null && Items.Cast<object>().Any()) { IsExpanded = true; } e.Handled = true; break; case Key.Left: IsExpanded = false; e.Handled = true; break; } } // Don't call base.OnKeyDown - let events bubble up to containing TreeView. } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { _header = e.NameScope.Find<IControl>("PART_Header"); } private static int CalculateDistanceFromLogicalParent<T>(ILogical? logical, int @default = -1) where T : class { var result = 0; while (logical != null && !(logical is T)) { ++result; logical = logical.LogicalParent; } return logical != null ? result : @default; } private void OnParentChanged(AvaloniaPropertyChangedEventArgs e) { if (!((ILogical)this).IsAttachedToLogicalTree && e.NewValue is null) { // If we're not attached to the logical tree, then OnDetachedFromLogicalTree isn't going to be // called when the item is removed. This results in the item not being removed from the index, // causing #3551. In this case, update the index when Parent is changed to null. ItemContainerGenerator.UpdateIndex(); } } } }
35.610837
134
0.566883
[ "MIT" ]
ErrorCraft/Avalonia
src/Avalonia.Controls/TreeViewItem.cs
7,229
C#
// Copyright (c) Samuel Cragg. // // Licensed under the MIT license. See LICENSE file in the project root for // full license information. namespace SharpKml.Dom.Xal { using SharpKml.Base; /// <summary> /// Contains information of a thoroughfare. /// </summary> /// <remarks>A thoroughfare could be a road, street, canal, river, etc.</remarks> [KmlElement("Thoroughfare", KmlNamespaces.XalNamespace)] public class Thoroughfare : Element { /// <summary> /// Gets or sets the name of the thoroughfare. /// </summary> [KmlElement("ThoroughfareName", KmlNamespaces.XalNamespace)] public string Name { get; set; } /// <summary> /// Gets or sets the number of the thoroughfare. /// </summary> [KmlElement("ThoroughfareNumber", KmlNamespaces.XalNamespace)] public string Number { get; set; } } }
31.266667
86
0.610874
[ "MIT" ]
D-Bullock/sharpkml
SharpKml/Dom/Xal/Thoroughfare.cs
940
C#
using System.Web; using System.Web.Optimization; namespace PushContentController { public class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include( "~/Scripts/jquery-ui-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css")); bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( "~/Content/themes/base/jquery.ui.core.css", "~/Content/themes/base/jquery.ui.resizable.css", "~/Content/themes/base/jquery.ui.selectable.css", "~/Content/themes/base/jquery.ui.accordion.css", "~/Content/themes/base/jquery.ui.autocomplete.css", "~/Content/themes/base/jquery.ui.button.css", "~/Content/themes/base/jquery.ui.dialog.css", "~/Content/themes/base/jquery.ui.slider.css", "~/Content/themes/base/jquery.ui.tabs.css", "~/Content/themes/base/jquery.ui.datepicker.css", "~/Content/themes/base/jquery.ui.progressbar.css", "~/Content/themes/base/jquery.ui.theme.css")); } } }
49.767442
112
0.557944
[ "Apache-2.0" ]
ASCITSOL/asp.net
samples/aspnet/WebApi/PushContentControllerSample/PushContentController/App_Start/BundleConfig.cs
2,142
C#
// // ConnectionTestFeatures.cs // // Author: // Martin Baulig <martin.baulig@xamarin.com> // // Copyright (c) 2015 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.IO; using System.Net; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Xamarin.AsyncTests; using Xamarin.AsyncTests.Constraints; using Xamarin.AsyncTests.Portable; namespace Xamarin.WebTests.TestFramework { using TestRunners; using ConnectionFramework; public static class ConnectionTestHelper { static readonly ConnectionProviderFactory Factory; static ConnectionTestHelper () { Factory = DependencyInjector.Get<ConnectionProviderFactory> (); } public static ConnectionProviderFlags GetProviderFlags (ConnectionProviderType type) { return Factory.GetProviderFlags (type); } public static EndPoint GetEndPoint () { var port = TestContext.GetUniquePort (); return new IPEndPoint (IPAddress.Loopback, port); } public static bool IsMicrosoftRuntime { get { return DependencyInjector.Get<IPortableSupport> ().IsMicrosoftRuntime; } } public static IEnumerable<R> Join<T, U, R> (IEnumerable<T> first, IEnumerable<U> second, Func<T, U, R> resultSelector, bool filterOutNull = true) { foreach (var e1 in first) { foreach (var e2 in second) { var result = resultSelector (e1, e2); if (!filterOutNull || result != null) yield return result; } } } } }
32.623377
147
0.746815
[ "MIT" ]
xamarin/web-tests
Xamarin.WebTests.Framework/Xamarin.WebTests.TestFramework/ConnectionTestHelper.cs
2,514
C#
using System; using Newtonsoft.Json; namespace TdLib { /// <summary> /// Autogenerated TDLib APIs /// </summary> public static partial class TdApi { /// <summary> /// Describes a chat administrator with a number of active and revoked chat invite links /// </summary> public partial class ChatInviteLinkCount : Object { /// <summary> /// Data type for serialization /// </summary> [JsonProperty("@type")] public override string DataType { get; set; } = "chatInviteLinkCount"; /// <summary> /// Extra data attached to the object /// </summary> [JsonProperty("@extra")] public override string Extra { get; set; } /// <summary> /// Administrator's user identifier /// </summary> [JsonConverter(typeof(Converter))] [JsonProperty("user_id")] public int UserId { get; set; } /// <summary> /// Number of active invite links /// </summary> [JsonConverter(typeof(Converter))] [JsonProperty("invite_link_count")] public int InviteLinkCount { get; set; } /// <summary> /// Number of revoked invite links /// </summary> [JsonConverter(typeof(Converter))] [JsonProperty("revoked_invite_link_count")] public int RevokedInviteLinkCount { get; set; } } } }
31.04
96
0.523196
[ "MIT" ]
Kolibarus/tdsharp
TDLib.Api/Objects/ChatInviteLinkCount.cs
1,552
C#
using System; using System.Diagnostics; using System.Xml; using System.Xml.Linq; using FluentAssertions.Common; using FluentAssertions.Execution; using FluentAssertions.Primitives; using FluentAssertions.Xml.Equivalency; namespace FluentAssertions.Xml { /// <summary> /// Contains a number of methods to assert that an <see cref="XDocument"/> is in the expected state. /// </summary> [DebuggerNonUserCode] public class XDocumentAssertions : ReferenceTypeAssertions<XDocument, XDocumentAssertions> { /// <summary> /// Initializes a new instance of the <see cref="XDocumentAssertions" /> class. /// </summary> public XDocumentAssertions(XDocument document) : base(document) { } /// <summary> /// Asserts that the current <see cref="XDocument"/> equals the <paramref name="expected"/> document, /// using its <see cref="object.Equals(object)" /> implementation. /// </summary> /// <param name="expected">The expected document</param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndConstraint<XDocumentAssertions> Be(XDocument expected, string because = "", params object[] becauseArgs) { Execute.Assertion .ForCondition(Equals(Subject, expected)) .BecauseOf(because, becauseArgs) .FailWith("Expected XML document to be {0}{reason}, but found {1}.", expected, Subject); return new AndConstraint<XDocumentAssertions>(this); } /// <summary> /// Asserts that the current <see cref="XDocument"/> does not equal the <paramref name="unexpected"/> document, /// using its <see cref="object.Equals(object)" /> implementation. /// </summary> /// <param name="unexpected">The unexpected document</param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndConstraint<XDocumentAssertions> NotBe(XDocument unexpected, string because = "", params object[] becauseArgs) { Execute.Assertion .BecauseOf(because, becauseArgs) .ForCondition(!Equals(Subject, unexpected)) .FailWith("Did not expect XML document to be {0}{reason}.", unexpected); return new AndConstraint<XDocumentAssertions>(this); } /// <summary> /// Asserts that the current <see cref="XDocument"/> is equivalent to the <paramref name="expected"/> document, /// using its <see cref="XNode.DeepEquals(XNode, XNode)" /> implementation. /// </summary> /// <param name="expected">The expected document</param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndConstraint<XDocumentAssertions> BeEquivalentTo(XDocument expected, string because = "", params object[] becauseArgs) { using (XmlReader subjectReader = Subject.CreateReader()) using (XmlReader otherReader = expected.CreateReader()) { var xmlReaderValidator = new XmlReaderValidator(subjectReader, otherReader, because, becauseArgs); xmlReaderValidator.Validate(true); } return new AndConstraint<XDocumentAssertions>(this); } /// <summary> /// Asserts that the current <see cref="XDocument"/> is not equivalent to the <paramref name="unexpected"/> document, /// using its <see cref="XNode.DeepEquals(XNode, XNode)" /> implementation. /// </summary> /// <param name="unexpected">The unexpected document</param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndConstraint<XDocumentAssertions> NotBeEquivalentTo(XDocument unexpected, string because = "", params object[] becauseArgs) { using (XmlReader subjectReader = Subject.CreateReader()) using (XmlReader otherReader = unexpected.CreateReader()) { var xmlReaderValidator = new XmlReaderValidator(subjectReader, otherReader, because, becauseArgs); xmlReaderValidator.Validate(false); } return new AndConstraint<XDocumentAssertions>(this); } /// <summary> /// Asserts that the current <see cref="XDocument"/> has a root element with the specified /// <paramref name="expected"/> name. /// </summary> /// <param name="expected">The name of the expected root element of the current document.</param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndWhichConstraint<XDocumentAssertions, XElement> HaveRoot(string expected, string because = "", params object[] becauseArgs) { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot assert the document has a root element if the element name is <null>*"); return HaveRoot(XNamespace.None + expected, because, becauseArgs); } /// <summary> /// Asserts that the current <see cref="XDocument"/> has a root element with the specified /// <paramref name="expected"/> name. /// </summary> /// <param name="expected">The full name <see cref="XName"/> of the expected root element of the current document.</param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndWhichConstraint<XDocumentAssertions, XElement> HaveRoot(XName expected, string because = "", params object[] becauseArgs) { if (Subject is null) { throw new InvalidOperationException("Cannot assert the document has a root element if the document itself is <null>."); } Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot assert the document has a root element if the element name is <null>*"); XElement root = Subject.Root; Execute.Assertion .ForCondition((root != null) && (root.Name == expected)) .BecauseOf(because, becauseArgs) .FailWith("Expected XML document to have root element \"" + expected.ToString().EscapePlaceholders() + "\"{reason}" + ", but found {0}.", Subject); return new AndWhichConstraint<XDocumentAssertions, XElement>(this, root); } /// <summary> /// Asserts that the <see cref="XDocument.Root"/> element of the current <see cref="XDocument"/> has a direct /// child element with the specified <paramref name="expected"/> name. /// </summary> /// <param name="expected"> /// The name of the expected child element of the current document's Root <see cref="XDocument.Root"/> element. /// </param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndWhichConstraint<XDocumentAssertions, XElement> HaveElement(string expected, string because = "", params object[] becauseArgs) { Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot assert the document has an element if the element name is <null>*"); return HaveElement(XNamespace.None + expected, because, becauseArgs); } /// <summary> /// Asserts that the <see cref="XDocument.Root"/> element of the current <see cref="XDocument"/> has a direct /// child element with the specified <paramref name="expected"/> name. /// </summary> /// <param name="expected"> /// The full name <see cref="XName"/> of the expected child element of the current document's Root <see cref="XDocument.Root"/> element. /// </param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <paramref name="because" />. /// </param> public AndWhichConstraint<XDocumentAssertions, XElement> HaveElement(XName expected, string because = "", params object[] becauseArgs) { if (Subject is null) { throw new InvalidOperationException("Cannot assert the document has an element if the document itself is <null>."); } Guard.ThrowIfArgumentIsNull(expected, nameof(expected), "Cannot assert the document has an element if the element name is <null>*"); string expectedText = expected.ToString().EscapePlaceholders(); Execute.Assertion .ForCondition(Subject.Root != null) .BecauseOf(because, becauseArgs) .FailWith("Expected XML document {0} to have root element with child \"" + expectedText + "\"{reason}" + ", but XML document has no Root element.", Subject); XElement xElement = Subject.Root.Element(expected); Execute.Assertion .ForCondition(xElement != null) .BecauseOf(because, becauseArgs) .FailWith("Expected XML document {0} to have root element with child \"" + expectedText + "\"{reason}" + ", but no such child element was found.", Subject); return new AndWhichConstraint<XDocumentAssertions, XElement>(this, xElement); } /// <summary> /// Returns the type of the subject the assertion applies on. /// </summary> protected override string Identifier => "XML document"; } }
51.422131
144
0.616243
[ "Apache-2.0" ]
Jacksondr5/fluentassertions
Src/FluentAssertions/Xml/XDocumentAssertions.cs
12,547
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.IO; using System.Linq; namespace Microsoft.DotNet.Build.Tasks { public class ChangeEntryPointLibraryName : BuildTask { [Required] public string DepsFile { get; set; } public string NewName { get; set; } public override bool Execute() { JToken deps; using (var file = File.OpenText(DepsFile)) using (JsonTextReader reader = new JsonTextReader(file)) { deps = JObject.ReadFrom(reader); } if (deps == null) return false; string version = string.Empty; foreach (JProperty target in deps["targets"]) { var targetLibrary = target.Value.Children<JProperty>().FirstOrDefault(); if (targetLibrary == null) { continue; } version = targetLibrary.Name.Substring(targetLibrary.Name.IndexOf('/') + 1); if (string.IsNullOrEmpty(NewName)) { targetLibrary.Remove(); } else { targetLibrary.Replace(new JProperty(NewName + '/' + version, targetLibrary.Value)); } } if (!string.IsNullOrEmpty(version)) { var library = deps["libraries"].Children<JProperty>().First(); if (string.IsNullOrEmpty(NewName)) { library.Remove(); } else { library.Replace(new JProperty(NewName + '/' + version, library.Value)); } using (var file = File.CreateText(DepsFile)) using (var writer = new JsonTextWriter(file) { Formatting = Formatting.Indented }) { deps.WriteTo(writer); } } return true; } } }
31.685714
103
0.501803
[ "MIT" ]
2m0nd/runtime
tools-local/tasks/installer.tasks/ChangeEntryPointLibraryName.cs
2,220
C#
 // Copyright (C) 2019 Luca Piccioni // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 // USA using OpenGL.Objects; using NUnit.Framework; namespace OpenGL.Objects.Test { [TestFixture] public class TextureTest : TestBase { protected static void Texture_DefaultConstructor(Texture texture) { Assert.AreEqual(PixelLayout.None, texture.PixelLayout); Assert.AreEqual(Vertex3ui.Zero, texture.Size); Assert.AreEqual(0, texture.Width); Assert.AreEqual(0, texture.Height); Assert.AreEqual(0, texture.Depth); Assert.AreEqual(0, texture.BaseLevel); Assert.AreEqual(0, texture.MipmapMaxLevel); Assert.DoesNotThrow(() => texture.HasMipMapLevel(0)); Assert.AreEqual(false, texture.IsMipmapComplete); Assert.AreNotEqual(null, texture.SamplerParams); Assert.AreEqual(null, texture.Sampler); Assert.AreEqual(false, texture.IsDirty); // Default is immutable Assert.AreEqual(true, texture.Immutable); } } }
32.8
76
0.746951
[ "MIT" ]
MagmaiKH/OpenGL.Net
OpenGL.Net.Objects.Test/Texture.cs
1,642
C#
using System; using System.Runtime.InteropServices; namespace CI.DataModel { /// <summary> /// Interface implemented by items which can be used in models /// </summary> [ComVisible(true)] public interface IModelItem : IComparable { /// <summary> /// Gets the Container ID which identifies the container where the object is stored. /// </summary> Guid ContainerID { get; } /// <summary> /// Gets, sets identifier of the model item /// </summary> int Id { get; set; } /// <summary> /// Name of the model item /// </summary> string Name { get; set; } /// <summary> /// Sets modification for database /// </summary> void Modify(); /// <summary> /// Notify all the changes that have happened in this object /// </summary> void NotifyAllChanges(); } }
17.804348
86
0.626374
[ "MIT" ]
idea-statica/ideastatica-plugin
IdeaStatiCa.PluginsTools/PluginTools/Tools/IModelItem.cs
821
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IEntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IDeviceCompliancePolicyScheduledActionsForRuleCollectionRequest. /// </summary> public partial interface IDeviceCompliancePolicyScheduledActionsForRuleCollectionRequest : IBaseRequest { /// <summary> /// Adds the specified DeviceComplianceScheduledActionForRule to the collection via POST. /// </summary> /// <param name="deviceComplianceScheduledActionForRule">The DeviceComplianceScheduledActionForRule to add.</param> /// <returns>The created DeviceComplianceScheduledActionForRule.</returns> System.Threading.Tasks.Task<DeviceComplianceScheduledActionForRule> AddAsync(DeviceComplianceScheduledActionForRule deviceComplianceScheduledActionForRule); /// <summary> /// Adds the specified DeviceComplianceScheduledActionForRule to the collection via POST. /// </summary> /// <param name="deviceComplianceScheduledActionForRule">The DeviceComplianceScheduledActionForRule to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DeviceComplianceScheduledActionForRule.</returns> System.Threading.Tasks.Task<DeviceComplianceScheduledActionForRule> AddAsync(DeviceComplianceScheduledActionForRule deviceComplianceScheduledActionForRule, CancellationToken cancellationToken); /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IDeviceCompliancePolicyScheduledActionsForRuleCollectionPage> GetAsync(); /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IDeviceCompliancePolicyScheduledActionsForRuleCollectionPage> GetAsync(CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IDeviceCompliancePolicyScheduledActionsForRuleCollectionRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IDeviceCompliancePolicyScheduledActionsForRuleCollectionRequest Expand(Expression<Func<DeviceComplianceScheduledActionForRule, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IDeviceCompliancePolicyScheduledActionsForRuleCollectionRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IDeviceCompliancePolicyScheduledActionsForRuleCollectionRequest Select(Expression<Func<DeviceComplianceScheduledActionForRule, object>> selectExpression); /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> IDeviceCompliancePolicyScheduledActionsForRuleCollectionRequest Top(int value); /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> IDeviceCompliancePolicyScheduledActionsForRuleCollectionRequest Filter(string value); /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> IDeviceCompliancePolicyScheduledActionsForRuleCollectionRequest Skip(int value); /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> IDeviceCompliancePolicyScheduledActionsForRuleCollectionRequest OrderBy(string value); } }
50.851852
201
0.674071
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IDeviceCompliancePolicyScheduledActionsForRuleCollectionRequest.cs
5,492
C#
using Gacho.MvpVm.Core; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebForms.Net45.Sample.ViewModels { public class HomeViewModel : ViewModel { private string text; public string Text { get { return text; } set { SetField(ref text, value, () => this.Text); } } } }
20.368421
63
0.609819
[ "Apache-2.0" ]
Micha-kun/Gacho.MvpVm
samples/WebForms.Net45.Sample/ViewModels/HomeViewModel.cs
389
C#
using System; using System.Threading.Tasks; namespace Blazor.Fluxor { /// <summary> /// An interface for implementing middleware /// </summary> public interface IMiddleware { /// <summary> /// If the Middleware requires scripts inside the browser in order to function /// then those scripts should be returned from this method /// </summary> /// <returns>Any required Javascript, or null</returns> string GetClientScripts(); /// <summary> /// Called exactly once by the store when the store initialises, or when /// the middleware is added to the store (if the store has already been initialised) /// </summary> /// <param name="store">A reference to the store</param> Task InitializeAsync(IStore store); /// <summary> /// Called exactly once by the store after <see cref="InitializeAsync(IStore)"/> has been /// called on all registered Middlewares /// </summary> void AfterInitializeAllMiddlewares(); /// <summary> /// Called before each action dispatched /// </summary> /// <param name="action">The action to be dispatched</param> /// <returns>True if the action may proceed, False if it should be prevented</returns> bool MayDispatchAction(object action); /// <summary> /// Called before each action dispatched /// </summary> /// <param name="action">The action being dispatched</param> void BeforeDispatch(object action); /// <summary> /// Called after each action dispatched /// </summary> /// <param name="action">The action that has just been dispatched</param> void AfterDispatch(object action); /// <summary> /// This should only be called via <see cref="IStore.BeginInternalMiddlewareChange"/>. /// </summary> /// <returns>An IDisposable that should be executed when the internal change ends</returns> /// <seealso cref="DisposableCallback"/> IDisposable BeginInternalMiddlewareChange(); } }
32.672414
93
0.699736
[ "MIT" ]
adamxoserve/blazor-fluxor
src/Blazor.Fluxor/IMiddleware.cs
1,897
C#
using System; using System.Collections.Generic; using XAS.Model; using XAS.Model.Paging; using XAS.Core.Logging; using XAS.Model.Database; using XAS.Core.Exceptions; using XAS.Core.Configuration; using DemoModel.Service; using DemoModelCommon.DataStructures; using DemoMicroServiceServer.Configuration.Extensions; namespace DemoMicroServiceServer.Web.Services { /// <summary> /// Service interface to Dinosaurs. /// </summary> /// public class DinoService: IDinoService { private object _critical = null; private readonly ILogger log = null; private readonly IManager manager = null; private readonly IConfiguration config = null; private readonly IErrorHandler handler = null; private readonly DemoModel.Service.Dinosaur dino = null; /// <summary> /// Constructor. /// </summary> /// <param name="config">An IConfiguration object.</param> /// <param name="handler">An IErrorHandler object.</param> /// <param name="logFactory">An ILoggerFactory object.</param> /// public DinoService(IConfiguration config, IErrorHandler handler, ILoggerFactory logFactory) { _critical = new Object(); this.config = config; this.handler = handler; var key = config.Key; var section = config.Section; string model = config.GetValue(section.Database(), key.Model(), "DemoDatabase"); var context = new DemoModel.Context(null, model); var repository = new DemoModel.Repositories(config, handler, logFactory, context); this.manager = new Manager(context, repository); this.dino = new DemoModel.Service.Dinosaur(config, handler, logFactory); this.log = logFactory.Create(typeof(DinoService)); log.Trace("Initialized DinoService()"); } public DinosaurDTO Get(Int32 id) { var dto = new DinosaurDTO(); using (var repo = manager.Repository as DemoModel.Repositories) { dto = dino.Get(repo, id); } return dto; } public DinosaurDTO Create(DinosaurPost binding) { Int32 id = 0; DinosaurDTO dto = null; using (var repo = manager.Repository as DemoModel.Repositories) { var dti = MoveBinding(repo, binding); if ((id = dino.Create(repo, dti)) > 0) { dto = dino.Get(repo, id); } } return dto; } public DinosaurDTO Update(Int32 id, DinosaurUpdate binding) { DinosaurDTO dto = null; using (var repo = manager.Repository as DemoModel.Repositories) { var dti = MoveBinding(repo, binding); if (dino.Update(repo, id, dti)) { dto = dino.Get(repo, id); } } return dto; } public Boolean Delete(Int32 id) { bool stat = false; using (var repo = manager.Repository as DemoModel.Repositories) { stat = dino.Delete(repo, id); } return stat; } public List<DinosaurDTO> List() { var dtos = new List<DinosaurDTO>(); using (var repo = manager.Repository as DemoModel.Repositories) { dtos = dino.List(repo); } return dtos; } public IPagedList<DinosaurDTO> Paged(DinosaursPagedCriteria criteria) { var dtos = new Object(); using (var repo = manager.Repository as DemoModel.Repositories) { dtos = dino.Paged(repo, criteria); } return dtos as PagedList<DinosaurDTO>; } #region Private Methods private DinosaurDTI MoveBinding(Repositories repo, DinosaurPost binding) { return new DinosaurDTI { Name = binding.Name, Status = binding.Status, Height = binding.Height }; } #endregion } }
24.494186
101
0.56207
[ "Artistic-2.0" ]
klesteb/XAS-Csharp
DemoMicroServiceServer/Web/Services/DinoService.cs
4,215
C#
using System; namespace NuDoq { /// <summary> /// Delegate configuration to use with the <see cref="DelegateVisitor"/>, /// which allows anonymous visitors to be used without having to create /// <see cref="Visitor"/>-derived classes. /// </summary> public class VisitorDelegates { /// <summary> /// Gets or sets the action to invoke when visiting all documented members of an XML document file. /// </summary> /// <seealso cref="Visitor.VisitDocument"/> public Action<DocumentMembers>? VisitDocument { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting all documented members of an assembly. /// </summary> /// <seealso cref="Visitor.VisitAssembly"/> public Action<AssemblyMembers>? VisitAssembly { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting a type member. /// </summary> /// <seealso cref="Visitor.VisitType"/> public Action<TypeDeclaration>? VisitType { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting an interface. /// </summary> /// <seealso cref="Visitor.VisitInterface"/> public Action<Interface>? VisitInterface { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting a class. /// </summary> /// <seealso cref="Visitor.VisitClass"/> public Action<Class>? VisitClass { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting a struct. /// </summary> /// <seealso cref="Visitor.VisitStruct"/> public Action<Struct>? VisitStruct { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting an enumeration. /// </summary> /// <seealso cref="Visitor.VisitEnum"/> public Action<Enum>? VisitEnum { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting a field. /// </summary> /// <seealso cref="Visitor.VisitField"/> public Action<Field>? VisitField { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting a property. /// </summary> /// <seealso cref="Visitor.VisitProperty"/> public Action<Property>? VisitProperty { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting an event. /// </summary> /// <seealso cref="Visitor.VisitEvent"/> public Action<Event>? VisitEvent { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting a method. /// </summary> /// <seealso cref="Visitor.VisitMethod"/> public Action<Method>? VisitMethod { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting an extension method. /// </summary> /// <seealso cref="Visitor.VisitExtensionMethod"/> public Action<ExtensionMethod>? VisitExtensionMethod { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting any member. /// </summary> /// <seealso cref="Visitor.VisitMember"/> public Action<Member>? VisitMember { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>summary</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitSummary"/> public Action<Summary>? VisitSummary { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>remarks</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitRemarks"/> public Action<Remarks>? VisitRemarks { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>para</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitPara"/> public Action<Para>? VisitPara { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>code</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitCode"/> public Action<Code>? VisitCode { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>c</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitC"/> public Action<C>? VisitC { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the literal text inside other documentation elements. /// </summary> /// <seealso cref="Visitor.VisitText"/> public Action<Text>? VisitText { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>example</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitExample"/> public Action<Example>? VisitExample { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>see</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitSee"/> public Action<See>? VisitSee { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>seealso</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitSeeAlso"/> public Action<SeeAlso>? VisitSeeAlso { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>param</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitParam"/> public Action<Param>? VisitParam { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>paramref</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitParamRef"/> public Action<ParamRef>? VisitParamRef { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>typeparam</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitTypeParam"/> public Action<TypeParam>? VisitTypeParam { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>typeparamref</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitTypeParamRef"/> public Action<TypeParamRef>? VisitTypeParamRef { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>value</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitValue"/> public Action<Value>? VisitValue { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>returns</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitReturns"/> public Action<Returns>? VisitReturns { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>list</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitList"/> public Action<List>? VisitList { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>listheader</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitListHeader"/> public Action<ListHeader>? VisitListHeader { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>term</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitTerm"/> public Action<Term>? VisitTerm { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>description</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitDescription"/> public Action<Description>? VisitDescription { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>item</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitItem"/> public Action<Item>? VisitItem { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting the <c>exception</c> documentation element. /// </summary> /// <seealso cref="Visitor.VisitException"/> public Action<Exception>? VisitException { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting an unknown member. /// </summary> /// <seealso cref="Visitor.VisitUnknownMember"/> public Action<UnknownMember>? VisitUnknownMember { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting an unknown element. /// </summary> /// <seealso cref="Visitor.VisitUnknownElement"/> public Action<UnknownElement>? VisitUnknownElement { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting any container element. /// </summary> /// <seealso cref="Visitor.VisitContainer"/> public Action<Container>? VisitContainer { get; set; } /// <summary> /// Gets or sets the action to invoke when visiting any element. /// </summary> /// <seealso cref="Visitor.VisitElement"/> public Action<Element>? VisitElement { get; set; } } /// <summary> /// A visitor that can receive delegates for each visit operation /// in the visitable model, via the <see cref="VisitorDelegates"/> /// type. /// </summary> public class DelegateVisitor : Visitor { readonly VisitorDelegates delegates; /// <summary> /// Initializes a new instance of the <see cref="DelegateVisitor"/> class. /// </summary> /// <param name="delegates">The delegates to use when visiting the model.</param> public DelegateVisitor(VisitorDelegates delegates) => this.delegates = delegates; /// <summary> /// See <see cref="Visitor.VisitDocument"/>. /// </summary> public override void VisitDocument(DocumentMembers document) { delegates.VisitDocument?.Invoke(document); base.VisitDocument(document); } /// <summary> /// See <see cref="Visitor.VisitAssembly"/>. /// </summary> public override void VisitAssembly(AssemblyMembers assembly) { delegates.VisitAssembly?.Invoke(assembly); base.VisitAssembly(assembly); } /// <summary> /// See <see cref="Visitor.VisitC"/>. /// </summary> public override void VisitC(C code) { delegates.VisitC?.Invoke(code); base.VisitC(code); } /// <summary> /// See <see cref="Visitor.VisitClass"/>. /// </summary> public override void VisitClass(Class type) { delegates.VisitClass?.Invoke(type); base.VisitClass(type); } /// <summary> /// See <see cref="Visitor.VisitCode"/>. /// </summary> public override void VisitCode(Code code) { delegates.VisitCode?.Invoke(code); base.VisitCode(code); } /// <summary> /// See <see cref="Visitor.VisitContainer"/>. /// </summary> protected override void VisitContainer(Container container) { delegates.VisitContainer?.Invoke(container); base.VisitContainer(container); } /// <summary> /// See <see cref="Visitor.VisitDescription"/>. /// </summary> public override void VisitDescription(Description description) { delegates.VisitDescription?.Invoke(description); base.VisitDescription(description); } /// <summary> /// See <see cref="Visitor.VisitElement"/>. /// </summary> protected override void VisitElement(Element element) { delegates.VisitElement?.Invoke(element); base.VisitElement(element); } /// <summary> /// See <see cref="Visitor.VisitEnum"/>. /// </summary> public override void VisitEnum(Enum type) { delegates.VisitEnum?.Invoke(type); base.VisitEnum(type); } /// <summary> /// See <see cref="Visitor.VisitEvent"/>. /// </summary> public override void VisitEvent(Event @event) { delegates.VisitEvent?.Invoke(@event); base.VisitEvent(@event); } /// <summary> /// See <see cref="Visitor.VisitExample"/>. /// </summary> public override void VisitExample(Example example) { delegates.VisitExample?.Invoke(example); base.VisitExample(example); } /// <summary> /// See <see cref="Visitor.VisitException"/>. /// </summary> public override void VisitException(Exception exception) { delegates.VisitException?.Invoke(exception); base.VisitException(exception); } /// <summary> /// See <see cref="Visitor.VisitExtensionMethod"/>. /// </summary> public override void VisitExtensionMethod(ExtensionMethod method) { delegates.VisitExtensionMethod?.Invoke(method); base.VisitExtensionMethod(method); } /// <summary> /// See <see cref="Visitor.VisitField"/>. /// </summary> public override void VisitField(Field field) { delegates.VisitField?.Invoke(field); base.VisitField(field); } /// <summary> /// See <see cref="Visitor.VisitInterface"/>. /// </summary> public override void VisitInterface(Interface type) { delegates.VisitInterface?.Invoke(type); base.VisitInterface(type); } /// <summary> /// See <see cref="Visitor.VisitItem"/>. /// </summary> public override void VisitItem(Item item) { delegates.VisitItem?.Invoke(item); base.VisitItem(item); } /// <summary> /// See <see cref="Visitor.VisitList"/>. /// </summary> public override void VisitList(List list) { delegates.VisitList?.Invoke(list); base.VisitList(list); } /// <summary> /// See <see cref="Visitor.VisitListHeader"/>. /// </summary> public override void VisitListHeader(ListHeader header) { delegates.VisitListHeader?.Invoke(header); base.VisitListHeader(header); } /// <summary> /// See <see cref="Visitor.VisitMember"/>. /// </summary> public override void VisitMember(Member member) { delegates.VisitMember?.Invoke(member); base.VisitMember(member); } /// <summary> /// See <see cref="Visitor.VisitMethod"/>. /// </summary> public override void VisitMethod(Method method) { delegates.VisitMethod?.Invoke(method); base.VisitMethod(method); } /// <summary> /// See <see cref="Visitor.VisitPara"/>. /// </summary> public override void VisitPara(Para para) { delegates.VisitPara?.Invoke(para); base.VisitPara(para); } /// <summary> /// See <see cref="Visitor.VisitParam"/>. /// </summary> public override void VisitParam(Param param) { delegates.VisitParam?.Invoke(param); base.VisitParam(param); } /// <summary> /// See <see cref="Visitor.VisitParamRef"/>. /// </summary> public override void VisitParamRef(ParamRef paramRef) { delegates.VisitParamRef?.Invoke(paramRef); base.VisitParamRef(paramRef); } /// <summary> /// See <see cref="Visitor.VisitProperty"/>. /// </summary> public override void VisitProperty(Property property) { delegates.VisitProperty?.Invoke(property); base.VisitProperty(property); } /// <summary> /// See <see cref="Visitor.VisitRemarks"/>. /// </summary> public override void VisitRemarks(Remarks remarks) { delegates.VisitRemarks?.Invoke(remarks); base.VisitRemarks(remarks); } /// <summary> /// See <see cref="Visitor.VisitSee"/>. /// </summary> public override void VisitSee(See see) { delegates.VisitSee?.Invoke(see); base.VisitSee(see); } /// <summary> /// See <see cref="Visitor.VisitSeeAlso"/>. /// </summary> public override void VisitSeeAlso(SeeAlso seeAlso) { delegates.VisitSeeAlso?.Invoke(seeAlso); base.VisitSeeAlso(seeAlso); } /// <summary> /// See <see cref="Visitor.VisitStruct"/>. /// </summary> public override void VisitStruct(Struct type) { delegates.VisitStruct?.Invoke(type); base.VisitStruct(type); } /// <summary> /// See <see cref="Visitor.VisitSummary"/>. /// </summary> public override void VisitSummary(Summary summary) { delegates.VisitSummary?.Invoke(summary); base.VisitSummary(summary); } /// <summary> /// See <see cref="Visitor.VisitTerm"/>. /// </summary> public override void VisitTerm(Term term) { delegates.VisitTerm?.Invoke(term); base.VisitTerm(term); } /// <summary> /// See <see cref="Visitor.VisitText"/>. /// </summary> public override void VisitText(Text text) { delegates.VisitText?.Invoke(text); base.VisitText(text); } /// <summary> /// See <see cref="Visitor.VisitType"/>. /// </summary> public override void VisitType(TypeDeclaration type) { delegates.VisitType?.Invoke(type); base.VisitType(type); } /// <summary> /// See <see cref="Visitor.VisitTypeParam"/>. /// </summary> public override void VisitTypeParam(TypeParam typeParam) { delegates.VisitTypeParam?.Invoke(typeParam); base.VisitTypeParam(typeParam); } /// <summary> /// See <see cref="Visitor.VisitTypeParamRef"/>. /// </summary> public override void VisitTypeParamRef(TypeParamRef typeParamRef) { delegates.VisitTypeParamRef?.Invoke(typeParamRef); base.VisitTypeParamRef(typeParamRef); } /// <summary> /// See <see cref="Visitor.VisitUnknownMember"/>. /// </summary> public override void VisitUnknownMember(UnknownMember member) { delegates.VisitUnknownMember?.Invoke(member); base.VisitUnknownMember(member); } /// <summary> /// See <see cref="Visitor.VisitUnknownElement"/>. /// </summary> public override void VisitUnknownElement(UnknownElement element) { delegates.VisitUnknownElement?.Invoke(element); base.VisitUnknownElement(element); } /// <summary> /// See <see cref="Visitor.VisitValue"/>. /// </summary> public override void VisitValue(Value value) { delegates.VisitValue?.Invoke(value); base.VisitValue(value); } /// <summary> /// See <see cref="Visitor.VisitReturns"/>. /// </summary> public override void VisitReturns(Returns returns) { delegates.VisitReturns?.Invoke(returns); base.VisitReturns(returns); } } }
32.316038
113
0.557826
[ "MIT" ]
aschuhardt/NuDoq
src/NuDoq/DelegateVisitor.cs
20,555
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="IHTMLPluginsCollection" /> struct.</summary> public static unsafe partial class IHTMLPluginsCollectionTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IHTMLPluginsCollection" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IHTMLPluginsCollection).GUID, Is.EqualTo(IID_IHTMLPluginsCollection)); } /// <summary>Validates that the <see cref="IHTMLPluginsCollection" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IHTMLPluginsCollection>(), Is.EqualTo(sizeof(IHTMLPluginsCollection))); } /// <summary>Validates that the <see cref="IHTMLPluginsCollection" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IHTMLPluginsCollection).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IHTMLPluginsCollection" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IHTMLPluginsCollection), Is.EqualTo(8)); } else { Assert.That(sizeof(IHTMLPluginsCollection), Is.EqualTo(4)); } } }
36.686275
145
0.700695
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/um/MsHTML/IHTMLPluginsCollectionTests.cs
1,873
C#
using System; using System.Data; namespace OMeta.VistaDB { #if ENTERPRISE using System.Runtime.InteropServices; [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IProcedures))] #endif public class VistaDBProcedures : Procedures { public VistaDBProcedures() { } override internal void LoadAll() { try { // DataTable metaData = this.LoadData(OleDbSchemaGuid.Procedures, null); // // PopulateArray(metaData); } catch {} } } }
17.344828
106
0.719682
[ "MIT" ]
kiler398/OMeta
src/OpenMeta/VistaDB/Procedures.cs
503
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GraphQL.Tests { public class CustomFixieConvention : Fixie.Convention { /// <summary> /// Initializes a new instance of the <see cref="CustomFixieConvention" /> class. /// </summary> public CustomFixieConvention() { this.Classes.NameEndsWith("Tests"); } } }
22.9
89
0.639738
[ "MIT" ]
mfeineis/graphql-draft-dot-net
src/GraphQL.Tests/CustomFixieConvention.cs
460
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// ContentObjectRelationForOpenapi Data Structure. /// </summary> [Serializable] public class ContentObjectRelationForOpenapi : AopObject { /// <summary> /// 对象id,如关联店铺则是shopId /// </summary> [XmlElement("object_id")] public string ObjectId { get; set; } /// <summary> /// 对象类型,内容的关联对象类型。 SHOP代表店铺, ITEM代表商品 /// </summary> [XmlElement("object_type")] public string ObjectType { get; set; } } }
24.72
61
0.563107
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/ContentObjectRelationForOpenapi.cs
684
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.InteropServices; using AltV.Net.Elements.Args; using AltV.Net.Elements.Entities; using AltV.Net.FunctionParser; namespace AltV.Net.Resources.Chat.Api { public class ChatModule : IModule { private delegate void CommandDelegate(IPlayer player, string[] arguments); private static readonly LinkedList<Function> Functions = new LinkedList<Function>(); private static readonly LinkedList<GCHandle> Handles = new LinkedList<GCHandle>(); private readonly IDictionary<string, LinkedList<CommandDelegate>> commandDelegates = new Dictionary<string, LinkedList<CommandDelegate>>(); private static readonly string[] EmptyArgs = new string[0]; public void OnScriptsStarted(IScript[] scripts) { //var chat = new Chat(); //AltChat.Init(chat); foreach (var script in scripts) { RegisterEvents(script /*, chat*/); } Alt.OnClient<IPlayer, string>("chat:message", OnChatMessage, OnChatMessageParser); //Alt.OnServer<IPlayer, string>("chat:message", OnChatMessage, OnChatMessageParserServer); } private static void OnChatMessageParser(IPlayer player, MValueConst[] mValueArray, Action<IPlayer, string> action) { if (mValueArray.Length != 1) return; var arg = mValueArray[0]; if (arg.type != MValueConst.Type.String) return; action(player, arg.GetString()); } private static void OnChatMessageParserServer(MValueConst[] mValueArray, Action<IPlayer, string> action) { if (mValueArray.Length != 1) return; var argMsg = mValueArray[0]; if (argMsg.type != MValueConst.Type.String) return; action(null, argMsg.GetString()); } private void OnChatMessage(IPlayer player, string message) { if (string.IsNullOrEmpty(message)) return; if (!message.StartsWith("/")) return; message = message.Trim().Remove(0, 1); if (message.Length > 0) { var args = message.Split(' '); var argsLength = args.Length; if (argsLength < 1) return; var cmd = args[0]; LinkedList<CommandDelegate> delegates; if (argsLength < 2) { if (commandDelegates.TryGetValue(cmd, out delegates) && delegates.Count > 0) { foreach (var commandDelegate in delegates) { commandDelegate(player, EmptyArgs); } } else { foreach (var doesNotExistsDelegate in AltChat.CommandDoesNotExistsDelegates) { doesNotExistsDelegate(player, cmd); } } return; } var argsArray = new string[argsLength - 1]; Array.Copy(args, 1, argsArray, 0, argsLength - 1); if (commandDelegates.TryGetValue(cmd, out delegates) && delegates.Count > 0) { foreach (var commandDelegate in delegates) { commandDelegate(player, argsArray); } } else { foreach (var doesNotExistsDelegate in AltChat.CommandDoesNotExistsDelegates) { doesNotExistsDelegate(player, cmd); } } } } //TODO: add function parsers for ReadOnlySpan<byte> that are same as the parsers for string for faster command parsing private void OnChatMessageSpan(IPlayer player, string message) { if (string.IsNullOrEmpty(message)) return; var messageSpan = message.AsSpan(); var length = messageSpan.Length; var start = true; var end = false; var currBlockIndex = -1; for(var i= 0;i < length;++i) { if (start && messageSpan[i] != ' ') { start = false; currBlockIndex = i; } else if(currBlockIndex != -1) { messageSpan.Slice(currBlockIndex, i - currBlockIndex); start = true; } } if (messageSpan.Length < 2 || messageSpan[0] != '/') return; //TODO: do all operations, including trim, slice and split for ' ' in single span manipulation messageSpan = messageSpan.Slice(1).Trim(); // Remove '/' and whitespace var args = message.Split(' '); var argsLength = args.Length; if (argsLength < 1) return; var cmd = args[0]; LinkedList<CommandDelegate> delegates; if (argsLength < 2) { if (commandDelegates.TryGetValue(cmd, out delegates) && delegates.Count > 0) { foreach (var commandDelegate in delegates) { commandDelegate(player, EmptyArgs); } } else { foreach (var doesNotExistsDelegate in AltChat.CommandDoesNotExistsDelegates) { doesNotExistsDelegate(player, cmd); } } return; } var argsArray = new string[argsLength - 1]; Array.Copy(args, 1, argsArray, 0, argsLength - 1); if (commandDelegates.TryGetValue(cmd, out delegates) && delegates.Count > 0) { foreach (var commandDelegate in delegates) { commandDelegate(player, argsArray); } } else { foreach (var doesNotExistsDelegate in AltChat.CommandDoesNotExistsDelegates) { doesNotExistsDelegate(player, cmd); } } } public void OnStop() { Functions.Clear(); //AltChat.Chat.Dispose(); foreach (var handle in Handles) { handle.Free(); } Handles.Clear(); } private void RegisterEvents(object target /*, Chat chat*/) { ModuleScriptMethodIndexer.Index(target, new[] {typeof(Command), typeof(CommandEvent)}, (baseEvent, eventMethod, eventMethodDelegate) => { if (baseEvent is Command command) { var commandName = command.Name ?? eventMethod.Name; Handles.AddLast(GCHandle.Alloc(eventMethodDelegate)); var function = Function.Create(Alt.Core, eventMethodDelegate); if (function == null) { Alt.Log("Unsupported Command method: " + eventMethod); return; } Functions.AddLast(function); /*chat.RegisterCommand(commandName, (player, arguments) => { function.InvokeNoResult(function.CalculateStringInvokeValues(arguments, player)); });*/ LinkedList<CommandDelegate> delegates; if (!commandDelegates.TryGetValue(commandName, out delegates)) { delegates = new LinkedList<CommandDelegate>(); commandDelegates[commandName] = delegates; } if (command.GreedyArg) { delegates.AddLast((player, arguments) => { function.Call(player, new[] {string.Join(" ", arguments)}); }); } else { delegates.AddLast((player, arguments) => { function.Call(player, arguments); }); } var aliases = command.Aliases; if (aliases != null) { foreach (var alias in aliases) { if (!commandDelegates.TryGetValue(alias, out delegates)) { delegates = new LinkedList<CommandDelegate>(); commandDelegates[alias] = delegates; } if (command.GreedyArg) { delegates.AddLast((player, arguments) => { function.Call(player, new[] {string.Join(" ", arguments)}); }); } else { delegates.AddLast((player, arguments) => { function.Call(player, arguments); }); } } } } else if (baseEvent is CommandEvent commandEvent) { var commandEventType = commandEvent.EventType; ScriptFunction scriptFunction; switch (commandEventType) { case CommandEventType.CommandNotFound: scriptFunction = ScriptFunction.Create(eventMethodDelegate, new[] {typeof(IPlayer), typeof(string)}); if (scriptFunction == null) return; AltChat.OnCommandDoesNotExists += (player, commandName) => { scriptFunction.Set(player); scriptFunction.Set(commandName); scriptFunction.Call(); }; break; } } }); } } }
40.428571
126
0.447042
[ "MIT" ]
ZackaryH8/coreclr-module
api/AltV.Net.Resources.Chat.Api/ChatModule.cs
11,037
C#
using System.Collections.Generic; using System.IO; using System.ServiceModel.Syndication; using InsanelySimpleBlog.Formatters; using InsanelySimpleBlog.Services; using InsanelySimpleBlog.Syndication; using InsanelySimpleBlog.ViewModel; using NUnit.Framework; using Rhino.Mocks; namespace InsanelySimpleBlog.Tests.Unit.Formatters { [TestFixture] public class SyndicationFormatterTests { private class NonAbstractSyndicationFormatter : SyndicationFormatter { public bool WrittenToFeed { get; set; } public NonAbstractSyndicationFormatter(string format, ISettingsService settingsService, ISyndication syndication) : base(format, settingsService, syndication) { WrittenToFeed = false; } protected override void WriteFeed(Stream writeStream, SyndicationFeed feed) { WrittenToFeed = true; } protected override SyndicationFeedFormatter GetFormatter(SyndicationFeed feed) { return null; } } private ISettingsService _settingsService; private ISyndication _syndication; [SetUp] public void Setup() { _syndication = MockRepository.GenerateStub<ISyndication>(); _settingsService = MockRepository.GenerateStub<ISettingsService>(); _settingsService.Stub(x => x.GetSettings()).Return(new SettingsViewModel { BlogPageUrl = "http://localhost/mypage", Name = "My blog" }); } [Test] public void WriteToStreamAsyncBuildsFeed() { // Arrange NonAbstractSyndicationFormatter formatter = new NonAbstractSyndicationFormatter("html/text", _settingsService, _syndication); MemoryStream ms = new MemoryStream(); IEnumerable<PostViewModel> posts = new List<PostViewModel>{ new PostViewModel { Subject = "Title", PostID = 1 }}; // Act formatter.WriteToStreamAsync(typeof(IEnumerable<PostViewModel>), posts, ms, null, null).Wait(); // Assert _syndication.AssertWasCalled(x => x.BuildFeed(posts, "My blog", "http://localhost/mypage")); Assert.That(formatter.WrittenToFeed, Is.True); } } }
40.708333
171
0.514159
[ "MIT" ]
JamesRandall/Insanely-Simple-Blog
InsanelySimpleBlog.Tests.Unit/Formatters/SyndicationFormatterTests.cs
2,933
C#
using System; using System.Text.Json.Serialization; using Julmar.TeslaApi.Internal; namespace Julmar.TeslaApi { public sealed class VehicleConfiguration { /// <summary> /// True if the car can receive map requests through /share /// </summary> [JsonPropertyName("can_accept_navigation_requests")] public bool CanAcceptNavigationRequests { get; set; } /// <summary> /// True if the trunk can open/close automatically /// </summary> [JsonPropertyName("can_actuate_trunks")] public bool CanActuateTrunks { get; set; } /// <summary> /// Extra info about car. /// </summary> [JsonPropertyName("car_special_type")] public string CarSpecialType { get; set; } /// <summary> /// Car type /// model3, etc. /// </summary> [JsonPropertyName("car_type")] public string CarType { get; set; } /// <summary> /// Charge port type /// "US" /// </summary> [JsonPropertyName("charge_port_type")] public string ChargePortType { get; set; } /// <summary> /// True if the vehicle has ECE regulations /// </summary> [JsonPropertyName("ece_restrictions")] public bool EceRestrictions { get; set; } /// <summary> /// True if this is an EU vehicle. /// </summary> [JsonPropertyName("eu_vehicle")] public bool EuVehicle { get; set; } /// <summary> /// Exterior color /// </summary> [JsonPropertyName("exterior_color")] public string ExteriorColor { get; set; } /// <summary> /// True if the car has air suspension. /// </summary> [JsonPropertyName("has_air_suspension")] public bool HasAirSuspension { get; set; } /// <summary> /// True if the car has ludicrous mode /// </summary> [JsonPropertyName("has_ludicrous_mode")] public bool HasLudicrousMode { get; set; } /// <summary> /// True if the charge port is motorized. /// </summary> [JsonPropertyName("motorized_charge_port")] public bool MotorizedChargePort { get; set; } /// <summary> /// TBD /// </summary> [JsonPropertyName("plg")] public bool Plg { get; set; } /// <summary> /// True if the car has rear seat heaters /// </summary> [JsonPropertyName("rear_seat_heaters"), JsonConverter(typeof(IntToBoolJsonConverter))] public bool RearSeatHeaters { get; set; } /// <summary> /// Rear seat type /// </summary> [JsonPropertyName("rear_seat_type")] public int? RearSeatType { get; set; } /// <summary> /// TBD /// </summary> [JsonPropertyName("rhd")] public bool Rhd { get; set; } /// <summary> /// Roof color /// </summary> [JsonPropertyName("roof_color")] public string RoofColor { get; set; } /// <summary> /// Seat type /// </summary> [JsonPropertyName("seat_type")] public int? SeatType { get; set; } /// <summary> /// Spoiler type /// </summary> [JsonPropertyName("spoiler_type")] public string SpoilerType { get; set; } /// <summary> /// Type of sun roof (null for none) /// </summary> [JsonPropertyName("sun_roof_installed")] public int? SunRoofInstalled { get; set; } /// <summary> /// Type of third row seats, "None" for none. /// </summary> [JsonPropertyName("third_row_seats")] public string ThirdRowSeats { get; set; } /// <summary> /// Timestamp of object. /// </summary> [JsonPropertyName("timestamp")] public long Timestamp { get; set; } /// <summary> /// TBD /// </summary> [JsonPropertyName("use_range_badging")] public bool UseRangeBadging { get; set; } /// <summary> /// Type of wheels /// </summary> [JsonPropertyName("wheel_type")] public string WheelType { get; set; } /// <summary>Returns a string that represents the current object.</summary> /// <returns>A string that represents the current object.</returns> public override string ToString() => $"CarType: {CarType}, ExteriorColor: {ExteriorColor}, RoofColor: {RoofColor}, WheelType: {WheelType}"; } }
29.793548
117
0.544825
[ "MIT" ]
markjulmar/teslaapi-net
src/Models/VehicleConfiguration.cs
4,620
C#
using FlipScreen.Code.Signals; using Zenject; namespace FlipScreen.Code.Installers { public class FlipScreenInstaller : MonoInstaller<FlipScreenInstaller> { public override void InstallBindings() { Container.DeclareSignal<PlayerMovedOutOfScreenSignal>(); Container.BindSignal<PlayerMovedOutOfScreenSignal>() .ToMethod<FlipScreenManager>((x, y) => x.FlipScreen(y.BorderPosition)) .FromResolve(); } } }
29.058824
86
0.661943
[ "MIT" ]
Mateo-Panadero/Ultimate-Hero
Assets/FlipScreen/Code/Installers/FlipScreenInstaller.cs
494
C#
using System.ComponentModel; using Android.App; using Android.Content; using Android.Support.V4.Widget; using Android.Views; using AListView = Android.Widget.ListView; using AView = Android.Views.View; using Xamarin.Forms.Internals; using System; using Xamarin.Forms.PlatformConfiguration.AndroidSpecific; namespace Xamarin.Forms.Platform.Android { public class ListViewRenderer : ViewRenderer<ListView, AListView>, SwipeRefreshLayout.IOnRefreshListener { ListViewAdapter _adapter; bool _disposed; IVisualElementRenderer _headerRenderer; IVisualElementRenderer _footerRenderer; Container _headerView; Container _footerView; bool _isAttached; ScrollToRequestedEventArgs _pendingScrollTo; SwipeRefreshLayout _refresh; IListViewController Controller => Element; ITemplatedItemsView<Cell> TemplatedItemsView => Element; public ListViewRenderer(Context context) : base(context) { AutoPackage = false; } [Obsolete("This constructor is obsolete as of version 2.5. Please use ListViewRenderer(Context) instead.")] public ListViewRenderer() { AutoPackage = false; } void SwipeRefreshLayout.IOnRefreshListener.OnRefresh() { IListViewController controller = Element; controller.SendRefreshing(); } protected override void Dispose(bool disposing) { if (_disposed) { return; } _disposed = true; if (disposing) { if (_headerRenderer != null) { ClearRenderer(_headerRenderer.View); _headerRenderer.Dispose(); _headerRenderer = null; } _headerView?.Dispose(); _headerView = null; if (_footerRenderer != null) { ClearRenderer(_footerRenderer.View); _footerRenderer.Dispose(); _footerRenderer = null; } _footerView?.Dispose(); _footerView = null; if (_adapter != null) { _adapter.Dispose(); _adapter = null; } Controller.ScrollToRequested -= OnScrollToRequested; } base.Dispose(disposing); } protected override Size MinimumSize() { return new Size(40, 40); } protected override void OnAttachedToWindow() { base.OnAttachedToWindow(); _isAttached = true; _adapter.IsAttachedToWindow = _isAttached; UpdateIsRefreshing(isInitialValue: true); } protected override void OnDetachedFromWindow() { base.OnDetachedFromWindow(); _isAttached = false; _adapter.IsAttachedToWindow = _isAttached; } protected override AListView CreateNativeControl() { return new AListView(Context); } protected override void OnElementChanged(ElementChangedEventArgs<ListView> e) { base.OnElementChanged(e); if (e.OldElement != null) { ((IListViewController)e.OldElement).ScrollToRequested -= OnScrollToRequested; if (_adapter != null) { _adapter.Dispose(); _adapter = null; } } if (e.NewElement != null) { AListView nativeListView = Control; if (nativeListView == null) { var ctx = Context; nativeListView = CreateNativeControl(); _refresh = new SwipeRefreshLayout(ctx); _refresh.SetOnRefreshListener(this); _refresh.AddView(nativeListView, LayoutParams.MatchParent); SetNativeControl(nativeListView, _refresh); _headerView = new Container(ctx); nativeListView.AddHeaderView(_headerView, null, false); _footerView = new Container(ctx); nativeListView.AddFooterView(_footerView, null, false); } ((IListViewController)e.NewElement).ScrollToRequested += OnScrollToRequested; nativeListView.DividerHeight = 0; nativeListView.Focusable = false; nativeListView.DescendantFocusability = DescendantFocusability.AfterDescendants; nativeListView.OnFocusChangeListener = this; nativeListView.Adapter = _adapter = e.NewElement.IsGroupingEnabled && e.NewElement.OnThisPlatform().IsFastScrollEnabled() ? new GroupedListViewAdapter(Context, nativeListView, e.NewElement) : new ListViewAdapter(Context, nativeListView, e.NewElement); _adapter.HeaderView = _headerView; _adapter.FooterView = _footerView; _adapter.IsAttachedToWindow = _isAttached; UpdateHeader(); UpdateFooter(); UpdateIsSwipeToRefreshEnabled(); UpdateFastScrollEnabled(); } } internal void LongClickOn(AView viewCell) { if (Control == null) { return; } var position = Control.GetPositionForView(viewCell); var id = Control.GetItemIdAtPosition(position); viewCell.PerformHapticFeedback(FeedbackConstants.ContextClick); _adapter.OnItemLongClick(Control, viewCell, position, id); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == "HeaderElement") UpdateHeader(); else if (e.PropertyName == "FooterElement") UpdateFooter(); else if (e.PropertyName == "RefreshAllowed") UpdateIsSwipeToRefreshEnabled(); else if (e.PropertyName == ListView.IsPullToRefreshEnabledProperty.PropertyName) UpdateIsSwipeToRefreshEnabled(); else if (e.PropertyName == ListView.IsRefreshingProperty.PropertyName) UpdateIsRefreshing(); else if (e.PropertyName == ListView.SeparatorColorProperty.PropertyName || e.PropertyName == ListView.SeparatorVisibilityProperty.PropertyName) _adapter.NotifyDataSetChanged(); else if (e.PropertyName == PlatformConfiguration.AndroidSpecific.ListView.IsFastScrollEnabledProperty.PropertyName) UpdateFastScrollEnabled(); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { base.OnLayout(changed, l, t, r, b); if (_pendingScrollTo != null) { OnScrollToRequested(this, _pendingScrollTo); _pendingScrollTo = null; } } void OnScrollToRequested(object sender, ScrollToRequestedEventArgs e) { if (!_isAttached) { _pendingScrollTo = e; return; } Cell cell; int position; var scrollArgs = (ITemplatedItemsListScrollToRequestedEventArgs)e; var templatedItems = TemplatedItemsView.TemplatedItems; if (Element.IsGroupingEnabled) { var results = templatedItems.GetGroupAndIndexOfItem(scrollArgs.Group, scrollArgs.Item); if (results.Item1 == -1 || results.Item2 == -1) return; var group = templatedItems.GetGroup(results.Item1); cell = group[results.Item2]; position = templatedItems.GetGlobalIndexForGroup(group) + results.Item2 + 1; } else { position = templatedItems.GetGlobalIndexOfItem(scrollArgs.Item); if (position == -1) return; cell = templatedItems[position]; } //Android offsets position of cells when using header int realPositionWithHeader = position + 1; if (e.Position == ScrollToPosition.MakeVisible) { if (e.ShouldAnimate) Control.SmoothScrollToPosition(realPositionWithHeader); else Control.SetSelection(realPositionWithHeader); return; } int height = Control.Height; var cellHeight = (int)cell.RenderHeight; if (cellHeight == -1) { int first = Control.FirstVisiblePosition; if (first <= position && position <= Control.LastVisiblePosition) cellHeight = Control.GetChildAt(position - first).Height; else { AView view = _adapter.GetView(position, null, null); view.Measure(MeasureSpecFactory.MakeMeasureSpec(Control.Width, MeasureSpecMode.AtMost), MeasureSpecFactory.MakeMeasureSpec(0, MeasureSpecMode.Unspecified)); cellHeight = view.MeasuredHeight; } } var y = 0; if (e.Position == ScrollToPosition.Center) y = height / 2 - cellHeight / 2; else if (e.Position == ScrollToPosition.End) y = height - cellHeight; if (e.ShouldAnimate) Control.SmoothScrollToPositionFromTop(realPositionWithHeader, y); else Control.SetSelectionFromTop(realPositionWithHeader, y); } void ClearRenderer(AView renderedView) { var element = (renderedView as IVisualElementRenderer)?.Element; var view = element as View; if (view != null) { var renderer = Platform.GetRenderer(view); if (renderer == renderedView) element.ClearValue(Platform.RendererProperty); renderer?.Dispose(); renderer = null; } var layout = view as IVisualElementRenderer; layout?.Dispose(); layout = null; } void UpdateFooter() { var footer = (VisualElement)Controller.FooterElement; if (_footerRenderer != null) { var reflectableType = _footerRenderer as System.Reflection.IReflectableType; var rendererType = reflectableType != null ? reflectableType.GetTypeInfo().AsType() : _footerRenderer.GetType(); if (footer == null || Registrar.Registered.GetHandlerTypeForObject(footer) != rendererType) { if (_footerView != null) _footerView.Child = null; ClearRenderer(_footerRenderer.View); _footerRenderer.Dispose(); _footerRenderer = null; } } if (footer == null) return; if (_footerRenderer != null) _footerRenderer.SetElement(footer); else { _footerRenderer = Platform.CreateRenderer(footer, Context); if (_footerView != null) _footerView.Child = _footerRenderer; } Platform.SetRenderer(footer, _footerRenderer); } void UpdateHeader() { var header = (VisualElement)Controller.HeaderElement; if (_headerRenderer != null) { var reflectableType = _headerRenderer as System.Reflection.IReflectableType; var rendererType = reflectableType != null ? reflectableType.GetTypeInfo().AsType() : _headerRenderer.GetType(); if (header == null || Registrar.Registered.GetHandlerTypeForObject(header) != rendererType) { if (_headerView != null) _headerView.Child = null; ClearRenderer(_headerRenderer.View); _headerRenderer.Dispose(); _headerRenderer = null; } } if (header == null) return; if (_headerRenderer != null) _headerRenderer.SetElement(header); else { _headerRenderer = Platform.CreateRenderer(header, Context); if (_headerView != null) _headerView.Child = _headerRenderer; } Platform.SetRenderer(header, _headerRenderer); } void UpdateIsRefreshing(bool isInitialValue = false) { if (_refresh != null) { var isRefreshing = Element.IsRefreshing; if (isRefreshing && isInitialValue) { _refresh.Refreshing = false; _refresh.Post(() => { _refresh.Refreshing = true; }); } else _refresh.Refreshing = isRefreshing; } } void UpdateIsSwipeToRefreshEnabled() { if (_refresh != null) _refresh.Enabled = Element.IsPullToRefreshEnabled && (Element as IListViewController).RefreshAllowed; } void UpdateFastScrollEnabled() { if (Control != null) { Control.FastScrollEnabled = Element.OnThisPlatform().IsFastScrollEnabled(); } } internal class Container : ViewGroup { IVisualElementRenderer _child; public Container(IntPtr p, global::Android.Runtime.JniHandleOwnership o) : base(p, o) { // Added default constructor to prevent crash when accessing header/footer row in ListViewAdapter.Dispose } public Container(Context context) : base(context) { } public IVisualElementRenderer Child { set { if (_child != null) RemoveView(_child.View); _child = value; if (value != null) AddView(value.View); } } protected override void OnLayout(bool changed, int l, int t, int r, int b) { if (_child == null) return; _child.UpdateLayout(); } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (_child == null) { SetMeasuredDimension(0, 0); return; } VisualElement element = _child.Element; Context ctx = Context; var width = (int)ctx.FromPixels(MeasureSpecFactory.GetSize(widthMeasureSpec)); SizeRequest request = _child.Element.Measure(width, double.PositiveInfinity, MeasureFlags.IncludeMargins); Xamarin.Forms.Layout.LayoutChildIntoBoundingRegion(_child.Element, new Rectangle(0, 0, width, request.Request.Height)); int widthSpec = MeasureSpecFactory.MakeMeasureSpec((int)ctx.ToPixels(width), MeasureSpecMode.Exactly); int heightSpec = MeasureSpecFactory.MakeMeasureSpec((int)ctx.ToPixels(request.Request.Height), MeasureSpecMode.Exactly); _child.View.Measure(widthMeasureSpec, heightMeasureSpec); SetMeasuredDimension(widthSpec, heightSpec); } } } }
26.993464
255
0.71025
[ "MIT" ]
1rfan786/xamarin.android
Xamarin.Forms.Platform.Android/Renderers/ListViewRenderer.cs
12,390
C#
using System; using System.Collections.Generic; using System.Text; using Common.Utils.Npa.DataAccess; using MySql.Data.MySqlClient; namespace Test.Utils.Npa { public class MySqlDataAccess : AbstractDataAccess { private MySqlConnection _Connection; public MySqlConnection Connection { get { return _Connection; } set { _Connection = value; } } public MySqlDataAccess(String connStr) { this.Connection = new MySqlConnection(connStr); this.Connection.Open(); } public override System.Data.Common.DbDataAdapter getAdapter() { return new MySqlDataAdapter(); } public override System.Data.Common.DbConnection getConnection() { return this.Connection; } } }
24.416667
72
0.592719
[ "MIT" ]
wenzqbaby/CommonTools
Test/Utils/Npa/MySqlDataAccess.cs
879
C#
using System.Linq; using System.Threading.Tasks; using Dynatrace.Net.Configuration.ConditionalNaming.Models; using Xunit; // ReSharper disable once CheckNamespace namespace Dynatrace.Net.Tests { public partial class DynatraceClientShould { [Fact] public async Task GetAllConditionalNamingRulesAsync() { var result = await _client.GetAllConditionalNamingRulesAsync(ConditionalNamingTypes.Host).ConfigureAwait(false); Assert.NotNull(result); } [Fact] public async Task GetConditionalNamingRuleAsync() { var results = await _client.GetAllConditionalNamingRulesAsync(ConditionalNamingTypes.Host).ConfigureAwait(false); var firstResult = results.Values.FirstOrDefault(); if (firstResult is null) { return; } var result = await _client.GetConditionalNamingRuleAsync(ConditionalNamingTypes.Host, firstResult.Id).ConfigureAwait(false); Assert.NotNull(result); } } }
28.606061
128
0.755297
[ "MIT" ]
lvermeulen/Dynatrace.Net
test/Dynatrace.Net.Tests/Configuration/ConditionalNaming/DynatraceClientShould.cs
946
C#
using JT809.Protocol.Extensions.JT1078.MessageBody; using JT809.Protocol.Formatters; using JT809.Protocol.MessagePack; using System; using System.Collections.Generic; using System.Text; namespace JT809.Protocol.Extensions.JT1078.Formatters { public class JT809_JT1078_0x1700_0x1701_Formatter : IJT809MessagePackFormatter<JT809_JT1078_0x1700_0x1701> { public JT809_JT1078_0x1700_0x1701 Deserialize(ref JT809MessagePackReader reader, IJT809Config config) { JT809_JT1078_0x1700_0x1701 jT808_JT1078_0X1701 = new JT809_JT1078_0x1700_0x1701(); jT808_JT1078_0X1701.PlateFormId = reader.ReadArray(11).ToArray(); jT808_JT1078_0X1701.AuthorizeCode1 = reader.ReadArray(64).ToArray(); jT808_JT1078_0X1701.AuthorizeCode2 = reader.ReadArray(64).ToArray(); return jT808_JT1078_0X1701; } public void Serialize(ref JT809MessagePackWriter writer, JT809_JT1078_0x1700_0x1701 value, IJT809Config config) { writer.WriteArray(value.PlateFormId); writer.WriteArray(value.AuthorizeCode1); writer.WriteArray(value.AuthorizeCode2); } } }
41.785714
119
0.738462
[ "MIT" ]
caocf/JT1078
src/JT809.Protocol.Extensions.JT1078/Formatters/JT809_JT1078_0x1700_0x1701_Formatter.cs
1,172
C#
using GS.DecoupleIt.Operations; using Samples.Clients.Command.QueryResult; namespace Samples.Clients.Command.Queries { public sealed class GetAllClientBaskets : Query<GetAllClientBasketsResult> { } }
25.75
82
0.81068
[ "MIT" ]
krzysztofdudek/DecoupleIt
Samples/Samples.Clients.Command/Queries/GetAllClientBaskets.cs
208
C#
using System; using System.Linq; using System.Collections.Generic; using QuickGraph; using Microsoft.Extensions.Logging; using Sandwych.MapMatchingKit.Utility; namespace Sandwych.MapMatchingKit.Topology.PrecomputedDijkstra { public class PrecomputedDijkstraTableGenerator<TVertex, TEdge> where TEdge : class, IEdge<TVertex> where TVertex : IEquatable<TVertex> { public ILogger Logger { get; set; } = NullLogger.Instance; public IEnumerable<PrecomputedDijkstraTableRow<TVertex, TEdge>> ComputeRows( IVertexAndEdgeListGraph<TVertex, TEdge> graph, Func<TEdge, double> cost, Func<TEdge, double> bound, double maxRadius) { var pquery = graph.Vertices.AsParallel(); var allRows = pquery.SelectMany(rootVertex => this.ComputeRowsSingleSource(graph, rootVertex, cost, bound, maxRadius)); var rowsList = allRows.ToArray(); if (this.Logger.IsEnabled(LogLevel.Debug)) { this.Logger.LogDebug("Rows count: {0}", rowsList.Length); } return rowsList; } private IEnumerable<PrecomputedDijkstraTableRow<TVertex, TEdge>> ComputeRowsSingleSource( IVertexAndEdgeListGraph<TVertex, TEdge> graph, TVertex sourceVertex, Func<TEdge, double> cost, Func<TEdge, double> bound, double maxRadius) { var dijkstra = new BoundedDijkstraShortestPathAlgorithm<TVertex, TEdge>(graph, cost, bound, maxRadius); try { dijkstra.Compute(sourceVertex); } catch (OutOfRadiusException) { } var pred = dijkstra.Predecessors; foreach (var u in dijkstra.VisitedVertices) { if (u.Equals(sourceVertex)) { continue; } var v = u; while (!pred[v].Source.Equals(sourceVertex)) { v = pred[v].Source; } graph.TryGetEdge(sourceVertex, v, out var sourceEdge); var targetEdge = pred[u]; var row = new PrecomputedDijkstraTableRow<TVertex, TEdge>(sourceEdge, targetEdge, dijkstra.GetDistance(u)); yield return row; } } } }
34.550725
131
0.583893
[ "Apache-2.0" ]
oldrev/mapmatchingkit
src/Sandwych.MapMatchingKit/Topology/PrecomputedDijkstra/PrecomputedDijkstraTableGenerator.cs
2,386
C#
using Basket.API.GrpcServices; using Basket.API.Repositories; using Discount.Grpc.Protos; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Basket.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Redis Configuration services.AddStackExchangeRedisCache(options => { options.Configuration = Configuration.GetValue<string>("CacheSettings:ConnectionString"); }); services.AddScoped<IBasketRepository, BasketRepository>(); // Grpc Configuration services.AddGrpcClient<DiscountProtoService.DiscountProtoServiceClient> (o => o.Address = new Uri(Configuration["GrpcSettings:DiscountUrl"])); services.AddScoped<DiscountGrpcService>(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Basket.API", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Basket.API v1")); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
32.314286
106
0.623342
[ "MIT" ]
ETabelev/AspnetMicroservices
src/Services/Basket/Basket.API/Startup.cs
2,262
C#
using System; class MinAndMaxNumsFromSequence { static void Main() { int n; int minNumber; int maxNumber; int number; Console.Write("Enter n="); n = int.Parse(Console.ReadLine()); Console.Write("Enter number 1:"); number = int.Parse(Console.ReadLine()); minNumber = maxNumber = number; for (int i = 2; i <= n; i++) { Console.Write("Enter number {0}:", i); number = int.Parse(Console.ReadLine()); minNumber = Math.Min(number, minNumber); maxNumber = Math.Max(number, maxNumber); } Console.WriteLine("The minimal number of the sequence is {0} and the maximum is {1}", minNumber, maxNumber); } }
29.192308
116
0.55336
[ "MIT" ]
madbadPi/TelerikAcademy
CSharpPartOne/Loops/3.MinAndMaxNumsFromSequence/MinAndMaxNumsFromSequence.cs
761
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401 { using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell; /// <summary>Properties of key vault.</summary> [System.ComponentModel.TypeConverter(typeof(KeyVaultPropertiesTypeConverter))] public partial class KeyVaultProperties { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.KeyVaultProperties" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultProperties" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new KeyVaultProperties(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.KeyVaultProperties" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultProperties" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new KeyVaultProperties(content); } /// <summary> /// Creates a new instance of <see cref="KeyVaultProperties" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.KeyVaultProperties" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal KeyVaultProperties(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyName = (string) content.GetValueForProperty("KeyName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyVaultUri = (string) content.GetValueForProperty("KeyVaultUri",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyVaultUri, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyVersion = (string) content.GetValueForProperty("KeyVersion",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyVersion, global::System.Convert.ToString); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.KeyVaultProperties" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal KeyVaultProperties(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyName = (string) content.GetValueForProperty("KeyName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyVaultUri = (string) content.GetValueForProperty("KeyVaultUri",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyVaultUri, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyVersion = (string) content.GetValueForProperty("KeyVersion",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.IKeyVaultPropertiesInternal)this).KeyVersion, global::System.Convert.ToString); AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Properties of key vault. [System.ComponentModel.TypeConverter(typeof(KeyVaultPropertiesTypeConverter))] public partial interface IKeyVaultProperties { } }
69.022222
324
0.702833
[ "MIT" ]
Arsasana/azure-powershell
src/Functions/generated/api/Models/Api20190401/KeyVaultProperties.PowerShell.cs
9,184
C#
namespace CookingPot.Data.Configurations { using CookingPot.Data.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; public class ApplicationUserConfiguration : IEntityTypeConfiguration<ApplicationUser> { public void Configure(EntityTypeBuilder<ApplicationUser> appUser) { appUser .HasMany(e => e.Claims) .WithOne() .HasForeignKey(e => e.UserId) .IsRequired() .OnDelete(DeleteBehavior.Restrict); appUser .HasMany(e => e.Logins) .WithOne() .HasForeignKey(e => e.UserId) .IsRequired() .OnDelete(DeleteBehavior.Restrict); appUser .HasMany(e => e.Roles) .WithOne() .HasForeignKey(e => e.UserId) .IsRequired() .OnDelete(DeleteBehavior.Restrict); } } }
30.088235
89
0.536657
[ "MIT" ]
vib1336/CookingPot
src/Data/CookingPot.Data/Configurations/ApplicationUserConfiguration.cs
1,025
C#
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Threading; using System.Timers; using System.Diagnostics; using System.Collections.Generic; namespace Battleship { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private bool shipShadow = false; private int calculatedCell = -1; private string player1Name; private static readonly int rows = 10; private static readonly int columns = 10; Random rnd = new(); char[,] playerPlayfield = new char[10, 10]; char[,] aiPlayfield = new char[10, 10]; bool aiShipsShow = false; bool left, right, down, up, con = false; int firstHitX, firstHitY, randomX, randomY; private int changePlayerCounter = 0; private int playerHits; private const double RefreshTimeSec = 10; private readonly DispatcherTimer _timer = new DispatcherTimer(DispatcherPriority.Send); public MainWindow(Grid playfield, char[,] playerPlayfield, string player1Name) { InitializeComponent(); this.playerPlayfield = playerPlayfield; this.player1Name = player1Name; playerShipsLoad(playfield); shipAI(rnd); //game(rnd); shipStatHpInit(); } private int calculateCell() //which cell the cursor is on { var point = Mouse.GetPosition(rightTable); int row = 0; int col = 0; double accumulatedHeight = 0.0; double accumulatedWidth = 0.0; foreach (var rowDefinition in rightTable.RowDefinitions) { accumulatedHeight += rowDefinition.ActualHeight; if (accumulatedHeight >= point.Y) break; row++; } foreach (var columnDefinition in rightTable.ColumnDefinitions) { accumulatedWidth += columnDefinition.ActualWidth; if (accumulatedWidth >= point.X) break; col++; } return (row * 10) + col; } private void deleteShipShadow(int shipLength) { if (shipShadow == true) { for (int i = 0; i < shipLength; i++) { int lastItem = rightTable.Children.Count - 1; rightTable.Children.RemoveAt(lastItem); } } } private void onGridMouseOver(object sender, MouseEventArgs e) //ship shadow { int shipLength = 1; if (shipLength != 0) { int cell = calculateCell(); if (calculatedCell != cell) { calculatedCell = cell; deleteShipShadow(shipLength); for (int i = 0; i < shipLength; i++) { var ship = new Rectangle(); ship.Fill = Brushes.LightGray; var Y = rightTable.Width / rows; var X = rightTable.Height / columns; ship.Width = Y; ship.Height = X; Grid.SetRow(ship, cell / rows + i); Grid.SetColumn(ship, cell % columns); shipShadow = true; rightTable.Children.Add(ship); } } } } private void onGridMouseClick(object sender, MouseButtonEventArgs e) //ship placement in the playfield { if(e.ClickCount == 1) { int shipLength = 1; deleteShipShadow(shipLength); shipShadow = false; int cell = calculateCell(); Debug.WriteLine($"{cell % columns}, {cell / rows}"); for (int i = 0; i < shipLength; i++) { if (char.IsDigit(aiPlayfield[cell % columns, cell / rows])) { var ship = shipSettings(shipLength); ship.Fill = Brushes.DarkRed; Grid.SetRow(ship, cell / rows); Grid.SetColumn(ship, cell % columns); Debug.WriteLine(aiPlayfield[cell % columns, cell / rows]); char c = aiPlayfield[cell % columns, cell / rows]; aiPlayfield[cell % columns, cell / rows] = 'T'; Debug.WriteLine(int.Parse(c.ToString())); shipHp(int.Parse(c.ToString())); ship.Visibility = Visibility.Visible; rightTable.Children.Add(ship); playerHits++; playerHitsLabel.Content = playerHits; if (isEndGame(0)) // player { onScore(player1Name); MessageBox.Show("The Player won!", "Winner", MessageBoxButton.OK, MessageBoxImage.Asterisk); StartWindow startWindow = new StartWindow(); this.Close(); startWindow.Show(); } } else if(!(aiPlayfield[cell % columns, cell / rows] == 'T' || aiPlayfield[cell % columns, cell / rows] == 'V' )) { var ship = shipSettings(shipLength); ship.Fill = Brushes.Gray; Grid.SetRow(ship, cell / rows); Grid.SetColumn(ship, cell % columns); aiPlayfield[cell % columns, cell / rows] = 'V'; ship.Visibility = Visibility.Visible; rightTable.Children.Add(ship); roundsLabelIncrement(); Random rnd = new Random(); game(rnd); if(isEndGame(1)) { onScore("AI"); MessageBox.Show("The AI won!", "Loser", MessageBoxButton.OK, MessageBoxImage.Asterisk); StartWindow startWindow = new StartWindow(); this.Close(); startWindow.Show(); } } } } } private void onScore(string winner) { //score List<Score> scores = ScoreResult.ReadResult("score.json"); if(scores == null) { scores = new List<Score>(); } Score newScore = new() { Enemy = "AI", EnemyHits = Convert.ToInt32(computerHitsLabel.Content), Player = player1Name, PlayerHits = Convert.ToInt32(playerHitsLabel.Content), Rounds = Convert.ToInt32(roundsLabel.Content), Winner = winner }; scores.Add(newScore); ScoreResult.WriteResult(scores, "score.json"); } private void shipHp(int s) { Debug.WriteLine(s); if (s == 1) { destroyerHpGrid.Children.RemoveAt(destroyerHpGrid.Children.Count - 1); } else if (s == 2) { submarineHpGrid.Children.RemoveAt(submarineHpGrid.Children.Count - 1); } else if (s == 3) { cruiserHpGrid.Children.RemoveAt(cruiserHpGrid.Children.Count - 1); } else if (s == 4) { battleshipHpGrid.Children.RemoveAt(battleshipHpGrid.Children.Count - 1); } else if (s == 5) { carrierHpGrid.Children.RemoveAt(carrierHpGrid.Children.Count - 1); } } public bool isEndGame(int player) { if(player == 0) { for (int row = 0; row < 10; row++) { for(int col = 0; col < 10; col++) { if(char.IsDigit(aiPlayfield[row, col])) { return false; } } } } else if(player == 1) { for (int row = 0; row < 10; row++) { for (int col = 0; col < 10; col++) { if (char.IsDigit(playerPlayfield[row, col])) { return false; } } } } return true; } private void shipStatHpInit() { for (int ship = 5; ship > 0; ship--) { for (int unit = 0; unit < ship; unit++) { Rectangle hpUnit = shipHpSettings(ship); Grid.SetColumn(hpUnit, unit); switch (ship) { case 5: carrierHpGrid.Children.Add(hpUnit); break; case 4: battleshipHpGrid.Children.Add(hpUnit); break; case 3: cruiserHpGrid.Children.Add(hpUnit); break; case 2: submarineHpGrid.Children.Add(hpUnit); break; case 1: destroyerHpGrid.Children.Add(hpUnit); break; } } } } private Rectangle shipHpSettings(int shipLength) { Rectangle hpUnit = new() { Fill = Brushes.Green }; var Y = carrierHpGrid.Width; var X = carrierHpGrid.Height / shipLength; hpUnit.Width = Y; hpUnit.Height = X; return hpUnit; } public MainWindow(Grid playfield, char[,] playerPlayfield, char[,] playerPlayfield2) { InitializeComponent(); this.playerPlayfield = playerPlayfield; playerShipsLoad(playfield); for (int row = 0; row < 10; row++) { for (int col = 0; col < 10; col++) { Rectangle ship = new() { Fill = Brushes.Red }; var Y = rightTable.Width / rows; var X = rightTable.Height / columns; ship.Width = Y; ship.Height = X; Grid.SetRow(ship, row); Grid.SetColumn(ship, col); if (char.IsDigit(playerPlayfield[row, col])) { rightTable.Children.Add(ship); } } } } private void playerShipsLoad(Grid playfield) { for (int unit = playfield.Children.Count - 1; unit >= 0; unit--) { var child = playfield.Children[unit]; playfield.Children.RemoveAt(unit); leftTable.Children.Add(child); } } private void shipAI(Random rnd) { int randomOrient; int randomPosX = (int)rnd.Next(0, 10); int randomPosY = (int)rnd.Next(0, 10); bool empty; for (int i = 5; i > 0; i--) { empty = false; randomOrient = (int)rnd.Next(0, 2); if (randomOrient == 0) // vízsintes { randomPosX = (int)rnd.Next(0, 10 - i + 1); randomPosY = (int)rnd.Next(0, 10); while (empty == false) { if ((randomPosX != 0 && char.IsDigit(aiPlayfield[randomPosY, randomPosX - 1])) || ((randomPosX + i - 1) != 9 && char.IsDigit(aiPlayfield[randomPosY, randomPosX + i]))) { randomPosX = (int)rnd.Next(0, 10 - i + 1); randomPosY = (int)rnd.Next(0, 10); } else { for (int k = 0; k < i; k++) { if (char.IsDigit(aiPlayfield[randomPosY, randomPosX + k]) || (randomPosY != 0 && char.IsDigit(aiPlayfield[randomPosY - 1, randomPosX + k])) || (randomPosY != 9 && char.IsDigit(aiPlayfield[randomPosY + 1, randomPosX + k]))) { randomPosX = (int)rnd.Next(0, 10 - i + 1); randomPosY = (int)rnd.Next(0, 10); k = 0; break; } else if (k == (i - 1)) { empty = true; } } } } for (int col = 0; col < i; col++) { Rectangle ship = shipSettings(i); Grid.SetRow(ship, col + randomPosX); Grid.SetColumn(ship, randomPosY); aiPlayfield[randomPosY, col + randomPosX] = Convert.ToChar(i.ToString()); rightTable.Children.Add(ship); } } else if (randomOrient == 1) //függőleges { randomPosY = (int)rnd.Next(0, 10 - i + 1); randomPosX = (int)rnd.Next(0, 10); while (empty == false) { if ((randomPosY != 0 && char.IsDigit(aiPlayfield[randomPosY - 1, randomPosX])) || ((randomPosY + i - 1) != 9 && char.IsDigit(aiPlayfield[randomPosY + i, randomPosX]))) { randomPosY = (int)rnd.Next(0, 10 - i + 1); randomPosX = (int)rnd.Next(0, 10); } else { for (int k = 0; k < i; k++) { if (char.IsDigit(aiPlayfield[randomPosY + k, randomPosX]) || (randomPosX != 0 && char.IsDigit(aiPlayfield[randomPosY + k, randomPosX - 1])) || (randomPosX != 9 && char.IsDigit(aiPlayfield[randomPosY + k, randomPosX + 1]))) { randomPosY = (int)rnd.Next(0, 10 - i + 1); randomPosX = (int)rnd.Next(0, 10); k = 0; break; } else if (k == (i - 1)) { empty = true; } } } } for (int row = 0; row < i; row++) { Rectangle ship = shipSettings(i); Grid.SetRow(ship, randomPosX); Grid.SetColumn(ship, row + randomPosY); aiPlayfield[randomPosY + row, randomPosX] = Convert.ToChar(i.ToString()); rightTable.Children.Add(ship); } } } } private Rectangle shipSettings(int shipLength) { Rectangle ship = new() { Fill = Brushes.DodgerBlue }; var Y = rightTable.Width / rows; var X = rightTable.Height / columns; ship.Width = Y; ship.Height = X; shipSetName(ship, shipLength); ship.Visibility = Visibility.Hidden; return ship; } private void shipSetName(Rectangle ship, int shipLength) { switch (shipLength) { case 5: ship.Name = "Carrier"; break; case 4: ship.Name = "Battleship"; break; case 3: ship.Name = "Cruiser"; break; case 2: ship.Name = "Submarine"; break; case 1: ship.Name = "Destroyer"; break; } } private void aiVisibility_KeyDown(object sender, KeyEventArgs e) { if (Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.S)) { aiShipsShow = !aiShipsShow; for (int unit = 0; unit < 15; unit++) { if (aiShipsShow) { rightTable.Children[unit].Visibility = Visibility.Visible; } else { rightTable.Children[unit].Visibility = Visibility.Hidden; } } } } private void surrendBtn_Click(object sender, RoutedEventArgs e) { onScore("AI"); StartWindow startWindow = new StartWindow(); this.Close(); startWindow.Show(); } private void stats_Click(object sender, RoutedEventArgs e) { Stats stats = new(); stats.Show(); } private void game(Random rnd) { bool player = false; // false - AI | true - Player bool isHit = false; while (!player) { if (!con) { int cell = AiMethods.generateAiShoot(rnd, playerPlayfield); randomY = cell / rows; randomX = cell % columns; isHit = shoot(randomY, randomX, "center"); if (isHit) { firstHitX = randomX; firstHitY = randomY; } } else { isHit = true; } while (isHit) //ha eltalálta vagy olyan helyre lőtt ahová nem lehet vagy már lőtt oda { con = true; int direction = rnd.Next(0, 4); switch (direction) { case 0: while (!up) { if (shoot(randomY, randomX, "Up")) { randomY++; computerHitsLabelIncerement(); right = true; left = true; } else { randomY = firstHitY; player = true; isHit = false; up = true; roundsLabelIncrement(); } } break; case 1: while (!down) { if (shoot(randomY, randomX, "Down")) { randomY--; right = true; left = true; computerHitsLabelIncerement(); } else { randomY = firstHitY; player = true; isHit = false; down = true; roundsLabelIncrement(); } } break; case 2: while (!left) { if (shoot(randomY, randomX, "Left")) { randomX--; up = true; down = true; computerHitsLabelIncerement(); } else { randomX = firstHitX; player = true; isHit = false; left = true; roundsLabelIncrement(); } } break; case 3: while (!right) { if (shoot(randomY, randomX, "Right")) { randomX++; up = true; down = true; computerHitsLabelIncerement(); } else { randomX = firstHitX; player = true; isHit = false; right = true; roundsLabelIncrement(); } } break; } if (shipDestroyed(up, down, left, right)) { break; } } player = true; } } private void roundsLabelIncrement() { changePlayerCounter++; if (changePlayerCounter % 2 == 0) { roundsLabel.Content = Convert.ToInt32(roundsLabel.Content) + 1; } } private void computerHitsLabelIncerement() { computerHitsLabel.Content = Convert.ToInt32(computerHitsLabel.Content) + 1; } private bool shipDestroyed(bool up, bool down, bool left, bool right) { if (up && down && left && right) { initializeDirection(); con = false; return true; } return false; } private void initializeDirection() { up = false; down = false; left = false; right = false; } private bool shoot(int randomY, int randomX, string direction) { switch (direction) { case "Up": randomY++; break; case "Down": randomY--; break; case "Left": randomX--; break; case "Right": randomX++; break; } if (!AiMethods.isCellWall(randomX, randomY)) { if (!AiMethods.isCellShootedAI(randomX, randomY, playerPlayfield)) { if (AiMethods.isHitPlayerShipUnit(randomX, randomY, playerPlayfield)) { shootedCellChange(randomX, randomY, true); paintHitCell(randomX, randomY); return true; } else { shootedCellChange(randomX, randomY, false); paintMissCell(randomX, randomY); return false; } } else { return false; } } else { return false; } } private void shootedCellChange(int randomX, int randomY, bool isHit) { if (isHit) { playerPlayfield[randomY, randomX] = 'T'; } else { playerPlayfield[randomY, randomX] = 'V'; } } private void paintMissCell(int randomX, int randomY) { Rectangle ship = shipHpSettings(1); ship.Fill = Brushes.Gray; Grid.SetRow(ship, randomY); Grid.SetColumn(ship, randomX); leftTable.Children.Add(ship); } private void paintHitCell(int randomX, int randomY) { Rectangle ship = shipHpSettings(1); ship.Fill = Brushes.DarkRed; Grid.SetRow(ship, randomY); Grid.SetColumn(ship, randomX); leftTable.Children.Add(ship); } } }
33.390704
254
0.372174
[ "MIT" ]
polonkaipal/CSharp-Projekt
Battleship/MainWindow.xaml.cs
26,587
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.TestCommon; namespace System.Web.Mvc.Test { public class ReaderWriterCacheTest { [Fact] public void PublicFetchOrCreateItemCreatesItemIfNotAlreadyInCache() { // Arrange ReaderWriterCacheHelper<int, string> helper = new ReaderWriterCacheHelper<int, string>(); Dictionary<int, string> cache = helper.PublicCache; // Act string item = helper.PublicFetchOrCreateItem(42, () => "new"); // Assert Assert.Equal("new", cache[42]); Assert.Equal("new", item); } [Fact] public void PublicFetchOrCreateItemReturnsExistingItemIfFound() { // Arrange ReaderWriterCacheHelper<int, string> helper = new ReaderWriterCacheHelper<int, string>(); Dictionary<int, string> cache = helper.PublicCache; helper.PublicCache[42] = "original"; // Act string item = helper.PublicFetchOrCreateItem(42, () => "new"); // Assert Assert.Equal("original", cache[42]); Assert.Equal("original", item); } [Fact] public void PublicFetchOrCreateItemReturnsFirstItemIfTwoThreadsUpdateCacheSimultaneously() { // Arrange ReaderWriterCacheHelper<int, string> helper = new ReaderWriterCacheHelper<int, string>(); Dictionary<int, string> cache = helper.PublicCache; Func<string> creator = delegate() { // fake a second thread coming along when we weren't looking string firstItem = helper.PublicFetchOrCreateItem(42, () => "original"); Assert.Equal("original", cache[42]); Assert.Equal("original", firstItem); return "new"; }; // Act string secondItem = helper.PublicFetchOrCreateItem(42, creator); // Assert Assert.Equal("original", cache[42]); Assert.Equal("original", secondItem); } private class ReaderWriterCacheHelper<TKey, TValue> : ReaderWriterCache<TKey, TValue> { public Dictionary<TKey, TValue> PublicCache { get { return Cache; } } public TValue PublicFetchOrCreateItem(TKey key, Func<TValue> creator) { return FetchOrCreateItem(key, creator); } } } }
33.746835
133
0.57802
[ "Apache-2.0" ]
charliefr/aspnetwebstack
test/System.Web.Mvc.Test/Test/ReaderWriterCacheTest.cs
2,668
C#
using System.Reflection; 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("SimpleBatchDownloader")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SimpleBatchDownloader")] [assembly: AssemblyCopyright("Public Domain")] [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("10e454b3-cf9c-4970-b86f-83c66a56919b")] // 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.972222
84
0.749086
[ "Unlicense" ]
ShyRed/simplebatchdownloader
SimpleBatchDownloader/Properties/AssemblyInfo.cs
1,369
C#
using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Internals; using Microsoft.Maui.Controls.Xaml; namespace Maui.Controls.Sample.Pages.SwipeViewGalleries { [Preserve(AllMembers = true)] [XamlCompilation(XamlCompilationOptions.Skip)] public partial class ResourceSwipeItemsGallery : ContentPage { public ResourceSwipeItemsGallery() { InitializeComponent(); BindingContext = new SwipeViewGalleryViewModel(); MessagingCenter.Subscribe<SwipeViewGalleryViewModel>(this, "favourite", sender => { DisplayAlert("SwipeView", "Favourite", "Ok"); }); MessagingCenter.Subscribe<SwipeViewGalleryViewModel>(this, "delete", sender => { DisplayAlert("SwipeView", "Delete", "Ok"); }); } } }
35.45
136
0.767278
[ "MIT" ]
10088/maui
src/Controls/samples/Controls.Sample/Pages/Controls/SwipeViewGalleries/ResourceSwipeItemsGallery.xaml.cs
711
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SwordCollisoin : MonoBehaviour { private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.layer == 8 || other.gameObject.layer == 11) { var boid = other.gameObject.GetComponent<BoidBehaviour>(); boid.DisableVisualAndPlay(); } } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
20.321429
72
0.608084
[ "Apache-2.0" ]
SiiMeR/LD44-mehu
Assets/SwordCollisoin.cs
571
C#
using IdentityServer4.Fsql.Storage.DbMark; using IdentityServer4.Fsql.Storage.Extensions; using IdentityServer4.Fsql.Storage.Options; using IdentityServer4.Fsql.Storage.TokenCleanup; using Microsoft.Extensions.DependencyInjection; using System; namespace IdentityServer4.Fsql.Storage.Configuration { public static class ServiceCollectionExtensions { /// <summary> /// 添加Configuration FreeSql实例到DI /// </summary> /// <param name="services"></param> /// <param name="storeOptionsAction">The store options action.</param> /// <returns></returns> public static IServiceCollection AddConfigurationDbContext(this IServiceCollection services, Action<ConfigurationStoreOptions> storeOptionsAction = null) { var options = new ConfigurationStoreOptions(); services.AddSingleton(options); storeOptionsAction?.Invoke(options); var fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(options.DataType, options.ConnectionString) .UseAutoSyncStructure(true) //自动同步实体结构到数据库 .Build<ConfigurationDb>(); //请务必定义成 Singleton 单例模式 fsql.ConfigureResourcesContext(); fsql.ConfigureClientContext(); fsql.SyncStructureResources(); fsql.SyncStructureClient(); services.AddSingleton(fsql); return services; } /// <summary> /// /// </summary> /// <param name="services"></param> /// <param name="storeOptionsAction"></param> /// <returns></returns> public static IServiceCollection AddOperationalDbContext(this IServiceCollection services, Action<OperationalStoreOptions> storeOptionsAction = null) { var options = new OperationalStoreOptions(); services.AddSingleton(options); storeOptionsAction?.Invoke(options); var fsql = new FreeSql.FreeSqlBuilder() .UseConnectionString(options.DataType, options.ConnectionString) .UseAutoSyncStructure(true) //自动同步实体结构到数据库 .Build<OperationalDb>(); //请务必定义成 Singleton 单例模式 fsql.ConfigurePersistedGrantContext(); fsql.SyncStructurePersistedGrant(); services.AddSingleton(fsql); //TODO services.AddTransient<TokenCleanupService>(); return services; } /// <summary> /// Adds an implementation of the IOperationalStoreNotification to the DI system. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddOperationalStoreNotification<T>(this IServiceCollection services) where T : class, IOperationalStoreNotification { services.AddTransient<IOperationalStoreNotification, T>(); return services; } } }
37.506024
110
0.619017
[ "MIT" ]
skyland-zero/IdentityServer4.Fsql
src/IdentigtyServer4.Fsql.Storage/Configuration/ServiceCollectionExtensions.cs
3,211
C#
/* * This file is part of LuaInterface. * * Copyright (C) 2003-2005 Fabio Mascarenhas de Queiroz. * Copyright (C) 2012 Megax <http://megax.yeahunter.hu/> * * 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.Reflection; namespace LuaInterface.Method { /* * Wrapper class for events that does registration/deregistration * of event handlers. * * Author: Fabio Mascarenhas * Version: 1.0 */ class RegisterEventHandler { private EventHandlerContainer pendingEvents; private EventInfo eventInfo; private object target; public RegisterEventHandler(EventHandlerContainer pendingEvents, object target, EventInfo eventInfo) { this.target = target; this.eventInfo = eventInfo; this.pendingEvents = pendingEvents; } /* * Adds a new event handler */ public Delegate Add(LuaFunction function) { //CP: Fix by Ben Bryant for event handling with one parameter //link: http://luaforge.net/forum/message.php?msg_id=9266 Delegate handlerDelegate = CodeGeneration.Instance.GetDelegate(eventInfo.EventHandlerType, function); eventInfo.AddEventHandler(target, handlerDelegate); pendingEvents.Add(handlerDelegate, this); return handlerDelegate; //MethodInfo mi = eventInfo.EventHandlerType.GetMethod("Invoke"); //ParameterInfo[] pi = mi.GetParameters(); //LuaEventHandler handler=CodeGeneration.Instance.GetEvent(pi[1].ParameterType,function); //Delegate handlerDelegate=Delegate.CreateDelegate(eventInfo.EventHandlerType,handler,"HandleEvent"); //eventInfo.AddEventHandler(target,handlerDelegate); //pendingEvents.Add(handlerDelegate, this); //return handlerDelegate; } /* * Removes an existing event handler */ public void Remove(Delegate handlerDelegate) { RemovePending(handlerDelegate); pendingEvents.Remove(handlerDelegate); } /* * Removes an existing event handler (without updating the pending handlers list) */ internal void RemovePending(Delegate handlerDelegate) { eventInfo.RemoveEventHandler(target, handlerDelegate); } } }
34.94382
104
0.752733
[ "MIT" ]
CCDotNetEmu/CCDotNetLua
LuaInterface/Method/RegisterEventHandler.cs
3,110
C#
using System; using System.Collections.Generic; using Android.Runtime; namespace Java.Lang { // Metadata.xml XPath interface reference: path="/api/package[@name='java.lang']/interface[@name='Comparable']" [Register ("java/lang/Comparable", "", "Java.Lang.IComparableInvoker")] [global::Java.Interop.JavaTypeParameters (new string [] {"T"})] public partial interface IComparable : IJavaObject { // Metadata.xml XPath method reference: path="/api/package[@name='java.lang']/interface[@name='Comparable']/method[@name='compareTo' and count(parameter)=1 and parameter[1][@type='T']]" [Register ("compareTo", "(Ljava/lang/Object;)I", "GetCompareTo_Ljava_lang_Object_Handler:Java.Lang.IComparableInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")] int CompareTo (global::Java.Lang.Object another); } [global::Android.Runtime.Register ("java/lang/Comparable", DoNotGenerateAcw=true)] internal partial class IComparableInvoker : global::Java.Lang.Object, IComparable { static IntPtr java_class_ref = JNIEnv.FindClass ("java/lang/Comparable"); protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (IComparableInvoker); } } new IntPtr class_ref; public static IComparable GetObject (IntPtr handle, JniHandleOwnership transfer) { return global::Java.Lang.Object.GetObject<IComparable> (handle, transfer); } static IntPtr Validate (IntPtr handle) { if (!JNIEnv.IsInstanceOf (handle, java_class_ref)) throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.", JNIEnv.GetClassNameFromInstance (handle), "java.lang.Comparable")); return handle; } protected override void Dispose (bool disposing) { if (this.class_ref != IntPtr.Zero) JNIEnv.DeleteGlobalRef (this.class_ref); this.class_ref = IntPtr.Zero; base.Dispose (disposing); } public IComparableInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer) { IntPtr local_ref = JNIEnv.GetObjectClass (((global::Java.Lang.Object) this).Handle); this.class_ref = JNIEnv.NewGlobalRef (local_ref); JNIEnv.DeleteLocalRef (local_ref); } static Delegate cb_compareTo_Ljava_lang_Object_; #pragma warning disable 0169 static Delegate GetCompareTo_Ljava_lang_Object_Handler () { if (cb_compareTo_Ljava_lang_Object_ == null) cb_compareTo_Ljava_lang_Object_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, int>) n_CompareTo_Ljava_lang_Object_); return cb_compareTo_Ljava_lang_Object_; } static int n_CompareTo_Ljava_lang_Object_ (IntPtr jnienv, IntPtr native__this, IntPtr native_another) { global::Java.Lang.IComparable __this = global::Java.Lang.Object.GetObject<global::Java.Lang.IComparable> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Java.Lang.Object another = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (native_another, JniHandleOwnership.DoNotTransfer); int __ret = __this.CompareTo (another); return __ret; } #pragma warning restore 0169 IntPtr id_compareTo_Ljava_lang_Object_; public unsafe int CompareTo (global::Java.Lang.Object another) { if (id_compareTo_Ljava_lang_Object_ == IntPtr.Zero) id_compareTo_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "compareTo", "(Ljava/lang/Object;)I"); IntPtr native_another = JNIEnv.ToLocalJniHandle (another); JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_another); int __ret = JNIEnv.CallIntMethod (((global::Java.Lang.Object) this).Handle, id_compareTo_Ljava_lang_Object_, __args); JNIEnv.DeleteLocalRef (native_another); return __ret; } } }
39.926316
191
0.754284
[ "MIT" ]
mattleibow/java.interop
tools/generator/Tests/expected/java.lang.Enum/Java.Lang.IComparable.cs
3,793
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 Windows.UI; namespace Microsoft.Toolkit.Uwp.UI.Controls { internal class InfiniteCanvasUpdateTextColorCommand : IInfiniteCanvasCommand { private readonly Color _oldColor; private readonly Color _newColor; private readonly TextDrawable _drawable; public InfiniteCanvasUpdateTextColorCommand(TextDrawable drawable, Color oldText, Color newText) { _oldColor = oldText; _newColor = newText; _drawable = drawable; } public void Execute() { _drawable.TextColor = _newColor; } public void Undo() { _drawable.TextColor = _oldColor; } } }
28.46875
104
0.650933
[ "MIT" ]
14632791/WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls/InfiniteCanvas/Commands/InfiniteCanvasUpdateTextColorCommand.cs
911
C#
namespace CatSystem { using System; class CatSystemStart // от тук(този клас, където е main метода)започва програмта { // правим си прогарамка за котки, Котката си има собственик, който правим в отделен клас public static void Main() { var peshoOwner = new Owner("Pesho","Stambinov"); // създаваме си нов обект(нов owner) от тим Owner, тук ни търси два стринг параметъра // да му подадем, за да направи обекта, защото си направихме конструктор, който // да приема винаги първо и последно име при създаването на нов owner, ако си бяхме направили // празен конструктор, или въобще не бяхме правили конструктор и да оставим дефоутният конструктор да се създаде, // нямаше да има нужда, да му подаваме два стринг параметъра, за да си направим новият Owner!!!! var goshoOwner = new Owner("Gosho", "Geshev"); // създаваме си още един нов Owner и сега имаме две инстанции от тип Owner(два обекта от този тип) peshoOwner.IncreaseAge(); // това ни вика метода за увеличаване на годините на пешо и увеличава годините на пешо с една peshoOwner.IncreaseAge(); // викаме си този метод 5 пъти което ще зададе на Пешо годините да са 5 peshoOwner.IncreaseAge(); peshoOwner.IncreaseAge(); peshoOwner.IncreaseAge(); Console.WriteLine(peshoOwner.Age); // принтираме си годините на пешо Console.WriteLine(peshoOwner.FullName); // изкарва ни пълното име на peshoOwner var cat = new Cat(CatColor.Mixed); // правим си една котка с исканият от конструктора параметър, цвят на котката var anotherCat = new Cat(CatColor.Black); // правим си още една котка var yetAnotherCat = new Cat(CatColor.Brown); // и още една peshoOwner.AddCat(cat, "Maca"); //пешо си взима котка и я кръщава Маца peshoOwner.AddCat(anotherCat, "Silvestyr"); // пешо си взима още една котка и я къщава силвестър Console.WriteLine(peshoOwner.AllCats); } } }
59.875
172
0.579958
[ "MIT" ]
shopOFF/Telerik-Academy-Courses
CSharp-OOP/OOP-Homeworks & Exams/ImportantTemplatesOOP/01.DefiningClasses/CatSystemStart.cs
3,254
C#
/* * Copyright (c) 2007, Ted Elliott * Code licensed under the New BSD License: * http://code.google.com/p/jsonexserializer/wiki/License */ using System; using System.Collections.Generic; using System.Text; namespace JsonExSerializer.Expression { sealed class NullExpression : ExpressionBase { public override object Evaluate(SerializationContext context) { return null; } public override object GetReference(SerializationContext context) { throw new Exception("Cannot reference null"); } public override ExpressionBase ResolveReference(ReferenceIdentifier refID) { throw new Exception("Cannot reference null"); } } }
25.8
83
0.639535
[ "MIT", "Unlicense" ]
sharedsafe/SharedSafe.Toolbox
JsonEx/Expression/NullExpression.cs
774
C#
using System; namespace DefaultInterfaces { class Program { static void Main(string[] args) { Console.WriteLine("Default Interfaces"); MyClass myClass = new MyClass(); myClass.AddNumbers(2, 2); // NOTE that unless you actually implement the new // methods in the class, you still won't get to see // them in your class even if they are default in // the interface contract. //myClass.MultiplyNumbers(2, 2); } } }
20.208333
57
0.63299
[ "Unlicense" ]
shawty/Csharp8features
DefaultInterfaces/Program.cs
487
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; // Based on https://gist.github.com/DanielSWolf/0ab6a96899cc5377bf54 namespace TwitchChatDownloader { /// <summary> /// An ASCII progress bar /// </summary> public class ConsoleProgressBar : IDisposable //, IProgress<int> { private const int kBlockCount = 20; private const int kFileNamePadding = 35; private const int kDisplayDurationPadding = 10; private readonly TimeSpan _animationInterval = TimeSpan.FromSeconds(1.0); private readonly Timer _timer; private bool _disposed = false; private class DownloadProgress { public readonly string FileName; public readonly string DisplayDuration; public readonly int DurationSeconds; public int CurrentOffset = default; public DownloadProgress(string fileName, string duration, int durationSeconds) { // NOTE: I can just use FileName + DisplayDuration string FileName = fileName.PadRight(kFileNamePadding); DisplayDuration = duration.PadRight(kDisplayDurationPadding); DurationSeconds = durationSeconds; } } private readonly Dictionary<string, DownloadProgress> _downloads; private int _currentDownloads = 0; private bool _isDisconnected = false; public ConsoleProgressBar(int maxConcurrentDownloads) { _downloads = new(maxConcurrentDownloads); _timer = new(TimerHandler, null, _animationInterval, _animationInterval); // A progress bar is only for temporary display in a console window. // If the console output is redirected to a file, draw nothing. // Otherwise, we'll end up with a lot of garbage in the target file. if (Console.IsOutputRedirected) { ResetTimer(); } } public void Add(string fileName, string videoID, string duration, int durationSeconds) { _downloads.Add(videoID, new DownloadProgress(fileName, duration, durationSeconds)); } public void Report(string videoID, int value) { value = Math.Min(value, _downloads[videoID].DurationSeconds); Interlocked.Exchange(ref _downloads[videoID].CurrentOffset, value); // NOTE: And now I need call this every time? Even when 99.99% of the time _isDisconnected will be = 0 // Good one. And probably I can just write _isDisconnected = 0; //Interlocked.CompareExchange(ref _isDisconnected, 0, 1); // NOTE: Fuck atomic, it should work. _isDisconnected = false; } public void ReportDisconnect() { // NOTE: Should this be atomic at all? //Interlocked.CompareExchange(ref _isDisconnected, 1, 0); _isDisconnected = true; } private void TimerHandler(object _) { lock (_timer) { if (_disposed) return; ClearPreviousOutput(_currentDownloads); PrintProgress(); PrintStatusBar(); } } private void ClearPreviousOutput(int lines) { int currentLineCursor = Console.CursorTop - lines; // Clear progress output Console.SetCursorPosition(0, currentLineCursor); Console.Write(new string(' ', Console.WindowWidth * lines)); // Clear status bar Console.SetCursorPosition(0, Console.WindowTop + Console.WindowHeight - 1); Console.Write(new string(' ', Console.BufferWidth)); Console.SetCursorPosition(0, currentLineCursor); } private void PrintProgress() { foreach (var videoID in _downloads.Keys.ToImmutableArray()) { var progress = _downloads[videoID]; if (progress.CurrentOffset == -1) { Console.WriteLine(progress.FileName + "Done."); _downloads.Remove(videoID); } } _currentDownloads = 0; foreach (var video in _downloads.Values) { if (video.CurrentOffset != 0) { Console.Write(video.FileName); if (video.CurrentOffset == video.DurationSeconds) { Console.WriteLine("Getting comments that were posted after the VOD finished"); } else { double percent = (double)video.CurrentOffset / video.DurationSeconds; int progressBlockCount = (int)(percent * kBlockCount); string s = new string('=', progressBlockCount) + ">"; string text = string.Format(" [{0}] {1,8:P2}", s.PadRight(kBlockCount), percent); Console.WriteLine(video.DisplayDuration + text); } ++_currentDownloads; } } } private void PrintStatusBar() { int currentLineCursor = Console.CursorTop; Console.SetCursorPosition(0, Console.WindowTop + Console.WindowHeight - 1); if (_isDisconnected) { Console.Write("Lost Internet connection. Reconecting ..."); } Console.SetCursorPosition(0, currentLineCursor); } private void ResetTimer() { _timer.Change(Timeout.Infinite, Timeout.Infinite); } public void Dispose() { lock (_timer) { _disposed = true; ClearPreviousOutput(_currentDownloads); PrintProgress(); } } } }
35.945122
114
0.57659
[ "MIT" ]
orikama/TwitchChatDownloader
TwitchChatDownloader/ConsoleProgressBar.cs
5,897
C#
using System.Linq; using Microsoft.EntityFrameworkCore; using Abp.Application.Editions; using Abp.Application.Features; using TCCAssociation.Editions; namespace TCCAssociation.EntityFrameworkCore.Seed.Host { public class DefaultEditionCreator { private readonly TCCAssociationDbContext _context; public DefaultEditionCreator(TCCAssociationDbContext context) { _context = context; } public void Create() { CreateEditions(); } private void CreateEditions() { var defaultEdition = _context.Editions.IgnoreQueryFilters().FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName); if (defaultEdition == null) { defaultEdition = new Edition { Name = EditionManager.DefaultEditionName, DisplayName = EditionManager.DefaultEditionName }; _context.Editions.Add(defaultEdition); _context.SaveChanges(); /* Add desired features to the standard edition, if wanted... */ } } private void CreateFeatureIfNotExists(int editionId, string featureName, bool isEnabled) { if (_context.EditionFeatureSettings.IgnoreQueryFilters().Any(ef => ef.EditionId == editionId && ef.Name == featureName)) { return; } _context.EditionFeatureSettings.Add(new EditionFeatureSetting { Name = featureName, Value = isEnabled.ToString(), EditionId = editionId }); _context.SaveChanges(); } } }
31.509434
139
0.607186
[ "MIT" ]
yuxincheng73/TCC_Associations
aspnet-core/src/TCCAssociation.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/DefaultEditionCreator.cs
1,670
C#
using System; using Improbable.Gdk.Core; using Improbable.Gdk.Core.Commands; using Unity.Entities; namespace Improbable.Gdk.Subscriptions { public class CommandRequestCallbackManager<T> : ICallbackManager where T : struct, IReceivedCommandRequest { private readonly IndexedCallbacks<T> callbacks = new IndexedCallbacks<T>(); private readonly CommandSystem commandSystem; private ulong nextCallbackId = 1; public CommandRequestCallbackManager(World world) { commandSystem = world.GetExistingSystem<CommandSystem>(); } public void InvokeCallbacks() { var requests = commandSystem.GetRequests<T>(); for (var i = 0; i < requests.Count; ++i) { ref readonly var request = ref requests[i]; callbacks.InvokeAll(request.EntityId.Id, request); } } public ulong RegisterCallback(EntityId entityId, Action<T> callback) { callbacks.Add(entityId.Id, nextCallbackId, callback); return nextCallbackId++; } public bool UnregisterCallback(ulong callbackKey) { return callbacks.Remove(callbackKey); } } }
29.809524
110
0.628594
[ "MIT" ]
nasakib/gdk-for-unity
workers/unity/Packages/io.improbable.gdk.core/Subscriptions/CallbackManagers/CommandRequestCallbackManager.cs
1,252
C#
using System; using System.Collections.Generic; using Xamarin.Forms; namespace XamForms.Controls { public partial class Calendar : ContentView { #region SpecialDates public static readonly BindableProperty SpecialDatesProperty = BindableProperty.Create(nameof(SpecialDates), typeof(ICollection<SpecialDate>), typeof(Calendar), new List<SpecialDate>(), propertyChanged: (bindable, oldValue, newValue) => (bindable as Calendar).ChangeCalendar(CalandarChanges.MaxMin)); public ICollection<SpecialDate> SpecialDates { get { return (ICollection<SpecialDate>)GetValue(SpecialDatesProperty); } set { SetValue(SpecialDatesProperty, value); } } #endregion public void RaiseSpecialDatesChanged() { ChangeCalendar(CalandarChanges.MaxMin); } protected void SetButtonSpecial(CalendarButton button, SpecialDate special) { if (button.IsOutOfMonth && HideSpecialOutOfMonth) { return; } Device.BeginInvokeOnMainThread(() => { button.BackgroundPattern = special.BackgroundPattern; button.BackgroundImage = special.BackgroundImage; button.CornerRadius = (int)Math.Ceiling(button.Width / 2.0); if (special.FontSize.HasValue) button.FontSize = special.FontSize.Value; if (special.BorderWidth.HasValue) button.BorderWidth = special.BorderWidth.Value; if (special.BorderColor.HasValue) button.BorderColor = special.BorderColor.Value; if (special.BackgroundColor.HasValue) button.BackgroundColor = special.BackgroundColor.Value; if (special.TextColor.HasValue) button.TextColor = special.TextColor.Value; if (special.FontAttributes.HasValue) button.FontAttributes = special.FontAttributes.Value; if (!string.IsNullOrEmpty(special.FontFamily)) button.FontFamily = special.FontFamily; button.IsEnabled = special.Selectable; }); } } }
41.018868
150
0.640754
[ "MIT" ]
LynxNetworks/Controls.Calendar
XamForms.Controls.Calendar/Calendar.SpecialDates.cs
2,176
C#
using System.Collections; using UnityEngine; namespace NFCoreEx { public class NFCPropertyManager : NFIPropertyManager { public NFCPropertyManager(NFIDENTID self) { mSelf = self; mhtProperty = new Hashtable(); } public override NFIProperty AddProperty(string strPropertyName, NFIValueList varData) { NFIProperty xProperty = null; if (!mhtProperty.ContainsKey(strPropertyName)) { xProperty = new NFCProperty(mSelf, strPropertyName, varData); mhtProperty[strPropertyName] = xProperty; } return xProperty; } public override bool SetProperty(string strPropertyName, NFIValueList varData) { if (mhtProperty.ContainsKey(strPropertyName)) { NFIProperty xProperty = (NFCProperty)mhtProperty[strPropertyName]; if (null != xProperty) { xProperty.SetValue(varData); } } return true; } public override NFIProperty GetProperty(string strPropertyName) { NFIProperty xProperty = null; if (mhtProperty.ContainsKey(strPropertyName)) { xProperty = (NFCProperty)mhtProperty[strPropertyName]; return xProperty; } return xProperty; } public override void RegisterCallback(string strPropertyName, NFIProperty.PropertyEventHandler handler) { if (mhtProperty.ContainsKey(strPropertyName)) { NFIProperty xProperty = (NFCProperty)mhtProperty[strPropertyName]; xProperty.RegisterCallback(handler); } } public override NFIValueList GetPropertyList() { NFIValueList varData = new NFCValueList(); foreach( DictionaryEntry de in mhtProperty) { varData.AddString(de.Key.ToString()); } return varData; } NFIDENTID mSelf; Hashtable mhtProperty; } }
23.027027
105
0.721244
[ "Apache-2.0" ]
lindianyin/NoahGameFrame
_Out/Server/ClientBin/source/Assets/_NF/NFCoreEx/NFCPropertyManager.cs
1,704
C#
using System.Numerics; using DirectX12GameEngine.Shaders; namespace DirectX12GameEngine.Rendering.Materials { [StaticResource] public class MaterialDiffuseMapFeature : IMaterialDiffuseFeature { public MaterialDiffuseMapFeature() { } public MaterialDiffuseMapFeature(IComputeColor diffuseMap) { DiffuseMap = diffuseMap; } public void Visit(MaterialGeneratorContext context) { DiffuseMap.Visit(context); } public IComputeColor DiffuseMap { get; set; } = new ComputeColor(); [ShaderMember] [ShaderMethod] public void Compute() { Vector4 colorBase = DiffuseMap.Compute(); MaterialPixelStream.MaterialColorBase = colorBase; MaterialPixelStream.MaterialDiffuse = colorBase; } } }
24.361111
75
0.631699
[ "MIT" ]
BAEK-Computer-Graphics/DirectX12GameEngine
DirectX12GameEngine.Rendering/Materials/MaterialDiffuseMapFeature.cs
879
C#
/* * Copyright (c) 2017-2020. RainyRizzle. All rights reserved * Contact to : https://www.rainyrizzle.com/ , contactrainyrizzle@gmail.com * * This file is part of [AnyPortrait]. * * AnyPortrait can not be copied and/or distributed without * the express perission of [Seungjik Lee]. * * Unless this file is downloaded from the Unity Asset Store or RainyRizzle homepage, * this file and its users are illegal. * In that case, the act may be subject to legal penalties. */ using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using AnyPortrait; namespace AnyPortrait { public class apPSDBakeData { // Members //----------------------------------------------------------- public int _atlasIndex = -1; public bool _isLeftover = false;//<<PSD에서 가져온 데이터면 False, PSD에 없지만 Reimport과정에서 Bake된 정보라면 True public int _width = 0; public int _height = 0; public List<apPSDLayerData> _bakedLayerData = new List<apPSDLayerData>(); public Color[] _colorData = null; public string _textureAssetPath = ""; public Texture2D _bakedImage = null; private int _nPixels = 0; public string Name { get { if(_isLeftover) { return "Atlas " + _atlasIndex + " (LO)"; } else { return "Atlas " + _atlasIndex; } } } // Init //----------------------------------------------------------- public apPSDBakeData(int atlasIndex, int width, int height, bool isLeftover) { _atlasIndex = atlasIndex; _width = width; _height = height; _nPixels = _width * _height; _colorData = new Color[_width * _height];//W x H x RGBA; _bakedImage = new Texture2D(width, height, TextureFormat.RGBA32, false, true); _isLeftover = isLeftover; } public void ReadyToBake() { for (int i = 0; i < _nPixels; i++) { _colorData[i] = Color.clear; } } public bool AddImage(apPSDLayerData layerData, int pixelX, int pixelY, float resizeRatio, int resizedWidth, int resizedHeight, int padding) { int iLastX = -1; int iLastY = -1; int iLastIndex = 0; try { Color curColor = Color.black; for (int iX = 0; iX < resizedWidth; iX++) { iLastX = iX; for (int iY = 0; iY < resizedHeight; iY++) { iLastY = iY; curColor = layerData._image.GetPixelBilinear((float)iX / (float)resizedWidth, (float)iY / (float)resizedHeight); iLastIndex = ((iY + pixelY + padding) * _width) + (iX + pixelX + padding); _colorData[iLastIndex] = curColor; } } _bakedLayerData.Add(layerData); return true; } catch (Exception ex) { Debug.LogError("Error"); Debug.LogError("X, Y Index : " + iLastX + ", " + iLastY + " (" + resizedWidth + ", " + resizedHeight + ")"); Debug.LogError("Width / Height : " + _width + " / " + _height); Debug.LogError("Data Length : " + _colorData.Length); Debug.LogError("Last Pixel X : " + (iLastX + pixelX)); Debug.LogError("Last Pixel Y : " + (iLastY + pixelY)); Debug.LogError("Last Data Pixel Index : " + (((iLastY + pixelY) * _width) + (iLastX + pixelX))); Debug.LogError("Last Index : " + iLastIndex); Debug.LogError("AddImage Exception : " + ex); return false; } } //TODO : Gaussian Blur를 활용한 이미지 마감을 추가해야한다. public void EndToBake(bool isBlur, int padding) { if (isBlur) { //RGB 채널 블러를 수행한다. //RGB만 이용하려 블러를 수행하고, 원래의 A 값을 이용하여 AlphaBlending을 하자 Color[] blurColorData = new Color[_colorData.Length]; int iColor = 0; int checkSize = padding / 2; if (checkSize < 2) { checkSize = 2; } else if (checkSize > 6) { checkSize = 6; } for (int iX = 0; iX < _width; iX++) { for (int iY = 0; iY < _height; iY++) { iColor = (iY * _width) + iX; blurColorData[iColor] = GetBlurredColor(iX, iY, checkSize); } } //이제 다시 돌면서 //Alpha Blend를 이용해서 값을 섞자 int dataLength = _colorData.Length; for (int i = 0; i < dataLength; i++) { _colorData[i] = GetAlphaBlendedColor(_colorData[i], blurColorData[i], _colorData[i].a); } } _bakedImage.SetPixels(_colorData); _bakedImage.Apply(); } // Functions //----------------------------------------------------------- private Color GetBlurredColor(int iX, int iY, int checkSize) { Color srcColor = Color.black; float colorR = 0; float colorG = 0; float colorB = 0; float totalWeight = 0.0f; int iSubColor = 0; float weight = 0.0f; for (int iSubX = iX - checkSize; iSubX <= iX + checkSize; iSubX++) { if (iSubX < 0 || iSubX >= _width) { continue; } for (int iSubY = iY - checkSize; iSubY <= iY + checkSize; iSubY++) { if (iSubY < 0 || iSubY >= _height) { continue; } iSubColor = (iSubY * _width) + iSubX; srcColor = _colorData[iSubColor]; if (srcColor.a < 0.01f) { continue; } weight = 10.0f / ((float)Mathf.Abs(iSubX - iX) + (float)Mathf.Abs(iSubY - iY) + 0.5f); //srcColor = _colorData[iSubColor]; //if(srcColor.a < 0.01f) //{ // weight = 0.0f; //} //else //{ // //weight *= srcColor.a; // weight *= 1.0f; //} totalWeight += weight; colorR += srcColor.r * weight; colorG += srcColor.g * weight; colorB += srcColor.b * weight; } } if (totalWeight > 0.0f) { colorR /= totalWeight; colorG /= totalWeight; colorB /= totalWeight; } return new Color(colorR, colorG, colorB, 1.0f); } private const float BLUR_ALPHA_BIAS = 0.3f; private Color GetAlphaBlendedColor(Color srcColor, Color blurColor, float alpha) { //return blurColor; //if (alpha < BLUR_ALPHA_BIAS) //{ // return new Color( ((srcColor.r * alpha) + (blurColor.r * (BLUR_ALPHA_BIAS - alpha))) / BLUR_ALPHA_BIAS, // ((srcColor.g * alpha) + (blurColor.g * (BLUR_ALPHA_BIAS - alpha))) / BLUR_ALPHA_BIAS, // ((srcColor.b * alpha) + (blurColor.b * (BLUR_ALPHA_BIAS - alpha))) / BLUR_ALPHA_BIAS, // alpha); //} return new Color((srcColor.r * alpha) + (blurColor.r * (1.0f - alpha)), (srcColor.g * alpha) + (blurColor.g * (1.0f - alpha)), (srcColor.b * alpha) + (blurColor.b * (1.0f - alpha)), alpha); //return srcColor; } } }
25.70082
141
0.590496
[ "MIT" ]
LuanmaStudio/Seek-The-Trace
Assets/AnyPortrait/Editor/Scripts/PSDLoadWizard/apPSDBakeData.cs
6,447
C#
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace Blackjack { public partial class App : Application { public App() { InitializeComponent(); MainPage = new MainPage(); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
20.30303
60
0.526866
[ "MIT" ]
BeckettMorsch/Blackjack
Blackjack/Blackjack/Blackjack/App.xaml.cs
672
C#
namespace Schema.NET.Tool.CustomOverrides { using System; using System.Collections.Generic; using Schema.NET.Tool.ViewModels; public class AddQueryInputPropertyToSearchAction : IClassOverride { public bool CanOverride(Class @class) => string.Equals(@class.Name, "SearchAction", StringComparison.Ordinal); public void Override(Class @class) { var property = new Property() { Class = @class, Description = "Gets or sets the query input search parameter.", JsonName = "query-input", Name = "QueryInput", }; property.Types.AddRange( new List<PropertyType>() { new PropertyType("Text", "string"), new PropertyType("PropertyValueSpecification", "PropertyValueSpecification") }); @class.Properties.Add(property); } } }
33.032258
97
0.538086
[ "MIT" ]
gladstonemrm/Schema.NET
Source/Schema.NET.Tool/CustomOverrides/AddQueryInputPropertyToSearchAction.cs
1,024
C#
using AutoFixture; using FluentAssertions; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using SFA.DAS.EmployerIncentives.Data.ApprenticeshipIncentives.Models; using SFA.DAS.EmployerIncentives.Data.Models; using System; using System.Linq; using System.Threading.Tasks; namespace SFA.DAS.EmployerIncentives.Data.UnitTests.AccountDataRepository { public class WhenUpdatePaidDateForPaymentIds { private Data.AccountDataRepository _sut; private Fixture _fixture; private EmployerIncentivesDbContext _dbContext; [SetUp] public void Arrange() { _fixture = new Fixture(); var options = new DbContextOptionsBuilder<EmployerIncentivesDbContext>() .UseInMemoryDatabase("EmployerIncentivesDbContext" + Guid.NewGuid()).Options; _dbContext = new EmployerIncentivesDbContext(options); _sut = new Data.AccountDataRepository(new Lazy<EmployerIncentivesDbContext>(_dbContext)); } [TearDown] public void CleanUp() { _dbContext.Dispose(); } [Test] public async Task Then_payment_paid_date_is_updated_for_correct_payments() { // Arrange var accountLegalEntityId = _fixture.Create<long>(); var payments = _fixture .Build<Payment>() .Without(p => p.PaidDate) .With(p => p.AccountLegalEntityId, accountLegalEntityId) .CreateMany(5).ToList(); payments.First().AccountLegalEntityId = accountLegalEntityId + 1; await _dbContext.AddRangeAsync(payments); await _dbContext.SaveChangesAsync(); var paymentIds = payments.Take(4).Select(p => p.Id).ToList(); var expected = _fixture.Create<DateTime>(); // Act await _sut.UpdatePaidDateForPaymentIds(paymentIds, accountLegalEntityId, expected); // Assert var matching = _dbContext.Payments.Where(p => paymentIds.Contains(p.Id) && p.AccountLegalEntityId == accountLegalEntityId); matching.Count().Should().Be(3); foreach (var payment in matching) { payment.PaidDate.Should().Be(expected); } var nonMatching = _dbContext.Payments.Where(p => !paymentIds.Contains(p.Id) || p.AccountLegalEntityId != accountLegalEntityId); nonMatching.Count().Should().Be(2); foreach (var payment in nonMatching) { payment.PaidDate.Should().BeNull(); } } } }
34.636364
101
0.620547
[ "MIT" ]
uk-gov-mirror/SkillsFundingAgency.das-employer-incentives
src/SFA.DAS.EmployerIncentives.Data.UnitTests/AccountDataRepository/WhenUpdatePaidDateForPaymentIds.cs
2,669
C#
using SharpDX; using System; using System.Linq; namespace Mixamo { public static class ColladaUtils { public static Matrix[] MatricesFromString(string str) { float[] values = str.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries) .Select(s => float.Parse(s)) .ToArray(); if (values.Length % 16 != 0) { throw new InvalidOperationException(); } int matrixCount = values.Length / 16; Matrix[] matrices = new Matrix[matrixCount]; for (int i = 0; i < matrixCount; ++i) { for (int j = 0; j < 16; ++j) { matrices[i][j] = values[i * 16 + j]; } matrices[i].Transpose(); //post-multiply transforms instead of pre-multiply } return matrices; } internal static Matrix MatrixFromString(string str) { Matrix[] matrices = MatricesFromString(str); if (matrices.Length != 1) { throw new InvalidOperationException("expected a single matrix"); } return matrices[0]; } } }
25.621622
83
0.654008
[ "MIT" ]
pimmelpansen/Frische-Haut
Importer/src/mixamo/ColladaUtils.cs
948
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using UnityEngine.InputSystem; using UnityEngine.InputSystem.LowLevel; using UnityEngine.InputSystem.Utilities; ////REVIEW: should this enumerate *backwards* in time rather than *forwards*? ////TODO: allow correlating history to frames/updates ////TODO: add ability to grow such that you can set it to e.g. record up to 4 seconds of history and it will automatically keep the buffer size bounded ////REVIEW: should we align the extra memory on a 4 byte boundary? namespace UnityEngine.InputSystem.LowLevel { /// <summary> /// Record a history of state changes applied to one or more controls. /// </summary> /// <remarks> /// This class makes it easy to track input values over time. It will automatically retain input state up to a given /// maximum history depth (<see cref="historyDepth"/>). When the history is full, it will start overwriting the oldest /// entry each time a new history record is received. /// /// The class listens to changes on the given controls by adding change monitors (<see cref="IInputStateChangeMonitor"/>) /// to each control. /// /// <example> /// <code> /// // Track all stick controls in the system. /// var history = new InputStateHistory&lt;Vector2&gt;("*/&lt;Stick&gt;"); /// foreach (var control in history.controls) /// Debug.Log("Capturing input on " + control); /// /// // Start capturing. /// history.StartRecording(); /// /// // Perform a couple artificial value changes. /// Gamepad.current.leftStick.QueueValueChange(new Vector2(0.123f, 0.234f)); /// Gamepad.current.leftStick.QueueValueChange(new Vector2(0.234f, 0.345f)); /// Gamepad.current.leftStick.QueueValueChange(new Vector2(0.345f, 0.456f)); /// InputSystem.Update(); /// /// // Every value change will be visible in the history. /// foreach (var record in history) /// Debug.Log($"{record.control} changed value to {record.ReadValue()}"); /// /// // Histories allocate unmanaged memory and must be disposed of in order to not leak. /// history.Dispose(); /// </code> /// </example> /// </remarks> public class InputStateHistory : IDisposable, IEnumerable<InputStateHistory.Record>, IInputStateChangeMonitor { private const int kDefaultHistorySize = 128; /// <summary> /// Total number of state records currently captured in the history. /// </summary> /// <value>Number of records in the collection.</value> /// <remarks> /// This will always be at most <see cref="historyDepth"/>. /// </remarks> /// <seealso cref="historyDepth"/> /// <seealso cref="RecordStateChange(InputControl,InputEventPtr)"/> public int Count => m_RecordCount; /// <summary> /// Current version stamp. Every time a record is stored in the history, /// this is incremented by one. /// </summary> /// <value>Version stamp that indicates the number of mutations.</value> /// <seealso cref="RecordStateChange(InputControl,InputEventPtr)"/> public uint version => m_CurrentVersion; /// <summary> /// Maximum number of records that can be recorded in the history. /// </summary> /// <value>Upper limit on number of records.</value> /// <exception cref="ArgumentException"><paramref name="value"/> is negative.</exception> /// <remarks> /// A fixed size memory block of unmanaged memory will be allocated to store history /// records. This property determines TODO /// </remarks> public int historyDepth { get => m_HistoryDepth; set { if (value < 0) throw new ArgumentException("History depth cannot be negative", nameof(value)); if (m_RecordBuffer.IsCreated) throw new NotImplementedException(); m_HistoryDepth = value; } } public int extraMemoryPerRecord { get => m_ExtraMemoryPerRecord; set { if (value < 0) throw new ArgumentException("Memory size cannot be negative", nameof(value)); if (m_RecordBuffer.IsCreated) throw new NotImplementedException(); m_ExtraMemoryPerRecord = value; } } public InputUpdateType updateMask { get => m_UpdateMask ?? InputSystem.s_Manager.updateMask & ~InputUpdateType.Editor; set { if (value == InputUpdateType.None) throw new ArgumentException("'InputUpdateType.None' is not a valid update mask", nameof(value)); m_UpdateMask = value; } } public ReadOnlyArray<InputControl> controls => new ReadOnlyArray<InputControl>(m_Controls, 0, m_ControlCount); public unsafe Record this[int index] { get { if (index < 0 || index >= m_RecordCount) throw new ArgumentOutOfRangeException( $"Index {index} is out of range for history with {m_RecordCount} entries", nameof(index)); var recordIndex = UserIndexToRecordIndex(index); return new Record(this, recordIndex, GetRecord(recordIndex)); } set { if (index < 0 || index >= m_RecordCount) throw new ArgumentOutOfRangeException( $"Index {index} is out of range for history with {m_RecordCount} entries", nameof(index)); var recordIndex = UserIndexToRecordIndex(index); new Record(this, recordIndex, GetRecord(recordIndex)).CopyFrom(value); } } public Action<Record> onRecordAdded { get; set; } public Func<InputControl, double, InputEventPtr, bool> onShouldRecordStateChange { get; set; } public InputStateHistory(int maxStateSizeInBytes) { if (maxStateSizeInBytes <= 0) throw new ArgumentException("State size must be >= 0", nameof(maxStateSizeInBytes)); m_AddNewControls = true; m_StateSizeInBytes = maxStateSizeInBytes.AlignToMultipleOf(4); } public InputStateHistory(string path) { using (var controls = InputSystem.FindControls(path)) { m_Controls = controls.ToArray(); m_ControlCount = m_Controls.Length; } } public InputStateHistory(InputControl control) { if (control == null) throw new ArgumentNullException(nameof(control)); m_Controls = new[] {control}; m_ControlCount = 1; } public InputStateHistory(IEnumerable<InputControl> controls) { if (controls != null) { m_Controls = controls.ToArray(); m_ControlCount = m_Controls.Length; } } ~InputStateHistory() { Dispose(); } public void Clear() { m_HeadIndex = 0; m_RecordCount = 0; ++m_CurrentVersion; } public unsafe Record AddRecord(Record record) { var recordPtr = AllocateRecord(out var index); var newRecord = new Record(this, index, recordPtr); newRecord.CopyFrom(record); return newRecord; } public void StartRecording() { // We defer allocation until we actually get values on a control. foreach (var control in controls) InputState.AddChangeMonitor(control, this); } public void StopRecording() { foreach (var control in controls) InputState.RemoveChangeMonitor(control, this); } public unsafe Record RecordStateChange(InputControl control, InputEventPtr eventPtr) { if (eventPtr.IsA<DeltaStateEvent>()) throw new NotImplementedException(); if (!eventPtr.IsA<StateEvent>()) throw new ArgumentException($"Event must be a state event but is '{eventPtr}' instead", nameof(eventPtr)); var statePtr = (byte*)StateEvent.From(eventPtr)->state - control.device.stateBlock.byteOffset; return RecordStateChange(control, statePtr, eventPtr.time); } public unsafe Record RecordStateChange(InputControl control, void* statePtr, double time) { var controlIndex = ArrayHelpers.IndexOfReference(m_Controls, control, m_ControlCount); if (controlIndex == -1) { if (m_AddNewControls) { if (control.stateBlock.alignedSizeInBytes > m_StateSizeInBytes) throw new InvalidOperationException( $"Cannot add control '{control}' with state larger than {m_StateSizeInBytes} bytes"); controlIndex = ArrayHelpers.AppendWithCapacity(ref m_Controls, ref m_ControlCount, control); } else throw new ArgumentException($"Control '{control}' is not part of InputStateHistory", nameof(control)); } var recordPtr = AllocateRecord(out var index); recordPtr->time = time; recordPtr->version = ++m_CurrentVersion; var stateBufferPtr = recordPtr->statePtrWithoutControlIndex; if (m_ControlCount > 1 || m_AddNewControls) { // If there's multiple controls, write index of control to which the state change // pertains as an int before the state memory contents following it. recordPtr->controlIndex = controlIndex; stateBufferPtr = recordPtr->statePtrWithControlIndex; } var stateSize = control.stateBlock.alignedSizeInBytes; var stateOffset = control.stateBlock.byteOffset; UnsafeUtility.MemCpy(stateBufferPtr, (byte*)statePtr + stateOffset, stateSize); // Trigger callback. var record = new Record(this, index, recordPtr); onRecordAdded?.Invoke(record); return record; } public IEnumerator<Record> GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Dispose() { StopRecording(); Destroy(); GC.SuppressFinalize(this); } protected void Destroy() { if (m_RecordBuffer.IsCreated) { m_RecordBuffer.Dispose(); m_RecordBuffer = new NativeArray<byte>(); } } private void Allocate() { // Find max size of state. if (!m_AddNewControls) { m_StateSizeInBytes = 0; foreach (var control in controls) m_StateSizeInBytes = (int)Math.Max((uint)m_StateSizeInBytes, control.stateBlock.alignedSizeInBytes); } else { Debug.Assert(m_StateSizeInBytes > 0, "State size must be have initialized!"); } // Allocate historyDepth times state blocks of the given max size. For each one // add space for the RecordHeader header. // NOTE: If we only have a single control, we omit storing the integer control index. var totalSizeOfBuffer = bytesPerRecord * m_HistoryDepth; m_RecordBuffer = new NativeArray<byte>(totalSizeOfBuffer, Allocator.Persistent, NativeArrayOptions.UninitializedMemory); } protected int RecordIndexToUserIndex(int index) { if (index < m_HeadIndex) return m_HistoryDepth - m_HeadIndex + index; // 10 - 3 + 1 return index - m_HeadIndex; } protected int UserIndexToRecordIndex(int index) { return (m_HeadIndex + index) % m_HistoryDepth; } protected unsafe RecordHeader* GetRecord(int index) { if (!m_RecordBuffer.IsCreated) throw new InvalidOperationException("History buffer has been disposed"); if (index < 0 || index >= m_HistoryDepth) throw new ArgumentOutOfRangeException(nameof(index)); return (RecordHeader*)((byte*)m_RecordBuffer.GetUnsafePtr() + index * bytesPerRecord); } protected unsafe RecordHeader* AllocateRecord(out int index) { if (!m_RecordBuffer.IsCreated) Allocate(); index = (m_HeadIndex + m_RecordCount) % m_HistoryDepth; // If we're full, advance head to make room. if (m_RecordCount == m_HistoryDepth) m_HeadIndex = (m_HeadIndex + 1) % m_HistoryDepth; else { // We have a fixed max size given by the history depth and will start overwriting // older entries once we reached max size. ++m_RecordCount; } return (RecordHeader*)((byte*)m_RecordBuffer.GetUnsafePtr() + bytesPerRecord * index); } protected unsafe TValue ReadValue<TValue>(RecordHeader* data) where TValue : struct { // Get control. If we only have a single one, the index isn't stored on the data. var haveSingleControl = m_ControlCount == 1 && !m_AddNewControls; var control = haveSingleControl ? controls[0] : controls[data->controlIndex]; if (!(control is InputControl<TValue> controlOfType)) throw new InvalidOperationException( $"Cannot read value of type '{TypeHelpers.GetNiceTypeName(typeof(TValue))}' from control '{control}' with value type '{TypeHelpers.GetNiceTypeName(control.valueType)}'"); // Grab state memory. var statePtr = haveSingleControl ? data->statePtrWithoutControlIndex : data->statePtrWithControlIndex; statePtr -= control.stateBlock.byteOffset; return controlOfType.ReadValueFromState(statePtr); } protected unsafe object ReadValueAsObject(RecordHeader* data) { // Get control. If we only have a single one, the index isn't stored on the data. var haveSingleControl = m_ControlCount == 1 && !m_AddNewControls; var control = haveSingleControl ? controls[0] : controls[data->controlIndex]; // Grab state memory. var statePtr = haveSingleControl ? data->statePtrWithoutControlIndex : data->statePtrWithControlIndex; statePtr -= control.stateBlock.byteOffset; return control.ReadValueFromStateAsObject(statePtr); } unsafe void IInputStateChangeMonitor.NotifyControlStateChanged(InputControl control, double time, InputEventPtr eventPtr, long monitorIndex) { // Ignore state change if it's in an input update we're not interested in. var currentUpdateType = InputState.currentUpdateType; var updateTypeMask = updateMask; if ((currentUpdateType & updateTypeMask) == 0 && // EXCEPTION: When we're recording fixed and/or dynamic updates, do NOT ignore the state change // if it is from an event. The reason is that the input system concurrently records // state changes from events into both fixed and dynamic update buffers if both updates // are enabled concurrently. This means that we will see input data going into // *dynamic* update state buffers during *fixed* update and vice versa. !((currentUpdateType & (InputUpdateType.Dynamic | InputUpdateType.Fixed)) != 0 && (updateTypeMask & (InputUpdateType.Dynamic | InputUpdateType.Fixed)) != 0 && eventPtr.valid)) { return; } // Ignore state change if we have a filter and the state change doesn't pass the check. if (onShouldRecordStateChange != null && !onShouldRecordStateChange(control, time, eventPtr)) return; RecordStateChange(control, control.currentStatePtr, time); } // Unused. void IInputStateChangeMonitor.NotifyTimerExpired(InputControl control, double time, long monitorIndex, int timerIndex) { } private InputControl[] m_Controls; private int m_ControlCount; private NativeArray<byte> m_RecordBuffer; private int m_StateSizeInBytes; private int m_RecordCount; private int m_HistoryDepth = kDefaultHistorySize; private int m_ExtraMemoryPerRecord; internal int m_HeadIndex; internal uint m_CurrentVersion; private InputUpdateType? m_UpdateMask; internal readonly bool m_AddNewControls; internal int bytesPerRecord => m_StateSizeInBytes + m_ExtraMemoryPerRecord + (m_ControlCount == 1 && !m_AddNewControls ? RecordHeader.kSizeWithoutControlIndex : RecordHeader.kSizeWithControlIndex); private struct Enumerator : IEnumerator<Record> { private readonly InputStateHistory m_History; private int m_Index; public Enumerator(InputStateHistory history) { m_History = history; m_Index = -1; } public bool MoveNext() { if (m_Index + 1 >= m_History.Count) return false; ++m_Index; return true; } public void Reset() { m_Index = -1; } public Record Current => m_History[m_Index]; object IEnumerator.Current => Current; public void Dispose() { } } [StructLayout(LayoutKind.Explicit)] protected internal unsafe struct RecordHeader { [FieldOffset(0)] public double time; [FieldOffset(8)] public uint version; [FieldOffset(12)] public int controlIndex; [FieldOffset(12)] private fixed byte m_StateWithoutControlIndex[1]; [FieldOffset(16)] private fixed byte m_StateWithControlIndex[1]; public byte* statePtrWithControlIndex { get { fixed(byte* ptr = m_StateWithControlIndex) return ptr; } } public byte* statePtrWithoutControlIndex { get { fixed(byte* ptr = m_StateWithoutControlIndex) return ptr; } } public const int kSizeWithControlIndex = 16; public const int kSizeWithoutControlIndex = 12; } public unsafe struct Record : IEquatable<Record> { // We store an index rather than a direct pointer to make this struct safer to use. private readonly InputStateHistory m_Owner; private readonly int m_IndexPlusOne; // Plus one so that default(int) works for us. private uint m_Version; internal RecordHeader* header => m_Owner.GetRecord(recordIndex); internal int recordIndex => m_IndexPlusOne - 1; internal uint version => m_Version; public bool valid => m_Owner != default && m_IndexPlusOne != default && header->version == m_Version; public InputStateHistory owner => m_Owner; public int index { get { CheckValid(); return m_Owner.RecordIndexToUserIndex(recordIndex); } } public double time { get { CheckValid(); return header->time; } } public InputControl control { get { CheckValid(); var controls = m_Owner.controls; if (controls.Count == 1 && !m_Owner.m_AddNewControls) return controls[0]; return controls[header->controlIndex]; } } public Record next { get { CheckValid(); var userIndex = m_Owner.RecordIndexToUserIndex(this.recordIndex); if (userIndex + 1 >= m_Owner.Count) return default; var recordIndex = m_Owner.UserIndexToRecordIndex(userIndex + 1); return new Record(m_Owner, recordIndex, m_Owner.GetRecord(recordIndex)); } } public Record previous { get { CheckValid(); var userIndex = m_Owner.RecordIndexToUserIndex(this.recordIndex); if (userIndex - 1 < 0) return default; var recordIndex = m_Owner.UserIndexToRecordIndex(userIndex - 1); return new Record(m_Owner, recordIndex, m_Owner.GetRecord(recordIndex)); } } internal Record(InputStateHistory owner, int index, RecordHeader* header) { m_Owner = owner; m_IndexPlusOne = index + 1; m_Version = header->version; } public TValue ReadValue<TValue>() where TValue : struct { CheckValid(); return m_Owner.ReadValue<TValue>(header); } public object ReadValueAsObject() { CheckValid(); return m_Owner.ReadValueAsObject(header); } public void* GetUnsafeMemoryPtr() { CheckValid(); if (m_Owner.controls.Count == 1 && !m_Owner.m_AddNewControls) return header->statePtrWithoutControlIndex; return header->statePtrWithControlIndex; } public void* GetUnsafeExtraMemoryPtr() { CheckValid(); if (m_Owner.extraMemoryPerRecord == 0) throw new InvalidOperationException("No extra memory has been set up for history records; set extraMemoryPerRecord"); return (byte*)header + m_Owner.bytesPerRecord - m_Owner.extraMemoryPerRecord; } public void CopyFrom(Record record) { if (!record.valid) throw new ArgumentException("Given history record is not valid", nameof(record)); CheckValid(); // Find control. var control = record.control; var controlIndex = m_Owner.controls.IndexOfReference(control); if (controlIndex == -1) { // We haven't found it. Throw if we can't add it. if (!m_Owner.m_AddNewControls) throw new InvalidOperationException($"Control '{record.control}' is not tracked by target history"); controlIndex = ArrayHelpers.AppendWithCapacity(ref m_Owner.m_Controls, ref m_Owner.m_ControlCount, control); } // Make sure memory sizes match. var numBytesForState = m_Owner.m_StateSizeInBytes; if (numBytesForState != record.m_Owner.m_StateSizeInBytes) throw new InvalidOperationException( $"Cannot copy record from owner with state size '{record.m_Owner.m_StateSizeInBytes}' to owner with state size '{numBytesForState}'"); // Copy and update header. var thisRecordPtr = header; var otherRecordPtr = record.header; UnsafeUtility.MemCpy(thisRecordPtr, otherRecordPtr, RecordHeader.kSizeWithoutControlIndex); thisRecordPtr->version = ++m_Owner.m_CurrentVersion; m_Version = thisRecordPtr->version; // Copy state. var dstPtr = thisRecordPtr->statePtrWithoutControlIndex; if (m_Owner.controls.Count > 1 || m_Owner.m_AddNewControls) { thisRecordPtr->controlIndex = controlIndex; dstPtr = thisRecordPtr->statePtrWithControlIndex; } var srcPtr = record.m_Owner.m_ControlCount > 1 || record.m_Owner.m_AddNewControls ? otherRecordPtr->statePtrWithControlIndex : otherRecordPtr->statePtrWithoutControlIndex; UnsafeUtility.MemCpy(dstPtr, srcPtr, numBytesForState); // Copy extra memory, but only if the size in the source and target // history are identical. var numBytesExtraMemory = m_Owner.m_ExtraMemoryPerRecord; if (numBytesExtraMemory > 0 && numBytesExtraMemory == record.m_Owner.m_ExtraMemoryPerRecord) UnsafeUtility.MemCpy(GetUnsafeExtraMemoryPtr(), record.GetUnsafeExtraMemoryPtr(), numBytesExtraMemory); // Notify. m_Owner.onRecordAdded?.Invoke(this); } internal void CheckValid() { if (m_Owner == default || m_IndexPlusOne == default) throw new InvalidOperationException("Value not initialized"); ////TODO: need to check whether memory has been disposed if (header->version != m_Version) throw new InvalidOperationException("Record is no longer valid"); } public bool Equals(Record other) { return ReferenceEquals(m_Owner, other.m_Owner) && m_IndexPlusOne == other.m_IndexPlusOne && m_Version == other.m_Version; } public override bool Equals(object obj) { return obj is Record other && Equals(other); } public override int GetHashCode() { unchecked { var hashCode = m_Owner != null ? m_Owner.GetHashCode() : 0; hashCode = (hashCode * 397) ^ m_IndexPlusOne; hashCode = (hashCode * 397) ^ (int)m_Version; return hashCode; } } public override string ToString() { if (!valid) return "<Invalid>"; return $"{{ control={control} value={ReadValueAsObject()} time={time} }}"; } } } /// <summary> /// Records value changes of a given control over time. /// </summary> /// <typeparam name="TValue"></typeparam> public class InputStateHistory<TValue> : InputStateHistory, IReadOnlyList<InputStateHistory<TValue>.Record> where TValue : struct { public InputStateHistory(int? maxStateSizeInBytes = null) // Using the size of the value here isn't quite correct but the value is used as an upper // bound on stored state size for which the size of the value should be a reasonable guess. : base(maxStateSizeInBytes ?? UnsafeUtility.SizeOf<TValue>()) { if (maxStateSizeInBytes < UnsafeUtility.SizeOf<TValue>()) throw new ArgumentException("Max state size cannot be smaller than sizeof(TValue)", nameof(maxStateSizeInBytes)); } public InputStateHistory(InputControl<TValue> control) : base(control) { } public InputStateHistory(string path) : base(path) { // Make sure that the value type of all matched controls is compatible with TValue. foreach (var control in controls) if (!typeof(TValue).IsAssignableFrom(control.valueType)) throw new ArgumentException( $"Control '{control}' matched by '{path}' has value type '{TypeHelpers.GetNiceTypeName(control.valueType)}' which is incompatible with '{TypeHelpers.GetNiceTypeName(typeof(TValue))}'"); } ~InputStateHistory() { Destroy(); } public unsafe Record AddRecord(Record record) { var recordPtr = AllocateRecord(out var index); var newRecord = new Record(this, index, recordPtr); newRecord.CopyFrom(record); return newRecord; } public unsafe Record RecordStateChange(InputControl<TValue> control, TValue value, double time = -1) { using (StateEvent.From(control.device, out var eventPtr)) { var statePtr = (byte*)StateEvent.From(eventPtr)->state - control.device.stateBlock.byteOffset; control.WriteValueIntoState(value, statePtr); if (time >= 0) eventPtr.time = time; var record = RecordStateChange(control, eventPtr); return new Record(this, record.recordIndex, record.header); } } public new IEnumerator<Record> GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public new unsafe Record this[int index] { get { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException( $"Index {index} is out of range for history with {Count} entries", nameof(index)); var recordIndex = UserIndexToRecordIndex(index); return new Record(this, recordIndex, GetRecord(recordIndex)); } set { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException( $"Index {index} is out of range for history with {Count} entries", nameof(index)); var recordIndex = UserIndexToRecordIndex(index); new Record(this, recordIndex, GetRecord(recordIndex)).CopyFrom(value); } } private struct Enumerator : IEnumerator<Record> { private readonly InputStateHistory<TValue> m_History; private int m_Index; public Enumerator(InputStateHistory<TValue> history) { m_History = history; m_Index = -1; } public bool MoveNext() { if (m_Index + 1 >= m_History.Count) return false; ++m_Index; return true; } public void Reset() { m_Index = -1; } public Record Current => m_History[m_Index]; object IEnumerator.Current => Current; public void Dispose() { } } public new unsafe struct Record : IEquatable<Record> { private readonly InputStateHistory<TValue> m_Owner; private readonly int m_IndexPlusOne; private uint m_Version; internal RecordHeader* header => m_Owner.GetRecord(recordIndex); internal int recordIndex => m_IndexPlusOne - 1; public bool valid => m_Owner != default && m_IndexPlusOne != default && header->version == m_Version; public InputStateHistory<TValue> owner => m_Owner; public int index { get { CheckValid(); return m_Owner.RecordIndexToUserIndex(recordIndex); } } public double time { get { CheckValid(); return header->time; } } public InputControl<TValue> control { get { CheckValid(); var controls = m_Owner.controls; if (controls.Count == 1 && !m_Owner.m_AddNewControls) return (InputControl<TValue>)controls[0]; return (InputControl<TValue>)controls[header->controlIndex]; } } public Record next { get { CheckValid(); var userIndex = m_Owner.RecordIndexToUserIndex(this.recordIndex); if (userIndex + 1 >= m_Owner.Count) return default; var recordIndex = m_Owner.UserIndexToRecordIndex(userIndex + 1); return new Record(m_Owner, recordIndex, m_Owner.GetRecord(recordIndex)); } } public Record previous { get { CheckValid(); var userIndex = m_Owner.RecordIndexToUserIndex(this.recordIndex); if (userIndex - 1 < 0) return default; var recordIndex = m_Owner.UserIndexToRecordIndex(userIndex - 1); return new Record(m_Owner, recordIndex, m_Owner.GetRecord(recordIndex)); } } internal Record(InputStateHistory<TValue> owner, int index, RecordHeader* header) { m_Owner = owner; m_IndexPlusOne = index + 1; m_Version = header->version; } public TValue ReadValue() { CheckValid(); return m_Owner.ReadValue<TValue>(header); } public void* GetUnsafeMemoryPtr() { CheckValid(); if (m_Owner.controls.Count == 1 && !m_Owner.m_AddNewControls) return header->statePtrWithoutControlIndex; return header->statePtrWithControlIndex; } public void* GetUnsafeExtraMemoryPtr() { CheckValid(); if (m_Owner.extraMemoryPerRecord == 0) throw new InvalidOperationException("No extra memory has been set up for history records; set extraMemoryPerRecord"); return (byte*)header + m_Owner.bytesPerRecord - m_Owner.extraMemoryPerRecord; } public void CopyFrom(Record record) { CheckValid(); if (!record.valid) throw new ArgumentException("Given history record is not valid", nameof(record)); var temp = new InputStateHistory.Record(m_Owner, recordIndex, header); temp.CopyFrom(new InputStateHistory.Record(record.m_Owner, record.recordIndex, record.header)); m_Version = temp.version; } private void CheckValid() { if (m_Owner == default || m_IndexPlusOne == default) throw new InvalidOperationException("Value not initialized"); if (header->version != m_Version) throw new InvalidOperationException("Record is no longer valid"); } public bool Equals(Record other) { return ReferenceEquals(m_Owner, other.m_Owner) && m_IndexPlusOne == other.m_IndexPlusOne && m_Version == other.m_Version; } public override bool Equals(object obj) { return obj is Record other && Equals(other); } public override int GetHashCode() { unchecked { var hashCode = m_Owner != null ? m_Owner.GetHashCode() : 0; hashCode = (hashCode * 397) ^ m_IndexPlusOne; hashCode = (hashCode * 397) ^ (int)m_Version; return hashCode; } } public override string ToString() { if (!valid) return "<Invalid>"; return $"{{ control={control} value={ReadValue()} time={time} }}"; } } } }
38.229124
209
0.551237
[ "Unlicense" ]
23SAMY23/Meet-and-Greet-MR
Meet & Greet MR (AR)/Library/PackageCache/com.unity.inputsystem@1.0.2/InputSystem/State/InputStateHistory.cs
37,541
C#
using System; using System.Net; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using System.Linq; using System.IO; namespace PresenceLight.Worker { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static void ConfigureConfiguration(IConfigurationBuilder config) { config .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("AADSettings.json", optional: false, reloadOnChange: false) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false) .AddUserSecrets<Startup>(); } public static IHostBuilder CreateHostBuilder(string[] args) { IConfigurationBuilder configBuilderForMain = new ConfigurationBuilder(); ConfigureConfiguration(configBuilderForMain); IConfiguration configForMain = configBuilderForMain.Build(); return Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration(ConfigureConfiguration) .ConfigureWebHostDefaults(webBuilder => { if (Convert.ToBoolean(configForMain["DeployedToServer"])) { webBuilder .ConfigureKestrel(options => { var server = Dns.GetHostName(); IPHostEntry heserver = Dns.GetHostEntry(server); var ip = heserver.AddressList.Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).FirstOrDefault(); if (ip != null) { options.Listen(ip, 5001); options.Listen(ip, 5002, listenOptions => { listenOptions.UseHttps(); listenOptions.UseHttps("presencelight.pfx", "presencelight"); }); } }); } webBuilder.UseStartup<Startup>(); }); } } }
38.203125
155
0.50184
[ "MIT" ]
IntissarBarkatiz/PresenceLight
src/PresenceLight.Worker/Program.cs
2,447
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Text.Json; using Azure.Core; using Azure.ResourceManager; namespace Azure.ResourceManager.AppService { public partial class DiagnosticCategoryData : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsDefined(Kind)) { writer.WritePropertyName("kind"); writer.WriteStringValue(Kind); } writer.WritePropertyName("properties"); writer.WriteStartObject(); writer.WriteEndObject(); writer.WriteEndObject(); } internal static DiagnosticCategoryData DeserializeDiagnosticCategoryData(JsonElement element) { Optional<string> kind = default; ResourceIdentifier id = default; string name = default; ResourceType type = default; Optional<string> description = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("kind")) { kind = property.Value.GetString(); continue; } if (property.NameEquals("id")) { id = new ResourceIdentifier(property.Value.GetString()); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("description")) { description = property0.Value.GetString(); continue; } } continue; } } return new DiagnosticCategoryData(id, name, type, kind.Value, description.Value); } } }
33.469136
101
0.486167
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/websites/Azure.ResourceManager.AppService/src/Generated/Models/DiagnosticCategoryData.Serialization.cs
2,711
C#
#region Copyright (c) 2011-2014 Gregory Nickonov and Andrew Nefedkin (Actis® Wunderman) // Copyright (c) 2011-2014 Gregory Nickonov and Andrew Nefedkin (Actis® Wunderman). // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #endregion using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Digillect.Mvvm.Services; namespace Digillect.Mvvm { /// <summary> /// Command that performs navigation to the specified view. /// </summary> public class NavigationCommand<T> : IRelayCommand { private readonly Func<T, bool> _canNavigate; private readonly INavigationService _navigationService; private readonly Func<T, XParameters> _parametersProvider; private readonly string _view; #region Constructors/Disposer /// <summary> /// Initializes a new instance of the <see cref="NavigationCommand" /> class. /// </summary> /// <param name="navigationService">Instance of navigation service to be used to perform navigation.</param> /// <param name="view">Target view.</param> public NavigationCommand( INavigationService navigationService, string view ) : this( navigationService, view, null, (Func<T, XParameters>) null ) { Contract.Requires<ArgumentNullException>( navigationService != null, "navigationService" ); Contract.Requires<ArgumentNullException>( view != null, "view" ); } /// <summary> /// Initializes a new instance of the <see cref="NavigationCommand" /> class. /// </summary> /// <param name="navigationService">Instance of navigation service to be used to perform navigation.</param> /// <param name="view">Target view.</param> /// <param name="canNavigate">Function that determines whether it is possible to navigate to the specified view.</param> public NavigationCommand( INavigationService navigationService, string view, Func<T, bool> canNavigate ) : this( navigationService, view, canNavigate, (Func<T, XParameters>) null ) { Contract.Requires<ArgumentNullException>( navigationService != null, "navigationService" ); Contract.Requires<ArgumentNullException>( view != null, "view" ); } /// <summary> /// Initializes a new instance of the <see cref="NavigationCommand" /> class. /// </summary> /// <param name="navigationService">Instance of navigation service to be used to perform navigation.</param> /// <param name="view">Target view.</param> /// <param name="parameters">Parameters to pass to the target view.</param> public NavigationCommand( INavigationService navigationService, string view, XParameters parameters ) : this( navigationService, view, null, item => parameters ) { Contract.Requires<ArgumentNullException>( navigationService != null, "navigationService" ); Contract.Requires<ArgumentNullException>( view != null, "view" ); } /// <summary> /// Initializes a new instance of the <see cref="NavigationCommand" /> class. /// </summary> /// <param name="navigationService">Instance of navigation service to be used to perform navigation.</param> /// <param name="view">Target view.</param> /// <param name="canNavigate">Function that determines whether it is possible to navigate to the specified view.</param> /// <param name="parameters">Parameters to pass to the target view.</param> public NavigationCommand( INavigationService navigationService, string view, Func<T, bool> canNavigate, XParameters parameters ) : this( navigationService, view, canNavigate, item => parameters ) { Contract.Requires<ArgumentNullException>( navigationService != null, "navigationService" ); Contract.Requires<ArgumentNullException>( view != null, "view" ); } /// <summary> /// Initializes a new instance of the <see cref="NavigationCommand" /> class. /// </summary> /// <param name="navigationService">Instance of navigation service to be used to perform navigation.</param> /// <param name="view">Target view.</param> /// <param name="parametersProvider">Function that returns parameters to pass to the target view.</param> public NavigationCommand( INavigationService navigationService, string view, Func<T, XParameters> parametersProvider ) : this( navigationService, view, null, parametersProvider ) { Contract.Requires<ArgumentNullException>( navigationService != null, "navigationService" ); Contract.Requires<ArgumentNullException>( view != null, "view" ); } /// <summary> /// Initializes a new instance of the <see cref="NavigationCommand" /> class. /// </summary> /// <param name="navigationService">Instance of navigation service to be used to perform navigation.</param> /// <param name="view">Target view.</param> /// <param name="canNavigate">Function that determines whether it is possible to navigate to the specified view.</param> /// <param name="parametersProvider">Function that returns parameters to pass to the target view.</param> /// <exception cref="ArgumentNullException"> /// If <paramref name="navigationService" /> or <paramref name="view" /> is <c>null</c>. /// </exception> public NavigationCommand( INavigationService navigationService, string view, Func<T, bool> canNavigate, Func<T, XParameters> parametersProvider ) { Contract.Requires<ArgumentNullException>( navigationService != null, "navigationService" ); Contract.Requires<ArgumentNullException>( view != null, "view" ); _navigationService = navigationService; _view = view; _canNavigate = canNavigate; _parametersProvider = parametersProvider; } #endregion #region IRelayCommand Members /// <summary> /// Occurs when changes occur that affect whether or not the command should execute. /// </summary> public event EventHandler CanExecuteChanged; /// <summary> /// Raises event that indicates that <see cref="CanExecute" /> return value has been changed. /// </summary> [SuppressMessage( "Microsoft.Design", "CA1030:UseEventsWhereAppropriate" )] public void RaiseCanExecuteChanged() { EventHandler handler = CanExecuteChanged; if( handler != null ) { handler( this, EventArgs.Empty ); } } /// <summary> /// Defines the method that determines whether the command can execute in its current state. /// </summary> /// <param name="parameter">Data used by the command. Always ignored in this implementation.</param> /// <returns> /// true if this command can be executed; otherwise, false. /// </returns> public bool CanExecute( object parameter ) { return _canNavigate == null || _canNavigate( (T) parameter ); } /// <summary> /// Defines the method to be called when the command is invoked. /// </summary> /// <param name="parameter">Data used by the command. Always ignored in this implementation.</param> public void Execute( object parameter ) { if( CanExecute( parameter ) ) { XParameters parameters = _parametersProvider == null ? null : _parametersProvider( (T) parameter ); _navigationService.Navigate( _view, parameters ); } } #endregion } }
46.137143
147
0.723681
[ "MIT" ]
Digillect/mvvm
src/Digillect.MVVM/NavigationCommand`1.cs
8,078
C#
using System; namespace IfTask1 { class Program { static void Main(string[] args) { Console.WriteLine("Ohjelma selvittää onko annettu luku positiivinen, negatiivinen vai nolla."); Console.Write("Syötä numero: "); string userInput = Console.ReadLine(); int number = int.Parse(userInput); if (number == 0) Console.WriteLine($"Numero {number} on nolla!"); else if (number < 0) Console.WriteLine($"Numero {number} on negatiivinen!"); else Console.WriteLine($"Numero {number} on positiivinen!"); Console.WriteLine($"Syötit numeron {userInput}"); } } }
27.62963
112
0.541555
[ "MIT" ]
VeeraHentinen/programming-basics
condition-tasks/IfTask1/IfTask1/Program.cs
753
C#
namespace DesignPatterns.SoftwareDesignPattern.Other.NullObject { public class NullAnimal : IAnimal { public string Speak() => default(string); } }
26.166667
66
0.745223
[ "Unlicense" ]
Venthe/Design-Patterns
DesignPatterns/SoftwareDesignPattern/Other/NullObject/NullAnimal.cs
159
C#
using Microsoft.Win32; // // This source code is released under the MIT License; Please read license.md file for more details. // using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpenCover.UI.Commands { public class MSTestSettingsFileSelectorCommand : Command { private OpenCoverUIPackage _package; internal string SelectedFile {get; private set;} public MSTestSettingsFileSelectorCommand(OpenCoverUIPackage package) : base(package, new CommandID(GuidList.GuidOpenCoverUICmdSet, (int)PkgCmdIDList.OpenCoverSelectMSTestSettings)) { _package = package; BeforeQueryStatus += OnBeforeQueryStatus; } private void OnBeforeQueryStatus(object sender, EventArgs e) { if (SelectedFile != null && File.Exists(SelectedFile)) { Text = String.Format("MSTest Settings: {0}", Path.GetFileName(SelectedFile)); } } protected override void OnExecute() { var dlg = new OpenFileDialog(); dlg.Filter = "TestSettings (*.testsettings,*.runsettings,*.vsmdi,*.testrunconfig)|*.testsettings;*.runsettings;*.vsmdi;*.testrunconfig"; if (dlg.ShowDialog() == true) { SelectedFile = dlg.FileName; } } } }
26.583333
139
0.742163
[ "MIT" ]
OpenCoverUI/OpenCover.UI
OpenCover.UI/Commands/MSTestSettingsFileSelectorCommand.cs
1,278
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using EkoRestaurant.Data; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace EkoRestaurant.Areas.Identity.Pages.Account.Manage { public class ChangePasswordModel : PageModel { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly ILogger<ChangePasswordModel> _logger; public ChangePasswordModel( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<ChangePasswordModel> logger) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } [BindProperty] public InputModel Input { get; set; } [TempData] public string StatusMessage { get; set; } public class InputModel { [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public async Task<IActionResult> OnGetAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var hasPassword = await _userManager.HasPasswordAsync(user); if (!hasPassword) { return RedirectToPage("./SetPassword"); } return Page(); } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword); if (!changePasswordResult.Succeeded) { foreach (var error in changePasswordResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return Page(); } await _signInManager.RefreshSignInAsync(user); _logger.LogInformation("User changed their password successfully."); StatusMessage = "Your password has been changed."; return RedirectToPage(); } } }
33.833333
129
0.594031
[ "MIT" ]
WenesLimem/PRO
EkoRestaurant/EkoRestaurant/Areas/Identity/Pages/Account/Manage/ChangePassword.cshtml.cs
3,453
C#
// Decompiled with JetBrains decompiler // Type: RoadFlow.Data.Interface.IMenu // Assembly: RoadFlow.Data.Interface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 2109DD37-8E2D-4F7C-8293-6084646C162F // Assembly location: C:\inetpub\wwwroot\RoadFlowMvc\bin\RoadFlow.Data.Interface.dll using RoadFlow.Data.Model; using System; using System.Collections.Generic; using System.Data; namespace RoadFlow.Data.Interface { public interface IMenu { int Add(Menu model); int Update(Menu model); List<Menu> GetAll(); Menu Get(Guid id); int Delete(Guid id); long GetCount(); DataTable GetAllDataTable(); List<Menu> GetChild(Guid id); bool HasChild(Guid id); int UpdateSort(Guid id, int sort); int GetMaxSort(Guid id); List<Menu> GetAllByApplibaryID(Guid applibaryID); } }
20.609756
91
0.715976
[ "Apache-2.0" ]
ArcherTrister/RoadFlowMvc
RoadFlow2.7.6/RoadFlow.Data.Interface/IMenu.cs
847
C#
namespace JustEat.StatsD.Buffered { internal enum StatsDMessageKind { Counter, Timing, Gauge } }
13.3
35
0.578947
[ "Apache-2.0" ]
AnthonySteele/JustEat.StatsD
src/JustEat.StatsD/Buffered/StatsDMessageKind.cs
133
C#
using System; using RabbitMQ.Client; namespace MessageBrokerRabbitMQ { public class RabbitConnectionFactory { private IConnection _connection; private readonly string _connectionUri; public RabbitConnectionFactory(string connectionUri) { _connectionUri = connectionUri; } public IModel CreateChannel() { var connection = GetConnection(_connectionUri); return connection.CreateModel(); } private IConnection GetConnection(string connectionUri) { if (_connection != null) return _connection; var factory = new ConnectionFactory { Uri = new Uri(connectionUri), // When the connection is lost, this will automatically reconnect us when it can get back up AutomaticRecoveryEnabled = true }; _connection = factory.CreateConnection(); return _connection; } } }
27.078947
108
0.595724
[ "MIT" ]
davydehaas98/message-broker-rabbitmq
MessageBroker/RabbitConnectionFactory.cs
1,031
C#
namespace Forum.App.Menus { using System; using System.Collections.Generic; using Models; using Contracts; public class AddReplyMenu : Menu, ITextAreaMenu, IIdHoldingMenu { private const int authorOffset = 8; private const int leftOffset = 18; private const int topOffset = 7; private const int buttonOffset = 14; private ILabelFactory labelFactory; private ITextAreaFactory textAreaFactory; private IForumReader reader; private ICommandFactory commandFactory; private bool error; private IPostViewModel post; public AddReplyMenu(ILabelFactory labelFactory, ITextAreaFactory textAreaFactory, IForumReader forumReader, ICommandFactory commandFactory) { this.labelFactory = labelFactory; this.textAreaFactory = textAreaFactory; this.reader = forumReader; this.commandFactory = commandFactory; this.InitializeTextArea(); this.Open(); } public ITextInputArea TextArea { get; private set; } public override IMenu ExecuteCommand() { throw new NotImplementedException(); } public void SetId(int id) { throw new NotImplementedException(); } protected override void InitializeStaticLabels(Position consoleCenter) { Position errorPosition = new Position(consoleCenter.Left - this.post.Title.Length / 2, consoleCenter.Top - 12); Position titlePosition = new Position(consoleCenter.Left - this.post.Title.Length / 2, consoleCenter.Top - 10); Position authorPosition = new Position(consoleCenter.Left - this.post.Author.Length, consoleCenter.Top - 9); var labels = new List<ILabel>() { this.labelFactory.CreateLabel("Cannot add an empty reply!", errorPosition, !error), this.labelFactory.CreateLabel(this.post.Title, titlePosition), this.labelFactory.CreateLabel($"Author: {this.post.Author}", authorPosition), }; int leftPosition = consoleCenter.Left - leftOffset; int lineCount = this.post.Content.Length; // Add post contents for (int i = 0; i < lineCount; i++) { Position position = new Position(leftPosition, consoleCenter.Top - (topOffset - i)); ILabel label = this.labelFactory.CreateLabel(this.post.Content[i], position); labels.Add(label); } this.Labels = labels.ToArray(); } protected override void InitializeButtons(Position consoleCenter) { int left = consoleCenter.Left + buttonOffset; int top = consoleCenter.Top - (topOffset - this.post.Content.Length); this.Buttons = new IButton[3]; this.Buttons[0] = this.labelFactory.CreateButton("Write", new Position(left, top + 1)); this.Buttons[1] = this.labelFactory.CreateButton("Submit", new Position(left - 1, top + 11)); this.Buttons[2] = this.labelFactory.CreateButton("Back", new Position(left + 1, top + 12)); } private void InitializeTextArea() { Position consoleCenter = Position.ConsoleCenter(); int top = consoleCenter.Top - (topOffset + this.post.Content.Length) + 5; this.TextArea = this.textAreaFactory.CreateTextArea(this.reader, consoleCenter.Left - 18, top, false); } } }
35.950495
114
0.611402
[ "MIT" ]
jackofdiamond5/Software-University
C# Fundamentals/C# OOP Advanced/Workshop_Forum/Forum.App/Menus/AddReplyMenu.cs
3,633
C#
/*------------------------------------------------------------*/ // <summary>GameCanvas for Unity</summary> // <author>Seibe TAKAHASHI</author> // <remarks> // (c) 2015-2020 Smart Device Programming. // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // </remarks> /*------------------------------------------------------------*/ namespace GameCanvas { /// <summary> /// 音声トラック /// </summary> public enum GcSoundTrack : byte { /// <summary> /// BGM1トラック /// </summary> BGM1 = 0, /// <summary> /// BGM2トラック /// </summary> BGM2 = 1, /// <summary> /// BGM3トラック /// </summary> BGM3 = 2, /// <summary> /// SEトラック /// </summary> SE = 3, /// <summary> /// マスタートラック /// </summary> Master = 255 } }
24.125
65
0.394819
[ "MIT" ]
KosukeOnishi/final
Packages/GameCanvas/Runtime/Scripts/Enum/GcSoundTrack.cs
986
C#
using System.Collections; using System.Collections.Generic; using System.Linq; namespace RethinkDb.Driver.Linq { public class RethinkDbGroup<T, TVal> : IGrouping<T, TVal> { public IEnumerator<TVal> GetEnumerator() { return Reduction.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public T Key { get; set; } public List<TVal> Reduction { get; set; } } }
21.608696
61
0.60161
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
ArnautS/Aetheria-Economy
Assets/Scripts/ServerShared/NIH/RethinkDb/RethinkDb.Driver.Linq/RethinkDbGroup.cs
499
C#
using DBLayer.Core; using DBLayer.Core.Condition; using DBLayer.Core.Interface; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq.Expressions; using System.Threading.Tasks; namespace DBLayer.Persistence { public abstract class BaseRepository<T, R> : BaseRepository, IRepository<T, R> where T : new() { public BaseRepository(IDbContext dbContext) : base(dbContext) { } #region public method #region GetEntity /// <summary> /// 获取 T 单个实体 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="func"></param> /// <returns></returns> public T GetEntity(Expression<Func<T, bool>> where, Expression<Func<OrderExpression<T>, object>> order = null, params string[] inclusionList) { var entity = base.GetEntity<T>(where, order, inclusionList); return entity; } /// <summary> /// 获取 T 单个实体 /// </summary> /// <typeparam name="T">实体(泛型)类</typeparam> /// <param name="paramers">参数数组</param> /// <returns>T 实体</returns> public T GetEntity(string cmdText, DbParameter[] paramers = null, params string[] inclusionList) { T entity = GetEntity<T>(cmdText, paramers, inclusionList); return entity; } /// <summary> /// 获得单个对象 /// </summary> /// <typeparam name="T">实体(泛型)类</typeparam> /// <param name="cmdText">sql</param> /// <param name="obj">参数</param> /// <param name="inclusionList"></param> /// <returns></returns> public T GetEntity(string cmdText, object obj, params string[] inclusionList) { T entity = GetEntity<T>(cmdText, obj, inclusionList); return entity; } /// <summary> /// 获取 T 单个实体 /// </summary> /// <typeparam name="T">实体(泛型)类</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="commandType">cmdText 执行类型</param> /// <param name="paramers">参数数组</param> /// <returns>T 实体</returns> public T GetEntity(string cmdText, CommandType commandType = CommandType.Text, DbParameter[] paramers = null, params string[] inclusionList) { T entity = GetEntity<T>(cmdText, commandType, paramers, inclusionList); return entity; } /// <summary> /// 获取 T 单个实体异步 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="where"></param> /// <param name="order"></param> /// <param name="inclusionList"></param> /// <returns></returns> public async Task<T> GetEntityAsync(Expression<Func<T, bool>> where, Expression<Func<OrderExpression<T>, object>> order = null, params string[] inclusionList) { var entity = await GetEntityAsync<T>(where, order, inclusionList); return entity; } /// <summary> /// 获取 T 单个实体异步 /// </summary> /// <typeparam name="T">实体(泛型)类</typeparam> /// <param name="cmdText">sql</param> /// <param name="obj">参数</param> /// <param name="inclusionList"></param> /// <returns></returns> public async Task<T> GetEntityAsync(string cmdText, object obj, params string[] inclusionList) { var entity = await GetEntityAsync<T>(cmdText, obj, inclusionList); return entity; } /// <summary> /// 获取 T 单个实体异步 /// </summary> /// <typeparam name="T">实体(泛型)类</typeparam> /// <param name="paramers">参数数组</param> /// <returns>T 实体</returns> public async Task<T> GetEntityAsync(string cmdText, DbParameter[] paramers = null, params string[] inclusionList) { var entity = await GetEntityAsync<T>(cmdText, paramers, inclusionList); return entity; } /// <summary> /// 获取 T 单个实体异步 /// </summary> /// <typeparam name="T">实体(泛型)类</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="commandType">cmdText 执行类型</param> /// <param name="paramers">参数数组</param> /// <returns>T 实体</returns> public async Task<T> GetEntityAsync(string cmdText, CommandType commandType = CommandType.Text, DbParameter[] paramers = null, params string[] inclusionList) { var entity = await GetEntityAsync<T>(cmdText, commandType, paramers, inclusionList); return entity; } /// <summary> /// 获取 查询 数量 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="where"></param> /// <returns></returns> public int GetEntityCount(Expression<Func<T, bool>> where) { var paramerList = new List<DbParameter>(); var whereStr = _dataSource.Where<T>(where, ref paramerList); var cmdText = GetCountCmdText<T>(whereStr); var result = this.ExecuteScalar<int>(cmdText.ToString(), CommandType.Text, paramerList.ToArray()); return result; } /// <summary> /// 获取 T 单个实体异步 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="where"></param> /// <returns></returns> public async Task<int> GetEntityCountAsync(Expression<Func<T, bool>> where) { var paramerList = new List<DbParameter>(); var whereStr = _dataSource.Where<T>(where, ref paramerList); var cmdText = GetCountCmdText<T>(whereStr); var result = await this.ExecuteScalarAsync<int>(cmdText.ToString(), CommandType.Text, paramerList.ToArray()); return result; } #endregion #region GetEntityDic /// <summary> /// 获得单个实体字典 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="func"></param> /// <returns></returns> public IDictionary<string, object> GetEntityDic(Expression<Func<T, bool>> where, Expression<Func<OrderExpression<T>, object>> order = null, params string[] inclusionList) { var result = GetEntityDic<T>(where, order, inclusionList); return result; } /// <summary> /// 获得单个实体字典异步 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="func"></param> /// <returns></returns> public async Task<IDictionary<string, object>> GetEntityDicAsync(Expression<Func<T, bool>> where, Expression<Func<OrderExpression<T>, object>> order = null, params string[] inclusionList) { var result = await GetEntityDicAsync<T>(where, order, inclusionList); return result; } #endregion #region GetEntityDicList /// <summary> /// 获得实体字典列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="where"></param> /// <param name="inclusionList"></param> /// <returns></returns> public IEnumerable<IDictionary<string, object>> GetEntityDicList(Expression<Func<T, bool>> where = null, Expression<Func<OrderExpression<T>, object>> order = null, int? top = null, params string[] inclusionList) { var result = base.GetEntityDicList<T>(where, order, top, inclusionList); return result; } /// <summary> /// 获得实体字典列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="where"></param> /// <param name="inclusionList"></param> /// <returns></returns> public async Task<IEnumerable<IDictionary<string, object>>> GetEntityDicListAsync(Expression<Func<T, bool>> where = null, Expression<Func<OrderExpression<T>, object>> order = null, int? top = null, params string[] inclusionList) { var result = await base.GetEntityDicListAsync<T>(where, order, top, inclusionList); return result; } #endregion #region GetEntityList /// <summary> /// 获取实体集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="where"></param> /// <param name="top"></param> /// <returns></returns> public IEnumerable<T> GetEntityList(Expression<Func<T, bool>> where = null, Expression<Func<OrderExpression<T>, object>> order = null, int? top = null, params string[] inclusionList) { var result = base.GetEntityList<T>(where, order, top, inclusionList); return result; } /// <summary> /// 获取实体集合 /// </summary> /// <typeparam name="T">实体(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="exeEntityType">按属性/特性映射</param> /// <param name="paramers">参数数组</param> /// <returns>实体集合</returns> public IEnumerable<T> GetEntityList(string cmdText, DbParameter[] paramers = null, params string[] inclusionList) { var entityList = GetEntityList<T>(cmdText, paramers, inclusionList); return entityList; } /// <summary> /// 获取实体集合 /// </summary> /// <typeparam name="T">实体(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="exeEntityType">按属性/特性映射</param> /// <param name="paramers">参数数组</param> /// <returns>实体集合</returns> public IEnumerable<T> GetEntityList(string cmdText, object obj, params string[] inclusionList) { var entityList = GetEntityList<T>(cmdText, obj, inclusionList); return entityList; } /// <summary> /// 获取 T 实体集合 /// </summary> /// <typeparam name="T">实体(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="commandType">cmdText 执行类型</param> /// <param name="paramers">参数数组</param> /// <returns>T 实体集合</returns> public IEnumerable<T> GetEntityList(string cmdText, CommandType commandType = CommandType.Text, DbParameter[] paramers = null, params string[] inclusionList) { var entityList = GetEntityList<T>(cmdText, commandType, paramers, inclusionList); return entityList; } /// <summary> /// 获取实体集合 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="where"></param> /// <param name="top"></param> /// <returns></returns> public async Task<IEnumerable<T>> GetEntityListAsync(Expression<Func<T, bool>> where = null, Expression<Func<OrderExpression<T>, object>> order = null, int? top = null, params string[] inclusionList) { var entityList = await GetEntityListAsync<T>(where, order, top, inclusionList); return entityList; } /// <summary> /// 获取实体集合 /// </summary> /// <typeparam name="T">实体(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="exeEntityType">按属性/特性映射</param> /// <param name="paramers">参数数组</param> /// <returns>实体集合</returns> public async Task<IEnumerable<T>> GetEntityListAsync(string cmdText, DbParameter[] paramers = null, params string[] inclusionList) { var result = await GetEntityListAsync<T>(cmdText, paramers, inclusionList); return result; } /// <summary> /// 获取实体集合 /// </summary> /// <typeparam name="T">实体(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="exeEntityType">按属性/特性映射</param> /// <param name="paramers">参数数组</param> /// <returns>实体集合</returns> public async Task<IEnumerable<T>> GetEntityListAsync(string cmdText, object obj, params string[] inclusionList) { var result = await GetEntityListAsync<T>(cmdText, obj, inclusionList); return result; } /// <summary> /// 获取 T 实体集合 /// </summary> /// <typeparam name="T">实体(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="commandType">cmdText 执行类型</param> /// <param name="paramers">参数数组</param> /// <returns>T 实体集合</returns> public async Task<IEnumerable<T>> GetEntityListAsync(string cmdText, CommandType commandType = CommandType.Text, DbParameter[] paramers = null, params string[] inclusionList) { var result = await GetEntityListAsync<T>(cmdText, commandType, paramers, inclusionList); return result; } #endregion /// <summary> /// 生成id /// </summary> /// <returns></returns> public R NewId() { var result = base.NewId<R>(); return result; } /// <summary> /// 获取用户id /// </summary> /// <returns></returns> public R GetUserId() { var result = base.GetUserId<R>(); return result; } #region GetList /// <summary> /// 获取 T 类型的数据集 /// </summary> /// <typeparam name="T">数据类型(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="paramers">参数数组</param> /// <returns>数据集合</returns> public IEnumerable<T> GetList(string cmdText, params DbParameter[] paramers) { var result = GetList<T>(cmdText, paramers); return result; } /// <summary> /// 获取 T 类型的数据集 /// </summary> /// <typeparam name="T">数据类型(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="paramers">参数数组</param> /// <returns>数据集合</returns> public IEnumerable<T> GetList(string cmdText, object obj) { var result = GetList<T>(cmdText, obj); return result; } /// <summary> /// 获取 T 类型的数据集 /// </summary> /// <typeparam name="T">数据类型(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="commandType">cmdText 执行类型</param> /// <param name="paramers">参数数组</param> /// <returns>数据集合</returns> public IEnumerable<T> GetList(string cmdText, CommandType commandType = CommandType.Text, params DbParameter[] paramers) { var result = GetList<T>(cmdText, commandType, paramers); return result; } /// <summary> /// 获取 T 类型的数据集 /// </summary> /// <typeparam name="T">数据类型(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="paramers">参数数组</param> /// <returns>数据集合</returns> public async Task<IEnumerable<T>> GetListAsync(string cmdText, params DbParameter[] paramers) { var result = await GetListAsync<T>(cmdText, paramers); return result; } /// <summary> /// 获取 T 类型的数据集 /// </summary> /// <typeparam name="T">数据类型(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="obj">参数数组</param> /// <returns>数据集合</returns> public async Task<IEnumerable<T>> GetListAsync(string cmdText, object obj) { var result = await GetListAsync<T>(cmdText, obj); return result; } /// <summary> /// 获取 T 类型的数据集 /// </summary> /// <typeparam name="T">数据类型(泛型)</typeparam> /// <param name="cmdText">SQL 语句</param> /// <param name="commandType">cmdText 执行类型</param> /// <param name="paramers">参数数组</param> /// <returns>数据集合</returns> public async Task<IEnumerable<T>> GetListAsync(string cmdText, CommandType commandType = CommandType.Text, params DbParameter[] paramers) { var result = await GetListAsync(cmdText, commandType, paramers); return result; } #endregion #region GetEntityDicStr /// <summary> /// 获得单个实体字符串字典 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="func"></param> /// <returns></returns> public IDictionary<string, string> GetEntityDicStr(Expression<Func<T, bool>> where, Expression<Func<OrderExpression<T>, object>> order, params string[] inclusionList) { var result = GetEntityDicStr<T>(where, order, inclusionList); return result; } /// <summary> /// 获得单个实体字符串字典 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="func"></param> /// <returns></returns> public async Task<IDictionary<string, string>> GetEntityDicStrAsync(Expression<Func<T, bool>> where, Expression<Func<OrderExpression<T>, object>> order, params string[] inclusionList) { var result = await GetEntityDicStrAsync<T>(where, order, inclusionList); return result; } #endregion #region GetEntityDicStrList /// <summary> /// 获得实体字典字符串列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="func"></param> /// <param name="inclusionList"></param> /// <returns></returns> public IEnumerable<IDictionary<string, string>> GetEntityDicStrList(Expression<Func<T, bool>> where = null, Expression<Func<OrderExpression<T>, object>> order = null, int? top = null, params string[] inclusionList) { var result = GetEntityDicStrList<T>(where, order, top, inclusionList); return result; } /// <summary> /// 获得实体字典字符串列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="func"></param> /// <param name="inclusionList"></param> /// <returns></returns> public async Task<IEnumerable<IDictionary<string, string>>> GetEntityDicStrListAsync(Expression<Func<T, bool>> where = null, Expression<Func<OrderExpression<T>, object>> order = null, int? top = null, params string[] inclusionList) { var result = await GetEntityDicStrListAsync<T>(where, order, top, inclusionList); return result; } #endregion #region InsertEntity /// <summary> /// 插入一条数据 /// </summary> /// <typeparam name="R"></typeparam> /// <param name="expression"></param> /// <returns></returns> public R InsertEntity(Expression<Func<T>> expression) { var result = InsertEntity<T, R>(expression); return result; } /// <summary> /// 通过实体类型 T 向表中增加一条记录 /// </summary> /// <typeparam name="T">实体泛型(类)</typeparam> /// <param name="entity">实体对象</param> /// <param name="inclusionList"></param> /// <returns>所新增记录的 ID,如果返回 -1 则表示增加失败</returns> public R InsertEntity(T entity, params string[] inclusionList) { var result = InsertEntity<T, R>(entity, inclusionList); return result; } /// <summary> /// 通过实体类型 T 向表中增加一条记录 /// </summary> /// <typeparam name="T">实体泛型(类)</typeparam> /// <param name="entity">实体对象</param> /// <param name="inclusionList"></param> /// <returns>所新增记录的 ID,如果返回 -1 则表示增加失败</returns> public async Task<R> InsertEntityAsync(T entity, params string[] inclusionList) { var result = await InsertEntityAsync<T, R>(entity, inclusionList); return result; } /// <summary> /// 插入一条数据 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="R"></typeparam> /// <param name="expression"></param> /// <returns></returns> public async Task<R> InsertEntityAsync(Expression<Func<T>> expression) { var result = await InsertEntityAsync<T, R>(expression); return result; } /// <summary> /// 插入一条数据 /// </summary> /// <param name="expression"></param> /// <returns></returns> public R InsertEntity<TR>(Expression<Func<TR>> expression) where TR : new() { var result = InsertEntity<TR, R>(expression); return result; } /// <summary> /// 插入一条数据 /// </summary> /// <param name="expression"></param> /// <returns></returns> public async Task<R> InsertEntityAsync<TR>(Expression<Func<TR>> expression) where TR : new() { var result = await InsertEntityAsync<TR, R>(expression); return result; } #endregion #region UpdateEntity /// <summary> /// 更新操作 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expression"></param> /// <param name="where"></param> /// <returns></returns> public int UpdateEntity(Expression<Func<T>> expression, Expression<Func<T, bool>> where) { var result = UpdateEntity<T>(expression, where); return result; } /// <summary> /// 修改 T 实体 /// </summary> /// <typeparam name="T">实体泛型</typeparam> /// <param name="entity">实体对象</param> /// <returns>影响数据条数</returns> public int UpdateEntity(T entity, params string[] inclusionList) { var result = UpdateEntity<T>(entity, inclusionList); return result; } /// <summary> /// 更新操作 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expression"></param> /// <param name="where"></param> /// <returns></returns> public async Task<int> UpdateEntityAsync(Expression<Func<T>> expression, Expression<Func<T, bool>> where) { var result = await UpdateEntityAsync<T>(expression, where); return result; } /// <summary> /// 修改 T 实体 /// </summary> /// <typeparam name="T">实体泛型</typeparam> /// <param name="entity">实体对象</param> /// <returns>影响数据条数</returns> public async Task<int> UpdateEntityAsync(T entity, params string[] inclusionList) { var result = await UpdateEntityAsync<T>(entity, inclusionList); return result; } #endregion #region DeleteEntity /// <summary> /// 删除数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="where"></param> /// <param name="logic"></param> /// <returns></returns> public int DeleteEntity(Expression<Func<T, bool>> where, bool logic = true) { var result = DeleteEntity<T>(where, logic); return result; } /// <summary> /// 删除数据异步 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="where"></param> /// <param name="logic"></param> /// <returns></returns> public async Task<int> DeleteEntityAsync(Expression<Func<T, bool>> where, bool logic = true) { var result = await DeleteEntityAsync<T>(where, true); return result; } #endregion #endregion #region pager /// <summary> /// 返回分页实体列表集合 /// </summary> /// <returns></returns> public IEnumerable<T> GetResultByPager<T1>(Pager<T1> page, params string[] inclusionList) where T1 : BasePageCondition, new() { var result = GetResultByPager<T, T1>(page,inclusionList); return result; } /// <summary> /// 返回分页实体列表集合异步 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T1"></typeparam> /// <param name="page"></param> /// <returns></returns> public async Task<IEnumerable<T>> GetResultByPageAsync<T1>(Pager<T1> page, params string[] inclusionList) where T1 : BasePageCondition, new() { var result = await GetResultByPageAsync<T, T1>(page, inclusionList); return result; } #endregion } }
36.208517
239
0.547855
[ "MIT" ]
wutao0315/DBLayer
src/DBLayer.Persistence/BaseRepositoryGeneric.cs
26,136
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SpacechemPatch.Patches { [Decoy("#=qgb_1dBoxJTxMr57bMeIXeThMSy7VcbiYQtte9Drmlz4=")] struct BoundingBox { [Decoy(".ctor")] public BoundingBox(Vector2i topLeft, Vector2i dimensions) { } [Decoy(".ctor")] public BoundingBox(int x, int y, int width, int height) { } [Decoy("#=qzZCFhMSRiU$M7Tzmtv$20w==")] public Vector2i GetCenter() { return new Vector2i(); } } }
20.821429
65
0.586621
[ "MIT" ]
csaboka/spacechempatch
SpacechemPatch/Patches/BoundingBox.cs
585
C#
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NhInterMySQL.Model; using System; using System.Collections.Generic; using NhInterMySQL; using TLJCommon; using TLJ_MySqlService.Utils; namespace TLJ_MySqlService.Handler { [Handler("LoginDataStatistics")] class StatictisLoginHandler : BaseHandler { private int i = 1; public override string OnResponse(string data) { StatictisLoginReq statictisLoginReq = null; try { statictisLoginReq = JsonConvert.DeserializeObject<StatictisLoginReq>(data); } catch (Exception e) { MySqlService.log.Warn("传入的参数有误:" + e); return null; } string uid = statictisLoginReq.uid; string ip = statictisLoginReq.ip; string apkVersion = statictisLoginReq.apkVersion; string channelname = statictisLoginReq.channelname; int type = statictisLoginReq.type; if (string.IsNullOrWhiteSpace(ip) || string.IsNullOrWhiteSpace(uid) || string.IsNullOrWhiteSpace(apkVersion) || string.IsNullOrWhiteSpace(channelname)|| type < 1) { MySqlService.log.Warn("字段有空:" + data); return null; } User user = NHibernateHelper.userManager.GetByUid(uid); if (user == null) { MySqlService.log.Warn("uid未注册:" + data); } switch (type) { case 1: StatictisLogUtil.Login(uid, user.Username, ip, channelname, apkVersion, MyCommon.OpType.Login); break; case 2: StatictisLogUtil.Login(uid, user.Username, ip, channelname, apkVersion, MyCommon.OpType.Register); break; } return null; } } }
32.3
118
0.56192
[ "Apache-2.0" ]
zhangfengqwer/TLJ_MySqlService
TLJ_MySqlService/Handler/Statictis/StatictisLoginHandler.cs
1,970
C#
using System; using System.Globalization; using System.Text; namespace RunTicks.AssertionMessages { internal class NotExceedAverageSecondsAssertionMessage : AssertionMessageBase { private readonly Int64 _expectedMaxAverageSeconds; private readonly Double _actualAverageSeconds; public NotExceedAverageSecondsAssertionMessage(Int64 expectedMaxAverageSeconds, Double actualAverageSeconds, string description) :base(description) { _expectedMaxAverageSeconds = expectedMaxAverageSeconds; _actualAverageSeconds = actualAverageSeconds; } internal Int64 ExpectedMaxAverageSeconds => _expectedMaxAverageSeconds; internal Double ActualAverageSeconds => _actualAverageSeconds; internal override void AddSpecificMessagePart(StringBuilder stringBuilder, CultureInfo culture) { stringBuilder.AppendLine($"Expected average (per run) seconds not to exceed {_expectedMaxAverageSeconds.ToString(culture)}, but had: {_actualAverageSeconds.ToString(culture)} average seconds."); } } }
39.678571
206
0.749775
[ "Apache-2.0" ]
khanlarmammadov/RunTicks
src/RunTicks/AssertionMessages/NotExceedAverageSecondsAssertionMessage.cs
1,113
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x1019_005c-9929")] public void /* sys_mve */ Method_1019_005c_v2() { ii(0x1019_005c, 2); mov(al, bl); /* mov al, bl */ } } }
24.866667
88
0.549598
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-1019-005c-sys-mve.2.cs
373
C#
using LitJson; using UnityEngine; namespace ROSBridgeLib { namespace bolt_msgs { public class SteeringCmdMsg : ROSBridgeMsg { public SteeringCmdMsg() : base() {} public SteeringCmdMsg(JsonData msg) : base(msg) {} public override string ROSMessageType() { return "bolt_msgs/SteeringCmd"; } public float SteeringWheelAngle { get { return (float)(_data["steering_wheel_angle_cmd"].GetReal()); } set { _data["steering_wheel_angle_cmd"] = value; } } public bool Enabled { get { return _data["enabled"].GetBoolean(); } set { _data["enabled"] = value; } } public bool Override { get { return _data["override"].GetBoolean(); } set { _data["override"] = value; } } public bool Timeout { get { return _data["timeout"].GetBoolean(); } set { _data["timeout"] = value; } } } } }
26.883721
84
0.474913
[ "MIT" ]
the-gooniest/autonomous_vehicle_sim
Assets/ROSBridgeLib/bolt_msgs/SteeringCmdMsg.cs
1,158
C#
using System; using System.Collections.Generic; using System.Linq; namespace JFlepp.Epub { internal static class ExtensionMethods { public static bool EqualsIgnoreCaseWithNull(this string? str1, string? str2) { if (str1 == null && str2 == null) return true; if (str1 == null || str2 == null) return false; return str1.Equals(str2, StringComparison.OrdinalIgnoreCase); } public static string[] SplitAndRemoveEmptyEntries(this string str, char separator) { return str.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries); } public static string JoinToString<T>(this IEnumerable<T> objects, string separator) { return string.Join(separator, objects); } public static string GetSHA256Hash(this byte[] bytes) { using (var crypt = new System.Security.Cryptography.SHA256Managed()) { return crypt .ComputeHash(bytes) .Select(b => b.ToString("x2")) .JoinToString(string.Empty); } } } }
30.947368
91
0.580782
[ "MIT" ]
jflepp/Epub
JFlepp.Epub/ExtensionMethods.cs
1,178
C#
using System; using System.Diagnostics; using clojure.lang; using clojure.clr.api; namespace sample { class Program { private readonly Stopwatch start = Stopwatch.StartNew(); void Log(string message) => Console.WriteLine($"{start.ElapsedMilliseconds,5:N0}: {message}"); void Run(string[] args) { Log($"starting..."); Log($" CLOJURE_LOAD_PATH={Environment.GetEnvironmentVariable("CLOJURE_LOAD_PATH")}"); IFn load = Clojure.var("clojure.core", "load-file"); Log($" clojure.load done."); load.invoke("./hello-world.clj"); Log($" ./hello-world.clj done."); Log("done."); } static void Main(string[] args) { new Program().Run(args); } } }
23.571429
97
0.549091
[ "MIT" ]
dnikku/clojure.clr.sample
sample/Program.cs
825
C#
using System.Text.Json; namespace ATI.Services.Serialization { internal static class SerializationOptions { public static JsonSerializerOptions SnakeCase = new JsonSerializerOptions { IgnoreNullValues = true, PropertyNamingPolicy = new SnakeCaseNamingPolicy() }; public static JsonSerializerOptions CamelCase = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true }; } }
28.526316
81
0.669742
[ "MIT" ]
atidev/ATI.Services.Serialization
ATI.Services.Serialization/SerializationOptions.cs
544
C#
#region LICENSE //----------------------------------------------------------------------------- // For the purpose of making video games, educational projects or gamification, // GeonBit is distributed under the MIT license and is totally free to use. // To use this source code or GeonBit as a whole for other purposes, please seek // permission from the library author, Ronen Ness. // // Copyright (c) 2017 Ronen Ness [ronenness@gmail.com]. // Do not remove this license notice. //----------------------------------------------------------------------------- #endregion #region File Description //----------------------------------------------------------------------------- // A component that renders a 3D bounding-box around this GameObject. // // Author: Ronen Ness. // Since: 2017. //----------------------------------------------------------------------------- #endregion using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace GeonBit.ECS.Components.Graphics { /// <summary> /// This component renders a bounding-box around this GameObject. /// </summary> public class BoundingBoxRenderer : BaseRendererComponent { // the entity used to draw the model Core.Graphics.BoundingBoxEntity _entity; /// <summary> /// Get the main entity instance of this renderer. /// </summary> protected override Core.Graphics.BaseRenderableEntity Entity { get { return _entity; } } /// <summary> /// Create the bounding-box renderer component. /// </summary> public BoundingBoxRenderer() { _entity = new Core.Graphics.BoundingBoxEntity(); } /// <summary> /// Clone this component. /// </summary> /// <returns>Cloned copy of this component.</returns> override public BaseComponent Clone() { return CopyBasics(new BoundingBoxRenderer()); } /// <summary> /// Called every frame to do the component events. /// </summary> protected override void OnUpdate() { // update bounding box if (_GameObject != null) { _entity.Box = _GameObject.SceneNode.GetBoundingBox(); } } } }
33.867647
96
0.53756
[ "MIT" ]
RonenNess/GeonBit
GeonBit/Source/ECS/Components/Graphics/Renderers/BoundingBoxRenderer.cs
2,305
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.EntityFrameworkCore.InMemory.ValueGeneration.Internal; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; namespace Microsoft.EntityFrameworkCore { public class InMemoryIntegerValueGeneratorFactoryTest { private static readonly IMutableModel _model = InMemoryTestHelpers.Instance.BuildModelFor<AnEntity>(); [Fact] public void Can_create_factories_for_all_integer_types() { var entityType = _model.FindEntityType(typeof(AnEntity)); Assert.Equal(1, CreateAndUseFactory(entityType.FindProperty("Id"))); Assert.Equal(1L, CreateAndUseFactory(entityType.FindProperty("Long"))); Assert.Equal((short)1, CreateAndUseFactory(entityType.FindProperty("Short"))); Assert.Equal((byte)1, CreateAndUseFactory(entityType.FindProperty("Byte"))); Assert.Equal((int?)1, CreateAndUseFactory(entityType.FindProperty("NullableInt"))); Assert.Equal((long?)1, CreateAndUseFactory(entityType.FindProperty("NullableLong"))); Assert.Equal((short?)1, CreateAndUseFactory(entityType.FindProperty("NullableShort"))); Assert.Equal((byte?)1, CreateAndUseFactory(entityType.FindProperty("NullableByte"))); Assert.Equal((uint)1, CreateAndUseFactory(entityType.FindProperty("UInt"))); Assert.Equal((ulong)1, CreateAndUseFactory(entityType.FindProperty("ULong"))); Assert.Equal((ushort)1, CreateAndUseFactory(entityType.FindProperty("UShort"))); Assert.Equal((sbyte)1, CreateAndUseFactory(entityType.FindProperty("SByte"))); Assert.Equal((uint?)1, CreateAndUseFactory(entityType.FindProperty("NullableUInt"))); Assert.Equal((ulong?)1, CreateAndUseFactory(entityType.FindProperty("NullableULong"))); Assert.Equal((ushort?)1, CreateAndUseFactory(entityType.FindProperty("NullableUShort"))); Assert.Equal((sbyte?)1, CreateAndUseFactory(entityType.FindProperty("NullableSByte"))); } private static object CreateAndUseFactory(IProperty property) => new InMemoryIntegerValueGeneratorFactory().Create(property).Next(null); [Fact] public void Throws_for_non_integer_property() { var property = _model.FindEntityType(typeof(AnEntity)).FindProperty("BadCheese"); Assert.Equal( CoreStrings.InvalidValueGeneratorFactoryProperty(nameof(InMemoryIntegerValueGeneratorFactory), "BadCheese", "AnEntity"), Assert.Throws<ArgumentException>(() => new InMemoryIntegerValueGeneratorFactory().Create(property)).Message); } private class AnEntity { public int Id { get; set; } public long Long { get; set; } public short Short { get; set; } public byte Byte { get; set; } public int? NullableInt { get; set; } public long? NullableLong { get; set; } public short? NullableShort { get; set; } public byte? NullableByte { get; set; } public uint UInt { get; set; } public ulong ULong { get; set; } public ushort UShort { get; set; } public sbyte SByte { get; set; } public uint? NullableUInt { get; set; } public ulong? NullableULong { get; set; } public ushort? NullableUShort { get; set; } public sbyte? NullableSByte { get; set; } public string BadCheese { get; set; } } } }
50.893333
136
0.66754
[ "Apache-2.0" ]
Alecu100/EntityFrameworkCore
test/EFCore.InMemory.Tests/InMemoryIntegerValueGeneratorFactoryTest.cs
3,817
C#
namespace $rootnamespace$ { using Catel.MVVM; using System.Threading.Tasks; public class $safeitemname$ : ViewModelBase { public $safeitemname$(/* dependency injection here */) { } public override string Title { get { return "View model title"; } } // TODO: Register models with the vmpropmodel codesnippet // TODO: Register view model properties with the vmprop or vmpropviewmodeltomodel codesnippets // TODO: Register commands with the vmcommand or vmcommandwithcanexecute codesnippets protected override async Task InitializeAsync() { await base.InitializeAsync(); // TODO: subscribe to events here } protected override async Task CloseAsync() { // TODO: unsubscribe from events here await base.CloseAsync(); } } }
27.454545
102
0.618102
[ "MIT" ]
Catel/Catel.Templates
templates/C#/ItemTemplates/Catel.ViewModel/UserControlViewModel.cs
908
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 BSpliner.Properties { /// <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()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BSpliner.Properties.Resources", typeof(Resources).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)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.513889
174
0.602236
[ "MIT" ]
PikminGuts92/BSpliner
BSpliner/Properties/Resources.Designer.cs
2,775
C#
using System; namespace SimplePagedList { public class PageMetadata { public int PageNumber { get; } public int? PreviousPageNumber { get; } public int? NextPageNumber { get; } public int FirstPageNumber { get; } public int LastPageNumber { get; set; } public int PageSize { get; } public int PageCount { get; } /// <summary> /// Used to represent an empty page /// </summary> internal PageMetadata() { PageCount = 1; PageNumber = 1; FirstPageNumber = PageNumber; LastPageNumber = PageNumber; } public PageMetadata(int supersetCount, int pageNumber, int pageSize) { if (pageNumber < 1) throw new ArgumentOutOfRangeException(nameof(pageNumber), "Page number can't be smaller than 1"); if (pageSize < 1) throw new ArgumentOutOfRangeException(nameof(pageSize), "Page size can't be smaller than 1"); PageSize = pageSize; var pageCount = CalculatePageCount(supersetCount, pageSize); PageCount = pageCount == 0 ? 1 : pageCount; PageNumber = pageCount == 0 ? 1 : pageNumber; FirstPageNumber = 1; LastPageNumber = PageCount; if (PageNumber > 1) { PreviousPageNumber = PageNumber - 1; PreviousPageNumber = PageNumber - 1; } if (PageNumber < PageCount) { NextPageNumber = PageNumber + 1; } } /// <summary> /// Calculates the total number of pages within the superset. /// </summary> /// <param name="supersetCount"></param> /// <param name="pageSize"></param> /// <returns></returns> private static int CalculatePageCount(int supersetCount, int pageSize) { return (int)Math.Ceiling(supersetCount / (double)pageSize); } } }
32.918033
129
0.555279
[ "MIT" ]
joakimskoog/PagedList
src/SimplePagedList/PageMetadata.cs
2,010
C#
using System.ComponentModel.DataAnnotations; namespace MyRestfulApp.Infraestructure.DataContext.DbModels { public class Usuario { [Key] public int Id { get; set; } [Required(ErrorMessage = "Name is required")] [StringLength(255, ErrorMessage = "Must be between 1 and 255 characters", MinimumLength = 1)] [DataType(DataType.Text)] public string Nombre { get; set; } [Required(ErrorMessage = "LastName is required")] [StringLength(255, ErrorMessage = "Must be between 1 and 255 characters", MinimumLength = 1)] [DataType(DataType.Text)] public string Apellido { get; set; } [Required(ErrorMessage = "Email is required")] [StringLength(255, ErrorMessage = "Must be between 5 and 255 characters", MinimumLength = 5)] [DataType(DataType.EmailAddress)] public string Email { get; set; } [Required(ErrorMessage = "Password is required")] [StringLength(255, ErrorMessage = "Must be between 5 and 255 characters", MinimumLength = 5)] [DataType(DataType.Password)] public string Password { get; set; } } }
37.354839
101
0.650259
[ "MIT" ]
emontenegro/MyRestfulApp
MyRestfulApp/MyRestfulApp.Infraestructure/DataContext/DbModels/Usuario.cs
1,160
C#
using EIS.AppBase; using EIS.AppModel.Service; using EIS.DataAccess; using EIS.DataModel.Access; using EIS.DataModel.Model; using EIS.Permission.Model; using EIS.Permission.Service; using WebBase.JZY.Tools; using EIS.WorkFlow.Access; using EIS.WorkFlow.Engine; using EIS.WorkFlow.Model; using EIS.WorkFlow.Service; using EIS.WorkFlow.XPDLParser.Elements; using NLog; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Data.Common; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace EIS.WebBase.SysFolder.WorkFlow { public partial class DealFlowBatch : PageBase { public StringBuilder sbToDo = new StringBuilder(); private string string_0 = ""; private string string_1 = ""; private StringDictionary stringDictionary_0 = new StringDictionary(); public string SubmitTaskIdList { get { string str; str = (this.ViewState["TaskIdList"] != null ? this.ViewState["TaskIdList"].ToString() : ""); return str; } set { this.ViewState["TaskIdList"] = value; } } public DealFlowBatch() { } protected void btnBack_Click(object sender, EventArgs e) { string item = base.Request["taskchk"]; if (!string.IsNullOrEmpty(item)) { string[] strArrays = item.Split(new char[] { ',' }); for (int i = 0; i < (int)strArrays.Length; i++) { this.method_5(strArrays[i], this.txtNewTitle.Text); } } this.method_0(this.string_0); base.ClientScript.RegisterStartupScript(base.GetType(), "", "afterSubmit();", true); } protected void btnSubmit_Click(object sender, EventArgs e) { string item = base.Request["taskchk"]; if (!string.IsNullOrEmpty(item)) { string[] strArrays = item.Split(new char[] { ',' }); for (int i = 0; i < (int)strArrays.Length; i++) { string str = strArrays[i]; this.method_4(DealAction.Submit, str, this.txtNewTitle.Text); } } this.method_0(this.string_0); base.ClientScript.RegisterStartupScript(base.GetType(), "", "afterSubmit();", true); } private string method_0(string string_2) { DataTable toDoGroupByEmployeeId = UserTaskService.GetToDoGroupByEmployeeId(base.EmployeeID); DataTable toDoUserTaskByEmployeeId = UserTaskService.GetToDoUserTaskByEmployeeId(base.EmployeeID); foreach (DataRow row in toDoGroupByEmployeeId.Rows) { string str = row["WorkflowCode"].ToString(); string str1 = row["WorkflowName"].ToString(); string str2 = row["AppName"].ToString(); if (this.string_1 != "") { if (this.string_1 != str2) { continue; } } else if (string_2 != "" && string_2 != str) { continue; } DataRow[] dataRowArray = toDoUserTaskByEmployeeId.Select(string.Concat("WorkflowCode='", str, "' and IsNull(CanBatch,'')='1'")); if ((int)dataRowArray.Length == 0) { continue; } this.sbToDo.AppendFormat("<div class='groupZone'><div class='groupHeader'><input type='checkbox' class='chklist' value='{0}' id='chkall_{0}'><label for='chkall_{0}' title='点击全选'>&nbsp;&nbsp;[{0}]&nbsp;-&nbsp;{1}&nbsp;</label></div>", str, str1); bool flag = false; DataRow[] dataRowArray1 = dataRowArray; for (int i = 0; i < (int)dataRowArray1.Length; i++) { DataRow dataRow = dataRowArray1[i]; string str3 = dataRow["uTaskId"].ToString(); if ((this.SubmitTaskIdList.Length <= 0 ? true : this.SubmitTaskIdList.IndexOf(str3) != -1)) { dataRow["OwnerId"].ToString(); string str4 = dataRow["AgentId"].ToString(); string str5 = dataRow["IsAssign"].ToString(); string str6 = dataRow["IsShare"].ToString(); string str7 = dataRow["DefineType"].ToString(); string str8 = ""; if (str7 != "Sign") { str8 = (str6 == "1" ? "共享" : "普通"); } else { str8 = "会签"; } string str9 = this.method_3(dataRow); StringBuilder stringBuilder = this.sbToDo; object[] item = new object[] { dataRow["uTaskId"], dataRow["instanceName"], dataRow["CreateUser"], dataRow["ArriveTime"], null, null, null, null, null, null, null, null, null }; item[4] = (dataRow["IsRead"].ToString() == "0" ? "unread" : "readed"); item[5] = (str4 == base.EmployeeID ? "[代]&nbsp;" : ""); item[6] = (str5 == "1" ? "[加]&nbsp;" : ""); item[7] = (flag ? "alt" : ""); item[8] = str8; item[9] = (str9.Length > 8 ? string.Concat(str9.Substring(0, 8), "…") : str9); item[10] = dataRow["taskName"]; item[11] = str; item[12] = str9; stringBuilder.AppendFormat("<div class='task {7}'>\r\n <table class='taskTbl' width='100%'>\r\n <tr>\r\n <td width='24'><input type='checkbox' class='taskchk_{11}' value='{0}' name='taskchk' checked='true' /></td>\r\n <td width='24'><div class='{4}'></div></td>\r\n <td>{5}{6}<a href='dealflow.aspx?taskId={0}' target='_blank'>{1}</a></td>\r\n <td width='40'>{8}</td>\r\n <td width='60' class='tdActName' title='{10}'>{10}</td>\r\n <td width='100' class='tdNextInfo' title='{12}'>{9}</td>\r\n <td width='70'><span class='lineuser'>{2}</span></td>\r\n <td width='100'><span class='linetime'>{3:yyyy-MM-dd HH:mm}</span></td>\r\n </tr>\r\n </table>\r\n </div>", item); this.sbToDo.Append(this.method_1(str, dataRow["AppId"].ToString())); flag = !flag; } } this.sbToDo.Append("</div>"); } return this.sbToDo.ToString(); } private string method_1(string wfCode, string appId) { string str; FieldInfo fieldInfo = null; StringBuilder stringBuilder = new StringBuilder(); DataTable dataTable = SysDatabase.ExecuteTable(string.Format("select * from T_E_WF_Config where Enable='是' and WFId='{0}' and IsNull(BatchQuery,'')<>''", wfCode)); if (dataTable.Rows.Count != 0) { string str1 = dataTable.Rows[0]["BatchQuery"].ToString(); List<FieldInfo> modelListDisp = (new _FieldInfo()).GetModelListDisp(str1); stringBuilder.Append("<table class='datatbl' width='100%'>"); stringBuilder.Append("<thead><tr>"); foreach (FieldInfo fieldInfoA in modelListDisp) { if (fieldInfoA.ColumnHidden == 1) { continue; } stringBuilder.AppendFormat("<td align='{2}' width='{1}'>{0}</td>", fieldInfoA.FieldNameCn, fieldInfoA.ColumnWidth, this.method_2(fieldInfoA.ColumnAlign)); } stringBuilder.Append("<td></td>"); stringBuilder.Append("</tr></thead>"); string str2 = string.Concat("select ListSQL,ConnectionId,OrderField from T_E_Sys_TableInfo where tablename='", str1, "'"); DataTable dataTable1 = SysDatabase.ExecuteTable(str2); if (dataTable1.Rows.Count > 0) { dataTable1.Rows[0]["ConnectionId"].ToString(); string str3 = dataTable1.Rows[0]["ListSQL"].ToString(); string str4 = string.Concat(" _AutoId = '", appId, "'"); str3 = str3.Replace("|^condition^|", string.Concat("(", str4, ")")).Replace("|^sortdir^|", "").Replace("\r\n", " ").Replace("\t", ""); DataTable dataTable2 = SysDatabase.ExecuteTable(str3); stringBuilder.Append("<tbody>"); foreach (DataRow row in dataTable2.Rows) { stringBuilder.Append("<tr>"); foreach (FieldInfo fieldInfo1 in modelListDisp) { if (fieldInfo1.ColumnHidden == 1) { continue; } stringBuilder.AppendFormat("<td align='{1}'>{0}</td>", row[fieldInfo1.FieldName], this.method_2(fieldInfo1.ColumnAlign)); } stringBuilder.Append("<td></td>"); stringBuilder.Append("</tr>"); } stringBuilder.Append("</tbody>"); } stringBuilder.Append("</table>"); str = stringBuilder.ToString(); } else { str = ""; } return str; } private string method_2(string string_2) { string str; if (string_2 == "1") { str = "left"; } else if (string_2 != "2") { str = (string_2 != "3" ? "left" : "right"); } else { str = "center"; } return str; } private string method_3(DataRow dataRow_0) { StringBuilder stringBuilder = new StringBuilder(); UserContext userInfo = base.UserInfo; DriverEngine driverEngine = new DriverEngine(userInfo); string str = dataRow_0["taskId"].ToString(); Task taskById = driverEngine.GetTaskById(str); Instance instanceById = driverEngine.GetInstanceById(taskById.InstanceId); Activity activityById = driverEngine.GetActivityById(instanceById, taskById.ActivityId); foreach (Activity activity in driverEngine.NextActivity(instanceById, taskById)) { DataRow appData = EIS.WorkFlow.Engine.Utility.GetAppData(instanceById); List<DeptEmployee> activityUser = EIS.WorkFlow.Engine.Utility.GetActivityUser(instanceById, activity, new WFSession(userInfo, instanceById, appData, activityById)); StringBuilder length = new StringBuilder(); foreach (DeptEmployee deptEmployee in activityUser) { length.AppendFormat("{0},", deptEmployee.EmployeeName); } if (length.Length > 0) { length.Length = length.Length - 1; } string name = activity.GetName(); if (activity.GetNodeType() == ActivityType.End) { stringBuilder.Append("结束"); } else { stringBuilder.AppendFormat("{1}", name, length); } } return stringBuilder.ToString(); } private void method_4(DealAction dealAction_0, string string_2, string string_3) { UserTask userTaskById = UserTaskService.GetUserTaskById(string_2, null); if (userTaskById != null) { UserContext userInfo = base.UserInfo; DeptEmployee deptEmployeeByPositionId = DeptEmployeeService.GetDeptEmployeeByPositionId(userTaskById.OwnerId, userTaskById.PositionId); if (deptEmployeeByPositionId != null) { userInfo = WebTools.GetUserInfo(deptEmployeeByPositionId._AutoID); } base.Server.ClearError(); DriverEngine driverEngine = new DriverEngine(userInfo); string taskId = userTaskById.TaskId; Task taskById = driverEngine.GetTaskById(taskId); Instance instanceById = driverEngine.GetInstanceById(taskById.InstanceId); Activity activityById = driverEngine.GetActivityById(instanceById, taskById.ActivityId); DbConnection dbConnection = SysDatabase.CreateConnection(); try { dbConnection.Open(); DbTransaction dbTransaction = dbConnection.BeginTransaction(); try { if ((taskById.DefineType != ActivityType.Normal.ToString() ? false : userTaskById.TaskState == 0.ToString())) { TaskService.ApplyShareTask(taskId, string_2, dbTransaction); taskById.MainPerformer = userTaskById.OwnerId; } userTaskById._UpdateTime = DateTime.Now; userTaskById.ReadTime = new DateTime?(DateTime.Now); userTaskById.IsRead = "1"; userTaskById.DealTime = new DateTime?(DateTime.Now); if ((!activityById.IsDecisionNode() ? false : string_3 == "")) { string_3 = "同意"; } userTaskById.DealAdvice = string_3; if (dealAction_0 != DealAction.Disagree && taskById.DefineType == ActivityType.Sign.ToString()) { dealAction_0 = DealAction.Agree; } userTaskById.DealAction = this.method_6(activityById, userTaskById, dealAction_0); userTaskById.TaskState = 2.ToString(); userTaskById.DealUser = base.EmployeeID; if (userTaskById.AgentId == base.EmployeeID && userTaskById.EmployeeName.IndexOf("代签") == -1) { userTaskById.EmployeeName = string.Concat(userTaskById.EmployeeName, "〔", base.EmployeeName, "代签〕"); } if (userTaskById.PositionId == "") { userTaskById.PositionId = userInfo.PositionId; userTaskById.PositionName = userInfo.PositionName; } if (userTaskById.DeptId == "") { userTaskById.DeptId = userInfo.DeptId; userTaskById.DeptName = userInfo.DeptName; } _UserTask __UserTask = new _UserTask(dbTransaction); __UserTask.UpdateAdvice(userTaskById); if ((taskById.DefineType == ActivityType.Sign.ToString() ? true : taskById.MainPerformer == userTaskById.OwnerId)) { List<Task> tasks = driverEngine.NextTask(instanceById, taskById, dbTransaction); if (instanceById.NeedUpdate) { (new _Instance(dbTransaction)).UpdateXPDL(instanceById); } if (tasks.Count > 0) { StringCollection stringCollections = new StringCollection(); foreach (Task task in tasks) { TaskService.GetTaskDealUser(task.TaskId, stringCollections, dbTransaction); } userTaskById.RecIds = EIS.AppBase.Utility.GetJoinString(stringCollections); userTaskById.RecNames = EmployeeService.GetEmployeeNameList(stringCollections); __UserTask.UpdateAdvice(userTaskById); } if ((taskById.DefineType != ActivityType.Normal.ToString() ? false : taskById.MainPerformer == userTaskById.OwnerId)) { EIS.WorkFlow.Engine.Utility.DeleteUnDoneUserTaskByTaskId(taskById.TaskId, dbTransaction); } } if (userTaskById.IsAssign == "1") { AppMsg appMsg = new AppMsg(base.UserInfo) { Title = string.Concat("加签任务处理完成提醒,来自", base.EmployeeName), MsgType = "", MsgUrl = string.Concat("SysFolder/Workflow/DealFlow.aspx?sysTaskId=", taskById.TaskId), RecIds = userTaskById._UserName, RecNames = EmployeeService.GetEmployeeName(userTaskById._UserName), SendTime = new DateTime?(DateTime.Now), Sender = base.EmployeeName, Content = string.Format("{0}已经在加签任务【{1}】中发表意见。\r\n以下是他(她)的意见:{2}", base.EmployeeName, instanceById.InstanceName, string_3) }; AppMsgService.SendMessage(appMsg); } dbTransaction.Commit(); } catch (Exception exception1) { Exception exception = exception1; dbTransaction.Rollback(); base.WriteExceptionLog("错误", this.FormatException(exception, "")); this.fileLogger.Error<Exception>(exception); this.stringDictionary_0.Add(string_2, exception.Message); } } finally { if (dbConnection != null) { ((IDisposable)dbConnection).Dispose(); } } } } private void method_5(string uTaskId, string reason) { UserTask userTaskById = UserTaskService.GetUserTaskById(uTaskId, null); if (userTaskById != null) { string taskId = userTaskById.TaskId; UserContext userInfo = base.UserInfo; DriverEngine driverEngine = new DriverEngine(userInfo); Task taskById = driverEngine.GetTaskById(taskId); if (taskById.DefineType == ActivityType.Sign.ToString()) { this.method_4(DealAction.Disagree, uTaskId, reason); } else if (userTaskById.IsAssign != "1") { Instance instanceById = driverEngine.GetInstanceById(taskById.InstanceId); Activity activityById = driverEngine.GetActivityById(instanceById, taskById.ActivityId); DbConnection dbConnection = SysDatabase.CreateConnection(); try { dbConnection.Open(); DbTransaction dbTransaction = dbConnection.BeginTransaction(); try { try { if ((taskById.DefineType != ActivityType.Normal.ToString() ? false : userTaskById.TaskState == 0.ToString())) { TaskService.ApplyShareTask(taskId, userTaskById.UserTaskId, dbTransaction); taskById.MainPerformer = userTaskById.OwnerId; } _UserTask __UserTask = new _UserTask(dbTransaction); userTaskById._UpdateTime = DateTime.Now; userTaskById.ReadTime = new DateTime?(DateTime.Now); userTaskById.IsRead = "1"; userTaskById.DealTime = new DateTime?(DateTime.Now); userTaskById.DealAdvice = reason; userTaskById.DealAction = EnumDescription.GetFieldText(DealAction.RollBack); userTaskById.TaskState = 2.ToString(); userTaskById.DealUser = base.EmployeeID; if (userTaskById.AgentId == base.EmployeeID) { userTaskById.EmployeeName = string.Concat(userTaskById.EmployeeName, "(", base.EmployeeName, "代签)"); } if (userTaskById.PositionId == "") { userTaskById.PositionId = userInfo.PositionId; userTaskById.PositionName = userInfo.PositionName; } if (userTaskById.DeptId == "") { userTaskById.DeptId = userInfo.DeptId; userTaskById.DeptName = userInfo.DeptName; } __UserTask.UpdateAdvice(userTaskById); EIS.WorkFlow.Engine.Utility.DeleteUnDoneUserTaskByTaskId(taskById.TaskId, dbTransaction); string item = ""; string rollBackScope = activityById.GetRollBackScope(); char[] chrArray = new char[] { '|' }; string[] strArrays = rollBackScope.Split(chrArray); StringCollection stringCollections = new StringCollection(); if (((int)strArrays.Length <= 1 ? false : rollBackScope.Length > 2)) { string str = strArrays[1]; chrArray = new char[] { ',' }; stringCollections.AddRange(str.Split(chrArray)); if (stringCollections.Count == 1) { item = stringCollections[0]; } } if (item != "") { List<Task> tasks = driverEngine.RollBackTask(taskId, item, dbTransaction); if (instanceById.NeedUpdate) { (new _Instance(dbTransaction)).UpdateXPDL(instanceById); } _Task __Task = new _Task(dbTransaction); taskById.TaskState = 2.ToString(); taskById._UpdateTime = DateTime.Now; __Task.Update(taskById); if (tasks.Count > 0) { StringCollection stringCollections1 = new StringCollection(); foreach (Task task in tasks) { TaskService.GetTaskDealUser(task.TaskId, stringCollections1, dbTransaction); } userTaskById.RecIds = EIS.AppBase.Utility.GetJoinString(stringCollections1); userTaskById.RecNames = EmployeeService.GetEmployeeNameList(stringCollections1); __UserTask.UpdateAdvice(userTaskById); } dbTransaction.Commit(); } else { return; } } catch (Exception exception1) { Exception exception = exception1; dbTransaction.Rollback(); this.stringDictionary_0.Add(uTaskId, exception.Message); } } finally { dbConnection.Close(); } } finally { if (dbConnection != null) { ((IDisposable)dbConnection).Dispose(); } } } else { this.method_4(DealAction.Submit, uTaskId, reason); } } } private string method_6(Activity activity_0, UserTask userTask_0, DealAction dealAction_0) { string fieldText; if (dealAction_0 == DealAction.Submit) { fieldText = (!activity_0.IsDecisionNode() ? "提交" : "同意"); } else if (dealAction_0 == DealAction.RollBack) { fieldText = EnumDescription.GetFieldText(dealAction_0); } else if (dealAction_0 != DealAction.Agree) { fieldText = (dealAction_0 != DealAction.Disagree ? "提交" : AppSettings.Instance.SignRejectAction); } else { fieldText = (userTask_0.DealType != "2" ? EnumDescription.GetFieldText(dealAction_0) : "提交"); } return fieldText; } protected void Page_Load(object sender, EventArgs e) { this.string_0 = base.GetParaValue("wfCode"); this.string_1 = base.GetParaValue("tblName"); if (!base.IsPostBack) { this.SubmitTaskIdList = base.GetParaValue("TaskIdList"); this.method_0(this.string_0); } } } }
50.548094
1,060
0.456807
[ "MIT" ]
chen1993nian/CPMPlatform
Dev/SysFolder/WorkFlow/DealFlowBatch.aspx.cs
28,008
C#
using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Parithon.StreamDeck.SDK.Models { public interface ISettings { dynamic Settings { get; } Coordinates Coordinates { get; } short State { get; } bool IsInMultiAction { get; } } public class SettingsPayload : ISettings { [JsonProperty("settings")] public dynamic Settings { get; private set; } [JsonProperty("coordinates")] public Coordinates Coordinates { get; private set; } [JsonProperty("state")] public short State { get; private set; } [JsonProperty("isInMultiAction")] public bool IsInMultiAction { get; private set; } } }
22.5
56
0.693056
[ "MIT" ]
parithon/sdsdk
Parithon.StreamDeck.SDK/Models/SettingsPayload.cs
722
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace Hong.Abp.Core.Utils { public class EnumUtil { /// <summary> /// 获取name,descriptions 数组 /// </summary> /// <typeparam name="T">玫举类型</typeparam> /// <returns></returns> public static Dictionary<string, string> GetNameDescriptions<T>() { var result = new Dictionary<string, string>(); Type t = typeof(T); Array arrays = Enum.GetValues(t); for (int i = 0; i < arrays.LongLength; i++) { object test = arrays.GetValue(i); if (test != null) { FieldInfo fieldInfo = test.GetType().GetField(test.ToString()); if (fieldInfo is not null) { object[] attribArray = fieldInfo.GetCustomAttributes(false); foreach (var item in attribArray) { DescriptionAttribute attrib = (DescriptionAttribute)item; result.Add(fieldInfo.Name.ToString(), attrib.Description); } } } } return result; } /// <summary> /// 根据值得到中文备注 /// </summary> /// <param name="e"></param> /// <param name="value"></param> /// <returns></returns> public static string GetEnumDescription<T>(int? value) { Type t = typeof(T); FieldInfo[] fields = t.GetFields(); for (int i = 1, count = fields.Length; i < count; i++) { if ((int)System.Enum.Parse(t, fields[i].Name) == value) { DescriptionAttribute[] enumAttributes = (DescriptionAttribute[])fields[i]. GetCustomAttributes(typeof(DescriptionAttribute), false); if (enumAttributes.Length > 0) { return enumAttributes[0].Description; } } } return ""; } } }
33.863636
94
0.465324
[ "MIT" ]
gzh4455/Hong.Abp
Hong.Abp.Core/Utils/EnumUtil.cs
2,271
C#
using System; using System.Windows.Forms; using System.Web; using System.IO; using System.Web.Mail; namespace CSScript { class Script { const string usage = "Usage: cscscript smtpMailTo smtpServer to subject body [file0] [fileN] ...\nSends e-mail to the specified address (use \"\" for local smtp server)\n"+ "Example: cscscript \"\" user@domain \"Test\" \"This mail was sent by CS-Scrypt.\" \"c:\\boot.ini\" \n"; [STAThread] static public void Main(string[] args) { if (args.Length < 4 || (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help"))) { Console.WriteLine(usage); } else { try { string server = args[0]; string to = args[1]; string subject = args[2]; string body = args[3]; string[] attachments = null; if (args.Length > 4) { attachments = new string[args.Length - 4]; for (int i = 0; i < attachments.Length; i++) { attachments[i] = args[4 + i]; } } MailMessage myMail = new MailMessage(); myMail.To = to; myMail.Subject = subject; myMail.Body = body; if (attachments != null) { foreach (string file in attachments) { if (File.Exists(file)) { string filePath = Path.GetFullPath(file); myMail.Attachments.Add(new MailAttachment(filePath, MailEncoding.Base64)); } else throw new Exception("File "+file+" cannot be attached"); } } SmtpMail.SmtpServer = server; SmtpMail.Send(myMail); } catch(Exception e) { Console.WriteLine(e.Message); return; } Console.WriteLine("Message has been sent"); } } } }
24.521127
174
0.570362
[ "MIT" ]
JTOne123/cs-script
Source/deployment/lib/SMTPMailTo.cs
1,741
C#
using System; using R5T.Frisia.Suebia; using R5T.T0064; namespace R5T.Antium.Default { [ServiceImplementationMarker] public class RemoteDeploymentSerializationAwsEc2ServerHostFriendlyNameProvider : IAwsEc2ServerHostFriendlyNameProvider, IServiceImplementation { private IRemoteDeploymentSecretsSerializationProvider RemoteDeploymentSecretsSerializationProvider { get; } public RemoteDeploymentSerializationAwsEc2ServerHostFriendlyNameProvider( IRemoteDeploymentSecretsSerializationProvider remoteDeploymentSecretsSerializationProvider) { this.RemoteDeploymentSecretsSerializationProvider = remoteDeploymentSecretsSerializationProvider; } public string GetHostFriendlyName() { var remoteDeploymentSecretsSerialization = this.RemoteDeploymentSecretsSerializationProvider.GetRemoteDeploymentSecretsSerialization(); var output = remoteDeploymentSecretsSerialization.HostConnectionFriendlyName; return output; } } }
32.90625
147
0.780627
[ "MIT" ]
MinexAutomation/R5T.Antium.Default
source/R5T.Antium.Default/Code/Services/Implementations/RemoteDeploymentSerializationAwsEc2ServerHostFriendlyNameProvider.cs
1,055
C#
using System; using System.Threading.Tasks; using JetBrains.Collections.Viewable; using JetBrains.Rd.Reflection; using NUnit.Framework; namespace Test.RdFramework.Reflection { [TestFixture] public class AsyncCornerCases : ProxyGeneratorAsyncCallsTest { protected override bool IsAsync => true; [Test] public async Task TestUnregisteredType() { await TestTemplate<UnknownSerializer, IUnknownSerializer>(s => { var task = s.M(new Derived()); Assert.Throws<AggregateException>(() => task.Wait(1000)); }); } public class Base { } public class Derived : Base { } [RdRpc] public interface IUnknownSerializer { Task M(Base val); } [RdExt] public class UnknownSerializer : RdExtReflectionBindableBase, IUnknownSerializer { public Task M(Base val) => Task.Factory.StartNew(() => { }); } } [TestFixture] [Apartment(System.Threading.ApartmentState.STA)] public class ProxyGeneratorCornerCasesTests : RdReflectionTestBase { [RdRpc] public interface IInvalid1 { void M(ref int refx); } [RdRpc] public interface IInvalid2 { void M(out int refx); } [RdRpc] public interface IInvalid3 { void M<T>(out int refx); } [RdRpc] public interface IInvalid4<T> { void M(out int refx); } [RdRpc] public interface IInvalid5 { ref int M(); } //[RdRpc] public interface IInvalid6 { int M(in int x); } [RdRpc] public interface IInvalid7 { event Action<string> Event; } [RdRpc] public interface IInvalid8 { string X { set; } } [RdRpc] public interface IInvalid9 { string X { get; set; } } public interface IInvalid10 { } // no RdRpcAttribute [RdRpc] public interface IInvalid11 { void M(Action x); } private bool TestType<T>() where T : class { try { CFacade.ProxyGenerator.CreateType<T>(); CFacade.ScalarSerializers.GetOrCreate(typeof(T)); } catch (Exception e) { return true; } return false; } [Test] public void TestInvalid1() { Assert.IsTrue(TestType<IInvalid1>()); } [Test] public void TestInvalid2() { Assert.IsTrue(TestType<IInvalid2>()); } [Test] public void TestInvalid3() { Assert.IsTrue(TestType<IInvalid3>()); } [Test] public void TestInvalid4() { Assert.IsTrue(TestType<IInvalid4<int>>()); } [Test] public void TestInvalid5() { Assert.IsTrue(TestType<IInvalid5>()); } [Test] public void TestInvalid7() { Assert.IsTrue(TestType<IInvalid7>()); } [Test] public void TestInvalid8() { Assert.IsTrue(TestType<IInvalid8>()); } [Test] public void TestInvalid9() { Assert.IsTrue(TestType<IInvalid9>()); } [Test] public void TestInvalid10() { Assert.IsTrue(TestType<IInvalid10>()); } [Test] public void TestInvalid11() { Assert.IsTrue(TestType<IInvalid11>()); } [Test] public void TestIncorrectInitialization() { try { WithExtsProxy<WrongInitializedTypeTest, IWrongInitialializedTypeTest>((c, s) => { c.ViewableProperty.Value = "test"; Assert.AreEqual(c.ViewableProperty.Value, s.ViewableProperty.Value); }); } catch (Exception e) { return; } Assert.Fail(); } [Test] public void TestUnexpectedInterfaceType() { Assert.Throws<Exception>(() => { WithExtsProxy<UnexpectedInterfaceType, IUnexpectedInterfaceType>((c, s) => { c.ViewableProperty.Value = "test"; }); }); } [RdRpc] public interface IUnexpectedInterfaceType { ViewableProperty<string> ViewableProperty { get; } } [RdExt] public class UnexpectedInterfaceType : RdExtReflectionBindableBase, IUnexpectedInterfaceType { public ViewableProperty<string> ViewableProperty { get; } } [RdRpc] public interface IWrongInitialializedTypeTest { IViewableProperty<string> ViewableProperty { get; } } [RdExt] public class WrongInitializedTypeTest : RdExtReflectionBindableBase, IWrongInitialializedTypeTest { public IViewableProperty<string> ViewableProperty { get; } public WrongInitializedTypeTest() { ViewableProperty = new ViewableProperty<string>(); } } } }
30.112676
101
0.65131
[ "Apache-2.0" ]
yvvan/rd
rd-net/Test.RdFramework/Reflection/ProxyGeneratorCornerCasesTests.cs
4,278
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("03.01 Sort Array of Strings")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("03.01 Sort Array of Strings")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("832fb00e-f314-4496-b1b0-c8a81351864f")] // 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.432432
84
0.746132
[ "MIT" ]
GabrielRezendi/Programming-Fundamentals-2017
02.Extented Fundamentals/18.ARRAY AND LIST ALGORITHMS - EXERCISES/03.01 Sort Array of Strings/Properties/AssemblyInfo.cs
1,425
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection.Emit; /// <summary> /// OpCodes.Ldlen [v-minch] /// </summary> public class OpCodesLdlen { public static int Main() { OpCodesLdlen test = new OpCodesLdlen(); TestLibrary.TestFramework.BeginTestCase("Test for the field of OpCodes.Ldlen"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Verify OpCodes Ldlen field value"); try { retVal = VerificationHelper(OpCodes.Ldlen, "ldlen", StackBehaviour.Popref, StackBehaviour.Pushi, OperandType.InlineNone, OpCodeType.Objmodel, 1, (byte)0xff, (byte)0x8e, FlowControl.Next, "001.", "Ldlen") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Private Methods private bool VerificationHelper(OpCode code, string name, StackBehaviour pop, StackBehaviour push, OperandType oprandType, OpCodeType type, int size, byte s1, byte s2, FlowControl ctrl, string errorno, string errordesp) { bool retVal = true; string actualName = code.Name; if (actualName != name) { TestLibrary.TestFramework.LogError(errorno + ".0", "Name returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualName = " + actualName + ", name = " + name); retVal = false; } StackBehaviour actualPop = code.StackBehaviourPop; if (actualPop != pop) { TestLibrary.TestFramework.LogError(errorno + ".1", "StackBehaviourPop returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualPop = " + actualPop + ", pop = " + pop); retVal = false; } StackBehaviour actualPush = code.StackBehaviourPush; if (actualPush != push) { TestLibrary.TestFramework.LogError(errorno + ".2", "StackBehaviourPush returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualPush = " + actualPush + ", push = " + push); retVal = false; } OperandType actualOperandType = code.OperandType; if (actualOperandType != oprandType) { TestLibrary.TestFramework.LogError(errorno + ".3", "OperandType returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualOperandType = " + actualOperandType + ", oprandType = " + oprandType); retVal = false; } OpCodeType actualOpCodeType = code.OpCodeType; if (actualOpCodeType != type) { TestLibrary.TestFramework.LogError(errorno + ".4", "OpCodeType returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualOpCodeType = " + actualOpCodeType + ", type = " + type); retVal = false; } int actualSize = code.Size; if (actualSize != size) { TestLibrary.TestFramework.LogError(errorno + ".5", "Size returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualSize = " + actualSize + ", size = " + size); retVal = false; } short expectedValue = 0; if (size == 2) expectedValue = (short)(s1 << 8 | s2); else expectedValue = (short)s2; short actualValue = code.Value; if (actualValue != expectedValue) { TestLibrary.TestFramework.LogError(errorno + ".6", "Value returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualValue = " + actualValue + ", s1 = " + s1 + ", s2 = " + s2 + ", expectedValue = " + expectedValue); retVal = false; } FlowControl actualCtrl = code.FlowControl; if (actualCtrl != ctrl) { TestLibrary.TestFramework.LogError(errorno + ".7", "FlowControl returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualCtrl = " + actualCtrl + ", ctrl = " + ctrl); retVal = false; } return retVal; } #endregion }
37.064935
183
0.589348
[ "MIT" ]
AaronRobinsonMSFT/coreclr
tests/src/CoreMangLib/cti/system/reflection/emit/opcodes/opcodesldlen.cs
5,708
C#
using System; using System.Linq; using System.Net; using EventStore.ClientAPI.Common.Log; using EventStore.ClientAPI.Common.Utils; using EventStore.ClientAPI.SystemData; namespace EventStore.ClientAPI { /// <summary> /// Used to build a connection settings (fluent API) /// </summary> public class ConnectionSettingsBuilder { private ILogger _log = new NoopLogger(); private bool _verboseLogging; private int _maxQueueSize = Consts.DefaultMaxQueueSize; private int _maxConcurrentItems = Consts.DefaultMaxConcurrentItems; private int _maxRetries = Consts.DefaultMaxOperationRetries; private int _maxReconnections = Consts.DefaultMaxReconnections; private bool _requireMaster = Consts.DefaultRequireMaster; private TimeSpan _reconnectionDelay = Consts.DefaultReconnectionDelay; private TimeSpan _operationTimeout = Consts.DefaultOperationTimeout; private TimeSpan _operationTimeoutCheckPeriod = Consts.DefaultOperationTimeoutCheckPeriod; private UserCredentials _defaultUserCredentials; private bool _useSslConnection; private string _targetHost; private bool _validateServer; private bool _failOnNoServerResponse; private TimeSpan _heartbeatInterval = TimeSpan.FromMilliseconds(750); private TimeSpan _heartbeatTimeout = TimeSpan.FromMilliseconds(1500); private TimeSpan _clientConnectionTimeout = TimeSpan.FromMilliseconds(1000); private string _clusterDns; private int _maxDiscoverAttempts = Consts.DefaultMaxClusterDiscoverAttempts; private int _gossipExternalHttpPort = Consts.DefaultClusterManagerExternalHttpPort; private TimeSpan _gossipTimeout = TimeSpan.FromSeconds(1); private GossipSeed[] _gossipSeeds; private bool _preferRandomNode = false; internal ConnectionSettingsBuilder() { } /// <summary> /// Configures the connection to output log messages to the given <see cref="ILogger" />. /// </summary> /// <param name="logger">The <see cref="ILogger"/> to use.</param> /// <returns></returns> public ConnectionSettingsBuilder UseCustomLogger(ILogger logger) { Ensure.NotNull(logger, "logger"); _log = logger; return this; } /// <summary> /// Configures the connection to output log messages to the console. /// </summary> public ConnectionSettingsBuilder UseConsoleLogger() { _log = new ConsoleLogger(); return this; } /// <summary> /// Configures the connection to output log messages to the listeners /// configured on <see cref="System.Diagnostics.Debug" />. /// </summary> public ConnectionSettingsBuilder UseDebugLogger() { _log = new DebugLogger(); return this; } /// <summary> /// Configures the connection to output log messages to a file. /// </summary> public ConnectionSettingsBuilder UseFileLogger(string filename) { _log = new FileLogger(filename); return this; } /// <summary> /// Turns on verbose <see cref="EventStoreConnection"/> internal logic logging. /// </summary> /// <returns></returns> public ConnectionSettingsBuilder EnableVerboseLogging() { _verboseLogging = true; return this; } /// <summary> /// Sets the limit for number of outstanding operations /// </summary> /// <param name="limit">The new limit of outstanding operations</param> /// <returns></returns> public ConnectionSettingsBuilder LimitOperationsQueueTo(int limit) { Ensure.Positive(limit, "limit"); _maxQueueSize = limit; return this; } /// <summary> /// Limits the number of concurrent operations that this connection can have /// </summary> /// <param name="limit"></param> /// <returns></returns> public ConnectionSettingsBuilder LimitConcurrentOperationsTo(int limit) { Ensure.Positive(limit, "limit"); _maxConcurrentItems = limit; return this; } /// <summary> /// Limits the number of operation attempts /// </summary> /// <param name="limit"></param> /// <returns></returns> public ConnectionSettingsBuilder LimitAttemptsForOperationTo(int limit) { Ensure.Positive(limit, "limit"); _maxRetries = limit - 1; return this; } /// <summary> /// Limits the number of operation retries /// </summary> /// <param name="limit"></param> /// <returns></returns> public ConnectionSettingsBuilder LimitRetriesForOperationTo(int limit) { Ensure.Nonnegative(limit, "limit"); _maxRetries = limit; return this; } /// <summary> /// Allows infinite operation retry attempts /// </summary> /// <returns></returns> public ConnectionSettingsBuilder KeepRetrying() { _maxRetries = -1; return this; } /// <summary> /// Limits the number of reconnections this connection can try to make /// </summary> /// <param name="limit"></param> /// <returns></returns> public ConnectionSettingsBuilder LimitReconnectionsTo(int limit) { Ensure.Nonnegative(limit, "limit"); _maxReconnections = limit; return this; } /// <summary> /// Allows infinite reconnection attempts /// </summary> /// <returns></returns> public ConnectionSettingsBuilder KeepReconnecting() { _maxReconnections = -1; return this; } /// <summary> /// Requires all write and read requests to be served only by master (cluster version only) /// </summary> /// <returns></returns> public ConnectionSettingsBuilder PerformOnMasterOnly() { _requireMaster = true; return this; } /// <summary> /// Allow for writes to be forwarded and read requests served locally if node is not master (cluster version only) /// </summary> /// <returns></returns> public ConnectionSettingsBuilder PerformOnAnyNode() { _requireMaster = false; return this; } /// <summary> /// Sets the delay between reconnection attempts /// </summary> /// <param name="reconnectionDelay"></param> /// <returns></returns> public ConnectionSettingsBuilder SetReconnectionDelayTo(TimeSpan reconnectionDelay) { _reconnectionDelay = reconnectionDelay; return this; } /// <summary> /// Sets the operation timeout duration /// </summary> /// <param name="operationTimeout"></param> /// <returns></returns> public ConnectionSettingsBuilder SetOperationTimeoutTo(TimeSpan operationTimeout) { _operationTimeout = operationTimeout; return this; } /// <summary> /// Sets how often timeouts should be checked for. /// </summary> /// <param name="timeoutCheckPeriod"></param> /// <returns></returns> public ConnectionSettingsBuilder SetTimeoutCheckPeriodTo(TimeSpan timeoutCheckPeriod) { _operationTimeoutCheckPeriod = timeoutCheckPeriod; return this; } /// <summary> /// Sets the default <see cref="UserCredentials"/> to be used for this connection. /// If user credentials are not given for an operation, these credentials will be used. /// </summary> /// <param name="userCredentials"></param> /// <returns></returns> public ConnectionSettingsBuilder SetDefaultUserCredentials(UserCredentials userCredentials) { _defaultUserCredentials = userCredentials; return this; } /// <summary> /// Uses a SSL connection over TCP. This should generally be used with authentication. /// </summary> /// <param name="targetHost">HostName of server certificate.</param> /// <param name="validateServer">Whether to accept connection from server with not trusted certificate.</param> /// <returns></returns> public ConnectionSettingsBuilder UseSslConnection(string targetHost, bool validateServer) { Ensure.NotNullOrEmpty(targetHost, "targetHost"); _useSslConnection = true; _targetHost = targetHost; _validateServer = validateServer; return this; } /// <summary> /// Marks that no response from server should cause an error on the request /// </summary> /// <returns></returns> public ConnectionSettingsBuilder FailOnNoServerResponse() { _failOnNoServerResponse = true; return this; } /// <summary> /// Sets how often heartbeats should be expected on the connection (lower values detect broken sockets faster) /// </summary> /// <param name="interval"></param> /// <returns></returns> public ConnectionSettingsBuilder SetHeartbeatInterval(TimeSpan interval) { _heartbeatInterval = interval; return this; } /// <summary> /// Sets how long to wait without heartbeats before determining a connection to be dead (must be longer than heartbeat interval) /// </summary> /// <param name="timeout"></param> /// <returns></returns> public ConnectionSettingsBuilder SetHeartbeatTimeout(TimeSpan timeout) { _heartbeatTimeout = timeout; return this; } /// <summary> /// Sets the timeout for attempting to connect to a server before aborting and attempting a reconnect. /// </summary> /// <param name="timeout"></param> /// <returns></returns> public ConnectionSettingsBuilder WithConnectionTimeoutOf(TimeSpan timeout) { _clientConnectionTimeout = timeout; return this; } /// <summary> /// Sets the DNS name under which cluster nodes are listed. /// </summary> /// <param name="clusterDns">The DNS name under which cluster nodes are listed.</param> /// <returns>A <see cref="DnsClusterSettingsBuilder"/> for further configuration.</returns> /// <exception cref="ArgumentNullException">If <paramref name="clusterDns" /> is null or empty.</exception> public ConnectionSettingsBuilder SetClusterDns(string clusterDns) { Ensure.NotNullOrEmpty(clusterDns, "clusterDns"); _clusterDns = clusterDns; return this; } /// <summary> /// Sets the maximum number of attempts for discovery. /// </summary> /// <param name="maxDiscoverAttempts">The maximum number of attempts for DNS discovery.</param> /// <returns>A <see cref="DnsClusterSettingsBuilder"/> for further configuration.</returns> /// <exception cref="ArgumentOutOfRangeException">If <paramref name="maxDiscoverAttempts" /> is less than or equal to 0.</exception> public ConnectionSettingsBuilder SetMaxDiscoverAttempts(int maxDiscoverAttempts) { if (maxDiscoverAttempts <= 0) throw new ArgumentOutOfRangeException("maxDiscoverAttempts", string.Format("maxDiscoverAttempts value is out of range: {0}. Allowed range: [1, infinity].", maxDiscoverAttempts)); _maxDiscoverAttempts = maxDiscoverAttempts; return this; } /// <summary> /// Sets the period after which gossip times out if none is received. /// </summary> /// <param name="timeout">The period after which gossip times out if none is received.</param> /// <returns>A <see cref="DnsClusterSettingsBuilder"/> for further configuration.</returns> public ConnectionSettingsBuilder SetGossipTimeout(TimeSpan timeout) { _gossipTimeout = timeout; return this; } /// <summary> /// Whether to randomly choose a node that's alive from the known nodes. /// </summary> /// <returns>A <see cref="DnsClusterSettingsBuilder"/> for further configuration.</returns> public ConnectionSettingsBuilder PreferRandomNode() { _preferRandomNode = true; return this; } /// <summary> /// Sets the well-known port on which the cluster gossip is taking place. /// /// If you are using the commercial edition of Event Store HA, with Manager nodes in /// place, this should be the port number of the External HTTP port on which the /// managers are running. /// /// If you are using the open source edition of Event Store HA, this should be the /// External HTTP port that the nodes are running on. If you cannot use a well-known /// port for this across all nodes, you can instead use gossip seed discovery and set /// the <see cref="IPEndPoint" /> of some seed nodes instead. /// </summary> /// <param name="clusterGossipPort">The cluster gossip port.</param> /// <returns>A <see cref="DnsClusterSettingsBuilder"/> for further configuration.</returns> public ConnectionSettingsBuilder SetClusterGossipPort(int clusterGossipPort) { Ensure.Positive(clusterGossipPort, "clusterGossipPort"); _gossipExternalHttpPort = clusterGossipPort; return this; } /// <summary> /// Sets gossip seed endpoints for the client. /// /// Note that this should be the external HTTP endpoint of the server, as it is required /// for the client to exchange gossip with the server. The standard port which should be /// used here is 2113. /// /// If the server requires a specific Host header to be sent as part of the gossip /// request, use the overload of this method taking <see cref="GossipSeed" /> instead. /// </summary> /// <param name="gossipSeeds"><see cref="IPEndPoint" />s representing the endpoints of nodes from which to seed gossip.</param> /// <returns>A <see cref="ClusterSettingsBuilder"/> for further configuration.</returns> /// <exception cref="ArgumentException">If no gossip seeds are specified.</exception> public ConnectionSettingsBuilder SetGossipSeedEndPoints(params IPEndPoint[] gossipSeeds) { if (gossipSeeds == null || gossipSeeds.Length == 0) throw new ArgumentException("Empty FakeDnsEntries collection."); _gossipSeeds = gossipSeeds.Select(x => new GossipSeed(x)).ToArray(); return this; } /// <summary> /// Sets gossip seed endpoints for the client. /// </summary> /// <param name="gossipSeeds"><see cref="GossipSeed"/>s representing the endpoints of nodes from which to seed gossip.</param> /// <returns>A <see cref="ClusterSettingsBuilder"/> for further configuration.</returns> /// <exception cref="ArgumentException">If no gossip seeds are specified.</exception> public ConnectionSettingsBuilder SetGossipSeedEndPoints(params GossipSeed[] gossipSeeds) { if (gossipSeeds == null || gossipSeeds.Length == 0) throw new ArgumentException("Empty FakeDnsEntries collection."); _gossipSeeds = gossipSeeds; return this; } /// <summary> /// Convert the mutable <see cref="ConnectionSettingsBuilder"/> object to an immutable /// <see cref="ConnectionSettings"/> object. /// </summary> /// <param name="builder">The <see cref="ConnectionSettingsBuilder"/> to convert.</param> /// <returns>An immutable <see cref="ConnectionSettings"/> object with the values specified by the builder.</returns> public static implicit operator ConnectionSettings(ConnectionSettingsBuilder builder) { return builder.Build(); } /// <summary> /// Convert the mutable <see cref="ConnectionSettingsBuilder"/> object to an immutable /// <see cref="ConnectionSettings"/> object. /// </summary> public ConnectionSettings Build() { return new ConnectionSettings(_log, _verboseLogging, _maxQueueSize, _maxConcurrentItems, _maxRetries, _maxReconnections, _requireMaster, _reconnectionDelay, _operationTimeout, _operationTimeoutCheckPeriod, _defaultUserCredentials, _useSslConnection, _targetHost, _validateServer, _failOnNoServerResponse, _heartbeatInterval, _heartbeatTimeout, _clientConnectionTimeout, _clusterDns, _gossipSeeds, _maxDiscoverAttempts, _gossipExternalHttpPort, _gossipTimeout, _preferRandomNode); } } }
40.265795
194
0.586841
[ "Apache-2.0" ]
accraze/EventStore
src/EventStore.ClientAPI/ConnectionSettingsBuilder.cs
18,484
C#
using UnityEngine; using System.Collections.Generic; public class Enlighten: SingleTarget { public override string animation { get { return "ClericCast"; }} public override Color castColor { get { return castColorEnhancer; }} public Enlighten() { range = 5; useLos = false; name = "Enlighten"; maxCooldown = 2; canTargetSelf = true; targetAlly(true); targetEnemy(false); } public override void additionalEffects (BattleCharacter target) { EnlightenEffect e = new EnlightenEffect(); e.effectValue = level; e.duration = 2; e.caster = self; target.applyEffect(e); Draconia.Event buffEvent = new Draconia.Event(self, EventHook.useBuffSkill); buffEvent.appliedBuff = e; self.onEvent(buffEvent); } }
23.424242
80
0.689521
[ "MIT" ]
Fellowship-of-the-Bus/Draconia-Unity
Assets/Script/Skills/Active/Enhancer/Enlighten.cs
773
C#