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 FHICORC.Integrations.UkGateway.Services;
using FHICORC.Integrations.UkGateway.Services.Interfaces;
using Microsoft.Extensions.DependencyInjection;
namespace FHICORC.Integrations.UkGateway
{
public static class ServiceCollectionExtension
{
public static IServiceCollection AddUkGatewayIntegration(this IServiceCollection serviceCollection)
{
serviceCollection
.AddHttpClient()
.AddScoped<IUkGatewayService, UkGatewayService>();
return serviceCollection;
}
}
}
| 29.473684 | 107 | 0.717857 | [
"MIT"
] | folkehelseinstituttet/Fhi.Koronasertifikat.Verifikasjon.Backend | FHICORC.Backend/FHICORC.Integrations.UKGateway/ServiceCollectionExtension.cs | 562 | C# |
using System;
using System.Xml.Serialization;
namespace Howatworks.SubEtha.Bindings
{
[Serializable]
public class Setting<T>
{
[XmlAttribute]
public T Value { get; set; }
}
}
| 16.076923 | 37 | 0.636364 | [
"MIT"
] | johnnysaucepn/SubEtha | src/Bindings/Howatworks.SubEtha.Bindings/Setting.cs | 211 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using Zyan.Communication.Discovery;
using Zyan.Communication.Discovery.Metadata;
using Zyan.Communication.Notification;
using Zyan.Communication.Protocols;
using Zyan.Communication.Protocols.Tcp;
using Zyan.Communication.Security;
using Zyan.Communication.SessionMgmt;
using Zyan.InterLinq.Expressions;
#if !XAMARIN
using DefaultServerProtocolSetup = Zyan.Communication.Protocols.Tcp.TcpBinaryServerProtocolSetup;
#else
using DefaultServerProtocolSetup = Zyan.Communication.Protocols.Tcp.TcpDuplexServerProtocolSetup;
#endif
namespace Zyan.Communication
{
/// <summary>
/// Host for publishing components with Zyan.
/// </summary>
public class ZyanComponentHost : IComponentCatalog, IDisposable
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ZyanComponentHost" /> class.
/// </summary>
/// <param name="name">The name of the component host.</param>
/// <param name="tcpPort">The TCP port.</param>
public ZyanComponentHost(string name, int tcpPort)
: this(name, new DefaultServerProtocolSetup(tcpPort), new InProcSessionManager(), new ComponentCatalog())
{
DisposeCatalogWithHost = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="ZyanComponentHost" /> class.
/// </summary>
/// <param name="name">The name of the component host.</param>
/// <param name="tcpPort">The TCP port.</param>
/// <param name="catalog">The component catalog.</param>
public ZyanComponentHost(string name, int tcpPort, IComponentCatalog catalog)
: this(name, new DefaultServerProtocolSetup(tcpPort), new InProcSessionManager(), catalog)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ZyanComponentHost" /> class.
/// </summary>
/// <param name="name">The name of the component host.</param>
/// <param name="protocolSetup">The protocol setup.</param>
public ZyanComponentHost(string name, IServerProtocolSetup protocolSetup)
: this(name, protocolSetup, new InProcSessionManager(), new ComponentCatalog())
{
DisposeCatalogWithHost = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="ZyanComponentHost" /> class.
/// </summary>
/// <param name="name">The name of the component host.</param>
/// <param name="protocolSetup">The protocol setup.</param>
/// <param name="catalog">The component catalog.</param>
public ZyanComponentHost(string name, IServerProtocolSetup protocolSetup, IComponentCatalog catalog)
: this(name, protocolSetup, new InProcSessionManager(), catalog)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ZyanComponentHost" /> class.
/// </summary>
/// <param name="name">The name of the component host.</param>
/// <param name="protocolSetup">The protocol setup.</param>
/// <param name="sessionManager">The session manager.</param>
public ZyanComponentHost(string name, IServerProtocolSetup protocolSetup, ISessionManager sessionManager)
: this(name, protocolSetup, sessionManager, new ComponentCatalog())
{
DisposeCatalogWithHost = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="ZyanComponentHost" /> class.
/// </summary>
/// <param name="name">The name of the component host.</param>
/// <param name="protocolSetup">The protocol setup.</param>
/// <param name="sessionManager">The session manager.</param>
/// <param name="catalog">The component catalog.</param>
public ZyanComponentHost(string name, IServerProtocolSetup protocolSetup, ISessionManager sessionManager, IComponentCatalog catalog)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException(LanguageResource.ArgumentException_ComponentHostNameMissing, "name");
if (protocolSetup == null)
throw new ArgumentNullException("protocolSetup");
if (sessionManager == null)
throw new ArgumentNullException("sessionManager");
if (catalog == null)
throw new ArgumentNullException("catalog");
_name = name;
_protocolSetup = protocolSetup;
_sessionManager = sessionManager;
_sessionManager.ClientSessionTerminated += (s, e) => OnClientSessionTerminated(e);
_catalog = catalog;
_serializationHandling = new SerializationHandlerRepository();
_dispatcher = new ZyanDispatcher(this);
// Set up authentication request delegate
_authProvider = protocolSetup.AuthenticationProvider;
this.Authenticate = _authProvider.Authenticate;
// Register standard serialization handlers
RegisterStandardSerializationHandlers();
_hosts.Add(this);
StartListening();
DiscoverableUrl = _protocolSetup.GetDiscoverableUrl(_name);
}
#endregion
#region Authentication
private IAuthenticationProvider _authProvider = null;
/// <summary>
/// Request for authentication.
/// </summary>
public Func<AuthRequestMessage, AuthResponseMessage> Authenticate;
#endregion
#region Session Management
private ISessionManager _sessionManager = null;
/// <summary>
/// Returns the session manager used by this host.
/// </summary>
public ISessionManager SessionManager
{
get { return _sessionManager; }
}
#endregion
#region Component Hosting
private bool DisposeCatalogWithHost { get; set; }
private IComponentCatalog _catalog;
private ZyanDispatcher _dispatcher;
private static List<ZyanComponentHost> _hosts = new List<ZyanComponentHost>();
/// <summary>
/// Gets a list of all known hosts.
/// </summary>
public static List<ZyanComponentHost> Hosts
{
get { return _hosts.ToList(); }
}
/// <summary>
/// Get or sets the component catalog for this host instance.
/// </summary>
public IComponentCatalog ComponentCatalog
{
get { return _catalog; }
set
{
if (value == null)
throw new ArgumentNullException();
_catalog = value;
}
}
/// <summary>
/// Returns an instance of a specified registered component.
/// </summary>
/// <param name="registration">Component registration</param>
/// <returns>Component instance</returns>
public object GetComponentInstance(ComponentRegistration registration)
{
return _catalog.GetComponentInstance(registration);
}
/// <summary>
/// Gets registration data for a specified component by its interface name.
/// </summary>
/// <param name="interfaceName">Name of the component´s interface</param>
/// <returns>Component registration</returns>
ComponentRegistration IComponentCatalog.GetRegistration(string interfaceName)
{
return _catalog.GetRegistration(interfaceName);
}
/// <summary>
/// Determines whether the specified interface name is registered.
/// </summary>
/// <param name="interfaceName">Name of the interface.</param>
bool IComponentCatalog.IsRegistered(string interfaceName)
{
return _catalog.IsRegistered(interfaceName);
}
/// <summary>
/// Deletes a component registration.
/// </summary>
/// <param name="uniqueName">Unique component name</param>
public void UnregisterComponent(string uniqueName)
{
_catalog.UnregisterComponent(uniqueName);
}
/// <summary>
/// Returns a list with information about all registered components.
/// </summary>
/// <returns>List with component information</returns>
public List<ComponentInfo> GetRegisteredComponents()
{
return _catalog.GetRegisteredComponents();
}
/// <summary>
/// Registers a component in the component catalog.
/// </summary>
/// <typeparam name="I">Interface type of the component</typeparam>
/// <typeparam name="T">Implementation type of the component</typeparam>
/// <param name="uniqueName">Unique component name</param>
/// <param name="activationType">Activation type (SingleCall/Singleton)</param>
/// <param name="cleanUpHandler">Delegate for external clean up method</param>
public void RegisterComponent<I, T>(string uniqueName, ActivationType activationType, Action<object> cleanUpHandler)
{
_catalog.RegisterComponent<I, T>(uniqueName, activationType, cleanUpHandler);
}
/// <summary>
/// Registers a component in the component catalog.
/// </summary>
/// <typeparam name="I">Interface type of the component</typeparam>
/// <param name="uniqueName">Unique component name</param>
/// <param name="factoryMethod">Delegate of factory method for external instance creation</param>
/// <param name="activationType">Activation type (SingleCall/Singleton)</param>
/// <param name="cleanUpHandler">Delegate for external clean up method</param>
public void RegisterComponent<I>(string uniqueName, Func<object> factoryMethod, ActivationType activationType, Action<object> cleanUpHandler)
{
_catalog.RegisterComponent<I>(uniqueName, factoryMethod, activationType, cleanUpHandler);
}
/// <summary>
/// Registeres a component instance in the component catalog.
/// </summary>
/// <typeparam name="I">Interface type of the component</typeparam>
/// <typeparam name="T">Implementation type of the component</typeparam>
/// <param name="uniqueName">Unique component name</param>
/// <param name="instance">Component instance</param>
/// <param name="cleanUpHandler">Delegate for external clean up method</param>
public void RegisterComponent<I, T>(string uniqueName, T instance, Action<object> cleanUpHandler)
{
_catalog.RegisterComponent<I, T>(uniqueName, instance, cleanUpHandler);
}
/// <summary>
/// Processes resource clean up logic for a specified registered Singleton activated component.
/// </summary>
/// <param name="regEntry">Component registration</param>
public void CleanUpComponentInstance(ComponentRegistration regEntry)
{
_catalog.CleanUpComponentInstance(regEntry);
}
/// <summary>
/// Processes resource clean up logic for a specified registered component.
/// </summary>
/// <param name="regEntry">Component registration</param>
/// <param name="instance">Component instance to clean up</param>
public void CleanUpComponentInstance(ComponentRegistration regEntry, object instance)
{
_catalog.CleanUpComponentInstance(regEntry, instance);
}
#endregion
#region Network Communication
// Protocol and communication settings
private IServerProtocolSetup _protocolSetup = null;
// Name of the component host (will be included in server URL)
private string _name = string.Empty;
// Name of the transport channel
private string _channelName = string.Empty;
/// <summary>
/// Gets the name of the component host.
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Starts listening to the client requests.
/// </summary>
private void StartListening()
{
var channel = _protocolSetup.CreateChannel();
if (channel == null)
{
throw new ApplicationException(LanguageResource.ApplicationException_NoChannel);
}
// register the channel if needed
_channelName = channel.ChannelName;
if (ChannelServices.GetChannel(_channelName) == null)
{
ChannelServices.RegisterChannel(channel, false);
}
// publish the dispatcher
RemotingServices.Marshal(_dispatcher, _name);
}
/// <summary>
/// Stop listening to the client requests.
/// </summary>
private void StopListening()
{
// detach the dispatcher and close the communication channel
RemotingServices.Disconnect(_dispatcher);
CloseChannel();
}
/// <summary>
/// Closes the channel if it is open.
/// </summary>
private void CloseChannel()
{
// unregister remoting channel
var channel = ChannelServices.GetChannel(_channelName);
if (channel != null)
ChannelServices.UnregisterChannel(channel);
// dispose channel if it's disposable
var disposableChannel = channel as IDisposable;
if (disposableChannel != null)
disposableChannel.Dispose();
}
#endregion
#region Service discovery
/// <summary>
/// Gets or sets the discoverable server URL.
/// </summary>
public string DiscoverableUrl { get; set; }
/// <summary>
/// Gets or sets the discoverable server version.
/// </summary>
public string DiscoverableVersion { get; set; }
private DiscoveryServer DiscoveryServer { get; set; }
/// <summary>
/// Enables the automatic <see cref="ZyanComponentHost"/> discovery.
/// </summary>
public void EnableDiscovery()
{
EnableDiscovery(DiscoveryServer.DefaultDiscoveryPort);
}
/// <summary>
/// Enables the automatic <see cref="ZyanComponentHost"/> discovery.
/// </summary>
/// <param name="port">The port.</param>
public void EnableDiscovery(int port)
{
if (string.IsNullOrEmpty(DiscoverableUrl))
{
throw new InvalidOperationException("DiscoverableUrl is not specified and cannot be autodetected for the selected server protocol.");
}
var discoveryMetadata = new DiscoveryResponse(DiscoverableUrl, DiscoverableVersion);
DiscoveryServer = new DiscoveryServer(discoveryMetadata, port);
DiscoveryServer.StartListening();
}
/// <summary>
/// Disables the automatic <see cref="ZyanComponentHost"/> discovery.
/// </summary>
public void DisableDiscovery()
{
if (DiscoveryServer != null)
{
DiscoveryServer.Dispose();
DiscoveryServer = null;
}
}
#endregion
#region Policy Injection
/// <summary>
/// Occurs before the component call is initiated.
/// </summary>
public event EventHandler<BeforeInvokeEventArgs> BeforeInvoke;
/// <summary>
/// Occurs after the component call is completed.
/// </summary>
public event EventHandler<AfterInvokeEventArgs> AfterInvoke;
/// <summary>
/// Occurs when the component call is canceled due to exception.
/// </summary>
public event EventHandler<InvokeCanceledEventArgs> InvokeCanceled;
/// <summary>
/// Occurs when the component call is rejected due to security reasons.
/// </summary>
public event EventHandler<InvokeCanceledEventArgs> InvokeRejected;
/// <summary>
/// Occurs when a client subscribes to a component's event.
/// </summary>
public event EventHandler<SubscriptionEventArgs> SubscriptionAdded;
/// <summary>
/// Occurs when a client unsubscribes to a component's event.
/// </summary>
public event EventHandler<SubscriptionEventArgs> SubscriptionRemoved;
/// <summary>
/// Occurs when a component cancels the subscription due to exceptions thrown by the client's event handler.
/// </summary>
public event EventHandler<SubscriptionEventArgs> SubscriptionCanceled;
/// <summary>
/// Occurs when a client resubscribes to all event handlers at once (for example, when the server is restarted).
/// </summary>
public event EventHandler SubscriptionsRestored;
/// <summary>
/// Checks whether the BeforeInvoke event has subscriptions.
/// </summary>
/// <returns>True, if subsciptions exist, otherwise, false.</returns>
protected internal bool HasBeforeInvokeSubscriptions()
{
return (BeforeInvoke != null);
}
/// <summary>
/// Checks whether the AfterInvoke event has subscriptions.
/// </summary>
/// <returns>True, if subsciptions exist, otherwise, false.</returns>
protected internal bool HasAfterInvokeSubscriptions()
{
return (AfterInvoke != null);
}
/// <summary>
/// Checks whether the InvokeCanceled event has subscriptions.
/// </summary>
/// <returns>True, if subsciptions exist, otherwise, false.</returns>
protected internal bool HasInvokeCanceledSubscriptions()
{
return (InvokeCanceled != null);
}
/// <summary>
/// Checks whether the InvokeRejected event has subscriptions.
/// </summary>
/// <returns>True, if subsciptions exist, otherwise, false.</returns>
protected internal bool HasInvokeRejectedSubscriptions()
{
return (InvokeRejected != null);
}
/// <summary>
/// Fires the BeforeInvoke event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected internal virtual void OnBeforeInvoke(BeforeInvokeEventArgs e)
{
BeforeInvoke?.Invoke(this, e);
}
/// <summary>
/// Fires the AfterInvoke event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected internal virtual void OnAfterInvoke(AfterInvokeEventArgs e)
{
AfterInvoke?.Invoke(this, e);
}
/// <summary>
/// Fires the InvokeCanceled event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected internal virtual void OnInvokeCanceled(InvokeCanceledEventArgs e)
{
InvokeCanceled?.Invoke(this, e);
}
/// <summary>
/// Fires the InvokeRejected event.
/// </summary>
/// <param name="e">Event arguments</param>
protected internal virtual void OnInvokeRejected(InvokeCanceledEventArgs e)
{
InvokeRejected?.Invoke(this, e);
}
/// <summary>
/// Raises the <see cref="E:SubscriptionAdded" /> event.
/// </summary>
/// <param name="e">The <see cref="SubscriptionEventArgs"/> instance containing the event data.</param>
protected internal virtual void OnSubscriptionAdded(SubscriptionEventArgs e)
{
SubscriptionAdded?.Invoke(this, e);
}
/// <summary>
/// Raises the <see cref="E:SubscriptionRemoved" /> event.
/// </summary>
/// <param name="e">The <see cref="SubscriptionEventArgs"/> instance containing the event data.</param>
protected internal virtual void OnSubscriptionRemoved(SubscriptionEventArgs e)
{
SubscriptionRemoved?.Invoke(this, e);
}
/// <summary>
/// Raises the <see cref="E:SubscriptionCanceled" /> event.
/// </summary>
/// <param name="e">The <see cref="SubscriptionEventArgs"/> instance containing the event data.</param>
protected internal virtual void OnSubscriptionCanceled(SubscriptionEventArgs e)
{
SubscriptionCanceled?.Invoke(this, e);
}
/// <summary>
/// Raises the <see cref="E:SubscriptionsRestored" /> event.
/// </summary>
/// <param name="e">Empty <see cref="EventArgs"/> instance.</param>
protected internal virtual void OnSubscriptionsRestored(EventArgs e)
{
SubscriptionsRestored?.Invoke(this, e);
}
#endregion
#region User defined Serialization Handling
// Repository of the serialization handlers.
private SerializationHandlerRepository _serializationHandling = null;
/// <summary>
/// Gets the serialization handling repository.
/// </summary>
public SerializationHandlerRepository SerializationHandling
{
get { return _serializationHandling; }
}
private void RegisterStandardSerializationHandlers()
{
// TODO: use MEF to discover and register standard serialization handlers:
// [Export(ISerializationHandler), ExportMetadata("SerializedType", typeof(Expression))]
SerializationHandling.RegisterSerializationHandler(typeof(Expression), new ExpressionSerializationHandler());
}
#endregion
#region IDisposable implementation
private bool _isDisposed = false;
/// <summary>
/// Occurs when this instance is disposed.
/// </summary>
public event EventHandler Disposing;
/// <summary>
/// Fires the Disposing event.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnDisposing(EventArgs e)
{
Disposing?.Invoke(this, e);
}
/// <summary>
/// Releases all managed resources.
/// </summary>
public void Dispose()
{
Dispose(false);
}
/// <summary>
/// Releases all managed resources.
/// </summary>
/// <param name="calledFromFinalizer">Specifies if this method is called from finalizer or not</param>
private void Dispose(bool calledFromFinalizer)
{
if (!_isDisposed)
{
OnDisposing(new EventArgs());
_isDisposed = true;
_hosts.Remove(this);
DisableDiscovery();
StopListening();
if (_sessionManager != null)
{
_sessionManager.Dispose();
_sessionManager = null;
}
_dispatcher = null;
Authenticate = null;
_authProvider = null;
if (_catalog != null && DisposeCatalogWithHost)
{
var catalog = _catalog as IDisposable;
if (catalog != null)
catalog.Dispose();
_catalog = null;
}
if (!calledFromFinalizer)
GC.SuppressFinalize(this);
}
}
/// <summary>
/// Is called from runtime when this object is finalized.
/// </summary>
~ZyanComponentHost()
{
Dispose(true);
}
#endregion
#region Login Events
/// <summary>
/// Occurs when new client is logged on.
/// </summary>
public event EventHandler<LoginEventArgs> ClientLoggedOn;
/// <summary>
/// Occurs when the client is logged off.
/// </summary>
public event EventHandler<LoginEventArgs> ClientLoggedOff;
/// <summary>
/// Occurs when the client logon operation is canceled due to an exception.
/// </summary>
public event EventHandler<LoginEventArgs> ClientLogonCanceled;
/// <summary>
/// Occurs when the client session is terminated abnormally.
/// </summary>
public event EventHandler<LoginEventArgs> ClientSessionTerminated;
/// <summary>
/// Fires "ClientLoggedOn" event.
/// </summary>
/// <param name="e">Arguments</param>
protected internal void OnClientLoggedOn(LoginEventArgs e)
{
ClientLoggedOn?.Invoke(this, e);
}
/// <summary>
/// Fires "ClientLoggedOff" event.
/// </summary>
/// <param name="e">Arguments</param>
protected internal void OnClientLoggedOff(LoginEventArgs e)
{
ClientLoggedOff?.Invoke(this, e);
}
/// <summary>
/// Fires "ClientLogonCanceled" event.
/// </summary>
/// <param name="e">Arguments</param>
protected internal void OnClientLogonCanceled(LoginEventArgs e)
{
ClientLogonCanceled?.Invoke(this, e);
}
/// <summary>
/// Fires "ClientSessionTerminated" event.
/// </summary>
/// <param name="e">Arguments</param>
protected internal void OnClientSessionTerminated(LoginEventArgs e)
{
ClientSessionTerminated?.Invoke(this, e);
}
#endregion
#region Trace Polling Events
// Switch to enable polling event trace
private bool _pollingEventTacingEnabled = false;
/// <summary>
/// Event: Occours when a heartbeat signal is received from a client.
/// </summary>
public event EventHandler<ClientHeartbeatEventArgs> ClientHeartbeatReceived;
/// <summary>
/// Fires the ClientHeartbeatReceived event.
/// </summary>
/// <param name="e">Event arguments</param>
protected virtual void OnClientHeartbeatReceived(ClientHeartbeatEventArgs e)
{
if (SessionManager.ExistSession(e.SessionID))
{
var session = SessionManager.GetSessionBySessionID(e.SessionID);
session.Timestamp = DateTime.Now;
var clientHeartbeatReceived = ClientHeartbeatReceived;
if (clientHeartbeatReceived != null)
{
clientHeartbeatReceived(this, e);
}
}
}
/// <summary>
/// Gets or sets whether polling event tracing is enabled.
/// </summary>
public virtual bool PollingEventTracingEnabled
{
get { return _pollingEventTacingEnabled; }
set
{
if (_pollingEventTacingEnabled != value)
{
_pollingEventTacingEnabled = value;
if (_pollingEventTacingEnabled)
_dispatcher.ClientHeartbeatReceived += _dispatcher_ClientHeartbeatReceived;
else
_dispatcher.ClientHeartbeatReceived -= _dispatcher_ClientHeartbeatReceived;
}
}
}
/// <summary>
/// Called, when dispatcher receives a heartbeat signal from a client.
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="e">Event arguments</param>
private void _dispatcher_ClientHeartbeatReceived(object sender, ClientHeartbeatEventArgs e)
{
OnClientHeartbeatReceived(e);
}
#endregion
}
}
| 31.063694 | 144 | 0.6878 | [
"MIT"
] | aTiKhan/Zyan | source/Zyan.Communication/ZyanComponentHost.cs | 24,388 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using DocumentFormat.OpenXml.Framework.Metadata;
using System;
using System.Xml;
using Xunit;
#pragma warning disable CA1812
namespace DocumentFormat.OpenXml.Framework.Tests
{
public class PropertyBuilderTests
{
[Fact]
public void Sanity()
{
var builder = new ElementMetadata.Builder(typeof(OpenXmlElement));
builder.AddElement<SomeElement>()
.AddAttribute("s", a => a.Str, a =>
{
});
var data = builder.Build();
var element = new Metadata.ElementState(data);
ref var str = ref element.Attributes.GetProperty(nameof(SomeElement.Str)).Value;
Assert.Null(str);
var tmp = new StringValue();
str = tmp;
Assert.NotNull(str);
var str2 = element.Attributes.GetProperty(nameof(SomeElement.Str)).Value;
Assert.Same(str, tmp);
}
[Fact]
public void IsRequired()
{
var builder = new ElementMetadata.Builder(typeof(OpenXmlElement));
builder.AddElement<SomeElement>()
.AddAttribute("s", a => a.Str, a =>
{
a.AddValidator(new RequiredValidator());
});
var data = builder.Build();
var elementData = Assert.Single(data.Attributes);
Assert.Collection(
elementData.Validators,
v => Assert.IsType<RequiredValidator>(v),
v => Assert.IsType<StringValidator>(v));
}
private class SomeElement : OpenXmlElement
{
public StringValue Str { get; set; }
public override bool HasChildren => throw new NotImplementedException();
public override void RemoveAllChildren() => throw new NotImplementedException();
internal override void WriteContentTo(XmlWriter w) => throw new NotImplementedException();
private protected override void Populate(XmlReader xmlReader, OpenXmlLoadMode loadMode) => throw new NotImplementedException();
}
}
}
| 30.546667 | 139 | 0.592318 | [
"MIT"
] | 929496959/Open-XML-SDK | test/DocumentFormat.OpenXml.Framework.Tests/PropertyBuilderTests.cs | 2,293 | C# |
namespace AjSharpure.Tests.Compiler
{
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AjSharpure.Compiler;
using AjSharpure.Expressions;
using AjSharpure.Language;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class ParserTests
{
[TestMethod]
public void ParseBooleans()
{
Parser parser = new Parser("true false");
object value = parser.ParseForm();
Assert.IsNotNull(value);
Assert.IsInstanceOfType(value, typeof(bool));
Assert.IsTrue((bool)value);
value = parser.ParseForm();
Assert.IsNotNull(value);
Assert.IsInstanceOfType(value, typeof(bool));
Assert.IsFalse((bool)value);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseSymbol()
{
Parser parser = new Parser("foo");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(Symbol));
Symbol symbol = (Symbol)form;
Assert.AreEqual("foo", symbol.Name);
Assert.IsNull(symbol.Namespace);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseEmptyString()
{
Parser parser = new Parser(string.Empty);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseString()
{
Parser parser = new Parser("\"foo\"");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(string));
Assert.AreEqual("foo", form);
}
[TestMethod]
public void ParseInteger()
{
Parser parser = new Parser("123");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(int));
Assert.AreEqual(123, (int) form);
}
[TestMethod]
public void ParseList()
{
Parser parser = new Parser("(1 2 3)");
object obj = parser.ParseForm();
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IList));
IList list = (IList)obj;
Assert.AreEqual(3, list.Count);
Assert.AreEqual(1, list[0]);
Assert.AreEqual(2, list[1]);
Assert.AreEqual(3, list[2]);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseArray()
{
Parser parser = new Parser("[1 2 3]");
object obj = parser.ParseForm();
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IPersistentVector));
IPersistentVector vector = (IPersistentVector)obj;
Assert.AreEqual(3, vector.Count);
Assert.AreEqual(1, vector[0]);
Assert.AreEqual(2, vector[1]);
Assert.AreEqual(3, vector[2]);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseMap()
{
Parser parser = new Parser("{:one 1 :two 2 :three 3}");
object obj = parser.ParseForm();
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IDictionary));
IDictionary dictionary = (IDictionary) obj;
Assert.AreEqual(3, dictionary.Count);
Assert.AreEqual(1, dictionary[Keyword.Create("one")]);
Assert.AreEqual(2, dictionary[Keyword.Create("two")]);
Assert.AreEqual(3, dictionary[Keyword.Create("three")]);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseMapAsAssociative()
{
Parser parser = new Parser("{:one 1 :two 2 :three 3}");
object obj = parser.ParseForm();
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(IAssociative));
IAssociative associative = (IAssociative)obj;
Assert.AreEqual(3, associative.Count);
Assert.AreEqual(1, associative.ValueAt(Keyword.Create("one")));
Assert.AreEqual(2, associative.ValueAt(Keyword.Create("two")));
Assert.AreEqual(3, associative.ValueAt(Keyword.Create("three")));
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseSymbolIgnoringComment()
{
Parser parser = new Parser("foo ; this is a symbol");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(Symbol));
Symbol symbol = (Symbol)form;
Assert.AreEqual("foo", symbol.Name);
Assert.IsNull(symbol.Namespace);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseSymbolIgnoringPrecedingComment()
{
Parser parser = new Parser("; this is a symbol\r\nfoo");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(Symbol));
Symbol symbol = (Symbol)form;
Assert.AreEqual("foo", symbol.Name);
Assert.IsNull(symbol.Namespace);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseQuotedSymbol()
{
Parser parser = new Parser("'foo");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(IList));
IList list = (IList)form;
Assert.AreEqual(2, list.Count);
Assert.IsInstanceOfType(list[0], typeof(Symbol));
Assert.IsInstanceOfType(list[1], typeof(Symbol));
Assert.AreEqual("quote", ((Symbol)list[0]).Name);
Assert.AreEqual("foo", ((Symbol)list[1]).Name);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseBackquotedSymbol()
{
Parser parser = new Parser("`foo");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(IList));
IList list = (IList)form;
Assert.AreEqual(2, list.Count);
Assert.IsInstanceOfType(list[0], typeof(Symbol));
Assert.IsInstanceOfType(list[1], typeof(Symbol));
Assert.AreEqual("backquote", ((Symbol)list[0]).Name);
Assert.AreEqual("foo", ((Symbol)list[1]).Name);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseUnquotedSymbol()
{
Parser parser = new Parser("~foo");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(IList));
IList list = (IList)form;
Assert.AreEqual(2, list.Count);
Assert.IsInstanceOfType(list[0], typeof(Symbol));
Assert.IsInstanceOfType(list[1], typeof(Symbol));
Assert.AreEqual("unquote", ((Symbol)list[0]).Name);
Assert.AreEqual("foo", ((Symbol)list[1]).Name);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseUnquotedSplicingSymbol()
{
Parser parser = new Parser("~@foo");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(IList));
IList list = (IList)form;
Assert.AreEqual(2, list.Count);
Assert.IsInstanceOfType(list[0], typeof(Symbol));
Assert.IsInstanceOfType(list[1], typeof(Symbol));
Assert.AreEqual("unquote-splicing", ((Symbol)list[0]).Name);
Assert.AreEqual("foo", ((Symbol)list[1]).Name);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseMetaForm()
{
Parser parser = new Parser("^foo");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(IList));
IList list = (IList)form;
Assert.AreEqual(2, list.Count);
Assert.IsInstanceOfType(list[0], typeof(Symbol));
Assert.IsInstanceOfType(list[1], typeof(Symbol));
Assert.AreEqual("meta", ((Symbol)list[0]).Name);
Assert.AreEqual("foo", ((Symbol)list[1]).Name);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseDerefForm()
{
Parser parser = new Parser("@foo");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(IList));
IList list = (IList)form;
Assert.AreEqual(2, list.Count);
Assert.IsInstanceOfType(list[0], typeof(Symbol));
Assert.IsInstanceOfType(list[1], typeof(Symbol));
Assert.AreEqual("deref", ((Symbol)list[0]).Name);
Assert.AreEqual("foo", ((Symbol)list[1]).Name);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseVarForm()
{
Parser parser = new Parser("#'foo");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(IList));
IList list = (IList)form;
Assert.AreEqual(2, list.Count);
Assert.IsInstanceOfType(list[0], typeof(Symbol));
Assert.IsInstanceOfType(list[1], typeof(Symbol));
Assert.AreEqual("var", ((Symbol)list[0]).Name);
Assert.AreEqual("foo", ((Symbol)list[1]).Name);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseSymbolWithMetadata()
{
Parser parser = new Parser("#^{:one 1 :two 2} foo");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(Symbol));
Symbol symbol = (Symbol)form;
Assert.AreEqual("foo", symbol.Name);
Assert.AreEqual("foo", symbol.FullName);
Assert.IsNotNull(symbol.Metadata);
Assert.IsInstanceOfType(symbol.Metadata, typeof(IDictionary));
IDictionary dict = (IDictionary)symbol.Metadata;
Assert.IsTrue(dict.Contains(Keyword.Create("one")));
Assert.IsTrue(dict.Contains(Keyword.Create("two")));
Assert.AreEqual(1, dict[Keyword.Create("one")]);
Assert.AreEqual(2, dict[Keyword.Create("two")]);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseListWithMetadata()
{
Parser parser = new Parser("#^{:one 1 :two 2} (1 2)");
object form = parser.ParseForm();
Assert.IsNotNull(form);
Assert.IsInstanceOfType(form, typeof(IList));
Assert.IsInstanceOfType(form, typeof(IObject));
IList list = (IList)form;
Assert.AreEqual(2, list.Count);
Assert.AreEqual(1, list[0]);
Assert.AreEqual(2, list[1]);
IObject iobj = (IObject)form;
Assert.IsNotNull(iobj.Metadata);
IDictionary dict = (IDictionary)iobj.Metadata;
Assert.IsTrue(dict.Contains(Keyword.Create("one")));
Assert.IsTrue(dict.Contains(Keyword.Create("two")));
Assert.AreEqual(1, dict[Keyword.Create("one")]);
Assert.AreEqual(2, dict[Keyword.Create("two")]);
Assert.IsNull(parser.ParseForm());
}
[TestMethod]
public void ParseACharacter()
{
Parser parser = new Parser("\\a");
object result = parser.ParseForm();
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(char));
Assert.AreEqual('a', result);
Assert.IsNull(parser.ParseForm());
}
}
}
| 29.128959 | 78 | 0.533359 | [
"MIT"
] | ajlopez/AjSharpure | Src/AjSharpure.Tests/Compiler/ParserTests.cs | 12,877 | C# |
// <auto-generated />
namespace MyAbpDemo.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")]
public sealed partial class Upgraded_To_ABP_v4_1_0 : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(Upgraded_To_ABP_v4_1_0));
string IMigrationMetadata.Id
{
get { return "201901110613114_Upgraded_To_ABP_v4_1_0"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 28.233333 | 105 | 0.634002 | [
"MIT"
] | yellowaug/testAbpApplication | src/MyAbpDemo.EntityFramework/Migrations/201901110613114_Upgraded_To_ABP_v4_1_0.Designer.cs | 847 | C# |
//
// Authors:
// Rafael Mizrahi <rafim@mainsoft.com>
// Erez Lotan <erezl@mainsoft.com>
// Vladimir Krasnov <vladimirk@mainsoft.com>
//
//
// Copyright (c) 2002-2005 Mainsoft Corporation.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace GHTTests.System_Web_dll.System_Web_UI_WebControls
{
public class RadioButtonList_CellSpacing
: GHTBaseWeb
{
protected System.Web.UI.WebControls.RadioButtonList RadioButtonList1;
protected GHTWebControls.GHTSubTest GHTSubTest1;
protected System.Web.UI.WebControls.RadioButtonList RadioButtonList2;
protected GHTWebControls.GHTSubTest GHTSubTest2;
protected System.Web.UI.WebControls.RadioButtonList RadioButtonList3;
protected GHTWebControls.GHTSubTest GHTSubTest3;
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Page_Load(object sender, System.EventArgs e)
{
HtmlForm frm = (HtmlForm)FindControl("Form1");
GHTTestBegin(frm);
//Negative CellSpacing value:
GHTSubTestBegin("Negative CellSpacing value");
try
{
System.Web.UI.WebControls.RadioButtonList rbl = new System.Web.UI.WebControls.RadioButtonList();
rbl.RepeatLayout = RepeatLayout.Table;
rbl.CellSpacing = -100;
GHTSubTestExpectedExceptionNotCaught("ArgumentOutOfRangeException");
}
catch (ArgumentOutOfRangeException ex)
{
GHTSubTestExpectedExceptionCaught(ex);
}
catch (Exception ex)
{
GHTSubTestUnexpectedExceptionCaught(ex);
}
GHTSubTestEnd();
GHTTestEnd();
}
}
}
| 32.333333 | 100 | 0.743557 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.Web/Test/mainsoft/MainsoftWebApp/System_Web_UI_WebControls/RadioButtonList/RadioButtonList_CellSpacing.aspx.cs | 3,104 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Tcss.V20201101.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeRiskListRequest : AbstractModel
{
/// <summary>
/// 要查询的集群ID,如果不指定,则查询用户所有的风险项
/// </summary>
[JsonProperty("ClusterId")]
public string ClusterId{ get; set; }
/// <summary>
/// 偏移量
/// </summary>
[JsonProperty("Offset")]
public ulong? Offset{ get; set; }
/// <summary>
/// 每次查询的最大记录数量
/// </summary>
[JsonProperty("Limit")]
public ulong? Limit{ get; set; }
/// <summary>
/// Name - String
/// Name 可取值:RiskLevel风险等级, RiskTarget检查对象,风险对象,RiskType风险类别,RiskAttribute检测项所属的风险类型,Name
/// </summary>
[JsonProperty("Filters")]
public ComplianceFilters[] Filters{ get; set; }
/// <summary>
/// 排序字段
/// </summary>
[JsonProperty("By")]
public string By{ get; set; }
/// <summary>
/// 排序方式 asc,desc
/// </summary>
[JsonProperty("Order")]
public string Order{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "ClusterId", this.ClusterId);
this.SetParamSimple(map, prefix + "Offset", this.Offset);
this.SetParamSimple(map, prefix + "Limit", this.Limit);
this.SetParamArrayObj(map, prefix + "Filters.", this.Filters);
this.SetParamSimple(map, prefix + "By", this.By);
this.SetParamSimple(map, prefix + "Order", this.Order);
}
}
}
| 30.925 | 97 | 0.595796 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Tcss/V20201101/Models/DescribeRiskListRequest.cs | 2,628 | C# |
namespace Tubumu.Mediasoup
{
public class PipeTransportStat : TransportStat
{
// PipeTransport specific.
public TransportTuple Tuple { get; set; }
}
}
| 20 | 50 | 0.65 | [
"MIT"
] | albyho/Tubumu.Mediasoup.Common | PipeTransport/PipeTransportStat.cs | 182 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Celia.io.Core.MicroServices.Utilities
{
/// <summary>
/// 系统扩展 - 类型转换
/// </summary>
public static partial class Extensions {
/// <summary>
/// 安全转换为字符串,去除两端空格,当值为null时返回""
/// </summary>
/// <param name="input">输入值</param>
public static string SafeString( this object input ) {
return input == null ? string.Empty : input.ToString().Trim();
}
}
}
| 24.190476 | 74 | 0.588583 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | keith-leung/celia.utilities | Celia.io.Core.MicroServices.Utilities/Extensions/Extensions.Convert.cs | 576 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using ExpressionPowerTools.Core.Dependencies;
using ExpressionPowerTools.Serialization.EFCore.AspNetCore.Extensions;
using ExpressionPowerTools.Serialization.EFCore.AspNetCore.Tests.TestHelpers;
using ExpressionPowerTools.Serialization.Extensions;
using ExpressionPowerTools.Serialization.Json;
using ExpressionPowerTools.Serialization.Signatures;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Xunit;
namespace ExpressionPowerTools.Serialization.EFCore.AspNetCore.Tests
{
public class EndToEndTests : TestServerBase
{
private readonly JsonWrapper jsonWrapper = new JsonWrapper();
public EndToEndTests(TestServerFactory factory) : base(factory)
{
}
private readonly IQueryable query = new List<TestWidget>().AsQueryable()
.Take(5).OrderBy(w => w.Id);
private readonly IQueryable productsQuery = new List<TestProduct>().AsQueryable()
.Take(1);
private IQueryable altQuery = null;
private string queryJson(
bool isCount = false,
bool useProduct = false,
bool isSingle = false) => JsonSerializer.Serialize(
new SerializationPayload(isCount ? PayloadType.Count : (isSingle ? PayloadType.Single : PayloadType.Array))
{
Json = jsonWrapper.FromSerializationRoot(
QueryExprSerializer.Serialize(altQuery ?? (useProduct ? productsQuery : query)))
});
private void DefaultHttpContext(
HttpContext context,
MemoryStream memoryStream = null,
bool isCount = false,
bool useProduct = false,
bool isSingle = false)
{
var request = context.Features.Get<IHttpRequestFeature>();
request.Method = HttpMethods.Post;
var contextName = useProduct ? nameof(TestProductsContext) :
nameof(TestWidgetsContext);
var collectionName = useProduct ? nameof(TestProductsContext.Products) :
nameof(TestWidgetsContext.Widgets);
request.Path = $"/efcore/{contextName}/{collectionName}";
var bytes = Encoding.UTF8.GetBytes(queryJson(isCount, useProduct, isSingle));
var requestStream = new MemoryStream(bytes);
request.Body = requestStream;
request.Headers.Add("Content-Type", "application/json");
request.Headers.Add("Content-Length", requestStream.Length.ToString());
var responseBody = memoryStream ?? new MemoryStream();
var responseBodyFeature = new StreamResponseBodyFeature(responseBody);
context.Features.Set<IHttpResponseBodyFeature>(responseBodyFeature);
}
private void BadPath(
HttpContext context,
MemoryStream memoryStream = null,
bool isCount = false,
bool useProduct = false)
{
DefaultHttpContext(context, memoryStream, isCount, useProduct);
context.Request.Path = context.Request.Path.Value.Replace("efcore", "dapper");
}
private void AltPath(
HttpContext context,
MemoryStream memoryStream = null,
bool isCount = false,
bool useProduct = false)
{
DefaultHttpContext(context, memoryStream, isCount, useProduct);
context.Request.Path = $"/alt/widgets/testwidgetscontext";
}
private void ComplexPath(
HttpContext context,
MemoryStream memoryStream = null,
bool isCount = false,
bool useProduct = false)
{
DefaultHttpContext(context, memoryStream, isCount, useProduct);
context.Request.Path = $"/alt/testwidgetscontext/x/y/widgets/z";
}
private (int statusCode, T result) ProcessResult<T>(
HttpContext context, MemoryStream stream)
{
var statusCode = context.Response.StatusCode;
if (statusCode != (int)HttpStatusCode.OK)
{
return (statusCode, default);
}
stream.Flush();
stream.Position = 0;
using var reader = new StreamReader(stream);
var json = reader.ReadToEnd();
Assert.False(string.IsNullOrWhiteSpace(json));
var result = JsonSerializer.Deserialize<T>(json);
return (statusCode, result);
}
[Fact]
public async Task SingleDbContextWorks()
{
var stream = new MemoryStream();
var testServer = CreateSimpleServer(
config => config.MapPowerToolsEFCore<TestWidgetsContext>());
var result = await testServer.SendAsync(context => DefaultHttpContext(context, stream));
var parsed = ProcessResult<TestWidget[]>(result, stream);
Assert.Equal((int)HttpStatusCode.OK, parsed.statusCode);
Assert.NotNull(parsed.result);
Assert.Equal(5, parsed.result.Length);
}
[Fact]
public async Task MultipleDbContextsWork()
{
var stream = new MemoryStream();
var testServer = CreateSimpleServer(
config => config.MapPowerToolsEFCore<TestWidgetsContext, TestProductsContext>(), alsoProducts: true);
var result = await testServer.SendAsync(context => DefaultHttpContext(context, stream, useProduct: true));
var parsed = ProcessResult<TestProduct[]>(result, stream);
Assert.Equal((int)HttpStatusCode.OK, parsed.statusCode);
Assert.NotNull(parsed.result);
Assert.Single(parsed.result);
}
[Fact]
public async Task CountRequestWorks()
{
var stream = new MemoryStream();
var testServer = CreateSimpleServer(
config => config.MapPowerToolsEFCore<TestWidgetsContext>());
var result = await testServer.SendAsync(context => DefaultHttpContext(context, stream, isCount: true));
var parsed = ProcessResult<long>(result, stream);
Assert.Equal((int)HttpStatusCode.OK, parsed.statusCode);
Assert.Equal(5, parsed.result);
}
[Fact]
public async Task SingleRequestWorks()
{
var stream = new MemoryStream();
var testServer = CreateSimpleServer(
config => config.MapPowerToolsEFCore<TestWidgetsContext>());
var result = await testServer.SendAsync(context => DefaultHttpContext(context, stream, isSingle: true));
var parsed = ProcessResult<TestWidget>(result, stream);
Assert.Equal((int)HttpStatusCode.OK, parsed.statusCode);
Assert.NotNull(parsed.result);
}
[Fact]
public async Task NotInPathIgnored()
{
var stream = new MemoryStream();
var testServer = CreateSimpleServer(
config => config.MapPowerToolsEFCore<TestWidgetsContext>());
var result = await testServer.SendAsync(context => BadPath(context, stream));
Assert.Equal((int)HttpStatusCode.NotFound, result.Response.StatusCode);
}
[Fact]
public async Task AlternatePathWorks()
{
var stream = new MemoryStream();
var testServer = CreateSimpleServer(
config => config.MapPowerToolsEFCore<TestWidgetsContext>("/alt/{collection}/{context}"));
var result = await testServer.SendAsync(context => AltPath(context, stream));
var parsed = ProcessResult<TestWidget[]>(result, stream);
Assert.Equal((int)HttpStatusCode.OK, parsed.statusCode);
Assert.NotNull(parsed.result);
Assert.Equal(5, parsed.result.Length);
}
[Fact]
public async Task ComplexAlternatePathWorks()
{
var stream = new MemoryStream();
var testServer = CreateSimpleServer(
config => config.MapPowerToolsEFCore<TestWidgetsContext>("/alt/{context}/x/y/{collection}/z"));
var result = await testServer.SendAsync(context => ComplexPath(context, stream));
var parsed = ProcessResult<TestWidget[]>(result, stream);
Assert.Equal((int)HttpStatusCode.OK, parsed.statusCode);
Assert.NotNull(parsed.result);
Assert.Equal(5, parsed.result.Length);
}
[Fact]
public async Task DefaultCtorRestrictionHonored()
{
altQuery = new List<TestWidget>().AsQueryable()
.Take(5).OrderBy(w => w.Id).Select(w => new TestWidget());
var stream = new MemoryStream();
var testServer = CreateSimpleServer(
config => config.MapPowerToolsEFCore<TestWidgetsContext>());
var result = await testServer.SendAsync(context => DefaultHttpContext(context, stream));
var parsed = ProcessResult<TestWidget[]>(result, stream);
Assert.Equal((int)HttpStatusCode.Unauthorized, parsed.statusCode);
}
[Fact]
public async Task NoDefaultRulesHonored()
{
var rules = ServiceHost.GetService<IRulesEngine>().Reset();
var stream = new MemoryStream();
var testServer = CreateSimpleServer(
config => config.MapPowerToolsEFCore<TestWidgetsContext>(noDefaultRules: true));
var result = await testServer.SendAsync(context => DefaultHttpContext(context, stream));
var parsed = ProcessResult<TestWidget[]>(result, stream);
Assert.Equal((int)HttpStatusCode.Unauthorized, parsed.statusCode);
ServiceHost.GetService<IRulesEngine>().Restore(rules);
}
[Fact]
public async void SpecificRulesApplied()
{
var ctor = typeof(TestWidget).GetConstructors().Single();
altQuery = new List<TestWidget>().AsQueryable()
.Take(5).OrderBy(w => w.Id).Select(w => new TestWidget());
var stream = new MemoryStream();
var testServer = CreateSimpleServer(
config => config.MapPowerToolsEFCore<TestWidgetsContext>(
rules: rules => rules.RuleForConstructor(
selector => selector.ByMemberInfo(ctor))));
var result = await testServer.SendAsync(context => DefaultHttpContext(context, stream));
var parsed = ProcessResult<TestWidget[]>(result, stream);
Assert.Equal((int)HttpStatusCode.OK, parsed.statusCode);
Assert.NotNull(parsed.result);
Assert.Equal(5, parsed.result.Length);
}
}
}
| 42.838583 | 119 | 0.620807 | [
"MIT"
] | JeremyLikness/ExpressionPowerTools | test/ExpressionPowerTools.Serialization.EFCore.AspNetCore.Tests/EndToEndTests.cs | 10,883 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
using Pulumi.Utilities;
namespace Pulumi.GoogleNative.PolicySimulator.V1
{
public static class GetReplay
{
/// <summary>
/// Gets the specified Replay. Each `Replay` is available for at least 7 days.
/// </summary>
public static Task<GetReplayResult> InvokeAsync(GetReplayArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetReplayResult>("google-native:policysimulator/v1:getReplay", args ?? new GetReplayArgs(), options.WithVersion());
/// <summary>
/// Gets the specified Replay. Each `Replay` is available for at least 7 days.
/// </summary>
public static Output<GetReplayResult> Invoke(GetReplayInvokeArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.Invoke<GetReplayResult>("google-native:policysimulator/v1:getReplay", args ?? new GetReplayInvokeArgs(), options.WithVersion());
}
public sealed class GetReplayArgs : Pulumi.InvokeArgs
{
[Input("location", required: true)]
public string Location { get; set; } = null!;
[Input("project")]
public string? Project { get; set; }
[Input("replayId", required: true)]
public string ReplayId { get; set; } = null!;
public GetReplayArgs()
{
}
}
public sealed class GetReplayInvokeArgs : Pulumi.InvokeArgs
{
[Input("location", required: true)]
public Input<string> Location { get; set; } = null!;
[Input("project")]
public Input<string>? Project { get; set; }
[Input("replayId", required: true)]
public Input<string> ReplayId { get; set; } = null!;
public GetReplayInvokeArgs()
{
}
}
[OutputType]
public sealed class GetReplayResult
{
/// <summary>
/// The configuration used for the `Replay`.
/// </summary>
public readonly Outputs.GoogleCloudPolicysimulatorV1ReplayConfigResponse Config;
/// <summary>
/// The resource name of the `Replay`, which has the following format: `{projects|folders|organizations}/{resource-id}/locations/global/replays/{replay-id}`, where `{resource-id}` is the ID of the project, folder, or organization that owns the Replay. Example: `projects/my-example-project/locations/global/replays/506a5f7f-38ce-4d7d-8e03-479ce1833c36`
/// </summary>
public readonly string Name;
/// <summary>
/// Summary statistics about the replayed log entries.
/// </summary>
public readonly Outputs.GoogleCloudPolicysimulatorV1ReplayResultsSummaryResponse ResultsSummary;
/// <summary>
/// The current state of the `Replay`.
/// </summary>
public readonly string State;
[OutputConstructor]
private GetReplayResult(
Outputs.GoogleCloudPolicysimulatorV1ReplayConfigResponse config,
string name,
Outputs.GoogleCloudPolicysimulatorV1ReplayResultsSummaryResponse resultsSummary,
string state)
{
Config = config;
Name = name;
ResultsSummary = resultsSummary;
State = state;
}
}
}
| 35.767677 | 360 | 0.643321 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/PolicySimulator/V1/GetReplay.cs | 3,541 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Add a service access code to a list.
/// The response is either SuccessResponse or ErrorResponse.
/// <see cref="SuccessResponse"/>
/// <see cref="ErrorResponse"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""f7ae3539fd471e995b07dc1bf8836e2d:1036""}]")]
public class SystemBroadWorksMobilityServiceAccessCodeAddRequest21 : BroadWorksConnector.Ocip.Models.C.OCIRequest
{
private string _serviceAccessCodeListName;
[XmlElement(ElementName = "serviceAccessCodeListName", IsNullable = false, Namespace = "")]
[Group(@"f7ae3539fd471e995b07dc1bf8836e2d:1036")]
[MinLength(1)]
[MaxLength(80)]
public string ServiceAccessCodeListName
{
get => _serviceAccessCodeListName;
set
{
ServiceAccessCodeListNameSpecified = true;
_serviceAccessCodeListName = value;
}
}
[XmlIgnore]
protected bool ServiceAccessCodeListNameSpecified { get; set; }
private string _countryCode;
[XmlElement(ElementName = "countryCode", IsNullable = false, Namespace = "")]
[Group(@"f7ae3539fd471e995b07dc1bf8836e2d:1036")]
[MaxLength(3)]
[RegularExpression(@"[0-9]|[1-9][0-9]{1,2}")]
public string CountryCode
{
get => _countryCode;
set
{
CountryCodeSpecified = true;
_countryCode = value;
}
}
[XmlIgnore]
protected bool CountryCodeSpecified { get; set; }
private string _serviceAccessCode;
[XmlElement(ElementName = "serviceAccessCode", IsNullable = false, Namespace = "")]
[Group(@"f7ae3539fd471e995b07dc1bf8836e2d:1036")]
[MinLength(1)]
[MaxLength(10)]
public string ServiceAccessCode
{
get => _serviceAccessCode;
set
{
ServiceAccessCodeSpecified = true;
_serviceAccessCode = value;
}
}
[XmlIgnore]
protected bool ServiceAccessCodeSpecified { get; set; }
private string _description;
[XmlElement(ElementName = "description", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"f7ae3539fd471e995b07dc1bf8836e2d:1036")]
[MinLength(1)]
[MaxLength(80)]
public string Description
{
get => _description;
set
{
DescriptionSpecified = true;
_description = value;
}
}
[XmlIgnore]
protected bool DescriptionSpecified { get; set; }
}
}
| 29.990099 | 130 | 0.591945 | [
"MIT"
] | JTOne123/broadworks-connector-net | BroadworksConnector/Ocip/Models/SystemBroadWorksMobilityServiceAccessCodeAddRequest21.cs | 3,029 | C# |
using System;
using System.Diagnostics;
namespace Com.Game.Utils
{
public class ClientLogger
{
private static ILogger _logger;
public static LogLevel Level
{
get;
set;
}
public static ILogger Logger
{
get
{
return ClientLogger._logger;
}
set
{
if (value == null)
{
value = new ConsoleLogger();
}
ClientLogger._logger = value;
}
}
static ClientLogger()
{
ClientLogger._logger = new ConsoleLogger();
ClientLogger.Level = LogLevel.Debug;
}
public static void Error(object message)
{
if (ClientLogger.Level <= LogLevel.Error)
{
ClientLogger._logger.Error(message);
}
}
public static void ErrorFormat(string fmt, params object[] objs)
{
if (ClientLogger.Level <= LogLevel.Error)
{
ClientLogger._logger.Error(string.Format(fmt, objs));
}
}
public static void Info(object message)
{
if (ClientLogger.Level <= LogLevel.Info)
{
ClientLogger._logger.Info(message);
}
}
public static void InfoFormat(string fmt, params object[] objs)
{
if (ClientLogger.Level <= LogLevel.Info)
{
ClientLogger._logger.Info(string.Format(fmt, objs));
}
}
public static void Warn(object message)
{
if (ClientLogger.Level <= LogLevel.Warn)
{
ClientLogger._logger.Warn(message);
}
}
public static void WarnFormat(string fmt, params object[] objs)
{
if (ClientLogger.Level <= LogLevel.Warn)
{
ClientLogger._logger.Warn(string.Format(fmt, objs));
}
}
public static void LogException(Exception e)
{
if (ClientLogger.Level <= LogLevel.Error)
{
ClientLogger._logger.LogException(e);
}
}
[Conditional("UNITY_EDITOR"), Conditional("LOGGER_DEBUG")]
public static void Debug(string tag, object message)
{
if (ClientLogger.Level <= LogLevel.Debug)
{
ClientLogger._logger.Debug(tag, message);
}
}
[Conditional("LOGGER_DEBUG"), Conditional("UNITY_EDITOR")]
public static void DebugFormat(string tag, string fmt, params object[] objs)
{
if (ClientLogger.Level <= LogLevel.Debug)
{
ClientLogger._logger.Debug(tag, string.Format(fmt, objs));
}
}
public static void Assert(bool expr, string msg = null)
{
if (msg == null)
{
msg = "Assert failed.";
}
if (!expr)
{
ClientLogger.Error(msg);
}
}
public static void AssertNotNull(object obj, string msg = null)
{
if (msg == null)
{
msg = "Assert failed, parameter is null";
}
if (obj == null)
{
ClientLogger.Error(msg);
}
}
}
}
| 19.649635 | 79 | 0.610698 | [
"MIT"
] | corefan/mobahero_src | Com.Game.Utils/ClientLogger.cs | 2,692 | C# |
using System;
using System.Diagnostics;
using T3.Core;
using T3.Core.Logging;
using T3.Core.Operator;
using T3.Core.Operator.Attributes;
using T3.Core.Operator.Slots;
namespace T3.Operators.Types.Id_0e1d5f4b_3ba0_4e71_aa26_7308b6df214d
{
public class CountInt : Instance<CountInt>
{
[Output(Guid = "2E172F90-3995-4B16-AF33-9957BE07323B", DirtyFlagTrigger = DirtyFlagTrigger.Animated)]
public readonly Slot<int> Result = new Slot<int>();
public CountInt()
{
Result.UpdateAction = Update;
}
private void Update(EvaluationContext context)
{
if (!_initialized || TriggerReset.GetValue(context))
{
Result.Value = DefaultValue.GetValue(context);
_initialized = true;
}
var triggered = Running.GetValue(context);
if (OnlyCountChanges.GetValue(context) && triggered == _lastTrigger)
return;
_lastTrigger = triggered;
if (triggered)
Result.Value += Increment.GetValue(context);
var modulo = Modulo.GetValue(context);
if (modulo != 0)
{
Result.Value %= modulo;
}
}
private bool _initialized;
private bool _lastTrigger;
[Input(Guid = "bfd95809-61d2-49eb-85d4-ff9e36b2d158")]
public readonly InputSlot<bool> Running = new InputSlot<bool>();
[Input(Guid = "01027ce6-f4ca-44b6-a8ec-e4ab96280864")]
public readonly InputSlot<bool> TriggerReset = new InputSlot<bool>();
[Input(Guid = "518A8BD6-D830-4F73-AC83-49BE2FD4B09D")]
public readonly InputSlot<bool> OnlyCountChanges = new InputSlot<bool>();
[Input(Guid = "ABE64676-CCF7-4163-B4DA-26D8B7179AF4")]
public readonly InputSlot<int> Increment = new InputSlot<int>();
[Input(Guid = "11F9CDB5-84FC-4413-8CA7-77E12047F521")]
public readonly InputSlot<int> DefaultValue = new InputSlot<int>();
[Input(Guid = "2FF3D674-90D7-4C8F-8551-AAD9992540DB")]
public readonly InputSlot<int> Modulo = new InputSlot<int>();
}
} | 32.552239 | 109 | 0.618524 | [
"MIT"
] | still-scene/t3 | Operators/Types/CountInt.cs | 2,181 | C# |
namespace Relay.RequestModel
{
using System.Threading.Tasks;
public interface IRequestDispatcher
{
Task<TResult> RunAsync<TResult>(IQuery<TResult> query);
Task ExecuteAsync<TCommand>(TCommand command) where TCommand : ICommand;
}
} | 25.090909 | 81 | 0.681159 | [
"MIT"
] | vborovikov/relator | src/Relay/RequestModel/IRequestDispatcher.cs | 278 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.Diagnostics.Runtime.Utilities
{
internal class RelativeAddressSpace : IAddressSpace
{
private readonly IAddressSpace _baseAddressSpace;
private readonly ulong _baseStart;
private readonly ulong _length;
private readonly long _baseToRelativeShift;
private readonly string _name;
public string Name => _name is null ? _baseAddressSpace.Name : $"{_baseAddressSpace.Name}:{_name}";
public RelativeAddressSpace(IAddressSpace baseAddressSpace, string name, ulong startOffset, ulong length)
: this(baseAddressSpace, name, startOffset, length, -(long)startOffset)
{
}
public RelativeAddressSpace(IAddressSpace baseAddressSpace, string name, ulong startOffset, ulong length, long baseToRelativeShift)
{
_baseAddressSpace = baseAddressSpace;
_baseStart = startOffset;
_length = length;
_baseToRelativeShift = baseToRelativeShift;
_name = name;
}
public int Read(ulong position, Span<byte> buffer)
{
ulong basePosition = (ulong)((long)position - _baseToRelativeShift);
if (basePosition < _baseStart)
return 0;
if ((int)_length < buffer.Length)
buffer = buffer.Slice(0, (int)_length);
return _baseAddressSpace.Read(basePosition, buffer);
}
public ulong Length => (ulong)((long)(_baseStart + _length) + _baseToRelativeShift);
}
} | 37.340426 | 139 | 0.662108 | [
"MIT"
] | QPC-database/clrmd | src/Microsoft.Diagnostics.Runtime/src/Linux/RelativeAddressSpace.cs | 1,757 | C# |
namespace OpenGL
{
partial class GlControl
{
/// <summary>
/// Variabile di progettazione necessaria.
/// </summary>
private System.ComponentModel.IContainer components = null;
#region Codice generato da Progettazione componenti
/// <summary>
/// Metodo necessario per il supporto della finestra di progettazione. Non modificare
/// il contenuto del metodo con l'editor di codice.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// GlControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.Name = "GlControl";
this.Size = new System.Drawing.Size(441, 246);
this.ResumeLayout(false);
}
#endregion
}
}
| 26.441176 | 119 | 0.674082 | [
"MIT"
] | GiantBlargg/OpenGL.Net | OpenGL.Net.WinForms/GlControl.Designer.cs | 901 | C# |
namespace Moway.Project.GraphicProject.Actions.Obstacle
{
partial class ObstacleForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ObstacleForm));
this.gbCommands = new Moway.Template.Controls.MowayGroupBox();
this.pbMoway = new SdlDotNet.Windows.SurfaceControl();
this.rbOr = new Moway.Template.Controls.MowayRadioButton();
this.rbAnd = new Moway.Template.Controls.MowayRadioButton();
this.lUpperLeft = new System.Windows.Forms.Label();
this.cbUpperLeft = new Moway.Template.Controls.MowayComboBox();
this.lLeft = new System.Windows.Forms.Label();
this.cbLeft = new Moway.Template.Controls.MowayComboBox();
this.cbUpperRight = new Moway.Template.Controls.MowayComboBox();
this.cbRight = new Moway.Template.Controls.MowayComboBox();
this.lUpperRight = new System.Windows.Forms.Label();
this.lRight = new System.Windows.Forms.Label();
this.lOuput = new System.Windows.Forms.Label();
this.tbOutput = new System.Windows.Forms.Label();
this.gbCommands.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pbMoway)).BeginInit();
this.SuspendLayout();
//
// bSave
//
this.bSave.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(132)))), ((int)(((byte)(132)))), ((int)(((byte)(132)))));
resources.ApplyResources(this.bSave, "bSave");
//
// bCancel
//
this.bCancel.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(132)))), ((int)(((byte)(132)))), ((int)(((byte)(132)))));
resources.ApplyResources(this.bCancel, "bCancel");
//
// llHelp
//
resources.ApplyResources(this.llHelp, "llHelp");
//
// pFormSeparator
//
resources.ApplyResources(this.pFormSeparator, "pFormSeparator");
//
// lFormDescription
//
resources.ApplyResources(this.lFormDescription, "lFormDescription");
//
// gbCommands
//
resources.ApplyResources(this.gbCommands, "gbCommands");
this.gbCommands.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240)))));
this.gbCommands.Controls.Add(this.pbMoway);
this.gbCommands.Controls.Add(this.rbOr);
this.gbCommands.Controls.Add(this.rbAnd);
this.gbCommands.Controls.Add(this.lUpperLeft);
this.gbCommands.Controls.Add(this.cbUpperLeft);
this.gbCommands.Controls.Add(this.lLeft);
this.gbCommands.Controls.Add(this.cbLeft);
this.gbCommands.Controls.Add(this.cbUpperRight);
this.gbCommands.Controls.Add(this.cbRight);
this.gbCommands.Controls.Add(this.lUpperRight);
this.gbCommands.Controls.Add(this.lRight);
this.gbCommands.Name = "gbCommands";
this.gbCommands.TabStop = false;
//
// pbMoway
//
resources.ApplyResources(this.pbMoway, "pbMoway");
this.pbMoway.AccessibleRole = System.Windows.Forms.AccessibleRole.Graphic;
this.pbMoway.BackColor = System.Drawing.Color.White;
this.pbMoway.Name = "pbMoway";
this.pbMoway.TabStop = false;
//
// rbOr
//
resources.ApplyResources(this.rbOr, "rbOr");
this.rbOr.Name = "rbOr";
this.rbOr.UseVisualStyleBackColor = true;
//
// rbAnd
//
resources.ApplyResources(this.rbAnd, "rbAnd");
this.rbAnd.Checked = true;
this.rbAnd.Name = "rbAnd";
this.rbAnd.TabStop = true;
this.rbAnd.UseVisualStyleBackColor = true;
this.rbAnd.CheckedChanged += new System.EventHandler(this.RbAnd_CheckedChanged);
//
// lUpperLeft
//
resources.ApplyResources(this.lUpperLeft, "lUpperLeft");
this.lUpperLeft.Name = "lUpperLeft";
//
// cbUpperLeft
//
this.cbUpperLeft.BackColor = System.Drawing.Color.White;
this.cbUpperLeft.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.cbUpperLeft.DropDownHeight = 100;
this.cbUpperLeft.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cbUpperLeft, "cbUpperLeft");
this.cbUpperLeft.FormattingEnabled = true;
this.cbUpperLeft.Items.AddRange(new object[] {
resources.GetString("cbUpperLeft.Items"),
resources.GetString("cbUpperLeft.Items1"),
resources.GetString("cbUpperLeft.Items2")});
this.cbUpperLeft.Name = "cbUpperLeft";
this.cbUpperLeft.SelectedIndexChanged += new System.EventHandler(this.CbSensor_SelectedIndexChanged);
//
// lLeft
//
resources.ApplyResources(this.lLeft, "lLeft");
this.lLeft.Name = "lLeft";
//
// cbLeft
//
this.cbLeft.BackColor = System.Drawing.Color.White;
this.cbLeft.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.cbLeft.DropDownHeight = 100;
this.cbLeft.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cbLeft, "cbLeft");
this.cbLeft.FormattingEnabled = true;
this.cbLeft.Items.AddRange(new object[] {
resources.GetString("cbLeft.Items"),
resources.GetString("cbLeft.Items1"),
resources.GetString("cbLeft.Items2")});
this.cbLeft.Name = "cbLeft";
this.cbLeft.SelectedIndexChanged += new System.EventHandler(this.CbSensor_SelectedIndexChanged);
//
// cbUpperRight
//
this.cbUpperRight.BackColor = System.Drawing.Color.White;
this.cbUpperRight.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.cbUpperRight.DropDownHeight = 100;
this.cbUpperRight.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cbUpperRight, "cbUpperRight");
this.cbUpperRight.FormattingEnabled = true;
this.cbUpperRight.Items.AddRange(new object[] {
resources.GetString("cbUpperRight.Items"),
resources.GetString("cbUpperRight.Items1"),
resources.GetString("cbUpperRight.Items2")});
this.cbUpperRight.Name = "cbUpperRight";
this.cbUpperRight.SelectedIndexChanged += new System.EventHandler(this.CbSensor_SelectedIndexChanged);
//
// cbRight
//
this.cbRight.BackColor = System.Drawing.Color.White;
this.cbRight.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.cbRight.DropDownHeight = 100;
this.cbRight.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cbRight, "cbRight");
this.cbRight.FormattingEnabled = true;
this.cbRight.Items.AddRange(new object[] {
resources.GetString("cbRight.Items"),
resources.GetString("cbRight.Items1"),
resources.GetString("cbRight.Items2")});
this.cbRight.Name = "cbRight";
this.cbRight.SelectedIndexChanged += new System.EventHandler(this.CbSensor_SelectedIndexChanged);
//
// lUpperRight
//
resources.ApplyResources(this.lUpperRight, "lUpperRight");
this.lUpperRight.Name = "lUpperRight";
//
// lRight
//
resources.ApplyResources(this.lRight, "lRight");
this.lRight.Name = "lRight";
//
// lOuput
//
resources.ApplyResources(this.lOuput, "lOuput");
this.lOuput.Name = "lOuput";
//
// tbOutput
//
resources.ApplyResources(this.tbOutput, "tbOutput");
this.tbOutput.BackColor = System.Drawing.Color.White;
this.tbOutput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbOutput.Name = "tbOutput";
//
// ObstacleForm
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
resources.ApplyResources(this, "$this");
this.Controls.Add(this.lOuput);
this.Controls.Add(this.tbOutput);
this.Controls.Add(this.gbCommands);
this.Name = "ObstacleForm";
this.Controls.SetChildIndex(this.gbCommands, 0);
this.Controls.SetChildIndex(this.bSave, 0);
this.Controls.SetChildIndex(this.bCancel, 0);
this.Controls.SetChildIndex(this.lFormDescription, 0);
this.Controls.SetChildIndex(this.pFormSeparator, 0);
this.Controls.SetChildIndex(this.llHelp, 0);
this.Controls.SetChildIndex(this.tbOutput, 0);
this.Controls.SetChildIndex(this.lOuput, 0);
this.gbCommands.ResumeLayout(false);
this.gbCommands.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pbMoway)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Moway.Template.Controls.MowayGroupBox gbCommands;
private SdlDotNet.Windows.SurfaceControl pbMoway;
private Moway.Template.Controls.MowayRadioButton rbOr;
private Moway.Template.Controls.MowayRadioButton rbAnd;
private System.Windows.Forms.Label lUpperLeft;
private Moway.Template.Controls.MowayComboBox cbUpperLeft;
private System.Windows.Forms.Label lLeft;
private Moway.Template.Controls.MowayComboBox cbLeft;
private Moway.Template.Controls.MowayComboBox cbUpperRight;
private Moway.Template.Controls.MowayComboBox cbRight;
private System.Windows.Forms.Label lUpperRight;
private System.Windows.Forms.Label lRight;
private System.Windows.Forms.Label lOuput;
private System.Windows.Forms.Label tbOutput;
}
} | 46.797571 | 156 | 0.599014 | [
"MIT"
] | Bizintek/mOway_SW_mOwayWorld | mOway_SW_mOwayWorld/MowayProject/GraphicProject/Actions/Obstacle/ObstacleForm.Designer.cs | 11,561 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CitizenFX.Core;
using static CitizenFX.Core.Native.API;
namespace Magicallity.Client.Enviroment
{
class AIController : ClientAccessor
{
private float pedDensityMult = 0.7f;
private float weaponDamageMult = 0.5f;
private float vehicleDensityMult = 0.5f;
private float parkedVehDensity = 0.6f;
private float scenarioPedDensity = 0.6f;
public AIController(Client client) : base(client)
{
client.RegisterTickHandler(OnTick);
client.RegisterTickHandler(RefreshValuesTick);
}
private async Task OnTick()
{
SetPedDensityMultiplierThisFrame(pedDensityMult);
SetPlayerWeaponDamageModifier(PlayerId(), weaponDamageMult);
SetPedAccuracy(Cache.PlayerPed.Handle, 20);
SetPlayerHealthRechargeMultiplier(PlayerId(), 0.0f);
SetVehicleDensityMultiplierThisFrame(vehicleDensityMult);
SetParkedVehicleDensityMultiplierThisFrame(parkedVehDensity);
SetScenarioPedDensityMultiplierThisFrame(scenarioPedDensity, scenarioPedDensity);
SetGarbageTrucks(false);
SetRandomBoats(false);
EnableDispatchService(1, false);
EnableDispatchService(2, false);
EnableDispatchService(3, false);
EnableDispatchService(4, false);
EnableDispatchService(5, false);
EnableDispatchService(6, false);
EnableDispatchService(7, false);
EnableDispatchService(8, false);
EnableDispatchService(9, false);
EnableDispatchService(10, false);
EnableDispatchService(11, false);
EnableDispatchService(12, false);
EnableDispatchService(13, false);
EnableDispatchService(14, false);
EnableDispatchService(15, false);
//ClearPlayerWantedLevel(PlayerId());
}
private async Task RefreshValuesTick()
{
pedDensityMult = GetConvarInt("mg_pedDensityMult", 100) / 100.0f;
weaponDamageMult = GetConvarInt("mg_weaponDamageMult", 100) / 100.0f;
vehicleDensityMult = GetConvarInt("mg_vehicleDensityMult", 50) / 100.0f;
parkedVehDensity = GetConvarInt("mg_parkedVehDensity", 100) / 100.0f;
scenarioPedDensity = GetConvarInt("mg_scenarioPedDensity", 100) / 100.0f;
await BaseScript.Delay(GetConvarInt("mg_aiRefreshTime", 300000));
}
}
}
| 39.772727 | 93 | 0.654476 | [
"MIT"
] | Jazzuh/Magicallity-public-source | src/Magicallity.Client/Enviroment/AIController.cs | 2,627 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Identity;
namespace WebApplication90.Models.ManageViewModels
{
public class ManageLoginsViewModel
{
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationDescription> OtherLogins { get; set; }
}
}
| 25.235294 | 73 | 0.7669 | [
"MIT"
] | csharpfritz/DevIntersection2016 | WebApplication90/src/WebApplication90/Models/ManageViewModels/ManageLoginsViewModel.cs | 431 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Fixtures.Components
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// CowbellOperations operations.
/// </summary>
public partial interface ICowbellOperations
{
/// <summary>
/// A swell description.
/// </summary>
/// <param name='id'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<Cowbell>> GetWithHttpMessagesAsync(long id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A good description.
/// </summary>
/// <param name='body'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> AddWithHttpMessagesAsync(Cowbell body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> EmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> GetImplementationAgnosticWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> GetImplementationSpecificWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='id'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> GetForwardToWithHttpMessagesAsync(long id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> GetForwardToCustomArgs1WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='name'>
/// </param>
/// <param name='id'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> GetForwardToCustomArgs2WithHttpMessagesAsync(string name, long id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='name'>
/// </param>
/// <param name='idx'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> GetForwardToCustomArgs3WithHttpMessagesAsync(string name, long idx, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='name'>
/// </param>
/// <param name='idx'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> GetForwardToCustomArgs4WithHttpMessagesAsync(string name, long idx, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 48.092593 | 225 | 0.63291 | [
"MIT"
] | ChristianEder/autorest.csharp | test/vanilla/Expected/Components/ICowbellOperations.cs | 7,791 | C# |
public sealed class PlaceFormatter : IMessagePackFormatter<Place>, IMessagePackFormatter // TypeDefIndex: 10203
{
// Methods
// RVA: 0x2430960 Offset: 0x2430A61 VA: 0x2430960 Slot: 4
public void Serialize(ref MessagePackWriter writer, Place value, MessagePackSerializerOptions options) { }
// RVA: 0x2430970 Offset: 0x2430A71 VA: 0x2430970 Slot: 5
public Place Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { }
// RVA: 0x2430980 Offset: 0x2430A81 VA: 0x2430980
public void .ctor() { }
}
| 35.466667 | 111 | 0.776316 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | MessagePack/Formatters/Define/PlaceFormatter.cs | 532 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using System.Linq;
public class GraphMe : MonoBehaviour {
LineRenderer line;
List<float> inputs = new List<float>();
Vector2 lMin = new Vector2();
Vector2 lMax = new Vector2();
//physical min/max
GraphLead gl;
// Use this for initialization
void Start () {
inputs.Add(0);
gl = transform.parent.GetComponent<GraphLead>();
lMin = Vector2.zero;
lMax = new Vector2(gl.maxPoints, 10);
Assert.IsNotNull(gl);
line = GetComponent<LineRenderer>();
line.numPositions = gl.maxPoints;
}
// Update is called once per frame
public void Tick (float input) {
if (input == -42)
{
if (inputs.Count > 0)
input = inputs[inputs.Count - 1];
}
if (inputs.Count >= gl.maxPoints)
{
inputs.RemoveAt(0);
inputs.Add(input);
//scan for max point
lMax.y = inputs.Max();
lMin.y = inputs.Min();
gl.ResetYBounds();
lMin.x += 1;
lMax.x += 1;
} else {
lMax.y = Mathf.Max(lMax.y, input);
lMin.y = Mathf.Min(lMin.y, input);
inputs.Add(input);
}
gl.UpdateLBounds(lMin, lMax);
}
public void LateUpdate()
{
for (int i = 0; i < inputs.Count; i++)
{
line.SetPosition(i, gl.L2PC_RelX(i, inputs[i]));
}
int x = inputs.Count-1;
var lastPos = gl.L2PC_RelX(x, inputs[inputs.Count-1]);
line.SetPosition(x, lastPos);
//set all points after
for (int i = x + 1; i < gl.maxPoints; i++)
{
line.SetPosition(i, lastPos);
}
//set text
}
}
| 24.257143 | 60 | 0.573027 | [
"MIT"
] | omikun/EconSim | Assets/Scripts/GraphMe.cs | 1,700 | C# |
namespace Unity.VisualScripting.Community
{
[UnitCategory("Community/Control/Delegates")]
[RenamedFrom("Bolt.Addons.Community.Fundamentals.BindActionUnit")]
public sealed class BindActionNode : BindDelegateNode<IAction>
{
}
}
| 27.444444 | 70 | 0.748988 | [
"MIT"
] | Fitz-YM/Bolt.Addons.Community | Runtime/Fundamentals/Nodes/Logic/Control/Delegates/BindActionNode.cs | 249 | C# |
using System;
using WorkflowCore.Interface;
using WorkflowCore.Models;
namespace WrokflowCoreDemo
{
public class Steps
{
}
public class HelloWorld : StepBody
{
public override ExecutionResult Run(IStepExecutionContext context)
{
Console.WriteLine("Hello World");
return ExecutionResult.Next();
}
}
public class ActiveWorld : StepBody
{
public override ExecutionResult Run(IStepExecutionContext context)
{
Console.WriteLine("I am activing in the World!");
return ExecutionResult.Next();
}
}
public class GoodbyeWorld : StepBody
{
public override ExecutionResult Run(IStepExecutionContext context)
{
Console.WriteLine("Goodbye World!");
return ExecutionResult.Next();
}
}
} | 22.868421 | 74 | 0.617952 | [
"MIT"
] | wturi/DemoList | DemoSample/WrokflowCoreDemo/WrokflowCoreDemo/Steps.cs | 871 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SaveFilePickerViewModel.cs" company="WildGums">
// Copyright (c) 2008 - 2015 WildGums. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Orc.Controls
{
using System.IO;
using System.Threading.Tasks;
using Catel;
using Catel.MVVM;
using Catel.Services;
public class SaveFilePickerViewModel : ViewModelBase
{
#region Constructors
public SaveFilePickerViewModel(ISaveFileService saveFileService, IProcessService processService)
{
Argument.IsNotNull(() => saveFileService);
Argument.IsNotNull(() => processService);
_saveFileService = saveFileService;
_processService = processService;
OpenDirectory = new Command(OnOpenDirectoryExecute, OnOpenDirectoryCanExecute);
SelectFile = new TaskCommand(OnSelectFileExecuteAsync);
Clear = new Command(OnClearExecute, OnClearCanExecute);
}
#endregion
#region Fields
private readonly IProcessService _processService;
private readonly ISaveFileService _saveFileService;
#endregion
#region Properties
public double LabelWidth { get; set; }
public string LabelText { get; set; }
public string SelectedFile { get; set; }
public string Filter { get; set; }
#endregion
#region Commands
public Command Clear { get; }
private bool OnClearCanExecute()
{
return OnOpenDirectoryCanExecute();
}
private void OnClearExecute()
{
SelectedFile = string.Empty;
}
/// <summary>
/// Gets the OpenDirectory command.
/// </summary>
public Command OpenDirectory { get; private set; }
/// <summary>
/// Method to check whether the OpenDirectory command can be executed.
/// </summary>
/// <returns><c>true</c> if the command can be executed; otherwise <c>false</c></returns>
private bool OnOpenDirectoryCanExecute()
{
if (string.IsNullOrWhiteSpace(SelectedFile))
{
return false;
}
var directory = Directory.GetParent(SelectedFile);
// Don't allow users to write text that they can "invoke" via our software
return directory.Exists;
}
/// <summary>
/// Method to invoke when the OpenDirectory command is executed.
/// </summary>
private void OnOpenDirectoryExecute()
{
var directory = Directory.GetParent(SelectedFile);
_processService.StartProcess(directory.FullName);
}
/// <summary>
/// Gets the SelectFile command.
/// </summary>
public TaskCommand SelectFile { get; private set; }
/// <summary>
/// Method to invoke when the SelectFile command is executed.
/// </summary>
private async Task OnSelectFileExecuteAsync()
{
string initialDirectory = null;
string fileName = null;
string filter = null;
if (!string.IsNullOrEmpty(SelectedFile))
{
initialDirectory = Directory.GetParent(SelectedFile).FullName;
fileName = SelectedFile;
}
if (!string.IsNullOrEmpty(Filter))
{
filter = Filter;
}
var result = await _saveFileService.DetermineFileAsync(new DetermineSaveFileContext
{
InitialDirectory = initialDirectory,
FileName = fileName,
Filter = filter,
});
if (result.Result)
{
var oldSelectedFile = SelectedFile;
SelectedFile = result.FileName;
// See here: https://github.com/WildGums/Orc.Controls/issues/13
if (!AlwaysInvokeNotifyChanged
&& string.Equals(oldSelectedFile, SelectedFile))
{
RaisePropertyChanged(nameof(SelectedFile));
}
}
}
#endregion
}
}
| 31.607143 | 120 | 0.541243 | [
"MIT"
] | 0matyesz0/Orc.Controls | src/Orc.Controls/Controls/SaveFilePicker/ViewModels/SaveFilePickerViewModel.cs | 4,427 | C# |
using System;
using System.Runtime.InteropServices;
namespace Meziantou.Framework.Win32.Natives
{
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct PROPERTYKEY
{
internal Guid fmtid;
internal uint pid;
}
}
| 19.538462 | 51 | 0.69685 | [
"MIT"
] | LePtitDev/Meziantou.Framework | src/Meziantou.Framework.Win32.Dialogs/Natives/PROPERTYKEY.cs | 256 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Interface.Execute.SubRISC
{
public class RegisterFile : SyncModuleBase
{
public const int EntryCount = 16;
public struct EntryElement
{
public uint Content;
public long ReadAccessCount;
public long WriteAccessCount;
}
public EntryElement[] Entries;
public long CycleCount = 0;
public struct ReadCommand
{
public bool Enabled;
public int No;
}
public struct WriteCommand
{
public bool Enabled;
public int No;
public uint Value;
}
#region 同期入力
public ModuleInputface<ReadCommand> Read0_IFace;
public ModuleInputface<ReadCommand> Read1_IFace;
public ModuleInputface<WriteCommand> Write_IFace;
#endregion
#region 同期出力
private ReadCommand PreviousRead0;
private ReadCommand PreviousRead1;
private WriteCommand PreviousWrite;
#endregion
#region 即時出力
public AsyncModuleOutputface<uint> Read0_OFace;
public AsyncModuleOutputface<uint> Read1_OFace;
#endregion
public RegisterFile()
{
Entries = new SubRISC.RegisterFile.EntryElement[EntryCount];
for (int i = 0; i < EntryCount; i++)
{
Entries[i] = new EntryElement()
{
Content = 0,
ReadAccessCount = 0,
WriteAccessCount = 0
};
}
Read0_IFace = CreateInputface<ReadCommand>();
Read1_IFace = CreateInputface<ReadCommand>();
Write_IFace = CreateInputface<WriteCommand>();
Read0_OFace = CreateAsyncOutputface<uint>();
Read1_OFace = CreateAsyncOutputface<uint>();
PreviousRead0 = new SubRISC.RegisterFile.ReadCommand()
{
Enabled = false,
No = -1
};
PreviousRead1 = new SubRISC.RegisterFile.ReadCommand()
{
Enabled = false,
No = -1
};
Read0_OFace.SetFunc(() =>
{
ReadCommand rCmd = Read0_IFace.Get();
WriteCommand wCmd = Write_IFace.Get();
int no = rCmd.No % EntryCount;
return wCmd.Enabled && wCmd.No == no ? wCmd.Value
: Entries[no].Content;
});
Read1_OFace.SetFunc(() =>
{
ReadCommand rCmd = Read1_IFace.Get();
WriteCommand wCmd = Write_IFace.Get();
int no = rCmd.No % EntryCount;
return wCmd.Enabled && wCmd.No == no ? wCmd.Value
: Entries[no].Content;
});
}
protected override void UpdateModuleCycle()
{
this.CycleCount++;
{ //Perform writing
WriteCommand wCmd = Write_IFace.Get();
int no = wCmd.No % EntryCount;
if (wCmd.Enabled)
{
Entries[no].Content = wCmd.Value;
Entries[no].WriteAccessCount++;
}
PreviousWrite = wCmd;
}
{ //Count reading
ReadCommand rCmd = Read0_IFace.Get();
WriteCommand wCmd = Write_IFace.Get();
int no = rCmd.No % EntryCount;
if (rCmd.Enabled && no != PreviousRead0.No && !(wCmd.Enabled && wCmd.No == no))
Entries[no].ReadAccessCount++;
PreviousRead0 = rCmd;
}
{ //Count reading
ReadCommand rCmd = Read1_IFace.Get();
WriteCommand wCmd = Write_IFace.Get();
int no = rCmd.No % EntryCount;
if (rCmd.Enabled && no != PreviousRead1.No && !(wCmd.Enabled && wCmd.No == no))
Entries[no].ReadAccessCount++;
PreviousRead1 = rCmd;
}
base.UpdateModuleCycle();
}
public string GetStatisticsInfo()
{
long readAccessCount = 0, writeAccessCount = 0;
for (int i = 0; i < EntryCount; i++)
{
readAccessCount += Entries[i].ReadAccessCount;
writeAccessCount += Entries[i].WriteAccessCount;
}
StringBuilder sb = new StringBuilder();
sb.AppendLine($"[Whole]\r\n" +
$"Read rate = { ((double)readAccessCount / CycleCount * 100).ToString("0.00") } %\r\n" +
$"Write rate = { ((double)writeAccessCount / CycleCount * 100).ToString("0.00") } %");
sb.AppendLine($"[Per entry]");
for (int i = 0; i < EntryCount; i++)
{
sb.AppendLine($"{i.ToString("00")}: Read rate = { ((double)Entries[i].ReadAccessCount / CycleCount * 100).ToString("0.00") } %, Write rate = { ((double)Entries[i].WriteAccessCount / CycleCount * 100).ToString("0.00") } %");
}
return sb.ToString();
}
}
}
| 35.94702 | 240 | 0.488209 | [
"Unlicense",
"MIT"
] | Hara-Laboratory/oiscsim | Interface/Execute/SubRisc/Cycle/RegisterFile.cs | 5,454 | C# |
using System;
using System.Diagnostics;
using System.Threading;
using BizHawk.Client.Common;
using BizHawk.Common;
//this throttle is nitsuja's fine-tuned techniques from desmume
namespace BizHawk.Client.EmuHawk
{
public class Throttle
{
private int lastSkipRate;
private int framesToSkip;
private int framesSkipped;
public bool skipNextFrame;
//if the emulator is paused then we don't need to behave as if unthrottled
public bool signal_paused;
public bool signal_frameAdvance;
public bool signal_unthrottle;
public bool signal_continuousFrameAdvancing;
public bool signal_overrideSecondaryThrottle;
public void Step(Config config, Sound sound, bool allowSleep, int forceFrameSkip)
{
//TODO - figure out what allowSleep is supposed to be used for
//TODO - figure out what forceFrameSkip is supposed to be used for
bool extraThrottle = false;
//if we're paused, none of this should happen. just clean out our state and don't skip
//notably, if we're frame-advancing, we should be paused.
if (signal_paused && !signal_continuousFrameAdvancing)
{
//Console.WriteLine($"THE THING: {signal_paused} {signal_continuousFrameAdvancing}");
skipNextFrame = false;
framesSkipped = 0;
framesToSkip = 0;
//keep from burning CPU
Thread.Sleep(10);
return;
}
#if false
//here's some ideas for how to begin cleaning this up
////at this point, its assumed that we're running.
////this could be a free run, an unthrottled run, or a 'continuous frame advance' (aka continuous) run
////free run: affected by frameskips and throttles
////unthrottled run: affected by frameskips only
////continuous run: affected by frameskips and throttles
////so continuous and free are the same?
bool continuous_run = signal_continuousFrameAdvancing;
bool unthrottled_run = signal_unthrottle;
bool free_run = !continuous_run && !unthrottled_run;
bool do_throttle, do_skip;
if (continuous_run || free_run) do_throttle = do_skip = true;
else if (unthrottled_run) do_skip = true;
else throw new InvalidOperationException();
#endif
int skipRate = (forceFrameSkip < 0) ? config.FrameSkip : forceFrameSkip;
int ffSkipRate = (forceFrameSkip < 0) ? 3 : forceFrameSkip;
if (lastSkipRate != skipRate)
{
lastSkipRate = skipRate;
framesToSkip = 0; // otherwise switches to lower frameskip rates will lag behind
}
if (!skipNextFrame || forceFrameSkip == 0 || (signal_continuousFrameAdvancing && !signal_unthrottle))
{
framesSkipped = 0;
if (signal_continuousFrameAdvancing)
{
//don't ever skip frames when continuous frame advancing. it's meant for precision work.
//but we DO need to throttle
if (config.ClockThrottle)
extraThrottle = true;
}
else
{
if (framesToSkip > 0)
skipNextFrame = true;
}
}
else
{
framesToSkip--;
skipNextFrame = framesToSkip > 0;
framesSkipped++;
}
if (signal_unthrottle)
{
if (framesSkipped < ffSkipRate)
{
skipNextFrame = true;
framesToSkip = 1;
}
if (framesToSkip < 1)
framesToSkip += ffSkipRate;
}
else if ((extraThrottle || signal_paused || config.ClockThrottle || signal_overrideSecondaryThrottle) && allowSleep)
{
SpeedThrottle(sound, signal_paused);
}
if (config.AutoMinimizeSkipping && config.FrameSkip != 0)
{
if (!signal_continuousFrameAdvancing)
{
AutoFrameSkip_NextFrame();
if (framesToSkip < 1)
framesToSkip += AutoFrameSkip_GetSkipAmount(0, skipRate);
}
}
else
{
if (framesToSkip < 1)
framesToSkip += skipRate;
}
}
private static ulong GetCurTime()
{
if (tmethod == 1)
return (ulong)Stopwatch.GetTimestamp();
else
return (ulong)Environment.TickCount;
}
private static readonly Func<uint, uint> TimeBeginPeriod = OSTailoredCode.IsUnixHost
? u => u
: (Func<uint, uint>) Win32Imports.timeBeginPeriod;
private static readonly int tmethod;
private static readonly ulong afsfreq;
private static readonly ulong tfreq;
static Throttle()
{
TimeBeginPeriod(1);
if (Stopwatch.IsHighResolution)
{
afsfreq = (ulong)Stopwatch.Frequency;
tmethod = 1;
}
else
{
afsfreq = 1000;
tmethod = 0;
}
Util.DebugWriteLine("throttle method: {0}; resolution: {1}", tmethod, afsfreq);
tfreq = afsfreq * 65536;
}
public void SetCoreFps(double desired_fps)
{
core_desiredfps = (ulong)(65536 * desired_fps);
int target_pct = pct;
pct = -1;
SetSpeedPercent(target_pct);
}
private int pct = -1;
public void SetSpeedPercent(int percent)
{
//Console.WriteLine($"throttle set percent {percent}");
if (pct == percent) return;
pct = percent;
float fraction = percent / 100.0f;
desiredfps = (ulong)(core_desiredfps * fraction);
//Console.WriteLine($"throttle set desiredfps {desiredfps}");
desiredspf = 65536.0f / desiredfps;
AutoFrameSkip_IgnorePreviousDelay();
}
private ulong core_desiredfps;
private ulong desiredfps;
private float desiredspf;
private ulong ltime;
private ulong beginticks, endticks, preThrottleEndticks;
private float fSkipFrames;
private float fSkipFramesError;
private int lastSkip;
private float lastError;
private float integral;
public void AutoFrameSkip_IgnorePreviousDelay()
{
beginticks = GetCurTime();
// this seems to be a stable way of allowing the skip frames to
// quickly adjust to a faster environment (e.g. after a loadstate)
// without causing oscillation or a sudden change in skip rate
fSkipFrames *= 0.5f;
}
private void AutoFrameSkip_BeforeThrottle()
{
preThrottleEndticks = GetCurTime();
}
private void AutoFrameSkip_NextFrame()
{
endticks = GetCurTime();
// calculate time since last frame
ulong diffticks = Math.Max(endticks - beginticks, 1);
float diff = (float)diffticks / afsfreq;
// calculate time since last frame not including throttle sleep time
if (preThrottleEndticks == 0) // if we didn't throttle, use the non-throttle time
preThrottleEndticks = endticks;
ulong diffticksUnthrottled = preThrottleEndticks - beginticks;
float diffUnthrottled = (float)diffticksUnthrottled / afsfreq;
float error = diffUnthrottled - desiredspf;
// reset way-out-of-range values
if (diff > 1.0f)
diff = 1.0f;
if (!(-1.0f).RangeTo(1.0f).Contains(error))
error = 0.0f;
if (diffUnthrottled > 1.0f)
diffUnthrottled = desiredspf;
float derivative = (error - lastError) / diff;
lastError = error;
integral += error * diff;
integral *= 0.99f; // since our integral isn't reliable, reduce it to 0 over time.
// "PID controller" constants
// this stuff is probably being done all wrong, but these seem to work ok
const float Kp = 40.0f;
const float Ki = 0.55f;
const float Kd = 0.04f;
float errorTerm = error * Kp;
float derivativeTerm = derivative * Kd;
float integralTerm = integral * Ki;
float adjustment = errorTerm + derivativeTerm + integralTerm;
// apply the output adjustment
fSkipFrames += adjustment;
// if we're running too slowly, prevent the throttle from kicking in
if (adjustment > 0 && fSkipFrames > 0)
ltime -= tfreq / desiredfps;
preThrottleEndticks = 0;
beginticks = GetCurTime();
}
private int AutoFrameSkip_GetSkipAmount(int min, int max)
{
int rv = (int)fSkipFrames;
fSkipFramesError += fSkipFrames - rv;
// resolve accumulated fractional error
// where doing so doesn't push us out of range
while (fSkipFramesError >= 1.0f && rv <= lastSkip && rv < max)
{
fSkipFramesError -= 1.0f;
rv++;
}
while (fSkipFramesError <= -1.0f && rv >= lastSkip && rv > min)
{
fSkipFramesError += 1.0f;
rv--;
}
// restrict skip amount to requested range
if (rv < min)
rv = min;
if (rv > max)
rv = max;
// limit maximum error accumulation (it's mainly only for fractional components)
if (fSkipFramesError >= 4.0f)
fSkipFramesError = 4.0f;
if (fSkipFramesError <= -4.0f)
fSkipFramesError = -4.0f;
// limit ongoing skipframes to requested range + 1 on each side
if (fSkipFrames < min - 1)
fSkipFrames = (float)min - 1;
if (fSkipFrames > max + 1)
fSkipFrames = (float)max + 1;
// printf("%d", rv);
lastSkip = rv;
return rv;
}
private void SpeedThrottle(Sound sound, bool paused)
{
AutoFrameSkip_BeforeThrottle();
ulong timePerFrame = tfreq / desiredfps;
while (true)
{
if (signal_unthrottle)
return;
ulong ttime = GetCurTime();
ulong elapsedTime = ttime - ltime;
if (elapsedTime >= timePerFrame)
{
int maxMissedFrames = (int)Math.Ceiling((sound.SoundMaxBufferDeficitMs / 1000.0) / ((double)timePerFrame / afsfreq));
if (maxMissedFrames < 3)
maxMissedFrames = 3;
if (elapsedTime > timePerFrame * (ulong)(1 + maxMissedFrames))
ltime = ttime;
else
ltime += timePerFrame;
return;
}
int sleepTime = (int)((timePerFrame - elapsedTime) * 1000 / afsfreq);
if (sleepTime >= 2 || paused)
{
switch (OSTailoredCode.CurrentOS)
{
case OSTailoredCode.DistinctOS.Linux: //TODO repro
case OSTailoredCode.DistinctOS.macOS:
// The actual sleep time on OS X with Mono is generally between the request time
// and up to 25% over. So we'll scale the sleep time back to account for that.
sleepTime = sleepTime * 4 / 5;
break;
case OSTailoredCode.DistinctOS.Windows:
// Assuming a timer period of 1 ms (i.e. TimeBeginPeriod(1)): The actual sleep time
// on Windows XP is generally within a half millisecond either way of the requested
// time. The actual sleep time on Windows 8 is generally between the requested time
// and up to a millisecond over. So we'll subtract 1 ms from the time to avoid
// sleeping longer than desired.
sleepTime -= 1;
break;
}
Thread.Sleep(Math.Max(sleepTime, 1));
}
else if (sleepTime > 0) // spin for <1 millisecond waits
{
Thread.Yield(); // limit to other threads on the same CPU core for other short waits
}
}
}
}
}
| 28.894022 | 123 | 0.654284 | [
"MIT"
] | CartoonFan/BizHawk | src/BizHawk.Client.EmuHawk/Throttle.cs | 10,635 | C# |
using System;
namespace Ipfs
{
public class MultiAddress : IEquatable<MultiAddress>
{
private string[] _components;
public MultiAddress(string uriString)
{
OriginalString = uriString;
_components = OriginalString.Split('/');
}
public string OriginalString { get; private set; }
public string Version
{
get { return _components[1]; }
}
public string Address
{
get { return _components[2]; }
}
public string Protocol
{
get { return _components[3]; }
}
public string Port
{
get { return _components[4]; }
}
public string Application
{
get { return _components[5]; }
}
public string Resource
{
get { return _components[6]; }
}
public bool Equals(MultiAddress other)
{
if (other == null) return false;
return Equals(other.OriginalString, OriginalString);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, this)) return true;
var other = obj as MultiAddress;
return Equals(other);
}
public override int GetHashCode()
{
return OriginalString.GetHashCode();
}
public static explicit operator string(MultiAddress multiAddress)
{
return multiAddress.ToString();
}
public override string ToString()
{
return OriginalString;
}
}
}
| 21.063291 | 73 | 0.517428 | [
"MIT"
] | TrekDev/net-ipfs-api | src/Ipfs/MultiAddress.cs | 1,666 | C# |
using Refit;
namespace Adnc.Application.RpcService.Rtos
{
public class ProductSearchListRto
{
[Query(CollectionFormat.Multi)]
public string[] Ids { get; set; }
public int StatusCode { get; set; }
}
} | 19.833333 | 43 | 0.634454 | [
"MIT"
] | lht6/Adnc | src/ServerApi/Services/Shared/Adnc.Application.RpcService/Rtos/ProductSearchListRto.cs | 240 | C# |
//
// BreakStatement.cs
//
// Author:
// Mike Krüger <mkrueger@novell.com>
//
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
//
// 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.
namespace ICSharpCode.NRefactory.CSharp
{
/// <summary>
/// break;
/// </summary>
public class BreakStatement : Statement
{
public static readonly TokenRole BreakKeywordRole = new TokenRole ("break");
public CSharpTokenNode BreakToken {
get { return GetChildByRole (BreakKeywordRole); }
}
public CSharpTokenNode SemicolonToken {
get { return GetChildByRole (Roles.Semicolon); }
}
public override void AcceptVisitor (IAstVisitor visitor)
{
visitor.VisitBreakStatement (this);
}
public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
{
return visitor.VisitBreakStatement (this);
}
public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitBreakStatement (this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
BreakStatement o = other as BreakStatement;
return o != null;
}
}
}
| 33.863636 | 87 | 0.709172 | [
"MIT"
] | GreenDamTan/simple-assembly-exploror | ILSpy/NRefactory/ICSharpCode.NRefactory.CSharp/Ast/Statements/BreakStatement.cs | 2,238 | C# |
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using StudentAgenda.Models;
using StudentAgenda.Views;
using StudentAgenda.ViewModels;
namespace StudentAgenda.Views
{
public partial class ClassesPage : ContentPage
{
ClassesViewModel _viewModel;
public ClassesPage()
{
InitializeComponent();
BindingContext = _viewModel = new ClassesViewModel();
}
protected override void OnAppearing()
{
base.OnAppearing();
_viewModel.OnAppearing();
}
}
} | 21.333333 | 65 | 0.671875 | [
"MIT"
] | eahs/StudentAgendaApp | Source/StudentAgenda/StudentAgenda/StudentAgenda/Views/ClassesPage.xaml.cs | 706 | C# |
#region License
// Copyright (c) 2016 1010Tires.com
//
// 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.Collections.Generic;
using MXTires.Microdata.Validators;
using Newtonsoft.Json;
namespace MXTires.Microdata.Intangible.Services
{
/// <summary>
/// A service provided by a government organization, e.g. food stamps, veterans benefits, etc.
/// </summary>
public class GovernmentService : Service
{
/// <summary>
/// The operating organization, if different from the provider. This enables the representation of services that are provided by an organization, but operated by another organization like a subcontractor.
/// </summary>
[JsonProperty("serviceOperator")]
public Organization ServiceOperator { get; set; }
}
}
| 41.954545 | 212 | 0.739978 | [
"MIT"
] | mizzos/MXTires.Microdata | Intangible/Services/GovernmentService.cs | 1,848 | C# |
using FistVR;
using UnityEngine;
namespace H3VRMod.GameModeScripts
{
[System.Serializable]
public class CookOffAssault : MonoBehaviour
{
/*public CookOffPatrol[] Patrols;*/
public float delayBetweenPatrols;
public float startingTimeGrace;
public float assaultLength;
public WurstMod.MappingComponents.Generic.SosigSpawner[] spawners;
}
} | 23.533333 | 68 | 0.793201 | [
"MIT"
] | Frityet/CookOffScripts | src/Plugin/src/GameModeScripts/CookOffAssault.cs | 355 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.As.V1.Model
{
/// <summary>
/// 修改伸缩组详情
/// </summary>
public class UpdateScalingGroupOption
{
/// <summary>
/// 伸缩组实例健康检查方式:ELB_AUDIT和NOVA_AUDIT。当伸缩组参数中设置负载均衡时,默认为ELB_AUDIT;否则默认为NOVA_AUDIT。ELB_AUDIT表示负载均衡健康检查方式,在有监听器的伸缩组中有效。NOVA_AUDIT表示弹性伸缩自带的健康检查方式。
/// </summary>
/// <value>伸缩组实例健康检查方式:ELB_AUDIT和NOVA_AUDIT。当伸缩组参数中设置负载均衡时,默认为ELB_AUDIT;否则默认为NOVA_AUDIT。ELB_AUDIT表示负载均衡健康检查方式,在有监听器的伸缩组中有效。NOVA_AUDIT表示弹性伸缩自带的健康检查方式。</value>
[JsonConverter(typeof(EnumClassConverter<HealthPeriodicAuditMethodEnum>))]
public class HealthPeriodicAuditMethodEnum
{
/// <summary>
/// Enum ELB_AUDIT for value: ELB_AUDIT
/// </summary>
public static readonly HealthPeriodicAuditMethodEnum ELB_AUDIT = new HealthPeriodicAuditMethodEnum("ELB_AUDIT");
/// <summary>
/// Enum NOVA_AUDIT for value: NOVA_AUDIT
/// </summary>
public static readonly HealthPeriodicAuditMethodEnum NOVA_AUDIT = new HealthPeriodicAuditMethodEnum("NOVA_AUDIT");
private static readonly Dictionary<string, HealthPeriodicAuditMethodEnum> StaticFields =
new Dictionary<string, HealthPeriodicAuditMethodEnum>()
{
{ "ELB_AUDIT", ELB_AUDIT },
{ "NOVA_AUDIT", NOVA_AUDIT },
};
private string Value;
public HealthPeriodicAuditMethodEnum(string value)
{
Value = value;
}
public static HealthPeriodicAuditMethodEnum FromValue(string value)
{
if(value == null){
return null;
}
if (StaticFields.ContainsKey(value))
{
return StaticFields[value];
}
return null;
}
public string GetValue()
{
return Value;
}
public override string ToString()
{
return $"{Value}";
}
public override int GetHashCode()
{
return this.Value.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (this.Equals(obj as HealthPeriodicAuditMethodEnum))
{
return true;
}
return false;
}
public bool Equals(HealthPeriodicAuditMethodEnum obj)
{
if ((object)obj == null)
{
return false;
}
return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value);
}
public static bool operator ==(HealthPeriodicAuditMethodEnum a, HealthPeriodicAuditMethodEnum b)
{
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
if ((object)a == null)
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(HealthPeriodicAuditMethodEnum a, HealthPeriodicAuditMethodEnum b)
{
return !(a == b);
}
}
/// <summary>
/// 伸缩组实例移除策略:OLD_CONFIG_OLD_INSTANCE(默认):从根据“较早创建的配置”创建的实例中筛选出较早创建的实例被优先移除。OLD_CONFIG_NEW_INSTANCE:从根据“较早创建的配置”创建的实例中筛选出较新创建的实例被优先移除。OLD_INSTANCE:较早创建的实例被优先移除。NEW_INSTANCE:较新创建的实例将被优先移除。
/// </summary>
/// <value>伸缩组实例移除策略:OLD_CONFIG_OLD_INSTANCE(默认):从根据“较早创建的配置”创建的实例中筛选出较早创建的实例被优先移除。OLD_CONFIG_NEW_INSTANCE:从根据“较早创建的配置”创建的实例中筛选出较新创建的实例被优先移除。OLD_INSTANCE:较早创建的实例被优先移除。NEW_INSTANCE:较新创建的实例将被优先移除。</value>
[JsonConverter(typeof(EnumClassConverter<InstanceTerminatePolicyEnum>))]
public class InstanceTerminatePolicyEnum
{
/// <summary>
/// Enum OLD_CONFIG_OLD_INSTANCE for value: OLD_CONFIG_OLD_INSTANCE
/// </summary>
public static readonly InstanceTerminatePolicyEnum OLD_CONFIG_OLD_INSTANCE = new InstanceTerminatePolicyEnum("OLD_CONFIG_OLD_INSTANCE");
/// <summary>
/// Enum OLD_CONFIG_NEW_INSTANCE for value: OLD_CONFIG_NEW_INSTANCE
/// </summary>
public static readonly InstanceTerminatePolicyEnum OLD_CONFIG_NEW_INSTANCE = new InstanceTerminatePolicyEnum("OLD_CONFIG_NEW_INSTANCE");
/// <summary>
/// Enum OLD_INSTANCE for value: OLD_INSTANCE
/// </summary>
public static readonly InstanceTerminatePolicyEnum OLD_INSTANCE = new InstanceTerminatePolicyEnum("OLD_INSTANCE");
/// <summary>
/// Enum NEW_INSTANCE for value: NEW_INSTANCE
/// </summary>
public static readonly InstanceTerminatePolicyEnum NEW_INSTANCE = new InstanceTerminatePolicyEnum("NEW_INSTANCE");
private static readonly Dictionary<string, InstanceTerminatePolicyEnum> StaticFields =
new Dictionary<string, InstanceTerminatePolicyEnum>()
{
{ "OLD_CONFIG_OLD_INSTANCE", OLD_CONFIG_OLD_INSTANCE },
{ "OLD_CONFIG_NEW_INSTANCE", OLD_CONFIG_NEW_INSTANCE },
{ "OLD_INSTANCE", OLD_INSTANCE },
{ "NEW_INSTANCE", NEW_INSTANCE },
};
private string Value;
public InstanceTerminatePolicyEnum(string value)
{
Value = value;
}
public static InstanceTerminatePolicyEnum FromValue(string value)
{
if(value == null){
return null;
}
if (StaticFields.ContainsKey(value))
{
return StaticFields[value];
}
return null;
}
public string GetValue()
{
return Value;
}
public override string ToString()
{
return $"{Value}";
}
public override int GetHashCode()
{
return this.Value.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (this.Equals(obj as InstanceTerminatePolicyEnum))
{
return true;
}
return false;
}
public bool Equals(InstanceTerminatePolicyEnum obj)
{
if ((object)obj == null)
{
return false;
}
return StringComparer.OrdinalIgnoreCase.Equals(this.Value, obj.Value);
}
public static bool operator ==(InstanceTerminatePolicyEnum a, InstanceTerminatePolicyEnum b)
{
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
if ((object)a == null)
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(InstanceTerminatePolicyEnum a, InstanceTerminatePolicyEnum b)
{
return !(a == b);
}
}
/// <summary>
/// 伸缩组名称(1-64个字符),只能包含中文、字母、数字、下划线、中划线。
/// </summary>
[JsonProperty("scaling_group_name", NullValueHandling = NullValueHandling.Ignore)]
public string ScalingGroupName { get; set; }
/// <summary>
/// 期望实例数量,默认值为最小实例数。最小实例数<=期望实例数<=最大实例数
/// </summary>
[JsonProperty("desire_instance_number", NullValueHandling = NullValueHandling.Ignore)]
public int? DesireInstanceNumber { get; set; }
/// <summary>
/// 最小实例数量。
/// </summary>
[JsonProperty("min_instance_number", NullValueHandling = NullValueHandling.Ignore)]
public int? MinInstanceNumber { get; set; }
/// <summary>
/// 最大实例数量,大于等于最小实例数。
/// </summary>
[JsonProperty("max_instance_number", NullValueHandling = NullValueHandling.Ignore)]
public int? MaxInstanceNumber { get; set; }
/// <summary>
/// 冷却时间,取值范围0-86400,单位是秒。
/// </summary>
[JsonProperty("cool_down_time", NullValueHandling = NullValueHandling.Ignore)]
public int? CoolDownTime { get; set; }
/// <summary>
/// 可用分区信息。弹性伸缩活动中自动添加的云服务器会被创建在指定的可用区中。如果没有指定可用分区,会由系统自动指定可用分区。详情请参考地区和终端节点。仅当同时满足以下条件时才可以修改:伸缩组中无伸缩活动;实例数为0;伸缩组为非启用状态。
/// </summary>
[JsonProperty("available_zones", NullValueHandling = NullValueHandling.Ignore)]
public List<string> AvailableZones { get; set; }
/// <summary>
/// 网络信息,最多支持选择5个子网,传入的第一个子网默认作为云服务器的主网卡。使用vpc_id通过查询VPC服务子网列表接口获取,仅当同时满足以下条件时,才可以修改:伸缩组中无伸缩活动;实例数为0;伸缩组为非启用状态。
/// </summary>
[JsonProperty("networks", NullValueHandling = NullValueHandling.Ignore)]
public List<Networks> Networks { get; set; }
/// <summary>
/// 安全组信息,最多支持选择1个安全组。使用vpc_id通过查询VPC服务安全组列表接口获取,详见《虚拟私有云API参考》的“查询安全组列表”。当伸缩配置和伸缩组同时指定安全组时,将以伸缩配置中的安全组为准;当伸缩配置和伸缩组都没有指定安全组时,将使用默认安全组。为了使用灵活性更高,推荐在伸缩配置中指定安全组。仅当同时满足以下条件时,才可以修改:伸缩组无伸缩活动;实例数为0;伸缩组为非启用状态。
/// </summary>
[JsonProperty("security_groups", NullValueHandling = NullValueHandling.Ignore)]
public List<SecurityGroup> SecurityGroups { get; set; }
/// <summary>
/// 弹性负载均衡(经典型)监听器ID,最多支持绑定3个负载均衡监听器,多个负载均衡监听器ID以逗号分隔。首先使用vpc_id通过查询ELB服务负载均衡器列表接口获取负载均衡器的ID,详见《弹性负载均衡API参考》的“查询负载均衡器列表”,再使用该ID查询监听器列表获取,详见《弹性负载均衡API参考》的“查询监听器列表”。仅当同时满足以下条件时,才可以修改:伸缩组无伸缩活动;实例数为0;伸缩组为非启用状态。
/// </summary>
[JsonProperty("lb_listener_id", NullValueHandling = NullValueHandling.Ignore)]
public string LbListenerId { get; set; }
/// <summary>
/// 弹性负载均衡器(增强型)信息,最多支持绑定3个负载均衡。该字段与lb_listener_id互斥。
/// </summary>
[JsonProperty("lbaas_listeners", NullValueHandling = NullValueHandling.Ignore)]
public List<LbaasListeners> LbaasListeners { get; set; }
/// <summary>
/// 伸缩组实例健康检查方式:ELB_AUDIT和NOVA_AUDIT。当伸缩组参数中设置负载均衡时,默认为ELB_AUDIT;否则默认为NOVA_AUDIT。ELB_AUDIT表示负载均衡健康检查方式,在有监听器的伸缩组中有效。NOVA_AUDIT表示弹性伸缩自带的健康检查方式。
/// </summary>
[JsonProperty("health_periodic_audit_method", NullValueHandling = NullValueHandling.Ignore)]
public HealthPeriodicAuditMethodEnum HealthPeriodicAuditMethod { get; set; }
/// <summary>
/// 伸缩组实例健康检查周期(分钟):1、5、15、60、180。若设置为0,可以实现10秒级健康检查。
/// </summary>
[JsonProperty("health_periodic_audit_time", NullValueHandling = NullValueHandling.Ignore)]
public int? HealthPeriodicAuditTime { get; set; }
/// <summary>
/// 伸缩组实例健康状况检查宽限期,取值范围0-86400,单位是秒。当实例加入伸缩组并且进入已启用状态后,健康状况检查宽限期才会启动,伸缩组会等健康状况检查宽限期结束后才检查实例的运行状况。当伸缩组实例健康检查方式为ELB_AUDIT时,该参数生效,若不设置该参数,默认为10分钟。
/// </summary>
[JsonProperty("health_periodic_audit_grace_period", NullValueHandling = NullValueHandling.Ignore)]
public int? HealthPeriodicAuditGracePeriod { get; set; }
/// <summary>
/// 伸缩组实例移除策略:OLD_CONFIG_OLD_INSTANCE(默认):从根据“较早创建的配置”创建的实例中筛选出较早创建的实例被优先移除。OLD_CONFIG_NEW_INSTANCE:从根据“较早创建的配置”创建的实例中筛选出较新创建的实例被优先移除。OLD_INSTANCE:较早创建的实例被优先移除。NEW_INSTANCE:较新创建的实例将被优先移除。
/// </summary>
[JsonProperty("instance_terminate_policy", NullValueHandling = NullValueHandling.Ignore)]
public InstanceTerminatePolicyEnum InstanceTerminatePolicy { get; set; }
/// <summary>
/// 伸缩配置ID,通过查询弹性伸缩配置列表接口获取,详见查询弹性伸缩配置列表
/// </summary>
[JsonProperty("scaling_configuration_id", NullValueHandling = NullValueHandling.Ignore)]
public string ScalingConfigurationId { get; set; }
/// <summary>
/// 通知方式:EMAIL为发送邮件通知。该通知方式即将被废除,建议给弹性伸缩组配置通知功能。详见通知。
/// </summary>
[JsonProperty("notifications", NullValueHandling = NullValueHandling.Ignore)]
public List<string> Notifications { get; set; }
/// <summary>
/// 配置删除云服务器时是否删除云服务器绑定的弹性IP。取值为true或false,默认为false。true:删除云服务器时,会同时删除绑定在云服务器上的弹性IP。当弹性IP的计费方式为包年包月时,不会被删除。false:删除云服务器时,仅解绑定在云服务器上的弹性IP,不删除弹性IP。
/// </summary>
[JsonProperty("delete_publicip", NullValueHandling = NullValueHandling.Ignore)]
public bool? DeletePublicip { get; set; }
/// <summary>
/// 配置删除云服务器时是否删除云服务器绑定的数据盘。取值为true或false,默认为false。 true:删除云服务器时,会同时删除绑定在云服务器上的数据盘。当数据盘的计费方式为包年包月时,不会被删除。 false:删除务器时,仅云服解绑定在云服务器上的数据盘,不删除数据盘。
/// </summary>
[JsonProperty("delete_volume", NullValueHandling = NullValueHandling.Ignore)]
public bool? DeleteVolume { get; set; }
/// <summary>
/// 企业项目ID,用于指定伸缩组归属的企业项目。当伸缩组配置企业项目时,由该伸缩组创建的弹性云服务器将归属于该企业项目。当没有指定企业项目时,将使用企业项目ID为0的默认项目。
/// </summary>
[JsonProperty("enterprise_project_id", NullValueHandling = NullValueHandling.Ignore)]
public string EnterpriseProjectId { get; set; }
/// <summary>
/// 伸缩组扩缩容时目标AZ选择的优先级策略: EQUILIBRIUM_DISTRIBUTE(默认):均衡分布,虚拟机扩缩容时优先保证available_zones列表中各AZ下虚拟机数量均衡,当无法在目标AZ下完成虚拟机扩容时,按照PICK_FIRST原则选择其他可用AZ。 PICK_FIRST:选择优先,虚拟机扩缩容时目标AZ的选择按照available_zones列表的顺序进行优先级排序。
/// </summary>
[JsonProperty("multi_az_priority_policy", NullValueHandling = NullValueHandling.Ignore)]
public string MultiAzPriorityPolicy { get; set; }
/// <summary>
/// Get the string
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class UpdateScalingGroupOption {\n");
sb.Append(" scalingGroupName: ").Append(ScalingGroupName).Append("\n");
sb.Append(" desireInstanceNumber: ").Append(DesireInstanceNumber).Append("\n");
sb.Append(" minInstanceNumber: ").Append(MinInstanceNumber).Append("\n");
sb.Append(" maxInstanceNumber: ").Append(MaxInstanceNumber).Append("\n");
sb.Append(" coolDownTime: ").Append(CoolDownTime).Append("\n");
sb.Append(" availableZones: ").Append(AvailableZones).Append("\n");
sb.Append(" networks: ").Append(Networks).Append("\n");
sb.Append(" securityGroups: ").Append(SecurityGroups).Append("\n");
sb.Append(" lbListenerId: ").Append(LbListenerId).Append("\n");
sb.Append(" lbaasListeners: ").Append(LbaasListeners).Append("\n");
sb.Append(" healthPeriodicAuditMethod: ").Append(HealthPeriodicAuditMethod).Append("\n");
sb.Append(" healthPeriodicAuditTime: ").Append(HealthPeriodicAuditTime).Append("\n");
sb.Append(" healthPeriodicAuditGracePeriod: ").Append(HealthPeriodicAuditGracePeriod).Append("\n");
sb.Append(" instanceTerminatePolicy: ").Append(InstanceTerminatePolicy).Append("\n");
sb.Append(" scalingConfigurationId: ").Append(ScalingConfigurationId).Append("\n");
sb.Append(" notifications: ").Append(Notifications).Append("\n");
sb.Append(" deletePublicip: ").Append(DeletePublicip).Append("\n");
sb.Append(" deleteVolume: ").Append(DeleteVolume).Append("\n");
sb.Append(" enterpriseProjectId: ").Append(EnterpriseProjectId).Append("\n");
sb.Append(" multiAzPriorityPolicy: ").Append(MultiAzPriorityPolicy).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public override bool Equals(object input)
{
return this.Equals(input as UpdateScalingGroupOption);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public bool Equals(UpdateScalingGroupOption input)
{
if (input == null)
return false;
return
(
this.ScalingGroupName == input.ScalingGroupName ||
(this.ScalingGroupName != null &&
this.ScalingGroupName.Equals(input.ScalingGroupName))
) &&
(
this.DesireInstanceNumber == input.DesireInstanceNumber ||
(this.DesireInstanceNumber != null &&
this.DesireInstanceNumber.Equals(input.DesireInstanceNumber))
) &&
(
this.MinInstanceNumber == input.MinInstanceNumber ||
(this.MinInstanceNumber != null &&
this.MinInstanceNumber.Equals(input.MinInstanceNumber))
) &&
(
this.MaxInstanceNumber == input.MaxInstanceNumber ||
(this.MaxInstanceNumber != null &&
this.MaxInstanceNumber.Equals(input.MaxInstanceNumber))
) &&
(
this.CoolDownTime == input.CoolDownTime ||
(this.CoolDownTime != null &&
this.CoolDownTime.Equals(input.CoolDownTime))
) &&
(
this.AvailableZones == input.AvailableZones ||
this.AvailableZones != null &&
input.AvailableZones != null &&
this.AvailableZones.SequenceEqual(input.AvailableZones)
) &&
(
this.Networks == input.Networks ||
this.Networks != null &&
input.Networks != null &&
this.Networks.SequenceEqual(input.Networks)
) &&
(
this.SecurityGroups == input.SecurityGroups ||
this.SecurityGroups != null &&
input.SecurityGroups != null &&
this.SecurityGroups.SequenceEqual(input.SecurityGroups)
) &&
(
this.LbListenerId == input.LbListenerId ||
(this.LbListenerId != null &&
this.LbListenerId.Equals(input.LbListenerId))
) &&
(
this.LbaasListeners == input.LbaasListeners ||
this.LbaasListeners != null &&
input.LbaasListeners != null &&
this.LbaasListeners.SequenceEqual(input.LbaasListeners)
) &&
(
this.HealthPeriodicAuditMethod == input.HealthPeriodicAuditMethod ||
(this.HealthPeriodicAuditMethod != null &&
this.HealthPeriodicAuditMethod.Equals(input.HealthPeriodicAuditMethod))
) &&
(
this.HealthPeriodicAuditTime == input.HealthPeriodicAuditTime ||
(this.HealthPeriodicAuditTime != null &&
this.HealthPeriodicAuditTime.Equals(input.HealthPeriodicAuditTime))
) &&
(
this.HealthPeriodicAuditGracePeriod == input.HealthPeriodicAuditGracePeriod ||
(this.HealthPeriodicAuditGracePeriod != null &&
this.HealthPeriodicAuditGracePeriod.Equals(input.HealthPeriodicAuditGracePeriod))
) &&
(
this.InstanceTerminatePolicy == input.InstanceTerminatePolicy ||
(this.InstanceTerminatePolicy != null &&
this.InstanceTerminatePolicy.Equals(input.InstanceTerminatePolicy))
) &&
(
this.ScalingConfigurationId == input.ScalingConfigurationId ||
(this.ScalingConfigurationId != null &&
this.ScalingConfigurationId.Equals(input.ScalingConfigurationId))
) &&
(
this.Notifications == input.Notifications ||
this.Notifications != null &&
input.Notifications != null &&
this.Notifications.SequenceEqual(input.Notifications)
) &&
(
this.DeletePublicip == input.DeletePublicip ||
(this.DeletePublicip != null &&
this.DeletePublicip.Equals(input.DeletePublicip))
) &&
(
this.DeleteVolume == input.DeleteVolume ||
(this.DeleteVolume != null &&
this.DeleteVolume.Equals(input.DeleteVolume))
) &&
(
this.EnterpriseProjectId == input.EnterpriseProjectId ||
(this.EnterpriseProjectId != null &&
this.EnterpriseProjectId.Equals(input.EnterpriseProjectId))
) &&
(
this.MultiAzPriorityPolicy == input.MultiAzPriorityPolicy ||
(this.MultiAzPriorityPolicy != null &&
this.MultiAzPriorityPolicy.Equals(input.MultiAzPriorityPolicy))
);
}
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.ScalingGroupName != null)
hashCode = hashCode * 59 + this.ScalingGroupName.GetHashCode();
if (this.DesireInstanceNumber != null)
hashCode = hashCode * 59 + this.DesireInstanceNumber.GetHashCode();
if (this.MinInstanceNumber != null)
hashCode = hashCode * 59 + this.MinInstanceNumber.GetHashCode();
if (this.MaxInstanceNumber != null)
hashCode = hashCode * 59 + this.MaxInstanceNumber.GetHashCode();
if (this.CoolDownTime != null)
hashCode = hashCode * 59 + this.CoolDownTime.GetHashCode();
if (this.AvailableZones != null)
hashCode = hashCode * 59 + this.AvailableZones.GetHashCode();
if (this.Networks != null)
hashCode = hashCode * 59 + this.Networks.GetHashCode();
if (this.SecurityGroups != null)
hashCode = hashCode * 59 + this.SecurityGroups.GetHashCode();
if (this.LbListenerId != null)
hashCode = hashCode * 59 + this.LbListenerId.GetHashCode();
if (this.LbaasListeners != null)
hashCode = hashCode * 59 + this.LbaasListeners.GetHashCode();
if (this.HealthPeriodicAuditMethod != null)
hashCode = hashCode * 59 + this.HealthPeriodicAuditMethod.GetHashCode();
if (this.HealthPeriodicAuditTime != null)
hashCode = hashCode * 59 + this.HealthPeriodicAuditTime.GetHashCode();
if (this.HealthPeriodicAuditGracePeriod != null)
hashCode = hashCode * 59 + this.HealthPeriodicAuditGracePeriod.GetHashCode();
if (this.InstanceTerminatePolicy != null)
hashCode = hashCode * 59 + this.InstanceTerminatePolicy.GetHashCode();
if (this.ScalingConfigurationId != null)
hashCode = hashCode * 59 + this.ScalingConfigurationId.GetHashCode();
if (this.Notifications != null)
hashCode = hashCode * 59 + this.Notifications.GetHashCode();
if (this.DeletePublicip != null)
hashCode = hashCode * 59 + this.DeletePublicip.GetHashCode();
if (this.DeleteVolume != null)
hashCode = hashCode * 59 + this.DeleteVolume.GetHashCode();
if (this.EnterpriseProjectId != null)
hashCode = hashCode * 59 + this.EnterpriseProjectId.GetHashCode();
if (this.MultiAzPriorityPolicy != null)
hashCode = hashCode * 59 + this.MultiAzPriorityPolicy.GetHashCode();
return hashCode;
}
}
}
}
| 43.332756 | 214 | 0.567132 | [
"Apache-2.0"
] | mawenbo-huawei/huaweicloud-sdk-net-v3 | Services/As/V1/Model/UpdateScalingGroupOption.cs | 28,893 | C# |
namespace DesignPatterns.GangOfFour.Behavioral.Interpreter
{
public class NumberExpression : IExpression
{
private readonly int number;
public NumberExpression(int number)
{
this.number = number;
}
public int Interpret()
{
return this.number;
}
}
} | 20.176471 | 59 | 0.574344 | [
"MIT"
] | jimtsikos/DesignPatternsCSharp | DesignPatternsStandard/GangOfFour/Behavioral/Interpreter/NumberExpression.cs | 345 | C# |
//------------------------------------------------------------------------------
// <自動產生的>
// 這段程式碼是由工具產生的。
//
// 變更這個檔案可能會導致不正確的行為,而且如果已重新產生
// 程式碼,則會遺失變更。
// </自動產生的>
//------------------------------------------------------------------------------
namespace UbayProject
{
public partial class SubPageMasterPage
{
/// <summary>
/// head 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder head;
/// <summary>
/// form1 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// a_Login 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlAnchor a_Login;
/// <summary>
/// linkLogout 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton linkLogout;
/// <summary>
/// Breadcrumbs 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder Breadcrumbs;
/// <summary>
/// BoardLink 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl BoardLink;
/// <summary>
/// AddMainCategoryArea 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl AddMainCategoryArea;
/// <summary>
/// AddMainCategoryName 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox AddMainCategoryName;
/// <summary>
/// btnAddMainCategory 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnAddMainCategory;
/// <summary>
/// AddSubCategoryArea 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl AddSubCategoryArea;
/// <summary>
/// AddSubCategoryName 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox AddSubCategoryName;
/// <summary>
/// AddSubCateUnderMainName 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox AddSubCateUnderMainName;
/// <summary>
/// btnAddSubCategory 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnAddSubCategory;
/// <summary>
/// PicUP 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.FileUpload PicUP;
/// <summary>
/// ltMsg 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltMsg;
/// <summary>
/// PicNameInp 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox PicNameInp;
/// <summary>
/// btnPicUP 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnPicUP;
/// <summary>
/// ltPager 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltPager;
/// <summary>
/// ContentPlaceHolder1 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder1;
}
}
| 28.132275 | 92 | 0.508934 | [
"MIT"
] | who000238/UbayProject | Project/UbayProject/SubMasterPage.Master.designer.cs | 6,961 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.Alias.Implementation.Holder;
using Orchard.Alias.Implementation.Storage;
using Orchard.Data;
using Orchard.Environment;
using Orchard.Tasks;
using Orchard.Logging;
namespace Orchard.Alias.Implementation.Updater {
public class AliasHolderUpdater : IOrchardShellEvents, IBackgroundTask {
private readonly IAliasHolder _aliasHolder;
private readonly IAliasStorage _storage;
public ILogger Logger { get; set; }
public AliasHolderUpdater(IAliasHolder aliasHolder, IAliasStorage storage) {
_aliasHolder = aliasHolder;
_storage = storage;
Logger = NullLogger.Instance;
}
void IOrchardShellEvents.Activated() {
Refresh();
}
void IOrchardShellEvents.Terminating() {
}
private void Refresh() {
try {
var aliases = _storage.List();
_aliasHolder.SetAliases(aliases.Select(alias => new AliasInfo { Path = alias.Item1, Area = alias.Item2, RouteValues = alias.Item3 }));
}
catch (Exception ex) {
Logger.Error(ex, "Exception during Alias refresh");
}
}
public void Sweep() {
Refresh();
}
}
}
| 28.744681 | 150 | 0.627683 | [
"BSD-3-Clause"
] | Trifectgaming/Trifect-CMS | Modules/Orchard.Alias/Implementation/Updater/AliasUpdater.cs | 1,353 | C# |
//***************************************************
//* This file was generated by JSharp
//***************************************************
namespace java.net
{
internal partial class NetworkInterface_1subIFs : global::java.lang.Object, global::java.util.Enumeration<NetworkInterface>
{
public NetworkInterface_1subIFs(){}
public virtual bool hasMoreElements(){return default(bool);}
public virtual NetworkInterface nextElement(){return default(NetworkInterface);}
}
}
| 39.307692 | 127 | 0.581213 | [
"MIT"
] | SharpKit/Cs2Java | Runtime/rt/java/net/NetworkInterface_1subIFs.cs | 511 | C# |
/*
* A C#.NET class to communicate with SICK SENSOR LMS1xx
*
* Author : beolabs.io / Benjamin Oms
* Update : 12/06/2017
* Github : https://github.com/beolabs-io/SICK-Sensor-LMS1XX
*
* --- MIT LICENCE ---
*
* Copyright (c) 2017 beolabs.io
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace BSICK.Sensors.LMS1xx
{
public class LMDScandataResult
{
public const byte StartMark = 0x02;
public const byte EndMark = 0x03;
public bool IsError;
public Exception ErrorException;
public byte[] RawData;
public String RawDataString;
public String CommandType;
public String Command;
public int? VersionNumber;
public int? DeviceNumber;
public int? SerialNumber;
public String DeviceStatus;
public int? TelegramCounter;
public int? ScanCounter;
public uint? TimeSinceStartup;
public uint? TimeOfTransmission;
public String StatusOfDigitalInputs;
public String StatusOfDigitalOutputs;
public int? Reserved;
public double? ScanFrequency;
public double? MeasurementFrequency;
public int? AmountOfEncoder;
public int? EncoderPosition;
public int? EncoderSpeed;
public int? AmountOf16BitChannels;
public String Content;
public String ScaleFactor;
public String ScaleFactorOffset;
public double? StartAngle;
public double? SizeOfSingleAngularStep;
public int? AmountOfData;
public List<double> DistancesData;
public static LMDScandataResult Parse(Stream br)
{
//if (br.ReadByte() != StartMark)
// throw new LMSBadDataException("StartMark not found");
var result = new LMDScandataResult();
while (true)
{
if (br.ReadChar() != StartMark)
return null;
if (br.ReadChar() != 's')
return null;
if (br.ReadChar() != 'R')
return null;
if (br.ReadChar() != 'A')
return null;
if (br.ReadChar() != ' ')
return null;
}
//rawData.Write
//result.CommandType = br.ReadWord();
//if (result.CommandType != "sRA")
//{
// br.Flush();
// return result;
//}
result.Command = br.ReadWord();
result.VersionNumber = br.ReadIntAsHex();
result.DeviceNumber = br.ReadIntAsHex();
result.SerialNumber = (int) br.ReadUIntAsHex();
result.DeviceStatus = $"{br.ReadWord()}-{br.ReadWord()}";
result.TelegramCounter = (int)br.ReadUIntAsHex(); // todo uint
result.ScanCounter = (int)br.ReadUIntAsHex();
result.TimeSinceStartup = br.ReadUIntAsHex() / 1000000;
result.TimeOfTransmission = br.ReadUIntAsHex() / 1000000;
result.StatusOfDigitalInputs = $"{br.ReadWord()}-{br.ReadWord()}";
result.StatusOfDigitalOutputs = $"{br.ReadWord()}-{br.ReadWord()}";
result.Reserved = br.ReadIntAsHex();
result.ScanFrequency = br.ReadIntAsHex() / 100d;
result.MeasurementFrequency = br.ReadIntAsHex() / 10d;
result.AmountOfEncoder = br.ReadIntAsHex();
if (result.AmountOfEncoder > 0)
{
result.EncoderPosition = br.ReadIntAsHex();
result.EncoderSpeed = br.ReadIntAsHex();
}
result.AmountOf16BitChannels = br.ReadIntAsHex();
result.Content = br.ReadWord();
result.ScaleFactor = br.ReadWord();
result.ScaleFactorOffset = br.ReadWord();
result.StartAngle = br.ReadIntAsHex() / 10000.0;
result.SizeOfSingleAngularStep = br.ReadUIntAsHex() / 10000.0;
result.AmountOfData = br.ReadIntAsHex();
result.DistancesData = br.ReadListAsHex(result.AmountOfData ?? 0, (x) => ((double)x) / 1000.0);
while (br.ReadByte() != EndMark);
//br.Flush();
result.IsError = false;
return result;
}
public static LMDScandataResult ParseContinious(byte[] data)
{
using var ms = new MemoryStream(data);
return ParseContinious(ms);
}
public static LMDScandataResult ParseContinious(Stream stream)
{
//if (br.ReadByte() != StartMark)
// throw new LMSBadDataException("StartMark not found");
var result = new LMDScandataResult();
while (true)
{
if (stream.ReadByte() != StartMark)
return null;
if (stream.ReadChar() != 's')
return null;
if (stream.ReadChar() != 'S')
return null;
if (stream.ReadChar() != 'N')
return null;
if (stream.ReadChar() != ' ')
return null;
break;
}
//result.CommandType = br.ReadWord();
//if (result.CommandType != "sRA")
//{
// br.Flush();
// return result;
//}
result.Command = stream.ReadWord();
result.VersionNumber = stream.ReadIntAsHex();
result.DeviceNumber = stream.ReadIntAsHex();
result.SerialNumber = (int)stream.ReadUIntAsHex();
result.DeviceStatus = $"{stream.ReadWord()}-{stream.ReadWord()}";
result.TelegramCounter = (int)stream.ReadUIntAsHex(); // todo uint
result.ScanCounter = (int)stream.ReadUIntAsHex();
result.TimeSinceStartup = stream.ReadUIntAsHex() /*/ 1000000*/;
result.TimeOfTransmission = stream.ReadUIntAsHex()/* / 1000000*/;
result.StatusOfDigitalInputs = $"{stream.ReadWord()}-{stream.ReadWord()}";
result.StatusOfDigitalOutputs = $"{stream.ReadWord()}-{stream.ReadWord()}";
result.Reserved = stream.ReadIntAsHex();
result.ScanFrequency = stream.ReadIntAsHex() / 100d;
result.MeasurementFrequency = stream.ReadIntAsHex() / 10d;
result.AmountOfEncoder = stream.ReadIntAsHex();
if (result.AmountOfEncoder > 0)
{
result.EncoderPosition = stream.ReadIntAsHex();
result.EncoderSpeed = stream.ReadIntAsHex();
}
result.AmountOf16BitChannels = stream.ReadIntAsHex();
result.Content = stream.ReadWord();
result.ScaleFactor = stream.ReadWord();
result.ScaleFactorOffset = stream.ReadWord();
result.StartAngle = stream.ReadIntAsHex() / 10000.0;
result.SizeOfSingleAngularStep = stream.ReadUIntAsHex() / 10000.0;
result.AmountOfData = stream.ReadIntAsHex();
result.DistancesData = stream.ReadListAsHex(result.AmountOfData ?? 0, (x) => ((double)x) / 1000.0);
var AmountOf8BitData1 = stream.ReadIntAsHex();
var Position = stream.ReadIntAsHex();
var Comment = stream.ReadIntAsHex();
var Time = stream.ReadIntAsHex();
var EventInfo = stream.ReadIntAsHex();
while (stream.ReadByte() != EndMark);
//br.Flush();
result.IsError = false;
return result;
}
public LMDScandataResult(byte[] rawData)
{
IsError = true;
ErrorException = null;
RawData = rawData;
RawDataString = Encoding.ASCII.GetString(rawData).Trim();
DistancesData = new List<double>();
CommandType = String.Empty;
Command = String.Empty;
VersionNumber = null;
DeviceNumber = null;
SerialNumber = null;
DeviceStatus = String.Empty;
TelegramCounter = null;
ScanCounter = null;
TimeSinceStartup = null;
TimeOfTransmission = null;
StatusOfDigitalInputs = String.Empty;
StatusOfDigitalOutputs = String.Empty;
Reserved = null;
ScanFrequency = null;
MeasurementFrequency = null;
AmountOfEncoder = null;
EncoderPosition = null;
EncoderSpeed = null;
AmountOf16BitChannels = null;
Content = String.Empty;
ScaleFactor = String.Empty;
ScaleFactorOffset = String.Empty;
StartAngle = null;
SizeOfSingleAngularStep = null;
AmountOfData = null;
}
public LMDScandataResult()
{
IsError = true;
ErrorException = null;
RawData = null ;
RawDataString = String.Empty;
DistancesData = null;
CommandType = String.Empty;
Command = String.Empty;
VersionNumber = null;
DeviceNumber = null;
SerialNumber = null;
DeviceStatus = String.Empty;
TelegramCounter = null;
ScanCounter = null;
TimeSinceStartup = null;
TimeOfTransmission = null;
StatusOfDigitalInputs = String.Empty;
StatusOfDigitalOutputs = String.Empty;
Reserved = null;
ScanFrequency = null;
MeasurementFrequency = null;
AmountOfEncoder = null;
EncoderPosition = null;
EncoderSpeed = null;
AmountOf16BitChannels = null;
Content = String.Empty;
ScaleFactor = String.Empty;
ScaleFactorOffset = String.Empty;
StartAngle = null;
SizeOfSingleAngularStep = null;
AmountOfData = null;
}
}
}
| 39.724014 | 111 | 0.572318 | [
"MIT"
] | dnik2000/SICK-Sensor-LMS1XX | LMDScandataResult.cs | 11,085 | C# |
namespace MyTested.HttpServer
{
using Builders;
using Servers;
using System;
using System.Net.Http;
/// <summary>
/// Starting point of the testing framework, which provides a way to specify the remote server to be tested.
/// </summary>
public static class MyHttpServer
{
/// <summary>
/// Configures global remote server.
/// </summary>
/// <param name="baseAddress">Base address to use for the requests.</param>
/// <returns>Server builder.</returns>
public static IServerBuilder IsLocatedAt(string baseAddress)
{
return IsLocatedAt(baseAddress, null);
}
/// <summary>
/// Configures global remote server.
/// </summary>
/// <param name="baseAddress">Base address to use for the requests.</param>
/// <param name="httpClientHandlerSetup">Action setting the HttpClientHandler options.</param>
/// <returns>Server builder.</returns>
public static IServerBuilder IsLocatedAt(string baseAddress, Action<HttpClientHandler> httpClientHandlerSetup)
{
RemoteServer.ConfigureGlobal(baseAddress, httpClientHandlerSetup);
return WorkingRemotely();
}
/// <summary>
/// Processes HTTP request on globally configured remote HTTP server.
/// </summary>
/// <returns>Server builder to set specific HTTP requests.</returns>
public static IServerBuilder WorkingRemotely()
{
if (RemoteServer.GlobalIsConfigured)
{
return new ServerTestBuilder(RemoteServer.GlobalClient);
}
throw new InvalidOperationException("No remote server is configured for this particular test case. Either call MyHttpServer.IsLocatedAt() to configure a new remote server or provide test specific base address.");
}
/// <summary>
/// Processes HTTP request on the remote HTTP server located at the provided base address.
/// </summary>
/// <param name="baseAddress">Base address to use for the requests.</param>
/// <returns>Server builder to set specific HTTP requests.</returns>
public static IServerBuilder WorkingRemotely(string baseAddress)
{
return WorkingRemotely(baseAddress, null);
}
/// <summary>
/// Processes HTTP request on the remote HTTP server located at the provided base address.
/// </summary>
/// <param name="baseAddress">Base address to use for the requests.</param>
/// <returns>Server builder to set specific HTTP requests.</returns>
public static IServerBuilder WorkingRemotely(string baseAddress, Action<HttpClientHandler> httpClientHandlerSetup)
{
return new ServerTestBuilder(RemoteServer.CreateNewClient(baseAddress, httpClientHandlerSetup), disposeClient: true);
}
}
}
| 42.085714 | 224 | 0.646979 | [
"MIT"
] | Magicianred/MyTested.HttpServer | src/MyTested.HttpServer/MyHttpServer.cs | 2,948 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Zeltex.Voxels;
using Zeltex.Util;
using System.IO;
/// <summary>
/// Run functions in the editor
/// </summary>
[ExecuteInEditMode]
public class EditorFunctions : MonoBehaviour
{
public bool IsRunCommand = false;
public string Command;
public List<string> MyCommands = new List<string>();
[Header("References")]
public VoxelManager MyDatabase;
// Update is called once per frame
void Update ()
{
if (IsRunCommand)
{
IsRunCommand = false;
/*Texture2D MyTexture = MyDatabase.MyMaterial.mainTexture as Texture2D;
// Encode texture into PNG
byte[] MyBytes = MyTexture.EncodeToPNG();
string FilePath = FileUtil.GetWorldFolderPath() + "TileMap.png";
File.WriteAllBytes(FilePath, MyBytes);*/
}
}
IEnumerator UploadPNG()
{
// We should only read the screen buffer after rendering is complete
yield return new WaitForEndOfFrame();
// Create a texture the size of the screen, RGB24 format
int width = Screen.width;
int height = Screen.height;
Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
// Encode texture into PNG
byte[] bytes = tex.EncodeToPNG();
Object.Destroy(tex);
// For testing purposes, also write to a file in the project folder
// File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
// Create a Web Form
WWWForm form = new WWWForm();
form.AddField("frameCount", Time.frameCount.ToString());
form.AddBinaryData("fileUpload", bytes);
// Upload to a cgi script
WWW w = new WWW("http://localhost/cgi-bin/env.cgi?post", form);
yield return w;
if (w.error != null)
{
Debug.Log(w.error);
}
else {
Debug.Log("Finished Uploading Screenshot");
}
}
}
| 29.216216 | 83 | 0.615634 | [
"Apache-2.0"
] | Deus0/Zeltexium | Assets/Scripts/Editor/EditorFunctions.cs | 2,164 | C# |
using Newtonsoft.Json;
using SamsungWatchGarage.Integration.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Action = SamsungWatchGarage.Integration.Models.Action;
namespace SamsungWatchGarage.Integration
{
public class MyQApi : IGarageApi
{
private string accountId;
private string token;
private List<Device> devices;
public MyQApi()
{
devices = new List<Device>();
}
public async Task<bool> Login(string email, string password)
{
if (string.IsNullOrEmpty(email))
{
throw new ArgumentNullException(nameof(email));
}
else if (string.IsNullOrEmpty(password))
{
throw new ArgumentNullException(nameof(email));
}
else
{
var json = JsonConvert.SerializeObject(new UserCredentials
{
Username = email,
Password = password
});
var data = new StringContent(json, Encoding.UTF8, "application/json");
var url = Constants.AuthUrl + "Login";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("MyQApplicationId", Constants.MyQApplicationId);
try
{
var response = await client.PostAsync(url, data);
response.EnsureSuccessStatusCode();
var result = JsonConvert.DeserializeObject<UserToken>(response.Content.ReadAsStringAsync().Result);
token = result.SecurityToken;
if (string.IsNullOrEmpty(token))
{
return false;
}
return true;
}
catch (Exception e)
{
return false;
}
}
}
public async Task<Device> GetDevice(string serialNumber)
{
if (devices.Count == 0)
{
GetDevices();
}
return devices.Where(x => x.SerialNumber == serialNumber).FirstOrDefault();
}
public async Task<List<Device>> GetDevices()
{
if (string.IsNullOrEmpty(accountId))
{
accountId = await GetAccountId();
}
var url = Constants.DeviceUrl + $"Accounts/{accountId}/Devices";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("MyQApplicationId", Constants.MyQApplicationId);
client.DefaultRequestHeaders.Add("SecurityToken", token);
try
{
var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
var result = JsonConvert.DeserializeObject<DeviceResponse>(response.Content.ReadAsStringAsync().Result);
devices = result.Items;
return devices;
}
catch (Exception e)
{
return new List<Device>();
}
}
public async Task<DoorState> GetDoorState(string serialNumber)
{
//door_state: opening, closed, open, closing
var state = await GetState(serialNumber, nameof(DoorState));
return (DoorState)Enum.Parse(typeof(DoorState), state);
}
public async Task<bool> SetDoorState(string serialNumber, string action)
{
return await SetDeviceState(serialNumber, action, Constants.DoorState);
}
private async Task<string> GetAccountId()
{
var url = Constants.AuthUrl + "My?expand=account";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("MyQApplicationId", Constants.MyQApplicationId);
client.DefaultRequestHeaders.Add("SecurityToken", token);
try
{
var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
var result = JsonConvert.DeserializeObject<AccountData>(response.Content.ReadAsStringAsync().Result);
return result.Account.Id;
}
catch (Exception e)
{
return string.Empty;
}
}
private async Task<bool> SetDeviceState(string serialNo, string action, string stateProp)
{
var url = Constants.DeviceUrl + $"Accounts/{accountId}/Devices/{serialNo}/Actions";
var client = new HttpClient();
client.DefaultRequestHeaders.Add("MyQApplicationId", Constants.MyQApplicationId);
client.DefaultRequestHeaders.Add("SecurityToken", token);
var json = JsonConvert.SerializeObject(new Action
{
ActionType = action
});
var data = new StringContent(json, Encoding.UTF8, "application/json");
try
{
var response = await client.PutAsync(url, data);
response.EnsureSuccessStatusCode();
devices = await GetDevices();
return true;
}
catch (Exception e)
{
return false;
}
}
private async Task<string> GetState(string serialNo, string stateProp)
{
var source = await GetDevice(serialNo);
var value = GetPropValue(source.State, stateProp);
return value.ToString();
}
public static object GetPropValue(object source, string propertyName)
{
var property = source.GetType().GetRuntimeProperties().FirstOrDefault(p => string.Equals(p.Name, propertyName, StringComparison.OrdinalIgnoreCase));
return property?.GetValue(source);
}
}
}
| 33.502762 | 160 | 0.549967 | [
"Apache-2.0"
] | asebak/samsung-galaxywatch3-myqgarage-app | GalaxyWatchGarage/GalaxyWatchGarage/Integration/MyQApi.cs | 6,066 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using TemplateSourceName.Models;
namespace TemplateSourceName.Pages.Account
{
[AllowAnonymous]
public class ConfirmEmailModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
public ConfirmEmailModel(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGetAsync(string userId, string code)
{
if (userId == null || code == null)
{
return RedirectToPage("/Index");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return NotFound($"Unable to load user with ID '{userId}'.");
}
code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
var result = await _userManager.ConfirmEmailAsync(user, code);
StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email.";
return Page();
}
}
}
| 30.75 | 119 | 0.647696 | [
"MIT"
] | IdentitySolution/SSO-Solution | template/TemplateSourceName/Pages/Account/ConfirmEmail.cshtml.cs | 1,478 | C# |
using System.Collections.Immutable;
using System.Text.RegularExpressions;
using Microsoft.Recognizers.Definitions.Arabic;
using Microsoft.Recognizers.Text.Number;
namespace Microsoft.Recognizers.Text.DateTime.Arabic
{
public class ArabicDurationExtractorConfiguration : BaseDateTimeOptionsConfiguration, IDurationExtractorConfiguration
{
public static readonly Regex DurationUnitRegex =
new Regex(DateTimeDefinitions.DurationUnitRegex, RegexFlags);
public static readonly Regex SuffixAndRegex =
new Regex(DateTimeDefinitions.SuffixAndRegex, RegexFlags);
public static readonly Regex DurationFollowedUnit =
new Regex(DateTimeDefinitions.DurationFollowedUnit, RegexFlags);
public static readonly Regex NumberCombinedWithDurationUnit =
new Regex(DateTimeDefinitions.NumberCombinedWithDurationUnit, RegexFlags);
public static readonly Regex AnUnitRegex =
new Regex(DateTimeDefinitions.AnUnitRegex, RegexFlags);
public static readonly Regex DuringRegex =
new Regex(DateTimeDefinitions.DuringRegex, RegexFlags);
public static readonly Regex AllRegex =
new Regex(DateTimeDefinitions.AllRegex, RegexFlags);
public static readonly Regex HalfRegex =
new Regex(DateTimeDefinitions.HalfRegex, RegexFlags);
public static readonly Regex ConjunctionRegex =
new Regex(DateTimeDefinitions.ConjunctionRegex, RegexFlags);
public static readonly Regex InexactNumberRegex =
new Regex(DateTimeDefinitions.InexactNumberRegex, RegexFlags);
public static readonly Regex InexactNumberUnitRegex =
new Regex(DateTimeDefinitions.InexactNumberUnitRegex, RegexFlags);
public static readonly Regex RelativeDurationUnitRegex =
new Regex(DateTimeDefinitions.RelativeDurationUnitRegex, RegexFlags);
public static readonly Regex DurationConnectorRegex =
new Regex(DateTimeDefinitions.DurationConnectorRegex, RegexFlags);
public static readonly Regex SpecialNumberUnitRegex = null;
public static readonly Regex MoreThanRegex =
new Regex(DateTimeDefinitions.MoreThanRegex, RegexFlags | RegexOptions.RightToLeft);
public static readonly Regex LessThanRegex =
new Regex(DateTimeDefinitions.LessThanRegex, RegexFlags | RegexOptions.RightToLeft);
private const RegexOptions RegexFlags = RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.RightToLeft;
public ArabicDurationExtractorConfiguration(IDateTimeOptionsConfiguration config)
: base(config)
{
var numOptions = NumberOptions.None;
if ((config.Options & DateTimeOptions.NoProtoCache) != 0)
{
numOptions = NumberOptions.NoProtoCache;
}
var numConfig = new BaseNumberOptionsConfiguration(config.Culture, numOptions);
CardinalExtractor = Number.Arabic.CardinalExtractor.GetInstance(numConfig);
UnitMap = DateTimeDefinitions.UnitMap.ToImmutableDictionary();
UnitValueMap = DateTimeDefinitions.UnitValueMap.ToImmutableDictionary();
}
public IExtractor CardinalExtractor { get; }
public IImmutableDictionary<string, string> UnitMap { get; }
public IImmutableDictionary<string, long> UnitValueMap { get; }
bool IDurationExtractorConfiguration.CheckBothBeforeAfter => DateTimeDefinitions.CheckBothBeforeAfter;
Regex IDurationExtractorConfiguration.FollowedUnit => DurationFollowedUnit;
Regex IDurationExtractorConfiguration.NumberCombinedWithUnit => NumberCombinedWithDurationUnit;
Regex IDurationExtractorConfiguration.AnUnitRegex => AnUnitRegex;
Regex IDurationExtractorConfiguration.DuringRegex => DuringRegex;
Regex IDurationExtractorConfiguration.AllRegex => AllRegex;
Regex IDurationExtractorConfiguration.HalfRegex => HalfRegex;
Regex IDurationExtractorConfiguration.SuffixAndRegex => SuffixAndRegex;
Regex IDurationExtractorConfiguration.ConjunctionRegex => ConjunctionRegex;
Regex IDurationExtractorConfiguration.InexactNumberRegex => InexactNumberRegex;
Regex IDurationExtractorConfiguration.InexactNumberUnitRegex => InexactNumberUnitRegex;
Regex IDurationExtractorConfiguration.RelativeDurationUnitRegex => RelativeDurationUnitRegex;
Regex IDurationExtractorConfiguration.DurationUnitRegex => DurationUnitRegex;
Regex IDurationExtractorConfiguration.DurationConnectorRegex => DurationConnectorRegex;
Regex IDurationExtractorConfiguration.SpecialNumberUnitRegex => SpecialNumberUnitRegex;
Regex IDurationExtractorConfiguration.MoreThanRegex => MoreThanRegex;
Regex IDurationExtractorConfiguration.LessThanRegex => LessThanRegex;
}
} | 41.923729 | 130 | 0.749343 | [
"MIT"
] | carbon/Recognizers-Text | .NET/Microsoft.Recognizers.Text.DateTime/Arabic/Extractors/ArabicDurationExtractorConfiguration.cs | 4,949 | C# |
using UnityEngine;
namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityCharacterController
{
[TaskCategory("Basic/CharacterController")]
[TaskDescription("Sets the step offset of the CharacterController. Returns Success.")]
public class SetStepOffset : Action
{
[Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")]
public SharedGameObject targetGameObject;
[Tooltip("The step offset of the CharacterController")]
public SharedFloat stepOffset;
private CharacterController characterController;
private GameObject prevGameObject;
public override void OnStart()
{
var currentGameObject = GetDefaultGameObject(targetGameObject.Value);
if (currentGameObject != prevGameObject) {
characterController = currentGameObject.GetComponent<CharacterController>();
prevGameObject = currentGameObject;
}
}
public override TaskStatus OnUpdate()
{
if (characterController == null) {
Debug.LogWarning("CharacterController is null");
return TaskStatus.Failure;
}
characterController.stepOffset = stepOffset.Value;
return TaskStatus.Success;
}
public override void OnReset()
{
targetGameObject = null;
stepOffset = 0;
}
}
} | 33.204545 | 99 | 0.638604 | [
"MIT"
] | Aver58/ColaFrameWork | Assets/3rd/Behavior Designer/Runtime/Basic Tasks/CharacterController/SetStepOffset.cs | 1,461 | C# |
using System;
namespace Lion.AbpPro.AuditLogs
{
public class GetAuditLogPageListOutput
{
public string ApplicationName { get; set; }
public Guid? UserId { get; set; }
public string UserName { get; set; }
public Guid? TenantId { get; set; }
public string TenantName { get; set; }
public Guid? ImpersonatorUserId { get; set; }
public Guid? ImpersonatorTenantId { get; set; }
public DateTime ExecutionTime { get; set; }
public int ExecutionDuration { get; set; }
public string ClientIpAddress { get; set; }
public string ClientName { get; set; }
public string ClientId { get; set; }
public string CorrelationId { get; set; }
public string BrowserInfo { get; set; }
public string HttpMethod { get; set; }
public string Url { get; set; }
public string Exceptions { get; set; }
public string Comments { get; set; }
public int? HttpStatusCode { get; set; }
}
} | 23.044444 | 55 | 0.599807 | [
"MIT"
] | 312977/abp-vnext-pro | aspnet-core/services/src/Lion.AbpPro.Application.Contracts/AuditLogs/GetAuditLogPageListOutput.cs | 1,037 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Umbraco.ModelsBuilder v8.5.3
//
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
using Umbraco.ModelsBuilder.Embedded;
namespace Our.Umbraco.Tables.Demo.Models
{
/// <summary>Image</summary>
[PublishedModel("Image")]
public partial class Image : PublishedContentModel
{
// helpers
#pragma warning disable 0109 // new is redundant
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.5.3")]
public new const string ModelTypeAlias = "Image";
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.5.3")]
public new const PublishedItemType ModelItemType = PublishedItemType.Media;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.5.3")]
public new static IPublishedContentType GetModelContentType()
=> PublishedModelUtility.GetModelContentType(ModelItemType, ModelTypeAlias);
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.5.3")]
public static IPublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Image, TValue>> selector)
=> PublishedModelUtility.GetModelPropertyType(GetModelContentType(), selector);
#pragma warning restore 0109
// ctor
public Image(IPublishedContent content)
: base(content)
{ }
// properties
///<summary>
/// Size: in bytes
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.5.3")]
[ImplementPropertyType("umbracoBytes")]
public long UmbracoBytes => this.Value<long>("umbracoBytes");
///<summary>
/// Type
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.5.3")]
[ImplementPropertyType("umbracoExtension")]
public string UmbracoExtension => this.Value<string>("umbracoExtension");
///<summary>
/// Upload image
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.5.3")]
[ImplementPropertyType("umbracoFile")]
public global::Umbraco.Core.PropertyEditors.ValueConverters.ImageCropperValue UmbracoFile => this.Value<global::Umbraco.Core.PropertyEditors.ValueConverters.ImageCropperValue>("umbracoFile");
///<summary>
/// Height: in pixels
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.5.3")]
[ImplementPropertyType("umbracoHeight")]
public int UmbracoHeight => this.Value<int>("umbracoHeight");
///<summary>
/// Width: in pixels
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.5.3")]
[ImplementPropertyType("umbracoWidth")]
public int UmbracoWidth => this.Value<int>("umbracoWidth");
}
}
| 38.072289 | 193 | 0.712342 | [
"Apache-2.0"
] | Mantus667/Our.Umbraco.Tables | samples/Our.Umbraco.Tables.Demo/App_Data/Models/Image.generated.cs | 3,160 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace OctreeDemo
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18 | 42 | 0.703704 | [
"MIT"
] | B3zaleel/helix-toolkit | Source/Examples/WPF.SharpDX/OctreeDemo/App.xaml.cs | 326 | C# |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android;
namespace CoBuster.Droid
{
[Activity(Label = "CoBuster", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
const int RequestLocationId = 0;
readonly string[] LocationPermissions =
{
Manifest.Permission.AccessCoarseLocation,
Manifest.Permission.AccessFineLocation
};
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.SetFlags("CollectionView_Experimental");
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
global::Xamarin.FormsMaps.Init(this, savedInstanceState);
global::Xamarin.Forms.FormsMaterial.Init(this,savedInstanceState);
LoadApplication(new App());
}
protected override void OnStart()
{
base.OnStart();
if ((int)Build.VERSION.SdkInt >= 23)
{
if (CheckSelfPermission(Manifest.Permission.AccessFineLocation) != Permission.Granted)
{
RequestPermissions(LocationPermissions, RequestLocationId);
}
else
{
// Permissions already granted - display a message.
}
}
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
} | 30.190476 | 180 | 0.761304 | [
"MIT"
] | CoVital-Project/CoBuster | src/CoBuster/CoBuster.Android/MainActivity.cs | 1,904 | 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("Interface")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Interface")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("f0eea7f3-26b3-41e1-83bd-5b5231086d23")]
// 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.432432 | 84 | 0.747292 | [
"MIT"
] | VanHakobyan/ISTC_Coding_School | ISTC.SecondStage.OOP/ISTC.SecondStage.OOP.Interface/Properties/AssemblyInfo.cs | 1,386 | C# |
using UnityEngine;
using System;
using System.Linq;
using System.Collections.Generic;
using Extensions;
namespace Modules.UI.TextColorTag
{
[Serializable]
public sealed class TextColorTagInfo
{
[SerializeField]
public string tag = null;
[SerializeField]
public Color color = Color.white;
}
public sealed class TextColorTagSetting : ScriptableObject
{
//----- params -----
//----- field -----
[SerializeField]
private TextColorTagInfo[] colorTagInfos = null;
//----- property -----
//----- method -----
public TextColorTagInfo[] GeTextColorTagInfos()
{
return colorTagInfos ?? (colorTagInfos = new TextColorTagInfo[0]);
}
}
}
| 20.473684 | 78 | 0.588689 | [
"MIT"
] | oTAMAKOo/UniModules | Scripts/Modules/UI/TextColorTag/TextColorTagSetting.cs | 780 | C# |
using System;
using Lab3sharp.TransportTypes;
namespace Lab3sharp.FactoryMethod
{
//The pattern Singleton is also used
class CarCreator : AbstractCreator
{
private static CarCreator instance;
private CarCreator() { }
public static CarCreator GetInstance()
{
if (instance == null)
instance = new CarCreator();
return instance;
}
public override Transport CreateTransport()
{
return new Car
{
Price = 100,
Speed = 60,
Volume = 50,
Distance = 0
};
}
public override Transport CreateTransport(Tuple<int, int, double> tuple, int dist)
{
return new Car
{
Volume = tuple.Item1,
Speed = tuple.Item2,
Price = tuple.Item3,
Distance = dist
};
}
}
}
| 22.976744 | 90 | 0.483806 | [
"MIT"
] | Vladislavhgtech/industrial-programming | lab3/Lab3sharp/FactoryMethod/CarCreator.cs | 990 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace WebMVC
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 31.03125 | 119 | 0.609768 | [
"MIT"
] | GabrielMelegaro/web-desenvolvimento-csharp | Startup.cs | 1,988 | C# |
using CryptoApisLibrary.DataTypes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CryptoApisLibrary.Tests.Blockchains.Transactions.GetInfoByTransactionId
{
[TestClass]
public class EtcMorden : BaseEthSimilarCoin
{
protected override NetworkCoin NetworkCoin { get; } = NetworkCoin.EtcMorden;
protected override string TransactionHash { get; } = Features.CorrectTransactionHash.EtcMorden;
}
} | 33.846154 | 103 | 0.777273 | [
"MIT"
] | Crypto-APIs/.NET-Library | CryptoApisLibrary.Tests/Blockchains/Transactions/GetInfoByTransactionId/EtcMorden.cs | 442 | C# |
using YJC.Toolkit.MetaData;
namespace YJC.Toolkit.Data
{
class TreeSelector : TableSelector
{
public TreeSelector(ITableScheme scheme, DbTreeDefinition treeDef, IDbDataSource source)
: base(new TreeScheme(scheme, treeDef), source)
{
SetFakeDelete(this, scheme);
}
public static void SetFakeDelete(TableSelector selector, ITableScheme scheme)
{
Tk5DataXml dataXml = scheme as Tk5DataXml;
if (dataXml != null)
selector.FakeDelete = dataXml.FakeDeleteInfo;
}
}
}
| 27.952381 | 96 | 0.626917 | [
"BSD-3-Clause"
] | madiantech/tkcore | Data/YJC.Toolkit.AdoData/Data/_Tree/TreeSelector.cs | 589 | C# |
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace LinqExpressionProjection.Test.Model
{
class ProjectsDbContext : DbContext
{
static SqliteConnection con = new SqliteConnection("DataSource=:memory:");
public DbSet<Project> Projects { get; set; }
public DbSet<Subproject> Subprojects { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
con.Open();
optionsBuilder.UseSqlite(con);
base.OnConfiguring(optionsBuilder);
}
}
}
| 27.130435 | 86 | 0.633013 | [
"MIT"
] | chrisevans9629/LINQ-Expression-Projection | LinqExpressionProjection.Test/Model/ProjectsDbContext.cs | 626 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace SirCachealot
{
public partial class MainWindow : Form
{
internal Controller controller;
private readonly List<string> gatedDetectorList = new List<string>()
{
"asymmetry",
"topProbeNoBackground",
"bottomProbeScaled",
"topProbe",
"bottomProbe",
"magnetometer",
"gnd",
"battery",
"rfCurrent",
"reflectedrf1Amplitude",
"reflectedrf2Amplitude",
"bottomProbeNoBackground"
};
private readonly List<string> pointDetectorList = new List<string>()
{
"MiniFlux1",
"MiniFlux2",
"MiniFlux3",
"PumpPD",
"ProbePD",
"NorthCurrent",
"SouthCurrent",
"PhaseLockFrequency",
"PhaseLockError"
};
public MainWindow()
{
InitializeComponent();
InitialiseGateListDataView();
}
private void InitialiseGateListDataView()
{
this.gateListDataView.AutoGenerateColumns = false;
DataGridViewComboBoxColumn col1 = new DataGridViewComboBoxColumn();
col1.DataPropertyName = "Detector";
col1.HeaderText = "Detector";
col1.DataSource = gatedDetectorList;
col1.ValueType = typeof(String);
this.gateListDataView.Columns.Add(col1);
DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
col2.DataPropertyName = "StartTime";
col2.HeaderText = "Start time (us)";
col2.ValueType = typeof(int);
this.gateListDataView.Columns.Add(col2);
DataGridViewTextBoxColumn col3 = new DataGridViewTextBoxColumn();
col3.DataPropertyName = "EndTime";
col3.HeaderText = "End time (us)";
col3.ValueType = typeof(int);
this.gateListDataView.Columns.Add(col3);
DataGridViewComboBoxColumn col4 = new DataGridViewComboBoxColumn();
col4.DataPropertyName = "Integrate";
col4.HeaderText = "Integrate?";
col4.DataSource = new List<bool>() { true, false };
col4.ValueType = typeof(bool);
this.gateListDataView.Columns.Add(col4);
this.gateListDataView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}
// choosing File->Exit is set to close the form.
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
// If the form closes, either from File->Exit, or by clicking the close
// box, then the controller is alerted, so that it can shut down.
private void formCloseHandler(object sender, FormClosingEventArgs e)
{
controller.Exit();
}
// this alerts the controller that the form is loaded and ready.
private void formLoadHandler(object sender, EventArgs e)
{
controller.MySQLInitialise();
controller.UIInitialise();
}
private void createToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.CreateDB();
}
internal void SetMemcachedStatsText(string p)
{
statsTextBox.Text = p;
}
private void selectToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.SelectDB();
}
public void AppendToLog(string txt)
{
logTextBox.BeginInvoke(new AppendTextDelegate(logTextBox.AppendText),
new object[] {txt + Environment.NewLine});
}
public void AppendToErrorLog(string txt)
{
errorLogTextBox.BeginInvoke(new AppendTextDelegate(errorLogTextBox.AppendText),
new object[] { txt + Environment.NewLine });
}
public void SetStatsText(string txt)
{
logTextBox.BeginInvoke(new AppendTextDelegate(SetStatsTextInternal),
new object[] { txt + Environment.NewLine });
}
public void PopulateGateConfigList(List<string> gateConfigNames)
{
gateConfigSelectionComboBox.DataSource = gateConfigNames;
}
public List<string> GetGateConfigList()
{
List<string> gateConfigList = new List<string>();
foreach(object item in gateConfigSelectionComboBox.Items)
{
gateConfigList.Add((string)item);
}
return gateConfigList;
}
public void AddGateListEntry(string detector, int startTime, int endTime, bool integrate)
{
if (gatedDetectorList.Contains(detector))
{
this.gateListDataView.Rows.Add(detector, startTime, endTime, integrate);
}
this.gateListDataView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}
public void ClearGateList()
{
this.gateListDataView.Rows.Clear();
}
public string GetGateConfigName()
{
return gateConfigSelectionComboBox.SelectedItem.ToString();
}
public string GetGateConfigNameTextBox()
{
return currentGateConfigNameTextBox.Text;
}
public void SelectGateConfig(string name)
{
if (gateConfigSelectionComboBox.Items.Contains(name))
{
gateConfigSelectionComboBox.SelectedItem = name;
}
}
public List<object[]> GetGateConfigFromDataView()
{
List<object[]> configData = new List<object[]>();
foreach (DataGridViewRow row in gateListDataView.Rows)
{
if (!row.IsNewRow)
{
object[] entry = new object[4];
int i = 0;
foreach (DataGridViewCell cell in row.Cells)
{
entry[i] = cell.Value;
i++;
}
configData.Add(entry);
}
}
return configData;
}
private void SetStatsTextInternal(string txt)
{
statsTextBox.Text = txt;
}
private delegate void AppendTextDelegate(String text);
private void test1ToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.Test1();
}
private void test2ToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.Test2();
}
private void loadGateSetToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.LoadGateSet();
}
private void gateConfigSelectionComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
controller.UpdateGateListInUI(gateConfigSelectionComboBox.SelectedItem.ToString());
currentGateConfigNameTextBox.Text = gateConfigSelectionComboBox.SelectedItem.ToString();
}
private void updateGatesButton_Click(object sender, EventArgs e)
{
controller.SaveCurrentGateConfig();
}
private void newGateConfigButton_Click(object sender, EventArgs e)
{
controller.NewGateConfig();
}
private void saveGateConfigSetToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.SaveGateSet();
}
private void addBlockToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.AddBlockFromMainWindow();
}
private void addGatedBlockToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.AddGatedBlockFromMainWindow();
}
}
}
| 31.851711 | 101 | 0.56106 | [
"MIT"
] | ColdMatter/EDMSuite | SirCachealot/MainWindow.cs | 8,377 | C# |
//-----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//-----------------------------------------------------------------------'r'n
namespace HR.TA.ScheduleService.UnitTest.Business
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using HR.TA.Common.Base.ServiceContext;
using HR.TA.Common.Provisioning.Entities.FalconEntities.Attract;
using HR.TA.ScheduleService.BusinessLibrary.Business.V1;
using HR.TA.ScheduleService.BusinessLibrary.Interface;
using HR.TA.ScheduleService.BusinessLibrary.Notification;
using HR.TA.ScheduleService.BusinessLibrary.Providers;
using HR.TA.ScheduleService.Contracts;
using HR.TA.ScheduleService.Contracts.V1;
using HR.TA.ScheduleService.Data.DataProviders;
using HR.TA.ScheduleService.FalconData.Query;
using HR.TA.ServicePlatform.Configuration;
using HR.TA.ServicePlatform.Context;
using HR.TA.ServicePlatform.Tracing;
using HR.TA.Talent.FalconEntities.Attract.Conference;
[TestClass]
public class CreateScheduleManagerTest
{
private Mock<IScheduleQuery> scheduleQueryMock;
private FalconQuery falconQuery;
private Mock<IFalconQueryClient> falconQueryClientMock;
private Mock<ILogger<FalconQuery>> falconLoggerMock;
private Mock<IServiceBusHelper> serviceBusHelperMock;
private Mock<IGraphSubscriptionManager> graphSubscriptionManagerMock;
private Mock<IEmailClient> emailClientMock;
private Mock<IEmailHelper> emailHelperMock;
private Mock<IOutlookProvider> outlookProviderMock;
private Mock<INotificationClient> notificationClientMock;
private Mock<ILogger<ScheduleManager>> loggerMock;
private ILoggerFactory loggerFactory = new LoggerFactory();
private Mock<IInternalsProvider> internalsProvider;
private Mock<IUserDetailsProvider> userDetailsProviderMock;
private Mock<IHCMServiceContext> contextMock;
private Mock<IConfigurationManager> configMock;
[TestInitialize]
public void BeforEach()
{
this.contextMock = new Mock<IHCMServiceContext>();
this.scheduleQueryMock = new Mock<IScheduleQuery>();
this.falconQueryClientMock = new Mock<IFalconQueryClient>();
this.falconLoggerMock = new Mock<ILogger<FalconQuery>>();
this.falconQuery = new FalconQuery(this.falconQueryClientMock.Object, this.falconLoggerMock.Object);
this.serviceBusHelperMock = new Mock<IServiceBusHelper>();
this.graphSubscriptionManagerMock = new Mock<IGraphSubscriptionManager>();
this.outlookProviderMock = new Mock<IOutlookProvider>();
this.emailClientMock = new Mock<IEmailClient>();
this.notificationClientMock = new Mock<INotificationClient>();
this.emailHelperMock = new Mock<IEmailHelper>();
this.loggerMock = new Mock<ILogger<ScheduleManager>>();
this.internalsProvider = new Mock<IInternalsProvider>();
this.userDetailsProviderMock = new Mock<IUserDetailsProvider>();
this.configMock = new Mock<IConfigurationManager>();
TraceSourceMeta.LoggerFactory = this.loggerFactory;
}
/// <summary>
/// CreateScheduleTest
/// </summary>
[TestMethod]
public void CreateScheduleTestWithNullInputs()
{
var logger = TraceSourceMeta.LoggerFactory.CreateLogger<ScheduleManager>();
logger.ExecuteRoot(
new RootExecutionContext
{
SessionId = Guid.NewGuid(),
RootActivityId = Guid.NewGuid(),
},
TestActivityType.Instance,
() =>
{
var scheduleManager = this.GetScheduleManagerInstance();
var exception = scheduleManager.CreateSchedule(null, string.Empty).Exception;
Assert.IsInstanceOfType(exception.InnerException, typeof(InvalidRequestDataValidationException));
});
}
/// <summary>
/// CreateScheduleTest
/// </summary>
[TestMethod]
public void CreateScheduleTestWithInValidInputs()
{
MeetingInfo meetingInfo = new MeetingInfo();
meetingInfo.Id = Guid.NewGuid().ToString();
var logger = TraceSourceMeta.LoggerFactory.CreateLogger<ScheduleManager>();
logger.ExecuteRoot(
new RootExecutionContext
{
SessionId = Guid.NewGuid(),
RootActivityId = Guid.NewGuid(),
},
TestActivityType.Instance,
() =>
{
var scheduleManager = this.GetScheduleManagerInstance();
var result = scheduleManager.CreateSchedule(meetingInfo, "12345");
Assert.IsNotNull(result);
Assert.IsTrue(result.IsCompleted);
});
}
/// <summary>
/// CreateScheduleTest
/// </summary>
[TestMethod]
public void CreateScheduleTestWithValidInputs()
{
MeetingInfo meetingInfo = new MeetingInfo();
meetingInfo.Id = Guid.NewGuid().ToString();
var logger = TraceSourceMeta.LoggerFactory.CreateLogger<ScheduleManager>();
string jobId = Guid.NewGuid().ToString();
string userId = Guid.NewGuid().ToString();
JobApplication jobApplication = new JobApplication()
{
JobApplicationID = jobId,
JobApplicationParticipants = new List<JobApplicationParticipant>()
{
new JobApplicationParticipant()
{
Role = TalentEntities.Enum.JobParticipantRole.Contributor,
OID = userId
}
}
};
logger.ExecuteRoot(
new RootExecutionContext
{
SessionId = Guid.NewGuid(),
RootActivityId = Guid.NewGuid(),
},
TestActivityType.Instance,
() =>
{
var scheduleManager = this.GetScheduleManagerInstance();
this.scheduleQueryMock.Setup(a => a.GetJobApplication(It.IsAny<string>())).Returns(Task.FromResult(jobApplication));
var result = scheduleManager.CreateSchedule(meetingInfo, jobId);
Assert.IsNotNull(result);
Assert.IsTrue(result.IsCompleted);
});
}
/// <summary>
/// UpdateScheduleTest
/// </summary>
[TestMethod]
public void UpdateScheduleTestWithNullInputs()
{
var logger = TraceSourceMeta.LoggerFactory.CreateLogger<ScheduleManager>();
logger.ExecuteRoot(
new RootExecutionContext
{
SessionId = Guid.NewGuid(),
RootActivityId = Guid.NewGuid(),
},
TestActivityType.Instance,
() =>
{
var scheduleManager = this.GetScheduleManagerInstance();
var exception = scheduleManager.UpdateSchedule(null).Exception;
Assert.IsInstanceOfType(exception.InnerException, typeof(InvalidRequestDataValidationException));
});
}
/// <summary>
/// UpdateScheduleTest
/// </summary>
[TestMethod]
public void UpdateScheduleTestWithValidInputs()
{
MeetingInfo meetingInfo = new MeetingInfo();
meetingInfo.Id = Guid.NewGuid().ToString();
meetingInfo.MeetingDetails = new System.Collections.Generic.List<MeetingDetails>()
{
new MeetingDetails()
{
CalendarEventId = Guid.NewGuid().ToString(),
Subject = "Test",
UtcStart = DateTime.Now,
UtcEnd = DateTime.UtcNow,
},
};
meetingInfo.UserGroups = new UserGroup()
{
FreeBusyTimeId = Guid.NewGuid().ToString(),
Users = new System.Collections.Generic.List<GraphPerson>()
{
new GraphPerson()
{
Name = "Test",
Email = "test@microsoft.com",
Id = Guid.NewGuid().ToString(),
},
new GraphPerson()
{
Name = "Test",
Email = "test@microsoft.com",
Id = Guid.NewGuid().ToString(),
}
},
};
var logger = TraceSourceMeta.LoggerFactory.CreateLogger<ScheduleManager>();
logger.ExecuteRoot(
new RootExecutionContext
{
SessionId = Guid.NewGuid(),
RootActivityId = Guid.NewGuid(),
},
TestActivityType.Instance,
() =>
{
this.scheduleQueryMock.Setup(a => a.GetScheduleByScheduleId(It.IsAny<string>())).Returns(Task.FromResult(meetingInfo));
var scheduleManager = this.GetScheduleManagerInstance();
var result = scheduleManager.UpdateSchedule(meetingInfo);
Assert.IsNotNull(result);
Assert.IsTrue(result.IsCompleted);
});
}
/// <summary>
/// UpdateScheduleTest
/// </summary>
[TestMethod]
public void UpdateScheduleTestWithValidTimeInput()
{
MeetingInfo meetingInfo = new MeetingInfo();
meetingInfo.Id = Guid.NewGuid().ToString();
meetingInfo.MeetingDetails = new System.Collections.Generic.List<MeetingDetails>()
{
new MeetingDetails()
{
CalendarEventId = Guid.NewGuid().ToString(),
Subject = "Test",
UtcStart = DateTime.Now,
UtcEnd = DateTime.UtcNow,
},
};
meetingInfo.UserGroups = new UserGroup()
{
FreeBusyTimeId = Guid.NewGuid().ToString(),
Users = new System.Collections.Generic.List<GraphPerson>()
{
new GraphPerson()
{
Name = "Test",
Email = "test@microsoft.com",
Id = Guid.NewGuid().ToString(),
},
new GraphPerson()
{
Name = "Test",
Email = "test@microsoft.com",
Id = Guid.NewGuid().ToString(),
}
},
};
var logger = TraceSourceMeta.LoggerFactory.CreateLogger<ScheduleManager>();
logger.ExecuteRoot(
new RootExecutionContext
{
SessionId = Guid.NewGuid(),
RootActivityId = Guid.NewGuid(),
},
TestActivityType.Instance,
() =>
{
this.scheduleQueryMock.Setup(a => a.GetScheduleByScheduleId(It.IsAny<string>())).Returns(Task.FromResult(meetingInfo));
var scheduleManager = this.GetScheduleManagerInstance();
MeetingInfo meeting = new MeetingInfo();
meeting.Id = meetingInfo.Id;
meeting.MeetingDetails = new System.Collections.Generic.List<MeetingDetails>()
{
new MeetingDetails()
{
CalendarEventId = Guid.NewGuid().ToString(),
Subject = "Test",
UtcStart = DateTime.Now,
UtcEnd = DateTime.UtcNow,
},
};
var result = scheduleManager.UpdateSchedule(meeting);
Assert.IsNotNull(result);
Assert.IsTrue(result.IsCompleted);
});
}
/// <summary>
/// UpdateScheduleTest
/// </summary>
[TestMethod]
public void UpdateScheduleTestWithValidParticipantsInput()
{
MeetingInfo meetingInfo = new MeetingInfo();
meetingInfo.Id = Guid.NewGuid().ToString();
meetingInfo.MeetingDetails = new System.Collections.Generic.List<MeetingDetails>()
{
new MeetingDetails()
{
CalendarEventId = Guid.NewGuid().ToString(),
Subject = "Test",
UtcStart = DateTime.Now,
UtcEnd = DateTime.UtcNow,
},
};
meetingInfo.UserGroups = new UserGroup()
{
FreeBusyTimeId = Guid.NewGuid().ToString(),
Users = new System.Collections.Generic.List<GraphPerson>()
{
new GraphPerson()
{
Name = "Test",
Email = "test@microsoft.com",
Id = Guid.NewGuid().ToString(),
},
new GraphPerson()
{
Name = "Test4",
Email = "test4@microsoft.com",
Id = Guid.NewGuid().ToString(),
}
},
};
var logger = TraceSourceMeta.LoggerFactory.CreateLogger<ScheduleManager>();
logger.ExecuteRoot(
new RootExecutionContext
{
SessionId = Guid.NewGuid(),
RootActivityId = Guid.NewGuid(),
},
TestActivityType.Instance,
() =>
{
this.scheduleQueryMock.Setup(a => a.GetScheduleByScheduleId(It.IsAny<string>())).Returns(Task.FromResult(meetingInfo));
var scheduleManager = this.GetScheduleManagerInstance();
MeetingInfo meeting = new MeetingInfo();
meeting.Id = meetingInfo.Id;
meeting.MeetingDetails = new System.Collections.Generic.List<MeetingDetails>()
{
new MeetingDetails()
{
CalendarEventId = Guid.NewGuid().ToString(),
Subject = "Test",
UtcStart = meetingInfo.MeetingDetails[0].UtcStart,
UtcEnd = meetingInfo.MeetingDetails[0].UtcEnd
},
};
meeting.UserGroups = new UserGroup()
{
FreeBusyTimeId = Guid.NewGuid().ToString(),
Users = new System.Collections.Generic.List<GraphPerson>()
{
new GraphPerson()
{
Name = "Test",
Email = "test3@microsoft.com",
Id = Guid.NewGuid().ToString(),
}
},
};
var result = scheduleManager.UpdateSchedule(meeting);
Assert.IsNotNull(result);
Assert.IsTrue(result.IsCompleted);
});
}
/// <summary>
/// UpdateScheduleTest
/// </summary>
[TestMethod]
public void UpdateScheduleTestWithValidParticipants2Input()
{
MeetingInfo meetingInfo = new MeetingInfo();
meetingInfo.Id = Guid.NewGuid().ToString();
meetingInfo.MeetingDetails = new System.Collections.Generic.List<MeetingDetails>()
{
new MeetingDetails()
{
CalendarEventId = Guid.NewGuid().ToString(),
Subject = "Test",
UtcStart = DateTime.Now,
UtcEnd = DateTime.UtcNow,
},
};
meetingInfo.UserGroups = new UserGroup()
{
FreeBusyTimeId = Guid.NewGuid().ToString(),
Users = new System.Collections.Generic.List<GraphPerson>()
{
new GraphPerson()
{
Name = "Test",
Email = "test@microsoft.com",
Id = Guid.NewGuid().ToString(),
},
new GraphPerson()
{
Name = "Test4",
Email = "test4@microsoft.com",
Id = Guid.NewGuid().ToString(),
}
},
};
var logger = TraceSourceMeta.LoggerFactory.CreateLogger<ScheduleManager>();
logger.ExecuteRoot(
new RootExecutionContext
{
SessionId = Guid.NewGuid(),
RootActivityId = Guid.NewGuid(),
},
TestActivityType.Instance,
() =>
{
this.scheduleQueryMock.Setup(a => a.GetScheduleByScheduleId(It.IsAny<string>())).Returns(Task.FromResult(meetingInfo));
var scheduleManager = this.GetScheduleManagerInstance();
MeetingInfo meeting = new MeetingInfo();
meeting.Id = meetingInfo.Id;
meeting.MeetingDetails = new System.Collections.Generic.List<MeetingDetails>()
{
new MeetingDetails()
{
CalendarEventId = Guid.NewGuid().ToString(),
Subject = "Test",
UtcStart = meetingInfo.MeetingDetails[0].UtcStart,
UtcEnd = meetingInfo.MeetingDetails[0].UtcEnd
},
};
meeting.UserGroups = new UserGroup()
{
FreeBusyTimeId = Guid.NewGuid().ToString(),
Users = new System.Collections.Generic.List<GraphPerson>()
{
new GraphPerson()
{
Name = "Test",
Email = "test4@microsoft.com",
Id = Guid.NewGuid().ToString(),
},
new GraphPerson()
{
Name = "Test4",
Email = "test3@microsoft.com",
Id = Guid.NewGuid().ToString(),
}
},
};
var result = scheduleManager.UpdateSchedule(meeting);
Assert.IsNotNull(result);
Assert.IsTrue(result.IsCompleted);
});
}
/// <summary>
/// UpdateScheduleTest
/// </summary>
[TestMethod]
public void UpdateScheduleTestWithInValidInputs()
{
MeetingInfo result = null;
MeetingInfo meetingInfo = new MeetingInfo();
meetingInfo.Id = Guid.NewGuid().ToString();
var logger = TraceSourceMeta.LoggerFactory.CreateLogger<ScheduleManager>();
logger.ExecuteRoot(
new RootExecutionContext
{
SessionId = Guid.NewGuid(),
RootActivityId = Guid.NewGuid(),
},
TestActivityType.Instance,
() =>
{
this.scheduleQueryMock.Setup(a => a.GetScheduleByScheduleId(It.IsAny<string>())).Returns(Task.FromResult(result));
var scheduleManager = this.GetScheduleManagerInstance();
var exception = scheduleManager.UpdateSchedule(meetingInfo).Exception;
Assert.IsInstanceOfType(exception.InnerException, typeof(InvalidRequestDataValidationException));
});
}
private ScheduleManager GetScheduleManagerInstance()
{
return new ScheduleManager(this.contextMock.Object, this.outlookProviderMock.Object, this.scheduleQueryMock.Object, this.falconQuery, this.serviceBusHelperMock.Object, this.graphSubscriptionManagerMock.Object, this.emailClientMock.Object, this.notificationClientMock.Object, this.emailHelperMock.Object, this.internalsProvider.Object, this.userDetailsProviderMock.Object, this.configMock.Object, this.loggerMock.Object);
}
}
}
| 39.852399 | 432 | 0.499769 | [
"MIT"
] | QPC-database/msrecruit-scheduling-engine | schedule-service/HR-TA-ScheduleService/HR.TA.ScheduleService.UnitTest/Business/CreateScheduleManagerTest.cs | 21,600 | C# |
/*<FILE_LICENSE>
* NFX (.NET Framework Extension) Unistack Library
* Copyright 2003-2014 IT Adapter Inc / 2015 Aum Code LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
</FILE_LICENSE>*/
/* NFX by ITAdapter
* Originated: 2006.01
* Revision: NFX 1.0 2013.12.18
* Author: Denis Latushkin<dxwizard@gmail.com>
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using NFX;
using NFX.Environment;
using System.Collections;
namespace NFX.Collections
{
/// <summary>
/// Provides bit array with automatic resizing
/// </summary>
public class BitList: IEquatable<BitList>
{
#region .ctor
public BitList(int initSize = 0)
{
m_BitArray = new BitArray(initSize);
m_Size = initSize;
}
#endregion
#region Pvt/Prot/Int Fields
private BitArray m_BitArray;
private int m_Size;
#endregion
#region Properties
public int Size { get { return m_Size; } }
public int ByteSize { get { return (Size + 7) >> 3; } }
public bool this[int i]
{
get { return m_BitArray[i]; }
set { m_BitArray[i] = value; }
}
#endregion
#region Public
public void AppendBit(bool bit)
{
ensureCapacity(++m_Size);
m_BitArray[m_Size-1] = bit;
}
public void AppendBits(int value, int numBits)
{
if (numBits < 0 || numBits >= 8 * sizeof(int))
throw new NFXException(StringConsts.ARGUMENT_ERROR + GetType().Name + ".AppendBits(numBits>=0|<8*sizeof(int))");
ensureCapacity(m_Size + numBits);
for (int leftBitIndex = numBits; leftBitIndex > 0; leftBitIndex--)
{
int bitValue = (value >> (leftBitIndex - 1)) & 0x01;
AppendBit(bitValue == 1);
}
}
public void AppendBitList(BitList other)
{
ensureCapacity( m_Size + other.Size);
for (int i = 0; i < other.m_Size; i++)
AppendBit(other.m_BitArray[i]);
}
public void Xor(BitList other)
{
if (m_BitArray.Length != other.m_BitArray.Length)
throw new NFXException(StringConsts.ARGUMENT_ERROR + GetType().Name + ".Xor(other.Length!=this.Length)");
m_BitArray.Xor(other.m_BitArray);
}
public void GetBytes(byte[] buf, int bitOffset, int offset, int numBytes)
{
for (int i = 0; i < numBytes; i++)
{
int theByte = 0;
for (int j = 0; j < 8; j++)
{
if (this[bitOffset])
{
theByte |= 1 << (7 - j);
}
bitOffset++;
}
buf[offset + i] = (byte)theByte;
}
}
#endregion
#region Protected
public override string ToString()
{
StringBuilder b = new StringBuilder();
for (int i = 0; i < m_Size; i++)
{
if (i > 0 && i % 8 == 0)
b.Append(' ');
bool elem = m_BitArray[i];
b.Append(elem ? '1' : '0');
}
return b.ToString();
}
public override int GetHashCode()
{
return m_BitArray.GetHashCode();
}
public bool Equals(BitList otherObj)
{
return m_BitArray.Equals( otherObj.m_BitArray);
}
#endregion
#region .pvt. impl.
private void ensureCapacity(int size)
{
if (size >= m_BitArray.Length)
{
int newLength = 1 << (int)Math.Ceiling( Math.Log(size, 2));
m_BitArray.Length = newLength;
}
}
#endregion
}//class
}
| 24.693182 | 123 | 0.554533 | [
"Apache-2.0"
] | PavelTorgashov/nfx | Source/NFX/Collections/BitList.cs | 4,346 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ecr-2015-09-21.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ECR.Model
{
/// <summary>
/// The manifest list is referencing an image that does not exist.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class ReferencedImagesNotFoundException : AmazonECRException
{
/// <summary>
/// Constructs a new ReferencedImagesNotFoundException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public ReferencedImagesNotFoundException(string message)
: base(message) {}
/// <summary>
/// Construct instance of ReferencedImagesNotFoundException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public ReferencedImagesNotFoundException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of ReferencedImagesNotFoundException
/// </summary>
/// <param name="innerException"></param>
public ReferencedImagesNotFoundException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of ReferencedImagesNotFoundException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ReferencedImagesNotFoundException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of ReferencedImagesNotFoundException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ReferencedImagesNotFoundException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the ReferencedImagesNotFoundException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected ReferencedImagesNotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 48.903226 | 179 | 0.671504 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ECR/Generated/Model/ReferencedImagesNotFoundException.cs | 6,064 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using Microsoft.MixedReality.Toolkit.WindowsDevicePortal;
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Build.Editor
{
public static class UwpBuildDeployPreferences
{
/// <summary>
/// The minimum Windows SDK that must be present on the build machine in order
/// for a build to be successful.
/// </summary>
/// <remarks>
/// This controls the version of the Windows SDK that is build against on the local
/// machine, NOT the version of the OS that must be present on the device that
/// the built application is deployed to (this other aspect is controlled by
/// MIN_PLATFORM_VERSION)
/// </remarks>
public static Version MIN_SDK_VERSION = new Version("10.0.18362.0");
/// <summary>
/// The minimum version of the OS that must exist on the device that the application
/// is deployed to.
/// </summary>
/// <remarks>
/// This is intentionally set to a very low version, so that the application can be
/// deployed to variety of different devices which may be on older OS versions.
/// </remarks>
public static Version MIN_PLATFORM_VERSION = new Version("10.0.10240.0");
private const string EDITOR_PREF_BUILD_CONFIG = "BuildDeployWindow_BuildConfig";
private const string EDITOR_PREF_PLATFORM_TOOLSET = "BuildDeployWindow_PlatformToolset";
private const string EDITOR_PREF_FORCE_REBUILD = "BuildDeployWindow_ForceRebuild";
private const string EDITOR_PREF_CONNECT_INFOS = "BuildDeployWindow_DeviceConnections";
private const string EDITOR_PREF_FULL_REINSTALL = "BuildDeployWindow_FullReinstall";
private const string EDITOR_PREF_USE_SSL = "BuildDeployWindow_UseSSL";
private const string EDITOR_PREF_PROCESS_ALL = "BuildDeployWindow_ProcessAll";
private const string EDITOR_PREF_GAZE_INPUT_CAPABILITY_ENABLED = "BuildDeployWindow_GazeInputCapabilityEnabled";
private const string EDITOR_PREF_MULTICORE_APPX_BUILD_ENABLED = "BuildDeployWindow_MulticoreAppxBuildEnabled";
private const string EDITOR_PREF_RESEARCH_MODE_CAPABILITY_ENABLED = "BuildDeployWindow_ResearchModeCapabilityEnabled";
private const string EDITOR_PREF_ALLOW_UNSAFE_CODE = "BuildDeployWindow_AllowUnsafeCode";
/// <summary>
/// The current Build Configuration. (Debug, Release, or Master)
/// </summary>
public static string BuildConfig
{
get => EditorPreferences.Get(EDITOR_PREF_BUILD_CONFIG, "master");
set => EditorPreferences.Set(EDITOR_PREF_BUILD_CONFIG, value.ToLower());
}
/// <summary>
/// The current Platform Toolset. (Solution, v141, or v142)
/// </summary>
public static string PlatformToolset
{
get => EditorPreferences.Get(EDITOR_PREF_PLATFORM_TOOLSET, string.Empty);
set => EditorPreferences.Set(EDITOR_PREF_PLATFORM_TOOLSET, value.ToLower());
}
/// <summary>
/// Current setting to force rebuilding the appx.
/// </summary>
public static bool ForceRebuild
{
get => EditorPreferences.Get(EDITOR_PREF_FORCE_REBUILD, false);
set => EditorPreferences.Set(EDITOR_PREF_FORCE_REBUILD, value);
}
/// <summary>
/// Current setting to fully uninstall and reinstall the appx.
/// </summary>
public static bool FullReinstall
{
get => EditorPreferences.Get(EDITOR_PREF_FULL_REINSTALL, true);
set => EditorPreferences.Set(EDITOR_PREF_FULL_REINSTALL, value);
}
/// <summary>
/// The current device portal connections.
/// </summary>
public static string DevicePortalConnections
{
get => EditorPreferences.Get(
EDITOR_PREF_CONNECT_INFOS,
JsonUtility.ToJson(
new DevicePortalConnections(
new DeviceInfo("127.0.0.1", string.Empty, string.Empty, "Local Machine"))));
set => EditorPreferences.Set(EDITOR_PREF_CONNECT_INFOS, value);
}
/// <summary>
/// Current setting to use Single Socket Layer connections to the device portal.
/// </summary>
public static bool UseSSL
{
get => EditorPreferences.Get(EDITOR_PREF_USE_SSL, true);
set => EditorPreferences.Set(EDITOR_PREF_USE_SSL, value);
}
/// <summary>
/// Current setting to target all the devices registered to the build window.
/// </summary>
public static bool TargetAllConnections
{
get => EditorPreferences.Get(EDITOR_PREF_PROCESS_ALL, false);
set => EditorPreferences.Set(EDITOR_PREF_PROCESS_ALL, value);
}
/// <summary>
/// If true, the 'Gaze Input' capability will be added to the AppX manifest
/// after the Unity build.
/// </summary>
public static bool GazeInputCapabilityEnabled
{
get => EditorPreferences.Get(EDITOR_PREF_GAZE_INPUT_CAPABILITY_ENABLED, false);
set => EditorPreferences.Set(EDITOR_PREF_GAZE_INPUT_CAPABILITY_ENABLED, value);
}
/// <summary>
/// If true, the appx will be built with multicore support enabled in the
/// MSBuild process.
/// </summary>
public static bool MulticoreAppxBuildEnabled
{
get => EditorPreferences.Get(EDITOR_PREF_MULTICORE_APPX_BUILD_ENABLED, false);
set => EditorPreferences.Set(EDITOR_PREF_MULTICORE_APPX_BUILD_ENABLED, value);
}
/// <summary>
/// Current setting to modify 'Package.appxmanifest' file for sensor access.
/// </summary>
public static bool ResearchModeCapabilityEnabled
{
get => EditorPreferences.Get(EDITOR_PREF_RESEARCH_MODE_CAPABILITY_ENABLED, false);
set => EditorPreferences.Set(EDITOR_PREF_RESEARCH_MODE_CAPABILITY_ENABLED, value);
}
/// <summary>
/// Current setting to modify 'Assembly-CSharp.csproj' file to allow unsafe code.
/// </summary>
public static bool AllowUnsafeCode
{
get => EditorPreferences.Get(EDITOR_PREF_ALLOW_UNSAFE_CODE, false);
set => EditorPreferences.Set(EDITOR_PREF_ALLOW_UNSAFE_CODE, value);
}
}
} | 45.361842 | 127 | 0.638579 | [
"MIT"
] | ForrestTrepte/azure-remote-rendering | Unity/AzureRemoteRenderingShowcase/arr-showcase-app/Assets/MixedRealityToolkit/Utilities/BuildAndDeploy/UwpBuildDeployPreferences.cs | 6,897 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// KeyInfoTest.cs - Test Cases for KeyInfo
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using Xunit;
namespace System.Security.Cryptography.Xml.Tests
{
public class KeyInfoTest
{
private KeyInfo info;
public KeyInfoTest()
{
info = new KeyInfo();
}
[Fact]
public void EmptyKeyInfo()
{
Assert.Equal("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />", (info.GetXml().OuterXml));
Assert.Equal(0, info.Count);
}
[Fact]
public void KeyInfoName()
{
KeyInfoName name = new KeyInfoName();
name.Value = "Mono::";
info.AddClause(name);
Assert.Equal("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyName>Mono::</KeyName></KeyInfo>", (info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
[Fact]
public void KeyInfoNode()
{
string test = "<Test>KeyInfoNode</Test>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(test);
KeyInfoNode node = new KeyInfoNode(doc.DocumentElement);
info.AddClause(node);
Assert.Equal("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><Test xmlns=\"\">KeyInfoNode</Test></KeyInfo>", (info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
private static string dsaP = "rjxsMU368YOCTQejWkiuO9e/vUVwkLtq1jKiU3TtJ53hBJqjFRuTa228vZe+BH2su9RPn/vYFWfQDv6zgBYe3eNdu4Afw+Ny0FatX6dl3E77Ra6Tsd3MmLXBiGSQ1mMNd5G2XQGpbt9zsGlUaexXekeMLxIufgfZLwYp67M+2WM=";
private static string dsaQ = "tf0K9rMyvUrU4cIkwbCrDRhQAJk=";
private static string dsaG = "S8Z+1pGCed00w6DtVcqZLKjfqlCJ7JsugEFIgSy/Vxtu9YGCMclV4ijGEbPo/jU8YOSMuD7E9M7UaopMRcmKQjoKZzoJjkgVFP48Ohxl1f08lERnButsxanx3+OstFwUGQ8XNaGg3KrIoZt1FUnfxN3RHHTvVhjzNSHxMGULGaU=";
private static string dsaY = "LnrxxRGLYeV2XLtK3SYz8RQHlHFZYrtznDZyMotuRfO5uC5YODhSFyLXvb1qB3WeGtF4h3Eo4KzHgMgfN2ZMlffxFRhJgTtH3ctbL8lfQoDkjeiPPnYGhspdJxr0tyZmiy0gkjJG3vwHYrLnvZWx9Wm/unqiOlGBPNuxJ+hOeP8=";
//private static string dsaJ = "9RhE5TycDtdEIXxS3HfxFyXYgpy81zY5lVjwD6E9JP37MWEi80BlX6ab1YPm6xYSEoqReMPP9RgGiW6DuACpgI7+8vgCr4i/7VhzModJAA56PwvTu6UMt9xxKU/fT672v8ucREkMWoc7lEey";
//private static string dsaSeed = "HxW3N4RHWVgqDQKuGg7iJTUTiCs=";
//private static string dsaPgenCounter = "Asw=";
// private static string xmlDSA = "<DSAKeyValue><P>" + dsaP + "</P><Q>" + dsaQ + "</Q><G>" + dsaG + "</G><Y>" + dsaY + "</Y><J>" + dsaJ + "</J><Seed>" + dsaSeed + "</Seed><PgenCounter>" + dsaPgenCounter + "</PgenCounter></DSAKeyValue>";
private static string xmlDSA = "<DSAKeyValue><P>" + dsaP + "</P><Q>" + dsaQ + "</Q><G>" + dsaG + "</G><Y>" + dsaY + "</Y></DSAKeyValue>";
[Fact]
public void DSAKeyValue()
{
using (DSA key = DSA.Create())
{
key.ImportParameters(new DSAParameters {
P = Convert.FromBase64String(dsaP),
Q = Convert.FromBase64String(dsaQ),
G = Convert.FromBase64String(dsaG),
Y = Convert.FromBase64String(dsaY),
//J = Convert.FromBase64String(dsaJ),
//Seed = Convert.FromBase64String(dsaSeed),
//Counter = BitConverter.ToUInt16(Convert.FromBase64String(dsaPgenCounter), 0)
});
DSAKeyValue dsa = new DSAKeyValue(key);
info.AddClause(dsa);
AssertCrypto.AssertXmlEquals("dsa",
"<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" +
xmlDSA + "</KeyValue></KeyInfo>", (info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
}
private static string rsaModulus = "9DC4XNdQJwMRnz5pP2a6U51MHCODRilaIoVXqUPhCUb0lJdGroeqVYT84ZyIVrcarzD7Tqs3aEOIa3rKox0N1bxQpZPqayVQeLAkjLLtzJW/ScRJx3uEDJdgT1JnM1FH0GZTinmEdCUXdLc7+Y/c/qqIkTfbwHbRZjW0bBJyExM=";
private static string rsaExponent = "AQAB";
private static string xmlRSA = "<RSAKeyValue><Modulus>" + rsaModulus + "</Modulus><Exponent>" + rsaExponent + "</Exponent></RSAKeyValue>";
[Fact]
public void RSAKeyValue()
{
using (RSA key = RSA.Create())
{
key.ImportParameters(new RSAParameters()
{
Modulus = Convert.FromBase64String(rsaModulus),
Exponent = Convert.FromBase64String(rsaExponent)
});
RSAKeyValue rsa = new RSAKeyValue(key);
info.AddClause(rsa);
AssertCrypto.AssertXmlEquals("rsa",
"<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" +
xmlRSA + "</KeyValue></KeyInfo>", (info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
}
[Fact]
public void RetrievalMethod()
{
KeyInfoRetrievalMethod retrieval = new KeyInfoRetrievalMethod();
retrieval.Uri = "http://www.go-mono.org/";
info.AddClause(retrieval);
Assert.Equal("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><RetrievalMethod URI=\"http://www.go-mono.org/\" /></KeyInfo>", (info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
static byte[] cert = { 0x30,0x82,0x02,0x1D,0x30,0x82,0x01,0x86,0x02,0x01,0x14,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x30,0x58,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x43,0x41,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x03,0x13,0x16,0x4B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,0x73,0x20,0x43,0x61,0x6E,0x61,0x64,0x61,0x20,0x49,0x6E,0x63,0x2E,0x31,0x28,0x30,0x26,0x06,0x0A,0x2B,0x06,0x01,0x04,0x01,0x2A,0x02,0x0B,0x02,0x01,0x13,0x18,0x6B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,
0x73,0x40,0x6B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,0x73,0x2E,0x63,0x61,0x30,0x1E,0x17,0x0D,0x39,0x36,0x30,0x35,0x30,0x37,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x39,0x39,0x30,0x35,0x30,0x37,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x30,0x58,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x43,0x41,0x31,0x1F,0x30,0x1D,0x06,0x03,0x55,0x04,0x03,0x13,0x16,0x4B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,0x73,0x20,0x43,0x61,0x6E,0x61,0x64,0x61,0x20,0x49,0x6E,0x63,0x2E,0x31,0x28,0x30,0x26,0x06,
0x0A,0x2B,0x06,0x01,0x04,0x01,0x2A,0x02,0x0B,0x02,0x01,0x13,0x18,0x6B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,0x73,0x40,0x6B,0x65,0x79,0x77,0x69,0x74,0x6E,0x65,0x73,0x73,0x2E,0x63,0x61,0x30,0x81,0x9D,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x81,0x8B,0x00,0x30,0x81,0x87,0x02,0x81,0x81,0x00,0xCD,0x23,0xFA,0x2A,0xE1,0xED,0x98,0xF4,0xE9,0xD0,0x93,0x3E,0xD7,0x7A,0x80,0x02,0x4C,0xCC,0xC1,0x02,0xAF,0x5C,0xB6,0x1F,0x7F,0xFA,0x57,0x42,0x6F,0x30,0xD1,0x20,0xC5,0xB5,
0x21,0x07,0x40,0x2C,0xA9,0x86,0xC2,0xF3,0x64,0x84,0xAE,0x3D,0x85,0x2E,0xED,0x85,0xBD,0x54,0xB0,0x18,0x28,0xEF,0x6A,0xF8,0x1B,0xE7,0x0B,0x16,0x1F,0x93,0x25,0x4F,0xC7,0xF8,0x8E,0xC3,0xB9,0xCA,0x98,0x84,0x0E,0x55,0xD0,0x2F,0xEF,0x78,0x77,0xC5,0x72,0x28,0x5F,0x60,0xBF,0x19,0x2B,0xD1,0x72,0xA2,0xB7,0xD8,0x3F,0xE0,0x97,0x34,0x5A,0x01,0xBD,0x04,0x9C,0xC8,0x78,0x45,0xCD,0x93,0x8D,0x15,0xF2,0x76,0x10,0x11,0xAB,0xB8,0x5B,0x2E,0x9E,0x52,0xDD,0x81,0x3E,0x9C,0x64,0xC8,0x29,0x93,0x02,0x01,0x03,0x30,0x0D,0x06,
0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x03,0x81,0x81,0x00,0x32,0x1A,0x35,0xBA,0xBF,0x43,0x27,0xD6,0xB4,0xD4,0xB8,0x76,0xE5,0xE3,0x9B,0x4D,0x6C,0xC0,0x86,0xC9,0x77,0x35,0xBA,0x6B,0x16,0x2D,0x13,0x46,0x4A,0xB0,0x32,0x53,0xA1,0x5B,0x5A,0xE9,0x99,0xE2,0x0C,0x86,0x88,0x17,0x4E,0x0D,0xFE,0x82,0xAC,0x4E,0x47,0xEF,0xFB,0xFF,0x39,0xAC,0xEE,0x35,0xC8,0xFA,0x52,0x37,0x0A,0x49,0xAD,0x59,0xAD,0xE2,0x8A,0xA9,0x1C,0xC6,0x5F,0x1F,0xF8,0x6F,0x73,0x7E,0xCD,0xA0,0x31,0xE8,0x0C,0xBE,0xF5,0x4D,
0xD9,0xB2,0xAB,0x8A,0x12,0xB6,0x30,0x78,0x68,0x11,0x7C,0x0D,0xF1,0x49,0x4D,0xA3,0xFD,0xB2,0xE9,0xFF,0x1D,0xF0,0x91,0xFA,0x54,0x85,0xFF,0x33,0x90,0xE8,0xC1,0xBF,0xA4,0x9B,0xA4,0x62,0x46,0xBD,0x61,0x12,0x59,0x98,0x41,0x89 };
[Fact]
public void X509Data()
{
using (X509Certificate x509 = new X509Certificate(cert))
{
KeyInfoX509Data x509data = new KeyInfoX509Data(x509);
info.AddClause(x509data);
AssertCrypto.AssertXmlEquals("X509Data",
"<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><X509Data xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><X509Certificate>MIICHTCCAYYCARQwDQYJKoZIhvcNAQEEBQAwWDELMAkGA1UEBhMCQ0ExHzAdBgNVBAMTFktleXdpdG5lc3MgQ2FuYWRhIEluYy4xKDAmBgorBgEEASoCCwIBExhrZXl3aXRuZXNzQGtleXdpdG5lc3MuY2EwHhcNOTYwNTA3MDAwMDAwWhcNOTkwNTA3MDAwMDAwWjBYMQswCQYDVQQGEwJDQTEfMB0GA1UEAxMWS2V5d2l0bmVzcyBDYW5hZGEgSW5jLjEoMCYGCisGAQQBKgILAgETGGtleXdpdG5lc3NAa2V5d2l0bmVzcy5jYTCBnTANBgkqhkiG9w0BAQEFAAOBiwAwgYcCgYEAzSP6KuHtmPTp0JM+13qAAkzMwQKvXLYff/pXQm8w0SDFtSEHQCyphsLzZISuPYUu7YW9VLAYKO9q+BvnCxYfkyVPx/iOw7nKmIQOVdAv73h3xXIoX2C/GSvRcqK32D/glzRaAb0EnMh4Rc2TjRXydhARq7hbLp5S3YE+nGTIKZMCAQMwDQYJKoZIhvcNAQEEBQADgYEAMho1ur9DJ9a01Lh25eObTWzAhsl3NbprFi0TRkqwMlOhW1rpmeIMhogXTg3+gqxOR+/7/zms7jXI+lI3CkmtWa3iiqkcxl8f+G9zfs2gMegMvvVN2bKrihK2MHhoEXwN8UlNo/2y6f8d8JH6VIX/M5Dowb+km6RiRr1hElmYQYk=</X509Certificate></X509Data></KeyInfo>",
(info.GetXml().OuterXml));
Assert.Equal(1, info.Count);
}
}
[Fact]
public void Complex()
{
KeyInfoName name = new KeyInfoName();
name.Value = "CoreFx::";
info.AddClause(name);
using (DSA keyDSA = DSA.Create())
{
keyDSA.ImportParameters(new DSAParameters
{
P = Convert.FromBase64String(dsaP),
Q = Convert.FromBase64String(dsaQ),
G = Convert.FromBase64String(dsaG),
Y = Convert.FromBase64String(dsaY),
});
DSAKeyValue dsa = new DSAKeyValue(keyDSA);
info.AddClause(dsa);
using (RSA keyRSA = RSA.Create())
{
keyRSA.ImportParameters(new RSAParameters()
{
Modulus = Convert.FromBase64String(rsaModulus),
Exponent = Convert.FromBase64String(rsaExponent)
});
RSAKeyValue rsa = new RSAKeyValue(keyRSA);
info.AddClause(rsa);
KeyInfoRetrievalMethod retrieval = new KeyInfoRetrievalMethod();
retrieval.Uri = "https://github.com/dotnet/corefx";
info.AddClause(retrieval);
using (X509Certificate x509 = new X509Certificate(cert))
{
KeyInfoX509Data x509data = new KeyInfoX509Data(x509);
info.AddClause(x509data);
string s = "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyName>CoreFx::</KeyName><KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><DSAKeyValue><P>rjxsMU368YOCTQejWkiuO9e/vUVwkLtq1jKiU3TtJ53hBJqjFRuTa228vZe+BH2su9RPn/vYFWfQDv6zgBYe3eNdu4Afw+Ny0FatX6dl3E77Ra6Tsd3MmLXBiGSQ1mMNd5G2XQGpbt9zsGlUaexXekeMLxIufgfZLwYp67M+2WM=</P><Q>tf0K9rMyvUrU4cIkwbCrDRhQAJk=</Q><G>S8Z+1pGCed00w6DtVcqZLKjfqlCJ7JsugEFIgSy/Vxtu9YGCMclV4ijGEbPo/jU8YOSMuD7E9M7UaopMRcmKQjoKZzoJjkgVFP48Ohxl1f08lERnButsxanx3+OstFwUGQ8XNaGg3KrIoZt1FUnfxN3RHHTvVhjzNSHxMGULGaU=</G><Y>LnrxxRGLYeV2XLtK3SYz8RQHlHFZYrtznDZyMotuRfO5uC5YODhSFyLXvb1qB3WeGtF4h3Eo4KzHgMgfN2ZMlffxFRhJgTtH3ctbL8lfQoDkjeiPPnYGhspdJxr0tyZmiy0gkjJG3vwHYrLnvZWx9Wm/unqiOlGBPNuxJ+hOeP8=</Y></DSAKeyValue></KeyValue>";
s += "<KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><RSAKeyValue><Modulus>9DC4XNdQJwMRnz5pP2a6U51MHCODRilaIoVXqUPhCUb0lJdGroeqVYT84ZyIVrcarzD7Tqs3aEOIa3rKox0N1bxQpZPqayVQeLAkjLLtzJW/ScRJx3uEDJdgT1JnM1FH0GZTinmEdCUXdLc7+Y/c/qqIkTfbwHbRZjW0bBJyExM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue>";
s += "<RetrievalMethod URI=\"https://github.com/dotnet/corefx\" />";
s += "<X509Data xmlns=\"http://www.w3.org/2000/09/xmldsig#\">";
s += "<X509Certificate>MIICHTCCAYYCARQwDQYJKoZIhvcNAQEEBQAwWDELMAkGA1UEBhMCQ0ExHzAdBgNVBAMTFktleXdpdG5lc3MgQ2FuYWRhIEluYy4xKDAmBgorBgEEASoCCwIBExhrZXl3aXRuZXNzQGtleXdpdG5lc3MuY2EwHhcNOTYwNTA3MDAwMDAwWhcNOTkwNTA3MDAwMDAwWjBYMQswCQYDVQQGEwJDQTEfMB0GA1UEAxMWS2V5d2l0bmVzcyBDYW5hZGEgSW5jLjEoMCYGCisGAQQBKgILAgETGGtleXdpdG5lc3NAa2V5d2l0bmVzcy5jYTCBnTANBgkqhkiG9w0BAQEFAAOBiwAwgYcCgYEAzSP6KuHtmPTp0JM+13qAAkzMwQKvXLYff/pXQm8w0SDFtSEHQCyphsLzZISuPYUu7YW9VLAYKO9q+BvnCxYfkyVPx/iOw7nKmIQOVdAv73h3xXIoX2C/GSvRcqK32D/glzRaAb0EnMh4Rc2TjRXydhARq7hbLp5S3YE+nGTIKZMCAQMwDQYJKoZIhvcNAQEEBQADgYEAMho1ur9DJ9a01Lh25eObTWzAhsl3NbprFi0TRkqwMlOhW1rpmeIMhogXTg3+gqxOR+/7/zms7jXI+lI3CkmtWa3iiqkcxl8f+G9zfs2gMegMvvVN2bKrihK2MHhoEXwN8UlNo/2y6f8d8JH6VIX/M5Dowb+km6RiRr1hElmYQYk=</X509Certificate></X509Data></KeyInfo>";
AssertCrypto.AssertXmlEquals("Complex", s, (info.GetXml().OuterXml));
Assert.Equal(5, info.Count);
}
}
}
}
[Fact]
public void ImportKeyNode()
{
string keyName = "Mono::";
string dsaP = "rjxsMU368YOCTQejWkiuO9e/vUVwkLtq1jKiU3TtJ53hBJqjFRuTa228vZe+BH2su9RPn/vYFWfQDv6zgBYe3eNdu4Afw+Ny0FatX6dl3E77Ra6Tsd3MmLXBiGSQ1mMNd5G2XQGpbt9zsGlUaexXekeMLxIufgfZLwYp67M+2WM=";
string dsaQ = "tf0K9rMyvUrU4cIkwbCrDRhQAJk=";
string dsaG = "S8Z+1pGCed00w6DtVcqZLKjfqlCJ7JsugEFIgSy/Vxtu9YGCMclV4ijGEbPo/jU8YOSMuD7E9M7UaopMRcmKQjoKZzoJjkgVFP48Ohxl1f08lERnButsxanx3+OstFwUGQ8XNaGg3KrIoZt1FUnfxN3RHHTvVhjzNSHxMGULGaU=";
string dsaY = "LnrxxRGLYeV2XLtK3SYz8RQHlHFZYrtznDZyMotuRfO5uC5YODhSFyLXvb1qB3WeGtF4h3Eo4KzHgMgfN2ZMlffxFRhJgTtH3ctbL8lfQoDkjeiPPnYGhspdJxr0tyZmiy0gkjJG3vwHYrLnvZWx9Wm/unqiOlGBPNuxJ+hOeP8=";
string dsaJ = "9RhE5TycDtdEIXxS3HfxFyXYgpy81zY5lVjwD6E9JP37MWEi80BlX6ab1YPm6xYSEoqReMPP9RgGiW6DuACpgI7+8vgCr4i/7VhzModJAA56PwvTu6UMt9xxKU/fT672v8ucREkMWoc7lEey";
string dsaSeed = "HxW3N4RHWVgqDQKuGg7iJTUTiCs=";
string dsaPgenCounter = "Asw=";
string rsaModulus = "9DC4XNdQJwMRnz5pP2a6U51MHCODRilaIoVXqUPhCUb0lJdGroeqVYT84ZyIVrcarzD7Tqs3aEOIa3rKox0N1bxQpZPqayVQeLAkjLLtzJW/ScRJx3uEDJdgT1JnM1FH0GZTinmEdCUXdLc7+Y/c/qqIkTfbwHbRZjW0bBJyExM=";
string rsaExponent = "AQAB";
string x509cert = "MIICHTCCAYYCARQwDQYJKoZIhvcNAQEEBQAwWDELMAkGA1UEBhMCQ0ExHzAdBgNVBAMTFktleXdpdG5lc3MgQ2FuYWRhIEluYy4xKDAmBgorBgEEASoCCwIBExhrZXl3aXRuZXNzQGtleXdpdG5lc3MuY2EwHhcNOTYwNTA3MDAwMDAwWhcNOTkwNTA3MDAwMDAwWjBYMQswCQYDVQQGEwJDQTEfMB0GA1UEAxMWS2V5d2l0bmVzcyBDYW5hZGEgSW5jLjEoMCYGCisGAQQBKgILAgETGGtleXdpdG5lc3NAa2V5d2l0bmVzcy5jYTCBnTANBgkqhkiG9w0BAQEFAAOBiwAwgYcCgYEAzSP6KuHtmPTp0JM+13qAAkzMwQKvXLYff/pXQm8w0SDFtSEHQCyphsLzZISuPYUu7YW9VLAYKO9q+BvnCxYfkyVPx/iOw7nKmIQOVdAv73h3xXIoX2C/GSvRcqK32D/glzRaAb0EnMh4Rc2TjRXydhARq7hbLp5S3YE+nGTIKZMCAQMwDQYJKoZIhvcNAQEEBQADgYEAMho1ur9DJ9a01Lh25eObTWzAhsl3NbprFi0TRkqwMlOhW1rpmeIMhogXTg3+gqxOR+/7/zms7jXI+lI3CkmtWa3iiqkcxl8f+G9zfs2gMegMvvVN2bKrihK2MHhoEXwN8UlNo/2y6f8d8JH6VIX/M5Dowb+km6RiRr1hElmYQYk=";
string retrievalElementUri = @"http://www.go-mono.org/";
string value = $@"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#"">
<KeyName>{keyName}</KeyName>
<KeyValue xmlns=""http://www.w3.org/2000/09/xmldsig#"">
<DSAKeyValue>
<P>{dsaP}</P>
<Q>{dsaQ}</Q>
<G>{dsaG}</G>
<Y>{dsaY}</Y>
<J>{dsaJ}</J>
<Seed>{dsaSeed}</Seed>
<PgenCounter>{dsaPgenCounter}</PgenCounter>
</DSAKeyValue>
</KeyValue>
<KeyValue xmlns=""http://www.w3.org/2000/09/xmldsig#"">
<RSAKeyValue>
<Modulus>{rsaModulus}</Modulus>
<Exponent>{rsaExponent}</Exponent>
</RSAKeyValue>
</KeyValue>
<RetrievalElement URI=""{retrievalElementUri}"" />
<X509Data xmlns=""http://www.w3.org/2000/09/xmldsig#"">
<X509Certificate>{x509cert}</X509Certificate>
</X509Data>
</KeyInfo>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(value);
info.LoadXml(doc.DocumentElement);
Assert.Equal(5, info.Count);
int i = 0;
int pathsCovered = 0;
foreach (var clause in info)
{
i++;
if (clause is KeyInfoName)
{
pathsCovered |= 1 << 0;
var name = clause as KeyInfoName;
Assert.Equal(keyName, name.Value);
}
else if (clause is DSAKeyValue)
{
pathsCovered |= 1 << 1;
var dsaKV = clause as DSAKeyValue;
DSA dsaKey = dsaKV.Key;
DSAParameters dsaParams = dsaKey.ExportParameters(false);
Assert.Equal(Convert.FromBase64String(dsaP), dsaParams.P);
Assert.Equal(Convert.FromBase64String(dsaQ), dsaParams.Q);
Assert.Equal(Convert.FromBase64String(dsaG), dsaParams.G);
Assert.Equal(Convert.FromBase64String(dsaY), dsaParams.Y);
// J is an optimization it should either be null or correct value
if (dsaParams.J != null)
{
Assert.Equal(Convert.FromBase64String(dsaJ), dsaParams.J);
}
// Seed and Counter are not guaranteed to roundtrip
// they should either both be non-null or both null
if (dsaParams.Seed != null)
{
Assert.Equal(Convert.FromBase64String(dsaSeed), dsaParams.Seed);
byte[] counter = Convert.FromBase64String(dsaPgenCounter);
Assert.InRange(counter.Length, 1, 4);
int counterVal = 0;
for (int j = 0; j < counter.Length; j++)
{
counterVal <<= 8;
counterVal |= counter[j];
}
Assert.Equal(counterVal, dsaParams.Counter);
}
else
{
Assert.Null(dsaParams.Seed);
Assert.Equal(default(int), dsaParams.Counter);
}
}
else if (clause is RSAKeyValue)
{
pathsCovered |= 1 << 2;
var rsaKV = clause as RSAKeyValue;
RSA rsaKey = rsaKV.Key;
RSAParameters rsaParameters = rsaKey.ExportParameters(false);
Assert.Equal(Convert.FromBase64String(rsaModulus), rsaParameters.Modulus);
Assert.Equal(Convert.FromBase64String(rsaExponent), rsaParameters.Exponent);
}
else if (clause is KeyInfoNode)
{
pathsCovered |= 1 << 3;
var keyInfo = clause as KeyInfoNode;
XmlElement keyInfoEl = keyInfo.GetXml();
Assert.Equal("RetrievalElement", keyInfoEl.LocalName);
Assert.Equal("http://www.w3.org/2000/09/xmldsig#", keyInfoEl.NamespaceURI);
Assert.Equal(1, keyInfoEl.Attributes.Count);
Assert.Equal("URI", keyInfoEl.Attributes[0].Name);
Assert.Equal(retrievalElementUri, keyInfoEl.GetAttribute("URI"));
}
else if (clause is KeyInfoX509Data)
{
pathsCovered |= 1 << 4;
var x509data = clause as KeyInfoX509Data;
Assert.Equal(1, x509data.Certificates.Count);
X509Certificate cert = x509data.Certificates[0] as X509Certificate;
Assert.NotNull(cert);
Assert.Equal(Convert.FromBase64String(x509cert), cert.GetRawCertData());
}
else
{
Assert.True(false, $"Unexpected clause type: {clause.GetType().FullName}");
}
}
// 0x1f = b11111, number of ones = 5
Assert.Equal(0x1f, pathsCovered);
Assert.Equal(5, i);
}
[Fact]
public void NullClause()
{
Assert.Equal(0, info.Count);
// null is accepted...
info.AddClause(null);
Assert.Equal(1, info.Count);
// but can't get XML out if it!
Assert.Throws<NullReferenceException>(() => info.GetXml());
}
[Fact]
public void NullXml()
{
Assert.Throws<ArgumentNullException>(() => info.LoadXml(null));
}
[Fact]
public void InvalidXml()
{
string bad = "<Test></Test>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(bad);
info.LoadXml(doc.DocumentElement);
// no expection but Xml isn't loaded
Assert.Equal("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />", (info.GetXml().OuterXml));
Assert.Equal(0, info.Count);
}
}
}
| 60.369973 | 916 | 0.630917 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Security.Cryptography.Xml/tests/KeyInfoTest.cs | 22,518 | C# |
/*
* C# Version Ported by Matt Bettcher and Ian Qvist 2009-2010
*
* Original C++ Version Copyright (c) 2007 Eric Jordan
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Genbox.VelcroPhysics.Shared;
using Genbox.VelcroPhysics.Utilities;
using Microsoft.Xna.Framework;
namespace Genbox.VelcroPhysics.Tools.Triangulation.Earclip
{
/// <summary>
/// Convex decomposition algorithm using ear clipping
/// Properties:
/// - Only works on simple polygons.
/// - Does not support holes.
/// - Running time is O(n^2), n = number of vertices.
/// Source: http://www.ewjordan.com/earClip/
/// </summary>
internal static class EarclipDecomposer
{
//box2D rev 32 - for details, see http://www.box2d.org/forum/viewtopic.php?f=4&t=83&start=50
/// <summary>
/// Decompose the polygon into several smaller non-concave polygon. Each resulting polygon will have no more than
/// Settings.MaxPolygonVertices vertices.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="tolerance">The tolerance.</param>
public static List<Vertices> ConvexPartition(Vertices vertices, float tolerance = 0.001f)
{
Debug.Assert(vertices.Count > 3);
Debug.Assert(!vertices.IsCounterClockWise());
return TriangulatePolygon(vertices, tolerance);
}
/// <summary>
/// Triangulates a polygon using simple ear-clipping algorithm. Returns size of Triangle array unless the polygon
/// can't be triangulated. This should only happen if the polygon self-intersects, though it will not _always_ return null
/// for a bad polygon - it is the caller's responsibility to check for self-intersection, and if it doesn't, it should at
/// least check that the return value is non-null before using. You're warned! Triangles may be degenerate, especially if
/// you have identical points in the input to the algorithm. Check this before you use them. This is totally unoptimized,
/// so for large polygons it should not be part of the simulation loop.
/// </summary>
/// <remarks>Only works on simple polygons.</remarks>
private static List<Vertices> TriangulatePolygon(Vertices vertices, float tolerance)
{
//Velcro note: Check is needed as invalid triangles can be returned in recursive calls.
if (vertices.Count < 3)
return new List<Vertices>();
List<Vertices> results = new List<Vertices>();
//Recurse and split on pinch points
Vertices pin = new Vertices(vertices);
if (ResolvePinchPoint(pin, out Vertices pA, out Vertices pB, tolerance))
{
List<Vertices> mergeA = TriangulatePolygon(pA, tolerance);
List<Vertices> mergeB = TriangulatePolygon(pB, tolerance);
if (mergeA.Count == -1 || mergeB.Count == -1)
throw new Exception("Can't triangulate your polygon.");
for (int i = 0; i < mergeA.Count; ++i)
{
results.Add(new Vertices(mergeA[i]));
}
for (int i = 0; i < mergeB.Count; ++i)
{
results.Add(new Vertices(mergeB[i]));
}
return results;
}
Vertices[] buffer = new Vertices[vertices.Count - 2];
int bufferSize = 0;
float[] xrem = new float[vertices.Count];
float[] yrem = new float[vertices.Count];
for (int i = 0; i < vertices.Count; ++i)
{
xrem[i] = vertices[i].X;
yrem[i] = vertices[i].Y;
}
int vNum = vertices.Count;
while (vNum > 3)
{
// Find an ear
int earIndex = -1;
float earMaxMinCross = -10.0f;
for (int i = 0; i < vNum; ++i)
{
if (IsEar(i, xrem, yrem, vNum))
{
int lower = Remainder(i - 1, vNum);
int upper = Remainder(i + 1, vNum);
Vector2 d1 = new Vector2(xrem[upper] - xrem[i], yrem[upper] - yrem[i]);
Vector2 d2 = new Vector2(xrem[i] - xrem[lower], yrem[i] - yrem[lower]);
Vector2 d3 = new Vector2(xrem[lower] - xrem[upper], yrem[lower] - yrem[upper]);
d1.Normalize();
d2.Normalize();
d3.Normalize();
MathUtils.Cross(ref d1, ref d2, out float cross12);
cross12 = Math.Abs(cross12);
MathUtils.Cross(ref d2, ref d3, out float cross23);
cross23 = Math.Abs(cross23);
MathUtils.Cross(ref d3, ref d1, out float cross31);
cross31 = Math.Abs(cross31);
//Find the maximum minimum angle
float minCross = Math.Min(cross12, Math.Min(cross23, cross31));
if (minCross > earMaxMinCross)
{
earIndex = i;
earMaxMinCross = minCross;
}
}
}
// If we still haven't found an ear, we're screwed.
// Note: sometimes this is happening because the
// remaining points are collinear. Really these
// should just be thrown out without halting triangulation.
if (earIndex == -1)
{
for (int i = 0; i < bufferSize; i++)
{
results.Add(buffer[i]);
}
return results;
}
// Clip off the ear:
// - remove the ear tip from the list
--vNum;
float[] newx = new float[vNum];
float[] newy = new float[vNum];
int currDest = 0;
for (int i = 0; i < vNum; ++i)
{
if (currDest == earIndex)
++currDest;
newx[i] = xrem[currDest];
newy[i] = yrem[currDest];
++currDest;
}
// - add the clipped triangle to the triangle list
int under = earIndex == 0 ? vNum : earIndex - 1;
int over = earIndex == vNum ? 0 : earIndex + 1;
Triangle toAdd = new Triangle(xrem[earIndex], yrem[earIndex], xrem[over], yrem[over], xrem[under],
yrem[under]);
buffer[bufferSize] = toAdd;
++bufferSize;
// - replace the old list with the new one
xrem = newx;
yrem = newy;
}
Triangle tooAdd = new Triangle(xrem[1], yrem[1], xrem[2], yrem[2], xrem[0], yrem[0]);
buffer[bufferSize] = tooAdd;
++bufferSize;
for (int i = 0; i < bufferSize; i++)
{
results.Add(new Vertices(buffer[i]));
}
return results;
}
/// <summary>
/// Finds and fixes "pinch points," points where two polygon vertices are at the same point. If a pinch point is
/// found, pin is broken up into poutA and poutB and true is returned; otherwise, returns false. Mostly for internal use.
/// O(N^2) time, which sucks...
/// </summary>
/// <param name="pin">The pin.</param>
/// <param name="poutA">The pout A.</param>
/// <param name="poutB">The pout B.</param>
/// <param name="tolerance"></param>
private static bool ResolvePinchPoint(Vertices pin, out Vertices poutA, out Vertices poutB, float tolerance)
{
poutA = new Vertices();
poutB = new Vertices();
if (pin.Count < 3)
return false;
bool hasPinchPoint = false;
int pinchIndexA = -1;
int pinchIndexB = -1;
for (int i = 0; i < pin.Count; ++i)
{
for (int j = i + 1; j < pin.Count; ++j)
{
//Don't worry about pinch points where the points
//are actually just dupe neighbors
if (Math.Abs(pin[i].X - pin[j].X) < tolerance && Math.Abs(pin[i].Y - pin[j].Y) < tolerance && j != i + 1)
{
pinchIndexA = i;
pinchIndexB = j;
hasPinchPoint = true;
break;
}
}
if (hasPinchPoint)
break;
}
if (hasPinchPoint)
{
int sizeA = pinchIndexB - pinchIndexA;
if (sizeA == pin.Count)
return false; //has dupe points at wraparound, not a problem here
for (int i = 0; i < sizeA; ++i)
{
int ind = Remainder(pinchIndexA + i, pin.Count); // is this right
poutA.Add(pin[ind]);
}
int sizeB = pin.Count - sizeA;
for (int i = 0; i < sizeB; ++i)
{
int ind = Remainder(pinchIndexB + i, pin.Count); // is this right
poutB.Add(pin[ind]);
}
}
return hasPinchPoint;
}
/// <summary>Fix for obnoxious behavior for the % operator for negative numbers...</summary>
/// <param name="x">The x.</param>
/// <param name="modulus">The modulus.</param>
/// <returns></returns>
private static int Remainder(int x, int modulus)
{
int rem = x % modulus;
while (rem < 0)
{
rem += modulus;
}
return rem;
}
/// <summary>Checks if vertex i is the tip of an ear in polygon defined by xv[] and yv[].</summary>
/// <param name="i">The i.</param>
/// <param name="xv">The xv.</param>
/// <param name="yv">The yv.</param>
/// <param name="xvLength">Length of the xv.</param>
/// <remarks>Assumes clockwise orientation of polygon.</remarks>
/// <returns><c>true</c> if the specified i is ear; otherwise, <c>false</c>.</returns>
private static bool IsEar(int i, float[] xv, float[] yv, int xvLength)
{
float dx0, dy0, dx1, dy1;
if (i >= xvLength || i < 0 || xvLength < 3)
return false;
int upper = i + 1;
int lower = i - 1;
if (i == 0)
{
dx0 = xv[0] - xv[xvLength - 1];
dy0 = yv[0] - yv[xvLength - 1];
dx1 = xv[1] - xv[0];
dy1 = yv[1] - yv[0];
lower = xvLength - 1;
}
else if (i == xvLength - 1)
{
dx0 = xv[i] - xv[i - 1];
dy0 = yv[i] - yv[i - 1];
dx1 = xv[0] - xv[i];
dy1 = yv[0] - yv[i];
upper = 0;
}
else
{
dx0 = xv[i] - xv[i - 1];
dy0 = yv[i] - yv[i - 1];
dx1 = xv[i + 1] - xv[i];
dy1 = yv[i + 1] - yv[i];
}
float cross = dx0 * dy1 - dx1 * dy0;
if (cross > 0)
return false;
Triangle myTri = new Triangle(xv[i], yv[i], xv[upper], yv[upper], xv[lower], yv[lower]);
for (int j = 0; j < xvLength; ++j)
{
if (j == i || j == lower || j == upper)
continue;
if (myTri.IsInside(xv[j], yv[j]))
return false;
}
return true;
}
}
} | 40.935583 | 131 | 0.47958 | [
"MIT"
] | D31m05z/VelcroPhysics | src/VelcroPhysics/Tools/Triangulation/Earclip/EarclipDecomposer.cs | 13,020 | C# |
using cloudscribe.Core.Blazor;
using cloudscribe.Extensions.Blazor.Oidc;
using cloudscribe.Extensions.Blazor.WebSockets;
using Microsoft.AspNetCore.Blazor.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace sourceDev.BlazorApp
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<OidcService>();
services.AddSingleton<SiteContextService>();
services.AddSingleton<WebSocketsService>();
services.AddToaster(config =>
{
config.PositionClass = Sotsera.Blazor.Toaster.Core.Models.Defaults.Classes.Position.BottomFullWidth;
config.PreventDuplicates = true;
config.NewestOnTop = false;
config.VisibleStateDuration = 3500;
});
}
public void Configure(IBlazorApplicationBuilder app)
{
app.AddComponent<App>("body");
}
}
}
| 31.0625 | 116 | 0.650905 | [
"Apache-2.0"
] | cloudscribe/graphql | src/sourceDev.BlazorApp/Startup.cs | 994 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UseEventsWhereAppropriateAnalyzer,
Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpUseEventsWhereAppropriateFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UseEventsWhereAppropriateAnalyzer,
Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicUseEventsWhereAppropriateFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class UseEventsWhereAppropriateTests
{
#region No Diagnostic Tests
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task NoDiagnostic_NamingCasesAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class EventsClass1
{
public event EventHandler RaiseFileEvent;
public string RaiseAnotherProperty => null;
public void SomeMethodThatDoesNotStartWithRaise()
{
}
public void RaisedRoutine()
{
}
public void AddOneAssembly()
{
}
public void Remover()
{
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class EventsClass1
Public Event RaiseFileEvent As EventHandler
Public ReadOnly Property RaiseAnotherProperty() As String
Get
Return Nothing
End Get
End Property
Public Sub SomeMethodThatDoesNotStartWithRaise()
End Sub
Public Sub RaisedRoutine()
End Sub
Public Sub AddOneAssembly()
End Sub
Public Sub Remover()
End Sub
End Class
");
}
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task NoDiagnostic_InterfaceMemberImplementationAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class InterfaceImplementation : I
{
// Explicit interface implementation - Rule does not fire.
void I.FireOnSomething_InterfaceMethod1()
{
throw new NotImplementedException();
}
// Implicit interface implementation - Rule does not fire.
public void FireOnSomething_InterfaceMethod2()
{
throw new NotImplementedException();
}
}
#pragma warning disable CA1030 // We are only testing no violations in InterfaceImplementation in this test, so suppress issues reported in the interface.
public interface I
{
// Interface methods - Rule fires.
void FireOnSomething_InterfaceMethod1();
void FireOnSomething_InterfaceMethod2();
}
#pragma warning restore CA1030
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class InterfaceImplementation
Implements I
' Explicit interface implementation - Rule does not fire.
Private Sub FireOnSomething_InterfaceMethod1() Implements I.FireOnSomething_InterfaceMethod1
Throw New NotImplementedException()
End Sub
' Implicit interface implementation - Rule does not fire.
Public Sub FireOnSomething_InterfaceMethod2() Implements I.FireOnSomething_InterfaceMethod2
Throw New NotImplementedException()
End Sub
End Class
#Disable Warning CA1030 ' We are only testing no violations in InterfaceImplementation in this test, so suppress issues reported in the interface.
Public Interface I
' Interface methods - Rule fires.
Sub FireOnSomething_InterfaceMethod1()
Sub FireOnSomething_InterfaceMethod2()
End Interface
#Enable Warning CA1030
");
}
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task NoDiagnostic_UnflaggedMethodKindsAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class FireOnSomethingDerivedClass : BaseClass
{
// Constructor - Rule does not fire.
public FireOnSomethingDerivedClass()
{
}
// Finalizer - Rule does not fire.
~FireOnSomethingDerivedClass()
{
}
// Overridden methods - Rule does not fire.
public override void FireOnSomething()
{
throw new NotImplementedException();
}
public override void RaiseOnSomething()
{
throw new NotImplementedException();
}
public override void AddOnSomething()
{
throw new NotImplementedException();
}
public override void RemoveOnSomething()
{
throw new NotImplementedException();
}
}
#pragma warning disable CA1030 // We are only testing no violations in FireOnSomethingDerivedClass in this test, so suppress issues reported in the BaseClass.
public abstract class BaseClass
{
// Abstract method - Rule fires.
public abstract void FireOnSomething();
// Abstract method - Rule fires.
public abstract void RaiseOnSomething();
// Abstract method - Rule fires.
public abstract void AddOnSomething();
// Abstract method - Rule fires.
public abstract void RemoveOnSomething();
}
#pragma warning restore CA1030
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class FireOnSomethingDerivedClass
Inherits BaseClass
' Constructor - Rule does not fire.
Public Sub New()
End Sub
' Finalizer - Rule does not fire.
Protected Overrides Sub Finalize()
Try
Finally
MyBase.Finalize()
End Try
End Sub
' Overridden methods - Rule does not fire.
Public Overrides Sub FireOnSomething()
Throw New NotImplementedException()
End Sub
Public Overrides Sub RaiseOnSomething()
Throw New NotImplementedException()
End Sub
Public Overrides Sub AddOnSomething()
Throw New NotImplementedException()
End Sub
Public Overrides Sub RemoveOnSomething()
Throw New NotImplementedException()
End Sub
End Class
#Disable Warning CA1030 ' We are only testing no violations in FireOnSomethingDerivedClass in this test, so suppress issues reported in the BaseClass.
Public MustInherit Class BaseClass
' Abstract method - Rule fires.
Public MustOverride Overloads Sub FireOnSomething()
' Abstract method - Rule fires.
Public MustOverride Overloads Sub RaiseOnSomething()
' Abstract method - Rule fires.
Public MustOverride Overloads Sub AddOnSomething()
' Abstract method - Rule fires.
Public MustOverride Overloads Sub RemoveOnSomething()
End Class
#Enable Warning CA1030
");
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task NoDiagnostic_FlaggedMethodKinds_NotExternallyVisibleAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
internal interface InterfaceWithViolations
{
// Interface methods.
void FireOnSomething_InterfaceMethod1();
void FireOnSomething_InterfaceMethod2();
}
public abstract class ClassWithViolations
{
private class InnerClass
{
// Static method.
public static void RaiseOnSomething_StaticMethod()
{
}
}
internal class InnerClass2
{
// Virtual method.
public virtual void FireOnSomething_VirtualMethod()
{
}
}
// Private method.
private static void RaiseOnSomething_StaticMethod()
{
}
// Abstract method.
internal abstract void FireOnSomething_AbstractMethod();
// Abstract method.
internal abstract void RaiseOnSomething_AbstractMethod();
// Abstract method.
internal abstract void AddOnSomething_AbstractMethod();
// Abstract method.
internal abstract void RemoveOnSomething_AbstractMethod();
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Friend Interface InterfaceWithViolations
' Interface methods.
Sub FireOnSomething_InterfaceMethod1()
Sub FireOnSomething_InterfaceMethod2()
End Interface
Public MustInherit Class ClassWithViolations
Private Class InnerClass
' Static method.
Public Shared Sub RaiseOnSomething_StaticMethod()
End Sub
End Class
Friend Class InnerClass2
' Virtual method.
Public Overridable Sub FireOnSomething_VirtualMethod()
End Sub
End Class
' Private method.
Private Shared Sub RaiseOnSomething_StaticMethod()
End Sub
' Abstract method.
Friend MustOverride Sub FireOnSomething_AbstractMethod()
' Abstract method.
Friend MustOverride Sub RaiseOnSomething_AbstractMethod()
' Abstract method.
Friend MustOverride Sub AddOnSomething_AbstractMethod()
' Abstract method.
Friend MustOverride Sub RemoveOnSomething_AbstractMethod()
End Class
");
}
#endregion
#region Diagnostic Tests
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task Diagnostic_FlaggedMethodKindsAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public interface InterfaceWithViolations
{
// Interface methods - Rule fires.
void FireOnSomething_InterfaceMethod1();
void FireOnSomething_InterfaceMethod2();
}
public abstract class ClassWithViolations
{
// Static method - Rule fires.
public static void RaiseOnSomething_StaticMethod()
{
}
// Virtual method - Rule fires.
public virtual void FireOnSomething_VirtualMethod()
{
}
// Abstract method - Rule fires.
public abstract void FireOnSomething_AbstractMethod();
// Abstract method - Rule fires.
public abstract void RaiseOnSomething_AbstractMethod();
// Abstract method - Rule fires.
public abstract void AddOnSomething_AbstractMethod();
// Abstract method - Rule fires.
public abstract void RemoveOnSomething_AbstractMethod();
}
",
// Test0.cs(7,10): warning CA1030: Consider making 'FireOnSomething_InterfaceMethod1' an event.
GetCSharpResultAt(7, 10, "FireOnSomething_InterfaceMethod1"),
// Test0.cs(8,10): warning CA1030: Consider making 'FireOnSomething_InterfaceMethod2' an event.
GetCSharpResultAt(8, 10, "FireOnSomething_InterfaceMethod2"),
// Test0.cs(14,24): warning CA1030: Consider making 'RaiseOnSomething_StaticMethod' an event.
GetCSharpResultAt(14, 24, "RaiseOnSomething_StaticMethod"),
// Test0.cs(19,25): warning CA1030: Consider making 'FireOnSomething_VirtualMethod' an event.
GetCSharpResultAt(19, 25, "FireOnSomething_VirtualMethod"),
// Test0.cs(24,26): warning CA1030: Consider making 'FireOnSomething_AbstractMethod' an event.
GetCSharpResultAt(24, 26, "FireOnSomething_AbstractMethod"),
// Test0.cs(27,26): warning CA1030: Consider making 'RaiseOnSomething_AbstractMethod' an event.
GetCSharpResultAt(27, 26, "RaiseOnSomething_AbstractMethod"),
// Test0.cs(30,26): warning CA1030: Consider making 'AddOnSomething_AbstractMethod' an event.
GetCSharpResultAt(30, 26, "AddOnSomething_AbstractMethod"),
// Test0.cs(33,26): warning CA1030: Consider making 'RemoveOnSomething_AbstractMethod' an event.
GetCSharpResultAt(33, 26, "RemoveOnSomething_AbstractMethod"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Interface InterfaceWithViolations
' Interface methods - Rule fires.
Sub FireOnSomething_InterfaceMethod1()
Sub FireOnSomething_InterfaceMethod2()
End Interface
Public MustInherit Class ClassWithViolations
' Static method - Rule fires.
Public Shared Sub RaiseOnSomething_StaticMethod()
End Sub
' Virtual method - Rule fires.
Public Overridable Sub FireOnSomething_VirtualMethod()
End Sub
' Abstract method - Rule fires.
Public MustOverride Sub FireOnSomething_AbstractMethod()
' Abstract method - Rule fires.
Public MustOverride Sub RaiseOnSomething_AbstractMethod()
' Abstract method - Rule fires.
Public MustOverride Sub AddOnSomething_AbstractMethod()
' Abstract method - Rule fires.
Public MustOverride Sub RemoveOnSomething_AbstractMethod()
End Class
",
// Test0.vb(4,6): warning CA1030: Consider making 'FireOnSomething_InterfaceMethod1' an event.
GetBasicResultAt(4, 6, "FireOnSomething_InterfaceMethod1"),
// Test0.vb(5,6): warning CA1030: Consider making 'FireOnSomething_InterfaceMethod2' an event.
GetBasicResultAt(5, 6, "FireOnSomething_InterfaceMethod2"),
// Test0.vb(10,20): warning CA1030: Consider making 'RaiseOnSomething_StaticMethod' an event.
GetBasicResultAt(10, 20, "RaiseOnSomething_StaticMethod"),
// Test0.vb(14,25): warning CA1030: Consider making 'FireOnSomething_VirtualMethod' an event.
GetBasicResultAt(14, 25, "FireOnSomething_VirtualMethod"),
// Test0.vb(18,26): warning CA1030: Consider making 'FireOnSomething_AbstractMethod' an event.
GetBasicResultAt(18, 26, "FireOnSomething_AbstractMethod"),
// Test0.vb(21,26): warning CA1030: Consider making 'RaiseOnSomething_AbstractMethod' an event.
GetBasicResultAt(21, 26, "RaiseOnSomething_AbstractMethod"),
// Test0.vb(24,26): warning CA1030: Consider making 'AddOnSomething_AbstractMethod' an event.
GetBasicResultAt(24, 26, "AddOnSomething_AbstractMethod"),
// Test0.vb(27,26): warning CA1030: Consider making 'RemoveOnSomething_AbstractMethod' an event.
GetBasicResultAt(27, 26, "RemoveOnSomething_AbstractMethod"));
}
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task Diagnostic_PascalCasedMethodNamesAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class EventsClassPascalCased
{
public void Fire() { }
public void Raise() { }
public void RaiseFileEvent() { }
public void FireFileEvent() { }
public void AddOnFileEvent() { }
public void RemoveOnFileEvent() { }
public void Add_OnFileEvent() { }
public void Remove_OnFileEvent() { }
}
",
// Test0.cs(4,17): warning CA1030: Consider making 'Fire' an event.
GetCSharpResultAt(4, 17, "Fire"),
// Test0.cs(6,17): warning CA1030: Consider making 'Raise' an event.
GetCSharpResultAt(6, 17, "Raise"),
// Test0.cs(8,17): warning CA1030: Consider making 'RaiseFileEvent' an event.
GetCSharpResultAt(8, 17, "RaiseFileEvent"),
// Test0.cs(10,17): warning CA1030: Consider making 'FireFileEvent' an event.
GetCSharpResultAt(10, 17, "FireFileEvent"),
// Test0.cs(12,17): warning CA1030: Consider making 'AddOnFileEvent' an event.
GetCSharpResultAt(12, 17, "AddOnFileEvent"),
// Test0.cs(14,17): warning CA1030: Consider making 'RemoveOnFileEvent' an event.
GetCSharpResultAt(14, 17, "RemoveOnFileEvent"),
// Test0.cs(16,17): warning CA1030: Consider making 'Add_OnFileEvent' an event.
GetCSharpResultAt(16, 17, "Add_OnFileEvent"),
// Test0.cs(18,17): warning CA1030: Consider making 'Remove_OnFileEvent' an event.
GetCSharpResultAt(18, 17, "Remove_OnFileEvent"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class EventsClassPascalCased
Public Sub Fire()
End Sub
Public Sub Raise()
End Sub
Public Sub RaiseFileEvent()
End Sub
Public Sub FireFileEvent()
End Sub
Public Sub AddOnFileEvent()
End Sub
Public Sub RemoveOnFileEvent()
End Sub
Public Sub Add_OnFileEvent()
End Sub
Public Sub Remove_OnFileEvent()
End Sub
End Class
",
// Test0.vb(3,13): warning CA1030: Consider making 'Fire' an event.
GetBasicResultAt(3, 13, "Fire"),
// Test0.vb(6,13): warning CA1030: Consider making 'Raise' an event.
GetBasicResultAt(6, 13, "Raise"),
// Test0.vb(9,13): warning CA1030: Consider making 'RaiseFileEvent' an event.
GetBasicResultAt(9, 13, "RaiseFileEvent"),
// Test0.vb(12,13): warning CA1030: Consider making 'FireFileEvent' an event.
GetBasicResultAt(12, 13, "FireFileEvent"),
// Test0.vb(15,13): warning CA1030: Consider making 'AddOnFileEvent' an event.
GetBasicResultAt(15, 13, "AddOnFileEvent"),
// Test0.vb(18,13): warning CA1030: Consider making 'RemoveOnFileEvent' an event.
GetBasicResultAt(18, 13, "RemoveOnFileEvent"),
// Test0.vb(21,13): warning CA1030: Consider making 'Add_OnFileEvent' an event.
GetBasicResultAt(21, 13, "Add_OnFileEvent"),
// Test0.vb(24,13): warning CA1030: Consider making 'Remove_OnFileEvent' an event.
GetBasicResultAt(24, 13, "Remove_OnFileEvent"));
}
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task Diagnostic_LowerCaseMethodNamesAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class EventsClassLowercase
{
public void fire() { }
public void raise() { }
public void raiseFileEvent() { }
public void fireFileEvent() { }
public void addOnFileEvent() { }
public void removeOnFileEvent() { }
public void add_onFileEvent() { }
public void remove_onFileEvent() { }
}
",
// Test0.cs(4,17): warning CA1030: Consider making 'fire' an event.
GetCSharpResultAt(4, 17, "fire"),
// Test0.cs(6,17): warning CA1030: Consider making 'raise' an event.
GetCSharpResultAt(6, 17, "raise"),
// Test0.cs(8,17): warning CA1030: Consider making 'raiseFileEvent' an event.
GetCSharpResultAt(8, 17, "raiseFileEvent"),
// Test0.cs(10,17): warning CA1030: Consider making 'fireFileEvent' an event.
GetCSharpResultAt(10, 17, "fireFileEvent"),
// Test0.cs(12,17): warning CA1030: Consider making 'addOnFileEvent' an event.
GetCSharpResultAt(12, 17, "addOnFileEvent"),
// Test0.cs(14,17): warning CA1030: Consider making 'removeOnFileEvent' an event.
GetCSharpResultAt(14, 17, "removeOnFileEvent"),
// Test0.cs(16,17): warning CA1030: Consider making 'add_onFileEvent' an event.
GetCSharpResultAt(16, 17, "add_onFileEvent"),
// Test0.cs(18,17): warning CA1030: Consider making 'remove_onFileEvent' an event.
GetCSharpResultAt(18, 17, "remove_onFileEvent"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class EventsClassLowercase
Public Sub fire()
End Sub
Public Sub raise()
End Sub
Public Sub raiseFileEvent()
End Sub
Public Sub fireFileEvent()
End Sub
Public Sub addOnFileEvent()
End Sub
Public Sub removeOnFileEvent()
End Sub
Public Sub add_onFileEvent()
End Sub
Public Sub remove_onFileEvent()
End Sub
End Class
",
// Test0.vb(3,13): warning CA1030: Consider making 'fire' an event.
GetBasicResultAt(3, 13, "fire"),
// Test0.vb(6,13): warning CA1030: Consider making 'raise' an event.
GetBasicResultAt(6, 13, "raise"),
// Test0.vb(9,13): warning CA1030: Consider making 'raiseFileEvent' an event.
GetBasicResultAt(9, 13, "raiseFileEvent"),
// Test0.vb(12,13): warning CA1030: Consider making 'fireFileEvent' an event.
GetBasicResultAt(12, 13, "fireFileEvent"),
// Test0.vb(15,13): warning CA1030: Consider making 'addOnFileEvent' an event.
GetBasicResultAt(15, 13, "addOnFileEvent"),
// Test0.vb(18,13): warning CA1030: Consider making 'removeOnFileEvent' an event.
GetBasicResultAt(18, 13, "removeOnFileEvent"),
// Test0.vb(21,13): warning CA1030: Consider making 'add_onFileEvent' an event.
GetBasicResultAt(21, 13, "add_onFileEvent"),
// Test0.vb(24,13): warning CA1030: Consider making 'remove_onFileEvent' an event.
GetBasicResultAt(24, 13, "remove_onFileEvent"));
}
#endregion
private static DiagnosticResult GetCSharpResultAt(int line, int column, params string[] arguments)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(arguments);
private static DiagnosticResult GetBasicResultAt(int line, int column, params string[] arguments)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(arguments);
}
} | 32.069401 | 158 | 0.71444 | [
"MIT"
] | JoeRobich/roslyn-analyzers | src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/UseEventsWhereAppropriateTests.cs | 20,332 | C# |
/*
* Payment Gateway API Specification.
*
* The documentation here is designed to provide all of the technical guidance required to consume and integrate with our APIs for payment processing. To learn more about our APIs please visit https://docs.firstdata.com/org/gateway.
*
* The version of the OpenAPI document: 21.2.0.20210406.001
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Org.OpenAPITools.Api;
using Org.OpenAPITools.Model;
using Org.OpenAPITools.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Test
{
/// <summary>
/// Class for testing ErrorMessage
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class ErrorMessageTests : IDisposable
{
// TODO uncomment below to declare an instance variable for ErrorMessage
//private ErrorMessage instance;
public ErrorMessageTests()
{
// TODO uncomment below to create an instance of ErrorMessage
//instance = new ErrorMessage();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of ErrorMessage
/// </summary>
[Fact]
public void ErrorMessageInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" ErrorMessage
//Assert.IsInstanceOfType<ErrorMessage> (instance, "variable 'instance' is a ErrorMessage");
}
/// <summary>
/// Test the property 'Code'
/// </summary>
[Fact]
public void CodeTest()
{
// TODO unit test for the property 'Code'
}
/// <summary>
/// Test the property 'Description'
/// </summary>
[Fact]
public void DescriptionTest()
{
// TODO unit test for the property 'Description'
}
}
}
| 27.6125 | 232 | 0.622001 | [
"MIT"
] | D4mo/DotNet | src/Org.OpenAPITools.Test/Model/ErrorMessageTests.cs | 2,209 | C# |
// ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
#nullable enable
namespace DurableTask.AzureStorage.Storage
{
using System;
using System.Threading;
using System.Threading.Tasks;
using DurableTask.AzureStorage.Monitoring;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Table;
class AzureStorageClient
{
static readonly TimeSpan StorageMaximumExecutionTime = TimeSpan.FromMinutes(2);
readonly CloudBlobClient blobClient;
readonly CloudQueueClient queueClient;
readonly CloudTableClient tableClient;
readonly SemaphoreSlim requestThrottleSemaphore;
public AzureStorageClient(AzureStorageOrchestrationServiceSettings settings) :
this(settings.StorageAccountDetails == null ?
CloudStorageAccount.Parse(settings.StorageConnectionString) : settings.StorageAccountDetails.ToCloudStorageAccount(),
settings)
{ }
public AzureStorageClient(CloudStorageAccount account, AzureStorageOrchestrationServiceSettings settings)
{
this.Settings = settings;
this.BlobAccountName = GetAccountName(account.Credentials, settings, account.BlobStorageUri, "blob");
this.QueueAccountName = GetAccountName(account.Credentials, settings, account.QueueStorageUri, "queue");
this.TableAccountName = GetAccountName(account.Credentials, settings, account.TableStorageUri, "table");
this.Stats = new AzureStorageOrchestrationServiceStats();
this.queueClient = account.CreateCloudQueueClient();
this.queueClient.BufferManager = SimpleBufferManager.Shared;
this.blobClient = account.CreateCloudBlobClient();
this.blobClient.BufferManager = SimpleBufferManager.Shared;
this.blobClient.DefaultRequestOptions.MaximumExecutionTime = StorageMaximumExecutionTime;
if (settings.HasTrackingStoreStorageAccount)
{
var trackingStoreAccount = settings.TrackingStoreStorageAccountDetails.ToCloudStorageAccount();
this.tableClient = trackingStoreAccount.CreateCloudTableClient();
}
else
{
this.tableClient = account.CreateCloudTableClient();
}
this.tableClient.BufferManager = SimpleBufferManager.Shared;
this.requestThrottleSemaphore = new SemaphoreSlim(this.Settings.MaxStorageOperationConcurrency);
}
public AzureStorageOrchestrationServiceSettings Settings { get; }
public AzureStorageOrchestrationServiceStats Stats { get; }
public string BlobAccountName { get; }
public string QueueAccountName { get; }
public string TableAccountName { get; }
public Blob GetBlobReference(string container, string blobName, string? blobDirectory = null)
{
NameValidator.ValidateBlobName(blobName);
return new Blob(this, this.blobClient, container, blobName, blobDirectory);
}
internal Blob GetBlobReference(Uri blobUri)
{
return new Blob(this, this.blobClient, blobUri);
}
public BlobContainer GetBlobContainerReference(string container)
{
NameValidator.ValidateContainerName(container);
return new BlobContainer(this, this.blobClient, container);
}
public Queue GetQueueReference(string queueName)
{
NameValidator.ValidateQueueName(queueName);
return new Queue(this, this.queueClient, queueName);
}
public Table GetTableReference(string tableName)
{
NameValidator.ValidateTableName(tableName);
return new Table(this, this.tableClient, tableName);
}
public Task<T> MakeBlobStorageRequest<T>(Func<OperationContext, CancellationToken, Task<T>> storageRequest, string operationName, string? clientRequestId = null) =>
this.MakeStorageRequest<T>(storageRequest, BlobAccountName, operationName, clientRequestId);
public Task<T> MakeQueueStorageRequest<T>(Func<OperationContext, CancellationToken, Task<T>> storageRequest, string operationName, string? clientRequestId = null) =>
this.MakeStorageRequest<T>(storageRequest, QueueAccountName, operationName, clientRequestId);
public Task<T> MakeTableStorageRequest<T>(Func<OperationContext, CancellationToken, Task<T>> storageRequest, string operationName, string? clientRequestId = null) =>
this.MakeStorageRequest<T>(storageRequest, TableAccountName, operationName, clientRequestId);
public Task MakeBlobStorageRequest(Func<OperationContext, CancellationToken, Task> storageRequest, string operationName, string? clientRequestId = null) =>
this.MakeStorageRequest(storageRequest, BlobAccountName, operationName, clientRequestId);
public Task MakeQueueStorageRequest(Func<OperationContext, CancellationToken, Task> storageRequest, string operationName, string? clientRequestId = null) =>
this.MakeStorageRequest(storageRequest, QueueAccountName, operationName, clientRequestId);
public Task MakeTableStorageRequest(Func<OperationContext, CancellationToken, Task> storageRequest, string operationName, string? clientRequestId = null) =>
this.MakeStorageRequest(storageRequest, TableAccountName, operationName, clientRequestId);
private async Task<T> MakeStorageRequest<T>(Func<OperationContext, CancellationToken, Task<T>> storageRequest, string accountName, string operationName, string? clientRequestId = null)
{
await requestThrottleSemaphore.WaitAsync();
try
{
return await TimeoutHandler.ExecuteWithTimeout<T>(operationName, accountName, this.Settings, storageRequest, this.Stats, clientRequestId);
}
catch (StorageException ex)
{
throw new DurableTaskStorageException(ex);
}
finally
{
requestThrottleSemaphore.Release();
}
}
private Task MakeStorageRequest(Func<OperationContext, CancellationToken, Task> storageRequest, string accountName, string operationName, string? clientRequestId = null) =>
this.MakeStorageRequest<object?>((context, cancellationToken) => WrapFunctionWithReturnType(storageRequest, context, cancellationToken), accountName, operationName, clientRequestId);
private static async Task<object?> WrapFunctionWithReturnType(Func<OperationContext, CancellationToken, Task> storageRequest, OperationContext context, CancellationToken cancellationToken)
{
await storageRequest(context, cancellationToken);
return null;
}
private static string GetAccountName(StorageCredentials credentials, AzureStorageOrchestrationServiceSettings settings, StorageUri serviceUri, string service) =>
credentials.AccountName ?? settings.StorageAccountDetails?.AccountName ?? serviceUri.GetAccountName(service) ?? "(unknown)";
}
}
| 50.791139 | 196 | 0.698816 | [
"Apache-2.0"
] | TrentCullinan9412/durabletask | src/DurableTask.AzureStorage/Storage/AzureStorageClient.cs | 8,027 | C# |
namespace CommonNews.Web.ViewModels.Post
{
using System.Collections.Generic;
using Comment;
public class PostWithCommentsViewModel
{
public ICollection<CommentViewModel> Comments { get; set; }
public PostViewModel Post { get; set; }
}
} | 23.833333 | 68 | 0.660839 | [
"MIT"
] | EmilPD/AutoParts | src/Web/CommonNews.Web/ViewModels/Post/PostWithCommentsViewModel.cs | 288 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProcessProbe
{
class ThreadAndStack
{
public int ManagedThreadId;
public IEnumerable<string> Stack;
}
}
| 17.333333 | 41 | 0.719231 | [
"MIT"
] | dinazil/dump-analyzer | ProcessProbe/ThreadAndStack.cs | 262 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using parent.Data;
using parent.Models;
namespace parent.Pages.UserPages
{
[Authorize]
public class EditModel : PageModel
{
private readonly parent.Data.ApplicationDbContext _context;
public EditModel(parent.Data.ApplicationDbContext context)
{
_context = context;
}
[BindProperty]
public UserPage UserPage { get; set; }
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
UserPage = await _context.UserPage.FirstOrDefaultAsync(m => m.ID == id);
if (UserPage == null)
{
return NotFound();
}
return Page();
}
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Attach(UserPage).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserPageExists(UserPage.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("./Index");
}
private bool UserPageExists(int id)
{
return _context.UserPage.Any(e => e.ID == id);
}
}
}
| 26.5375 | 111 | 0.518135 | [
"MIT"
] | hom3r/nested-web-application | parent-app/Pages/UserPages/Edit.cshtml.cs | 2,123 | C# |
using UnityEngine;
namespace Mirror
{
[DisallowMultipleComponent]
[AddComponentMenu("Network/NetworkTransform")]
[HelpURL("https://mirror-networking.com/docs/Components/NetworkTransform.html")]
public class NetworkTransform : NetworkTransformBase
{
protected override Transform TargetComponent => transform;
}
}
| 26.538462 | 84 | 0.744928 | [
"MIT"
] | JavierCondeIAR/MirrorNG | Assets/Mirror/Components/NetworkTransform.cs | 345 | C# |
namespace Renci.SshNet.Messages.Transport
{
/// <summary>
/// Represents SSH_MSG_KEXECDH_REPLY message.
/// </summary>
[Message("SSH_MSG_KEX_ECDH_REPLY", 31)]
public class KeyExchangeEcdhReplyMessage : Message
{
/// <summary>
/// Gets a string encoding an X.509v3 certificate containing the server's ECDSA public host key
/// </summary>
/// <value>The host key.</value>
public byte[] KS { get; private set; }
/// <summary>
/// Gets the server's ephemeral contribution to the ECDH exchange, encoded as an octet string.
/// </summary>
public byte[] QS { get; private set; }
/// <summary>
/// Gets an octet string containing the server's signature of the newly established exchange hash value.
/// </summary>
/// <value>The signature.</value>
public byte[] Signature { get; private set; }
/// <summary>
/// Gets the size of the message in bytes.
/// </summary>
/// <value>
/// The size of the messages in bytes.
/// </value>
protected override int BufferCapacity
{
get
{
var capacity = base.BufferCapacity;
capacity += 4; // KS length
capacity += KS.Length; // KS
capacity += 4; // QS length
capacity += QS.Length; // QS
capacity += 4; // Signature length
capacity += Signature.Length; // Signature
return capacity;
}
}
/// <summary>
/// Called when type specific data need to be loaded.
/// </summary>
protected override void LoadData()
{
KS = ReadBinary();
QS = ReadBinary();
Signature = ReadBinary();
}
/// <summary>
/// Called when type specific data need to be saved.
/// </summary>
protected override void SaveData()
{
WriteBinaryString(KS);
WriteBinaryString(QS);
WriteBinaryString(Signature);
}
internal override void Process(Session session)
{
session.OnKeyExchangeEcdhReplyMessageReceived(this);
}
}
}
| 31.452055 | 112 | 0.52831 | [
"MIT"
] | iodes/SSH.NET | src/Renci.SshNet/Messages/Transport/KeyExchangeEcdhReplyMessage.cs | 2,298 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.ContainerInstance.V20181001.Inputs
{
/// <summary>
/// The resource requirements.
/// </summary>
public sealed class ResourceRequirementsArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The resource limits of this container instance.
/// </summary>
[Input("limits")]
public Input<Inputs.ResourceLimitsArgs>? Limits { get; set; }
/// <summary>
/// The resource requests of this container instance.
/// </summary>
[Input("requests", required: true)]
public Input<Inputs.ResourceRequestsArgs> Requests { get; set; } = null!;
public ResourceRequirementsArgs()
{
}
}
}
| 29.2 | 81 | 0.643836 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/ContainerInstance/V20181001/Inputs/ResourceRequirementsArgs.cs | 1,022 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.IO;
using System.Linq;
using BuildXL.Engine;
using BuildXL.Utilities;
using BuildXL.Utilities.Configuration;
using Test.BuildXL.FrontEnd.Rush.IntegrationTests;
using Test.BuildXL.TestUtilities.Xunit;
using Xunit;
using Xunit.Abstractions;
using LogEventId = global::BuildXL.FrontEnd.Rush.Tracing.LogEventId;
namespace Test.BuildXL.FrontEnd.Rush
{
[Trait("Category", "RushExecuteTests")]
public class RushShrinkwrapTrackingTests : RushIntegrationTestBase
{
public RushShrinkwrapTrackingTests(ITestOutputHelper output)
: base(output)
{
}
// We don't actually need to execute anything, scheduling is enough
protected override EnginePhases Phase => EnginePhases.Schedule;
[Fact]
public void ShrinkwrapDepsIsUsedInsteadOfRealDependencies()
{
string commonTempFolder = Path.Combine(TestRoot, "CustomTempFolder").Replace("\\", "/"); ;
var config = Build(commonTempFolder: commonTempFolder)
.AddRushProject("@ms/project-A", "src/A").
PersistSpecsAndGetConfiguration();
var result = RunRushProjects(config, new[] {
("src/A", "@ms/project-A")
});
Assert.True(result.IsSuccess);
// The pip should have the common temp folder untracked, and shrinkwrap-deps.json
// should be a declared input
var pipA = result.EngineState.RetrieveProcess("@ms/project-A", "build");
XAssert.Contains(pipA.UntrackedScopes, CreatePath(commonTempFolder));
XAssert.Contains(
pipA.Dependencies.Select(fa => fa.Path),
pipA.WorkingDirectory.Combine(PathTable, RelativePath.Create(StringTable, ".rush/temp/shrinkwrap-deps.json")));
}
}
}
| 36.792453 | 128 | 0.644103 | [
"MIT"
] | Bhaskers-Blu-Org2/BuildXL | Public/Src/FrontEnd/UnitTests/Rush/IntegrationTests/RushShrinkwrapTrackingTests.cs | 1,950 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Data.Models
{
public class Shift
{
[Key]
public int Id { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
public virtual ICollection<CheckIn> CheckIns { get; set; }
public virtual Organization Organization { get; set; }
public virtual Schedule Schedule { get; set; }
}
} | 31.421053 | 68 | 0.668342 | [
"Apache-2.0"
] | AnalogIO/Analog-ShiftPlanner | API/Data/Models/Shift.cs | 599 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using IdentityWithoutEF.Models;
using IdentityWithoutEF.Services;
namespace IdentityWithoutEF
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddDefaultTokenProviders();
services.AddSingleton<IUserStore<ApplicationUser>, ExampleUserStore>();
services.AddSingleton<IRoleStore<IdentityRole>, ExampleRoleStore>();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 30.181818 | 106 | 0.61496 | [
"MIT"
] | MatthewKing/IdentityWithoutEF | src/IdentityWithoutEF-2.0/Startup.cs | 1,994 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
namespace GraphVisualizer
{
public class DefaultGraphRenderer : IGraphRenderer
{
protected event Action<Node> nodeClicked;
private static readonly Color s_EdgeColorMin = new Color(1.0f, 1.0f, 1.0f, 0.1f);
private static readonly Color s_EdgeColorMax = Color.white;
private static readonly Color s_LegendBackground = new Color(0, 0, 0, 0.1f);
private static readonly float s_BorderSize = 15;
private static readonly float s_LegendFixedOverheadWidth = 100;
private static readonly float s_DefaultMaximumNormalizedNodeSize = 0.8f;
private static readonly float s_DefaultMaximumNodeSizeInPixels = 100.0f;
private static readonly float s_DefaultAspectRatio = 1.5f;
private static readonly int s_NodeMaxFontSize = 14;
private GUIStyle m_LegendLabelStyle;
private GUIStyle m_SubTitleStyle;
private GUIStyle m_InspectorStyle;
private GUIStyle m_NodeRectStyle;
private static readonly int s_ActiveNodeThickness = 2;
private static readonly int s_SelectedNodeThickness = 4;
private static readonly Color s_ActiveNodeColor = Color.white;
private static readonly Color s_SelectedNodeColor = Color.yellow;
private readonly Dictionary<string, NodeTypeLegend> m_LegendForType = new Dictionary<string, NodeTypeLegend>();
private Node m_SelectedNode;
private Texture2D m_ColorBar;
Vector2 m_ScrollPos;
private struct NodeTypeLegend
{
public Color color;
public string label;
}
public DefaultGraphRenderer()
{
InitializeStyles();
}
public void Reset()
{
m_SelectedNode = null;
}
public void Draw(IGraphLayout graphLayout, Rect drawingArea)
{
GraphSettings defaults;
defaults.maximumNormalizedNodeSize = s_DefaultMaximumNormalizedNodeSize;
defaults.maximumNodeSizeInPixels = s_DefaultMaximumNodeSizeInPixels;
defaults.aspectRatio = s_DefaultAspectRatio;
defaults.showInspector = true;
defaults.showLegend = true;
Draw(graphLayout, drawingArea, defaults);
}
public void Draw(IGraphLayout graphLayout, Rect totalDrawingArea, GraphSettings graphSettings)
{
var legendArea = new Rect();
var drawingArea = new Rect(totalDrawingArea);
PrepareLegend(graphLayout.vertices);
if (graphSettings.showInspector)
{
legendArea = new Rect(totalDrawingArea)
{
width = Mathf.Max(EstimateLegendWidth(), drawingArea.width * 0.25f) + s_BorderSize * 2
};
legendArea.x = drawingArea.xMax - legendArea.width;
drawingArea.width -= legendArea.width; // + s_BorderSize;
DrawLegend(graphSettings, legendArea);
}
if (m_SelectedNode != null)
{
Event currentEvent = Event.current;
if (currentEvent.type == EventType.MouseUp && currentEvent.button == 0)
{
Vector2 mousePos = currentEvent.mousePosition;
if (drawingArea.Contains(mousePos))
{
m_SelectedNode = null;
if (nodeClicked != null)
nodeClicked(m_SelectedNode);
}
}
}
DrawGraph(graphLayout, drawingArea, graphSettings);
}
private void InitializeStyles()
{
m_LegendLabelStyle = new GUIStyle(GUI.skin.label)
{
margin = { top = 0 },
alignment = TextAnchor.UpperLeft
};
m_NodeRectStyle = new GUIStyle
{
normal =
{
background = (Texture2D)Resources.Load("Node"),
textColor = Color.black,
},
border = new RectOffset(10, 10, 10, 10),
alignment = TextAnchor.MiddleCenter,
wordWrap = true,
clipping = TextClipping.Clip
};
m_SubTitleStyle = EditorStyles.boldLabel;
m_InspectorStyle = new GUIStyle
{
normal =
{
textColor = Color.white,
},
richText = true,
alignment = TextAnchor.MiddleLeft,
wordWrap = true,
clipping = TextClipping.Clip
};
}
private void PrepareLegend(IEnumerable<Vertex> vertices)
{
m_LegendForType.Clear();
foreach (Vertex v in vertices)
{
if (v.node == null)
continue;
string nodeType = v.node.GetContentTypeName();
if (m_LegendForType.ContainsKey(nodeType))
continue;
m_LegendForType[nodeType] = new NodeTypeLegend
{
label = v.node.GetContentTypeShortName(),
color = v.node.GetColor()
};
}
}
private float EstimateLegendWidth()
{
float legendWidth = 0;
foreach (NodeTypeLegend legend in m_LegendForType.Values)
{
legendWidth = Mathf.Max(legendWidth, GUI.skin.label.CalcSize(new GUIContent(legend.label)).x);
}
legendWidth += s_LegendFixedOverheadWidth;
return legendWidth;
}
public void DrawRect(Rect rect, Color color, string text, bool active, bool selected = false)
{
var originalColor = GUI.color;
if (selected)
{
GUI.color = s_SelectedNodeColor;
float t = s_SelectedNodeThickness + (active ? s_ActiveNodeThickness : 0.0f);
GUI.Box(new Rect(rect.x - t, rect.y - t, rect.width + 2 * t, rect.height + 2 * t),
string.Empty, m_NodeRectStyle);
}
if (active)
{
GUI.color = s_ActiveNodeColor;
GUI.Box(new Rect(rect.x - s_ActiveNodeThickness, rect.y - s_ActiveNodeThickness,
rect.width + 2 * s_ActiveNodeThickness, rect.height + 2 * s_ActiveNodeThickness),
string.Empty, m_NodeRectStyle);
}
// Body + Text
GUI.color = color;
m_NodeRectStyle.fontSize = ComputeFontSize(rect.size, text);
GUI.Box(rect, text, m_NodeRectStyle);
GUI.color = originalColor;
}
private void DrawLegend(GraphSettings graphSettings, Rect legendArea)
{
EditorGUI.DrawRect(legendArea, s_LegendBackground);
// Add a border around legend area
legendArea.x += s_BorderSize;
legendArea.width -= s_BorderSize * 2;
legendArea.y += s_BorderSize;
legendArea.height -= s_BorderSize * 2;
GUILayout.BeginArea(legendArea);
GUILayout.BeginVertical();
if (graphSettings.showInspector)
{
GUILayout.Label("Inspector", m_SubTitleStyle);
if (m_SelectedNode != null)
{
using (var scrollView = new EditorGUILayout.ScrollViewScope(m_ScrollPos))
{
m_ScrollPos = scrollView.scrollPosition;
GUILayout.Label(m_SelectedNode.ToString(), m_InspectorStyle);
}
}
else
{
GUILayout.Label("Click on a node\nto display its details.");
}
}
GUILayout.FlexibleSpace();
if (graphSettings.showLegend)
{
GUILayout.Label("Legend", m_SubTitleStyle);
foreach (var pair in m_LegendForType)
{
DrawLegendEntry(pair.Value.color, pair.Value.label, false);
}
DrawLegendEntry(Color.gray, "Playing", true);
GUILayout.Space(20);
GUILayout.Label("Edge weight", m_SubTitleStyle);
GUILayout.BeginHorizontal();
GUILayout.Label("0");
GUILayout.FlexibleSpace();
GUILayout.Label("1");
GUILayout.EndHorizontal();
DrawEdgeWeightColorBar(legendArea.width);
GUILayout.Space(20);
}
GUILayout.EndVertical();
GUILayout.EndArea();
}
private void DrawLegendEntry(Color color, string label, bool active)
{
GUILayout.Space(5);
GUILayout.BeginHorizontal(GUILayout.Height(20));
Rect legendIconRect = GUILayoutUtility.GetRect(1, 1, GUILayout.Width(20), GUILayout.Height(20));
DrawRect(legendIconRect, color, string.Empty, active);
GUILayout.Label(label, m_LegendLabelStyle);
GUILayout.EndHorizontal();
}
private void DrawEdgeWeightColorBar(float width)
{
const int nbLevels = 64;
if (m_ColorBar == null)
{
m_ColorBar = new Texture2D(nbLevels, 1)
{
wrapMode = TextureWrapMode.Clamp
};
var cols = m_ColorBar.GetPixels();
for (int x = 0; x < nbLevels; x++)
{
Color c = Color.Lerp(s_EdgeColorMin, s_EdgeColorMax, (float)x / nbLevels);
cols[x] = c;
}
m_ColorBar.SetPixels(cols);
m_ColorBar.Apply(false);
}
const int colorbarHeight = 20;
GUI.DrawTexture(GUILayoutUtility.GetRect(width, colorbarHeight), m_ColorBar);
}
// Draw the graph and returns the selected Node if there's any.
private void DrawGraph(IGraphLayout graphLayout, Rect drawingArea, GraphSettings graphSettings)
{
// add border, except on right-hand side where the legend will provide necessary padding
drawingArea = new Rect(drawingArea.x + s_BorderSize,
drawingArea.y + s_BorderSize,
drawingArea.width - s_BorderSize * 2,
drawingArea.height - s_BorderSize * 2);
var b = new Bounds(Vector3.zero, Vector3.zero);
foreach (Vertex v in graphLayout.vertices)
{
b.Encapsulate(new Vector3(v.position.x, v.position.y, 0.0f));
}
// Increase b by maximum node size (since b is measured between node centers)
b.Expand(new Vector3(graphSettings.maximumNormalizedNodeSize, graphSettings.maximumNormalizedNodeSize, 0));
var scale = new Vector2(drawingArea.width / b.size.x, drawingArea.height / b.size.y);
var offset = new Vector2(-b.min.x, -b.min.y);
Vector2 nodeSize = ComputeNodeSize(scale, graphSettings);
GUI.BeginGroup(drawingArea);
foreach (var e in graphLayout.edges)
{
Vector2 v0 = ScaleVertex(e.source.position, offset, scale);
Vector2 v1 = ScaleVertex(e.destination.position, offset, scale);
Node node = e.source.node;
if (graphLayout.leftToRight)
DrawEdge(v1, v0, node.weight);
else
DrawEdge(v0, v1, node.weight);
}
Event currentEvent = Event.current;
bool oldSelectionFound = false;
Node newSelectedNode = null;
foreach (Vertex v in graphLayout.vertices)
{
Vector2 nodeCenter = ScaleVertex(v.position, offset, scale) - nodeSize / 2;
var nodeRect = new Rect(nodeCenter.x, nodeCenter.y, nodeSize.x, nodeSize.y);
bool clicked = false;
if (currentEvent.type == EventType.MouseUp && currentEvent.button == 0)
{
Vector2 mousePos = currentEvent.mousePosition;
if (nodeRect.Contains(mousePos))
{
clicked = true;
currentEvent.Use();
}
}
bool currentSelection = (m_SelectedNode != null)
&& v.node.content.Equals(m_SelectedNode.content); // Make sure to use Equals() and not == to call any overriden comparison operator in the content type.
DrawNode(nodeRect, v.node, currentSelection || clicked);
if (currentSelection)
{
// Previous selection still there.
oldSelectionFound = true;
}
else if (clicked)
{
// Just Selected a new node.
newSelectedNode = v.node;
}
}
if (newSelectedNode != null)
{
m_SelectedNode = newSelectedNode;
if (nodeClicked != null)
nodeClicked(m_SelectedNode);
}
else if (!oldSelectionFound)
{
m_SelectedNode = null;
}
GUI.EndGroup();
}
// Apply node constraints to node size
private static Vector2 ComputeNodeSize(Vector2 scale, GraphSettings graphSettings)
{
var extraTickness = (s_SelectedNodeThickness + s_ActiveNodeThickness) * 2.0f;
var nodeSize = new Vector2(graphSettings.maximumNormalizedNodeSize * scale.x - extraTickness,
graphSettings.maximumNormalizedNodeSize * scale.y - extraTickness);
// Adjust aspect ratio after scaling
float currentAspectRatio = nodeSize.x / nodeSize.y;
if (currentAspectRatio > graphSettings.aspectRatio)
{
// Shrink x dimension
nodeSize.x = nodeSize.y * graphSettings.aspectRatio;
}
else
{
// Shrink y dimension
nodeSize.y = nodeSize.x / graphSettings.aspectRatio;
}
// If node size is still too big, scale down
if (nodeSize.x > graphSettings.maximumNodeSizeInPixels)
{
nodeSize *= graphSettings.maximumNodeSizeInPixels / nodeSize.x;
}
if (nodeSize.y > graphSettings.maximumNodeSizeInPixels)
{
nodeSize *= graphSettings.maximumNodeSizeInPixels / nodeSize.y;
}
return nodeSize;
}
private static int ComputeFontSize(Vector2 nodeSize, string text)
{
if (string.IsNullOrEmpty(text))
return s_NodeMaxFontSize;
string[] words = text.Split('\n');
int nbLignes = words.Length;
int longuestWord = words.Max(s => s.Length);
// Approximate the text rectangle size using magic values.
int width = longuestWord * (int)(0.8f * s_NodeMaxFontSize);
int height = nbLignes * (int)(1.5f * s_NodeMaxFontSize);
float factor = Math.Min(nodeSize.x / width, nodeSize.y / height);
factor = Mathf.Clamp01(factor);
return Mathf.CeilToInt(s_NodeMaxFontSize * factor);
}
// Convert vertex position from normalized layout to render rect
private static Vector2 ScaleVertex(Vector2 v, Vector2 offset, Vector2 scaleFactor)
{
return new Vector2((v.x + offset.x) * scaleFactor.x, (v.y + offset.y) * scaleFactor.y);
}
// Draw a node an return true if it has been clicked
private void DrawNode(Rect nodeRect, Node node, bool selected)
{
string nodeType = node.GetContentTypeName();
NodeTypeLegend nodeTypeLegend = m_LegendForType[nodeType];
string formattedLabel = Regex.Replace(nodeTypeLegend.label, "((?<![A-Z])\\B[A-Z])", "\n$1"); // Split into multi-lines
DrawRect(nodeRect, nodeTypeLegend.color, formattedLabel, node.active, selected);
}
// Compute the tangents for the graphLayout edges. Assumes that graphLayout is drawn from left to right
private static void GetTangents(Vector2 start, Vector2 end, out Vector3[] points, out Vector3[] tangents)
{
points = new Vector3[] { start, end };
tangents = new Vector3[2];
// Heuristics to define the length of the tangents and tweak the look of the bezier curves.
const float minTangent = 30;
const float weight = 0.5f;
float cleverness = Mathf.Clamp01(((start - end).magnitude - 10) / 50);
tangents[0] = start + new Vector2((end.x - start.x) * weight + minTangent, 0) * cleverness;
tangents[1] = end + new Vector2((end.x - start.x) * -weight - minTangent, 0) * cleverness;
}
private static void DrawEdge(Vector2 a, Vector2 b, float weight)
{
Vector3[] points, tangents;
GetTangents(a, b, out points, out tangents);
Color color;
if (Mathf.Approximately(weight, float.MaxValue))
color = Color.yellow;
else
color = Color.Lerp(s_EdgeColorMin, s_EdgeColorMax, weight);
Handles.DrawBezier(points[0], points[1], tangents[0], tangents[1], color, null, 5f);
}
}
}
| 36.084507 | 172 | 0.550017 | [
"MIT"
] | Baste-RainGames/AnimationPlayer | GraphVisualizerFork/GraphVisualizer/Editor/Graph/Renderer/DefaultGraphRenderer.cs | 17,934 | C# |
// ------------------------------------------------------------------------------
// <copyright file="ForceData.cs" company="Drake53">
// Licensed under the MIT license.
// See the LICENSE file in the project root for more information.
// </copyright>
// ------------------------------------------------------------------------------
using System.IO;
using War3Net.Build.Common;
using War3Net.Build.Extensions;
using War3Net.Common.Extensions;
namespace War3Net.Build.Info
{
public sealed class ForceData
{
/// <summary>
/// Initializes a new instance of the <see cref="ForceData"/> class.
/// </summary>
public ForceData()
{
}
internal ForceData(BinaryReader reader, MapInfoFormatVersion formatVersion)
{
ReadFrom(reader, formatVersion);
}
public ForceFlags Flags { get; set; }
public Bitmask32 Players { get; set; }
public string Name { get; set; }
internal void ReadFrom(BinaryReader reader, MapInfoFormatVersion formatVersion)
{
Flags = reader.ReadInt32<ForceFlags>();
Players = reader.ReadBitmask32();
Name = reader.ReadChars();
}
internal void WriteTo(BinaryWriter writer, MapInfoFormatVersion formatVersion)
{
writer.Write((int)Flags);
writer.Write(Players);
writer.WriteString(Name);
}
}
} | 28.94 | 87 | 0.545957 | [
"MIT"
] | Bia10/War3Net | src/War3Net.Build.Core/Info/ForceData.cs | 1,449 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AwsNative.KinesisAnalyticsV2.Outputs
{
[OutputType]
public sealed class ApplicationOutputResourceKinesisStreamsOutput
{
public readonly string ResourceARN;
[OutputConstructor]
private ApplicationOutputResourceKinesisStreamsOutput(string resourceARN)
{
ResourceARN = resourceARN;
}
}
}
| 26.84 | 81 | 0.722802 | [
"Apache-2.0"
] | AaronFriel/pulumi-aws-native | sdk/dotnet/KinesisAnalyticsV2/Outputs/ApplicationOutputResourceKinesisStreamsOutput.cs | 671 | C# |
using System;
using System.Collections.Generic;
namespace DataStructures
{
public class BinaryHeap<T> where T : IComparable
{
private List<T> array = new List<T>();
public BinaryHeap()
{}
public BinaryHeap(List<T> list)
{
foreach(var data in list)
{
Insert(data);
}
}
~BinaryHeap()
{}
public T Min()
{
return array[0];
}
public T Max()
{
return array[array.Count - 1];
}
public bool Empty()
{
return array.Count == 0;
}
public void Insert(T data)
{
array.Add(data);
for(int i = array.Count - 1; i > 0; i--)
{
if(array[i].CompareTo(array[i - 1]) < 0)
{
T i1 = array[i];
T i2 = array[i - 1];
array[i] = i2;
array[i - 1] = i1;
}
}
}
public void RemoveMin()
{
array.RemoveAt(0);
}
public void RemoveMax()
{
array.RemoveAt(array.Count - 1);
}
}
} | 13.523077 | 49 | 0.551763 | [
"MIT"
] | DominicSieli/C-Sharp-Data-Structures | Source/Binary_Heap.cs | 879 | C# |
// This file has been autogenerated from a class added in the UI designer.
using System;
using Foundation;
using UIKit;
namespace tvTable
{
/// <summary>
/// The Table View used to display a collection of <c>CityInformation</c> as Sections and
/// <c>AttractionInformation</c> objects as the Rows in each section
/// </summary>
public partial class AttractionTableView : UITableView
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="T:tvTable.AttractionTableView"/> class.
/// </summary>
/// <param name="handle">Handle.</param>
public AttractionTableView (IntPtr handle) : base (handle)
{
}
#endregion
}
}
| 24.888889 | 91 | 0.703869 | [
"MIT"
] | Art-Lav/ios-samples | tvos/tvTable/tvTable/AttractionTableView.cs | 672 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotA2StatsParser.Model.Dotabuff;
using DotA2StatsParser.Model.Dotabuff.Path;
using HtmlAgilityPack;
namespace DotA2StatsParser.Controller.Dotabuff
{
internal class MatchController
{
private MainController mainController;
private dynamic PlayerPath { get { return mainController.DotabuffMappingController.PlayerPath; } }
private dynamic HtmlAttributes { get { return mainController.DotabuffMappingController.HtmlAttributes; } }
internal MatchController(MainController mainController)
{
this.mainController = mainController;
}
internal List<Match> FetchLatestMatches(string playerId)
{
HtmlNode root = mainController.HtmlDocumentController.GetDotabuffPlayerRoot(playerId);
IEnumerable<HtmlNode> latestMatches = root.SelectNodes(PlayerPath.LatestMatches.List.Value);
List<Match> matchList = new List<Match>();
MatchPath matchPath = new MatchPath
{
Duration = PlayerPath.LatestMatches.Duration.Value,
Hero = PlayerPath.LatestMatches.Hero.Value,
Id = PlayerPath.LatestMatches.Id.Value,
Kda = PlayerPath.LatestMatches.Kda.Value,
Mode = PlayerPath.LatestMatches.Mode.Value,
Result = PlayerPath.LatestMatches.Result.Value,
Skillbracket = PlayerPath.LatestMatches.Skillbracket.Value,
TimeAgo = PlayerPath.LatestMatches.TimeAgo.Value,
Type = PlayerPath.LatestMatches.Type.Value,
IdAttribute = HtmlAttributes.Match.Attribute.Value,
IdReplace = HtmlAttributes.Match.Replace.Value
};
for (int i = 1; i < latestMatches.Count() + 1; i++)
{
Match match = MapHtmlNodeToMatch(root, matchPath, i);
matchList.Add(match);
}
return matchList;
}
internal Match MapHtmlNodeToMatch(HtmlNode root, MatchPath matchPath, int currentCount)
{
Match match = new Match();
match.Id = HtmlEntity.DeEntitize(root.SelectSingleNode(mainController.CombinePathWithListCount(matchPath.Id, currentCount)).Attributes[matchPath.IdAttribute].Value).Replace(matchPath.IdReplace, "");
HtmlNode heroNode = root.SelectSingleNode(mainController.CombinePathWithListCount(matchPath.Hero, currentCount));
if (heroNode != null)
{
string heroReference = root.SelectSingleNode(mainController.CombinePathWithListCount(matchPath.Hero, currentCount)).Attributes[HtmlAttributes.Hero.Attribute.Value].Value.Replace(HtmlAttributes.Hero.Replace.Value, "");
match.Hero = mainController.HeroController.GetHero(heroReference);
}
match.Result = mainController.MapStringToEnum<Results>(root.SelectSingleNode(mainController.CombinePathWithListCount(matchPath.Result, currentCount)).InnerText);
match.TimeAgo = DateTime.Parse(root.SelectSingleNode(mainController.CombinePathWithListCount(matchPath.TimeAgo, currentCount)).Attributes[MainController.HTML_ATTRIBUTE_DATETIME].Value);
match.Type = mainController.MapStringToEnum<Types>(root.SelectSingleNode(mainController.CombinePathWithListCount(matchPath.Type, currentCount)).InnerText);
match.Mode = mainController.MapStringToEnum<Modes>(root.SelectSingleNode(mainController.CombinePathWithListCount(matchPath.Mode, currentCount)).InnerText);
HtmlNode skillBracketNode = root.SelectSingleNode(mainController.CombinePathWithListCount(matchPath.Skillbracket, currentCount));
if (skillBracketNode != null)
match.Skillbracket = mainController.MapStringToEnum<Skillbrackets>(HtmlEntity.DeEntitize(skillBracketNode.InnerText));
match.Duration = mainController.ConvertStringToTimeSpan(root.SelectSingleNode(mainController.CombinePathWithListCount(matchPath.Duration, currentCount)).InnerText);
match.Kda = mainController.ConvertStringToKda(root.SelectSingleNode(mainController.CombinePathWithListCount(matchPath.Kda, currentCount)).InnerText);
return match;
}
}
}
| 52.130952 | 233 | 0.707239 | [
"MIT"
] | Shamshiel/DotA2StatsParser | DotA2StatsParser/Controller/Dotabuff/MatchController.cs | 4,381 | C# |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// A user of the system
/// First published in XenServer 4.0.
/// </summary>
public partial class User : XenObject<User>
{
public User()
{
}
public User(string uuid,
string short_name,
string fullname,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.short_name = short_name;
this.fullname = fullname;
this.other_config = other_config;
}
/// <summary>
/// Creates a new User from a Proxy_User.
/// </summary>
/// <param name="proxy"></param>
public User(Proxy_User proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(User update)
{
uuid = update.uuid;
short_name = update.short_name;
fullname = update.fullname;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_User proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
short_name = proxy.short_name == null ? null : (string)proxy.short_name;
fullname = proxy.fullname == null ? null : (string)proxy.fullname;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_User ToProxy()
{
Proxy_User result_ = new Proxy_User();
result_.uuid = (uuid != null) ? uuid : "";
result_.short_name = (short_name != null) ? short_name : "";
result_.fullname = (fullname != null) ? fullname : "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new User from a Hashtable.
/// </summary>
/// <param name="table"></param>
public User(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
short_name = Marshalling.ParseString(table, "short_name");
fullname = Marshalling.ParseString(table, "fullname");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(User other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._short_name, other._short_name) &&
Helper.AreEqual2(this._fullname, other._fullname) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, User server)
{
if (opaqueRef == null)
{
Proxy_User p = this.ToProxy();
return session.proxy.user_create(session.uuid, p).parse();
}
else
{
if (!Helper.AreEqual2(_fullname, server._fullname))
{
User.set_fullname(session, opaqueRef, _fullname);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
User.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static User get_record(Session session, string _user)
{
return new User((Proxy_User)session.proxy.user_get_record(session.uuid, (_user != null) ? _user : "").parse());
}
/// <summary>
/// Get a reference to the user instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<User> get_by_uuid(Session session, string _uuid)
{
return XenRef<User>.Create(session.proxy.user_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<User> create(Session session, User _record)
{
return XenRef<User>.Create(session.proxy.user_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new user instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, User _record)
{
return XenRef<Task>.Create(session.proxy.async_user_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static void destroy(Session session, string _user)
{
session.proxy.user_destroy(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Destroy the specified user instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static XenRef<Task> async_destroy(Session session, string _user)
{
return XenRef<Task>.Create(session.proxy.async_user_destroy(session.uuid, (_user != null) ? _user : "").parse());
}
/// <summary>
/// Get the uuid field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_uuid(Session session, string _user)
{
return (string)session.proxy.user_get_uuid(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Get the short_name field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_short_name(Session session, string _user)
{
return (string)session.proxy.user_get_short_name(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Get the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static string get_fullname(Session session, string _user)
{
return (string)session.proxy.user_get_fullname(session.uuid, (_user != null) ? _user : "").parse();
}
/// <summary>
/// Get the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
public static Dictionary<string, string> get_other_config(Session session, string _user)
{
return Maps.convert_from_proxy_string_string(session.proxy.user_get_other_config(session.uuid, (_user != null) ? _user : "").parse());
}
/// <summary>
/// Set the fullname field of the given user.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_fullname">New value to set</param>
public static void set_fullname(Session session, string _user, string _fullname)
{
session.proxy.user_set_fullname(session.uuid, (_user != null) ? _user : "", (_fullname != null) ? _fullname : "").parse();
}
/// <summary>
/// Set the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _user, Dictionary<string, string> _other_config)
{
session.proxy.user_set_other_config(session.uuid, (_user != null) ? _user : "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given user.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _user, string _key, string _value)
{
session.proxy.user_add_to_other_config(session.uuid, (_user != null) ? _user : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given user. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_user">The opaque_ref of the given user</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _user, string _key)
{
session.proxy.user_remove_from_other_config(session.uuid, (_user != null) ? _user : "", (_key != null) ? _key : "").parse();
}
/// <summary>
/// Get all the user Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<User>, User> get_all_records(Session session)
{
return XenRef<User>.Create<Proxy_User>(session.proxy.user_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// short name (e.g. userid)
/// </summary>
public virtual string short_name
{
get { return _short_name; }
set
{
if (!Helper.AreEqual(value, _short_name))
{
_short_name = value;
Changed = true;
NotifyPropertyChanged("short_name");
}
}
}
private string _short_name;
/// <summary>
/// full name
/// </summary>
public virtual string fullname
{
get { return _fullname; }
set
{
if (!Helper.AreEqual(value, _fullname))
{
_fullname = value;
Changed = true;
NotifyPropertyChanged("fullname");
}
}
}
private string _fullname;
/// <summary>
/// additional configuration
/// First published in XenServer 5.0.
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| 39.992228 | 164 | 0.558399 | [
"BSD-2-Clause"
] | robertbreker/xenadmin | XenModel/XenAPI/User.cs | 15,437 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AwsNative.Lex.Inputs
{
/// <summary>
/// Settings that you can use for eliciting a slot value.
/// </summary>
public sealed class BotSlotValueElicitationSettingArgs : Pulumi.ResourceArgs
{
/// <summary>
/// A list of default values for a slot.
/// </summary>
[Input("defaultValueSpecification")]
public Input<Inputs.BotSlotDefaultValueSpecificationArgs>? DefaultValueSpecification { get; set; }
/// <summary>
/// The prompt that Amazon Lex uses to elicit the slot value from the user.
/// </summary>
[Input("promptSpecification")]
public Input<Inputs.BotPromptSpecificationArgs>? PromptSpecification { get; set; }
[Input("sampleUtterances")]
private InputList<Inputs.BotSampleUtteranceArgs>? _sampleUtterances;
/// <summary>
/// If you know a specific pattern that users might respond to an Amazon Lex request for a slot value, you can provide those utterances to improve accuracy.
/// </summary>
public InputList<Inputs.BotSampleUtteranceArgs> SampleUtterances
{
get => _sampleUtterances ?? (_sampleUtterances = new InputList<Inputs.BotSampleUtteranceArgs>());
set => _sampleUtterances = value;
}
/// <summary>
/// Specifies whether the slot is required or optional.
/// </summary>
[Input("slotConstraint", required: true)]
public Input<Pulumi.AwsNative.Lex.BotSlotConstraint> SlotConstraint { get; set; } = null!;
/// <summary>
/// Specifies the prompts that Amazon Lex uses while a bot is waiting for customer input.
/// </summary>
[Input("waitAndContinueSpecification")]
public Input<Inputs.BotWaitAndContinueSpecificationArgs>? WaitAndContinueSpecification { get; set; }
public BotSlotValueElicitationSettingArgs()
{
}
}
}
| 38.084746 | 164 | 0.660881 | [
"Apache-2.0"
] | AaronFriel/pulumi-aws-native | sdk/dotnet/Lex/Inputs/BotSlotValueElicitationSettingArgs.cs | 2,247 | C# |
namespace NoodleExtensions.HarmonyPatches
{
using System;
using System.Collections.Generic;
using System.Linq;
using CustomJSONData;
using CustomJSONData.CustomBeatmap;
using HarmonyLib;
using IPA.Utilities;
using static Plugin;
// Yeah i just harmony patched my own mod, you got a problem with it?
[HarmonyPatch(typeof(CustomBeatmapData))]
[HarmonyPatch(MethodType.Constructor)]
[HarmonyPatch(new Type[] { typeof(BeatmapLineData[]), typeof(BeatmapEventData[]), typeof(CustomEventData[]), typeof(object), typeof(object), typeof(object) })]
internal static class CustomBeatmapDataCtor
{
private static readonly PropertyAccessor<BeatmapData, int>.Setter _notesCountSetter = PropertyAccessor<BeatmapData, int>.GetSetter("notesCount");
private static readonly PropertyAccessor<BeatmapData, int>.Setter _obstaclesCountSetter = PropertyAccessor<BeatmapData, int>.GetSetter("obstaclesCount");
private static readonly PropertyAccessor<BeatmapData, int>.Setter _bombsCountSetter = PropertyAccessor<BeatmapData, int>.GetSetter("bombsCount");
#pragma warning disable SA1313 // Parameter names should begin with lower-case letter
private static void Postfix(CustomBeatmapData __instance)
#pragma warning restore SA1313 // Parameter names should begin with lower-case letter
{
IEnumerable<string> requirements = ((List<object>)Trees.at(__instance.beatmapCustomData, "_requirements"))?.Cast<string>();
bool noodleRequirement = requirements?.Contains(CAPABILITY) ?? false;
if (noodleRequirement)
{
// Recount for fake notes
int notesCount = 0;
int obstaclesCount = 0;
int bombsCount = 0;
BeatmapLineData[] beatmapLinesData = __instance.beatmapLinesData;
for (int i = 0; i < beatmapLinesData.Length; i++)
{
foreach (BeatmapObjectData beatmapObjectData in beatmapLinesData[i].beatmapObjectsData)
{
if (beatmapObjectData is CustomObstacleData || beatmapObjectData is CustomNoteData)
{
dynamic customObjectData = beatmapObjectData;
dynamic dynData = customObjectData.customData;
bool? fake = Trees.at(dynData, FAKENOTE);
if (fake.HasValue && fake.Value)
{
continue;
}
}
if (beatmapObjectData.beatmapObjectType == BeatmapObjectType.Note)
{
NoteType noteType = ((NoteData)beatmapObjectData).noteType;
if (noteType == NoteType.NoteA || noteType == NoteType.NoteB)
{
notesCount++;
}
else if (noteType == NoteType.Bomb)
{
bombsCount++;
}
}
else if (beatmapObjectData.beatmapObjectType == BeatmapObjectType.Obstacle)
{
obstaclesCount++;
}
}
}
BeatmapData beatmapData = __instance as BeatmapData;
_notesCountSetter(ref beatmapData, notesCount);
_obstaclesCountSetter(ref beatmapData, obstaclesCount);
_bombsCountSetter(ref beatmapData, bombsCount);
}
}
}
}
| 48.217949 | 163 | 0.560223 | [
"MIT"
] | Caeden117/NoodleExtensions | NoodleExtensions/HarmonyPatches/CustomBeatmapData.cs | 3,763 | 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.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
namespace Microsoft.CodeAnalysis.CodeStyle
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpFormattingAnalyzer : AbstractFormattingAnalyzer
{
protected override ISyntaxFormattingService SyntaxFormattingService
=> CSharpSyntaxFormattingService.Instance;
}
}
| 33.3 | 75 | 0.78979 | [
"MIT"
] | 333fred/roslyn | src/CodeStyle/CSharp/Analyzers/CSharpFormattingAnalyzer.cs | 668 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------
using System;
using System.Text.Json;
namespace Dapr.Actors.Runtime
{
/// <summary>
/// Represents Dapr actor configuration for this app. Includes the registration of actor types
/// as well as runtime options.
///
/// See https://docs.dapr.io/reference/api/actors_api/
/// </summary>
public sealed class ActorRuntimeOptions
{
private TimeSpan? actorIdleTimeout;
private TimeSpan? actorScanInterval;
private TimeSpan? drainOngoingCallTimeout;
private bool drainRebalancedActors;
private JsonSerializerOptions jsonSerializerOptions = JsonSerializerDefaults.Web;
private string daprApiToken = null;
private int? remindersStoragePartitions = null;
/// <summary>
/// Gets the collection of <see cref="ActorRegistration" /> instances.
/// </summary>
public ActorRegistrationCollection Actors { get; } = new ActorRegistrationCollection();
/// <summary>
/// Specifies how long to wait before deactivating an idle actor. An actor is idle
/// if no actor method calls and no reminders have fired on it.
/// See https://docs.dapr.io/reference/api/actors_api/#dapr-calling-to-user-service-code
/// for more including default values.
/// </summary>
public TimeSpan? ActorIdleTimeout
{
get
{
return this.actorIdleTimeout;
}
set
{
if (value <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(actorIdleTimeout), actorIdleTimeout, "must be positive");
}
this.actorIdleTimeout = value;
}
}
/// <summary>
/// A duration which specifies how often to scan for actors to deactivate idle actors.
/// Actors that have been idle longer than the actorIdleTimeout will be deactivated.
/// See https://docs.dapr.io/reference/api/actors_api/#dapr-calling-to-user-service-code
/// for more including default values.
/// </summary>
public TimeSpan? ActorScanInterval
{
get
{
return this.actorScanInterval;
}
set
{
if (value <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(actorScanInterval), actorScanInterval, "must be positive");
}
this.actorScanInterval = value;
}
}
/// <summary>
/// A duration used when in the process of draining rebalanced actors. This specifies
/// how long to wait for the current active actor method to finish. If there is no current actor method call, this is ignored.
/// See https://docs.dapr.io/reference/api/actors_api/#dapr-calling-to-user-service-code
/// for more including default values.
/// </summary>
public TimeSpan? DrainOngoingCallTimeout
{
get
{
return this.drainOngoingCallTimeout;
}
set
{
if (value <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(drainOngoingCallTimeout), drainOngoingCallTimeout, "must be positive");
}
this.drainOngoingCallTimeout = value;
}
}
/// <summary>
/// A bool. If true, Dapr will wait for drainOngoingCallTimeout to allow a current
/// actor call to complete before trying to deactivate an actor. If false, do not wait.
/// See https://docs.dapr.io/reference/api/actors_api/#dapr-calling-to-user-service-code
/// for more including default values.
/// </summary>
public bool DrainRebalancedActors
{
get
{
return this.drainRebalancedActors;
}
set
{
this.drainRebalancedActors = value;
}
}
/// <summary>
/// The <see cref="JsonSerializerOptions"/> to use for actor state persistence and message deserialization
/// </summary>
public JsonSerializerOptions JsonSerializerOptions
{
get
{
return this.jsonSerializerOptions;
}
set
{
if (value is null)
{
throw new ArgumentNullException(nameof(JsonSerializerOptions), $"{nameof(ActorRuntimeOptions)}.{nameof(JsonSerializerOptions)} cannot be null");
}
this.jsonSerializerOptions = value;
}
}
/// <summary>
/// The <see cref="DaprApiToken"/> to add to the headers in requests to Dapr runtime
/// </summary>
public string DaprApiToken
{
get
{
return this.daprApiToken;
}
set
{
if (value is null)
{
throw new ArgumentNullException(nameof(DaprApiToken), $"{nameof(ActorRuntimeOptions)}.{nameof(DaprApiToken)} cannot be null");
}
this.daprApiToken = value;
}
}
/// <summary>
/// An int used to determine how many partitions to use for reminders storage.
/// </summary>
public int? RemindersStoragePartitions
{
get
{
return this.remindersStoragePartitions;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(remindersStoragePartitions), remindersStoragePartitions, "must be positive");
}
this.remindersStoragePartitions = value;
}
}
/// <summary>
/// Gets or sets the HTTP endpoint URI used to communicate with the Dapr sidecar.
/// </summary>
/// <remarks>
/// The URI endpoint to use for HTTP calls to the Dapr runtime. The default value will be
/// <c>http://127.0.0.1:DAPR_HTTP_PORT</c> where <c>DAPR_HTTP_PORT</c> represents the value of the
/// <c>DAPR_HTTP_PORT</c> environment variable.
/// </remarks>
/// <value></value>
public string HttpEndpoint { get; set; } = DaprDefaults.GetDefaultHttpEndpoint();
}
}
| 34.080402 | 164 | 0.540991 | [
"MIT"
] | berndverst/dotnet-sdk | src/Dapr.Actors/Runtime/ActorRuntimeOptions.cs | 6,784 | C# |
namespace SF.Core.net46.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class adduserlocation : DbMigration
{
public override void Up()
{
AddColumn("dbo.User", "Location_City", c => c.String(nullable: false, maxLength: 100));
AddColumn("dbo.User", "Location_Address", c => c.String(nullable: false, maxLength: 100));
}
public override void Down()
{
DropColumn("dbo.User", "Location_Address");
DropColumn("dbo.User", "Location_City");
}
}
}
| 28.619048 | 102 | 0.579035 | [
"Apache-2.0"
] | etechi/ServiceFramework | Projects/Server/Test/SF.UT.Common/Migrations/201707251553296_add-user-location.cs | 601 | C# |
using System;
namespace Jasper.Tracking
{
public class EnvelopeRecord
{
public Envelope Envelope { get; }
public long SessionTime { get; }
public Exception Exception { get; }
public EventType EventType { get; }
public EnvelopeRecord(EventType eventType, Envelope envelope, long sessionTime, Exception exception)
{
Envelope = envelope;
SessionTime = sessionTime;
Exception = exception;
EventType = eventType;
AttemptNumber = envelope.Attempts;
}
public int AttemptNumber { get; }
public bool IsComplete { get; internal set; }
public string ServiceName { get; set; }
public int UniqueNodeId { get; set; }
public override string ToString()
{
var icon = IsComplete ? "+" : "-";
return $"{icon} Service: {ServiceName}, Id: {Envelope.Id}, {nameof(SessionTime)}: {SessionTime}, {nameof(EventType)}: {EventType}, MessageType: {Envelope.MessageType} at node #{UniqueNodeId} --> {IsComplete}";
}
}
}
| 30.694444 | 221 | 0.599095 | [
"MIT"
] | CodingGorilla/jasper | src/Jasper/Tracking/EnvelopeRecord.cs | 1,105 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Management.V20180101Preview.Outputs
{
[OutputType]
public sealed class EntityParentGroupInfoResponseResult
{
/// <summary>
/// The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000
/// </summary>
public readonly string? Id;
[OutputConstructor]
private EntityParentGroupInfoResponseResult(string? id)
{
Id = id;
}
}
}
| 30 | 166 | 0.695238 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Management/V20180101Preview/Outputs/EntityParentGroupInfoResponseResult.cs | 840 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VW;
using VW.Labels;
using VW.Serializer;
using VW.Serializer.Attributes;
using VW.Serializer.Intermediate;
namespace cs_unittest
{
[TestClass]
public class TestJsonClass
{
[TestMethod]
[TestCategory("JSON")]
public void TestJson()
{
using (var validator = new VowpalWabbitExampleJsonValidator())
{
validator.Validate("|a foo:1", "{\"a\":{\"foo\":1}}");
validator.Validate("|a foo:2.3", "{\"a\":{\"foo\":2.3}}");
validator.Validate("|a foo:2.3 bar", "{\"a\":{\"foo\":2.3, \"bar\":true}}");
validator.Validate("|a foo:1 |bcd Age25_old", "{\"a\":{\"foo\":1},\"bcd\":{\"Age\":\"25 old\"}}");
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonAux()
{
using (var validator = new VowpalWabbitExampleJsonValidator())
{
validator.Validate("|a foo:1", "{\"a\":{\"foo\":1},\"_aux\":{\"abc\":{\"def\":3}}}");
validator.Validate("|a foo:1", "{\"a\":{\"foo\":1},\"_aux\":5}");
validator.Validate("|a foo:1", "{\"a\":{\"foo\":1},\"_aux\":[1,2,[3,4],2]}");
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonArray()
{
using (var validator = new VowpalWabbitExampleJsonValidator())
{
validator.Validate("| :1 :2.3 :4", "{\"a\":[1,2.3,4]}");
validator.Validate("|a :1 :2.3 :4", "{\"a\":{\"b\":[1,2.3,4]}}");
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonSimpleLabel()
{
using (var validator = new VowpalWabbitExampleJsonValidator())
{
validator.Validate("1 |a foo:1", "{\"_label\":{\"Label\":1},\"a\":{\"foo\":1}}", VowpalWabbitLabelComparator.Simple);
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonVWLabel()
{
using (var validator = new VowpalWabbitExampleJsonValidator())
{
validator.Validate("1 |a foo:1", "{\"_label\":1,\"a\":{\"foo\":1}}", VowpalWabbitLabelComparator.Simple);
validator.Validate("1 |a foo:1", "{\"_label\":\"1\",\"a\":{\"foo\":1}}", VowpalWabbitLabelComparator.Simple);
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonSimpleLabelOverride()
{
using (var validator = new VowpalWabbitExampleJsonValidator())
{
validator.Validate("2 |a foo:1", "{\"_label\":{\"Label\":1},\"a\":{\"foo\":1}}", VowpalWabbitLabelComparator.Simple,
new SimpleLabel { Label = 2 });
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonContextualBanditLabel()
{
using (var validator = new VowpalWabbitExampleJsonValidator("--cb 2 --cb_type dr"))
{
//validator.Validate("1:-2:.3 |a foo:1",
// "{\"_label\":{\"Action\":1,\"Cost\":-2,\"Probability\":.3},\"a\":{\"foo\":1}}",
// VowpalWabbitLabelComparator.ContextualBandit);
validator.Validate("1:2:.5 |a foo:1", "{\"_label\":\"1:2:.5\",\"a\":{\"foo\":1}}", VowpalWabbitLabelComparator.ContextualBandit);
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonToVWString()
{
var jsonContext = new JsonContext()
{
Label = new SimpleLabel
{
Label = 25
},
Ns1 = new Namespace1
{
Foo = 1,
Age = "25",
DontConsider = "XXX"
},
Ns2 = new Namespace2
{
FeatureA = true
},
Clicks = 5
};
var jsonContextString = JsonConvert.SerializeObject(jsonContext);
using (var validator = new VowpalWabbitExampleJsonValidator(""))
{
validator.Validate("25 |a Bar:1 Age25 |b Marker | Clicks:5 MoreClicks:0",
jsonContextString,
VowpalWabbitLabelComparator.Simple);
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonMultiline()
{
using (var validator = new VowpalWabbitExampleJsonValidator("--cb 2 --cb_type dr"))
{
validator.Validate(new[] {
"shared | Age:25",
" | w1 w2 |a x:1",
" | w2 w3"
},
"{\"Age\":25,\"_multi\":[{\"_text\":\"w1 w2\", \"a\":{\"x\":1}}, {\"_text\":\"w2 w3\"}]}");
validator.Validate(new[] {
"shared | Age:25",
" | w1 w2 |a x:1",
"2:-1:.3 | w2 w3"
},
"{\"Age\":25,\"_multi\":[{\"_text\":\"w1 w2\", \"a\":{\"x\":1}}, {\"_text\":\"w2 w3\",\"_label\":\"2:-1:.3\"}]}",
VowpalWabbitLabelComparator.ContextualBandit);
}
using (var validator = new VowpalWabbitExampleJsonValidator(
new VowpalWabbitSettings
{
Arguments = "--cb 2 --cb_type dr",
PropertyConfiguration = new PropertyConfiguration
{
MultiProperty = "adf",
TextProperty = "someText",
LabelProperty = "theLabel",
FeatureIgnorePrefix = "xxx"
}
}))
{
validator.Validate(new[] {
"shared | Age:25",
" | w1 w2 |a x:1",
"2:-1:.3 | w2 w3"
},
"{\"Age\":25,\"adf\":[{\"someText\":\"w1 w2\", \"a\":{\"x\":1}, \"xxxxIgnoreMe\":2}, {\"someText\":\"w2 w3\",\"theLabel\":\"2:-1:.3\"}]}",
VowpalWabbitLabelComparator.ContextualBandit);
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonText()
{
using (var validator = new VowpalWabbitExampleJsonValidator(""))
{
validator.Validate("| a b c |a d e f", "{\"_text\":\"a b c\",\"a\":{\"_text\":\"d e f\"}}");
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonNumADFs()
{
using (var validator = new VowpalWabbitExampleJsonValidator(""))
{
Assert.AreEqual(2,
VowpalWabbitJsonSerializer.GetNumberOfActionDependentExamples(
"{\"_text\":\"a b c\",\"a\":{\"_text\":\"d e f\"},_multi:[{\"a\":1},{\"b\":2,\"c\":3}]}"));
Assert.AreEqual(0,
VowpalWabbitJsonSerializer.GetNumberOfActionDependentExamples(
"{\"_text\":\"a b c\",\"a\":{\"_text\":\"d e f\"},_multi:[]}"));
Assert.AreEqual(0,
VowpalWabbitJsonSerializer.GetNumberOfActionDependentExamples(
"{\"_text\":\"a b c\",\"a\":{\"_text\":\"d e f\"}}"));
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonLabel()
{
using (var validator = new VowpalWabbitExampleJsonValidator(""))
{
validator.Validate("1 | a:2 ", "{\"a\":2,\"_label_Label\":1}");
}
using (var validator = new VowpalWabbitExampleJsonValidator(new VowpalWabbitSettings
{
Arguments = "--cb_adf",
PropertyConfiguration = new PropertyConfiguration
{
MultiProperty = "adf",
TextProperty = "someText",
FeatureIgnorePrefix = "xxx"
}
}))
{
validator.Validate(new[] {
"shared | Age:25",
" | w1 w2 |a x:1",
"0:-1:.3 | w2 w3"
},
"{\"Age\":25,\"adf\":[{\"someText\":\"w1 w2\", \"a\":{\"x\":1}, \"xxxxIgnoreMe\":2}, {\"someText\":\"w2 w3\"}], \"_labelIndex\":1, \"_label_Cost\":-1, \"_label_Probability\":0.3}",
VowpalWabbitLabelComparator.ContextualBandit);
// all lower case (ASA issue)
validator.Validate(new[] {
" | w1 w2 |a x:1",
"0:-1:.3 | w2 w3"
},
"{\"adf\":[{\"someText\":\"w1 w2\", \"a\":{\"x\":1}, \"xxxxIgnoreMe\":2}, {\"someText\":\"w2 w3\"}], \"_labelindex\":1, \"_label_cost\":-1, \"_label_probability\":0.3}",
VowpalWabbitLabelComparator.ContextualBandit);
validator.Validate(new[] {
"shared | Age:25",
" | w1 w2 |a x:1",
" | w2 w3"
},
"{\"Age\":25,\"adf\":[{\"someText\":\"w1 w2\", \"a\":{\"x\":1}, \"xxxxIgnoreMe\":2}, {\"someText\":\"w2 w3\"}], \"_labelindex\":null}",
VowpalWabbitLabelComparator.ContextualBandit);
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonLabelExtraction()
{
using (var vw = new VowpalWabbit("--cb_adf --rank_all"))
{
using (var jsonSerializer = new VowpalWabbitJsonSerializer(vw))
{
string eventId = null;
jsonSerializer.RegisterExtension((state, property) =>
{
Assert.AreEqual(property, "_eventid");
Assert.IsTrue(state.Reader.Read());
eventId = (string)state.Reader.Value;
return true;
});
jsonSerializer.Parse("{\"_eventid\":\"abc123\",\"a\":1,\"_label_cost\":-1,\"_label_probability\":0.3}");
Assert.AreEqual("abc123", eventId);
using (var examples = jsonSerializer.CreateExamples())
{
var single = examples as VowpalWabbitSingleLineExampleCollection;
Assert.IsNotNull(single);
var label = single.Example.Label as ContextualBanditLabel;
Assert.IsNotNull(label);
Assert.AreEqual(-1, label.Cost);
Assert.AreEqual(0.3, label.Probability, 0.0001);
}
}
using (var jsonSerializer = new VowpalWabbitJsonSerializer(vw))
{
jsonSerializer.Parse("{\"_multi\":[{\"_text\":\"w1 w2\", \"a\":{\"x\":1}}, {\"_text\":\"w2 w3\"}], \"_labelindex\":1, \"_label_cost\":-1, \"_label_probability\":0.3}");
using (var examples = jsonSerializer.CreateExamples())
{
var multi = examples as VowpalWabbitMultiLineExampleCollection;
Assert.IsNotNull(multi);
Assert.AreEqual(2, multi.Examples.Length);
var label = multi.Examples[0].Label as ContextualBanditLabel;
Assert.AreEqual(0, label.Cost);
Assert.AreEqual(0, label.Probability);
label = multi.Examples[1].Label as ContextualBanditLabel;
Assert.IsNotNull(label);
Assert.AreEqual(-1, label.Cost);
Assert.AreEqual(0.3, label.Probability, 0.0001);
}
}
}
}
[TestMethod]
[TestCategory("JSON")]
public void TestJsonRedirection()
{
using (var validator = new VowpalWabbitExampleJsonValidator(new VowpalWabbitSettings("--cb_adf")))
{
validator.Validate(new[] {
"shared | Age:25",
" | w1 w2 |a x:1",
"0:-1:.3 | w2 w3"
},
"{\"_ignoreMe\":5,\"_sub\":{\"Age\":25,\"_multi\":[{\"_text\":\"w1 w2\", \"a\":{\"x\":1}}, {\"_text\":\"w2 w3\"}]}, \"_labelIndex\":1, \"_label_Cost\":-1, \"_label_Probability\":0.3}",
VowpalWabbitLabelComparator.ContextualBandit,
extension: (state, property) =>
{
if (!property.Equals("_sub"))
return false;
state.Parse();
return true;
});
}
}
public class MyContext
{
[Feature]
public int Feature { get; set; }
[JsonProperty("_multi")]
public IEnumerable<MyADF> Multi { get; set; }
}
public class MyADF
{
[Feature]
public int Foo { get; set; }
}
[TestMethod]
public void TestNumADFs()
{
var jsonDirectSerializer = VowpalWabbitSerializerFactory.CreateSerializer<MyContext>(new VowpalWabbitSettings { TypeInspector = JsonTypeInspector.Default })
as IVowpalWabbitMultiExampleSerializerCompiler<MyContext>;
Assert.IsNotNull(jsonDirectSerializer);
Assert.AreEqual(3,
jsonDirectSerializer.GetNumberOfActionDependentExamples(new MyContext { Multi = new MyADF[3] }));
}
}
}
| 38.747253 | 204 | 0.451999 | [
"BSD-3-Clause"
] | andraztori/vowpal_wabbit | cs/unittest/TestJson.cs | 14,106 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Portfolio.API.ViewModels;
using SendGrid;
using SendGrid.Helpers.Mail;
namespace Portfolio.API.Controllers
{
[Produces("application/json")]
[Route("message")]
public class MessageController : Controller
{
private readonly ApplicationConfiguration _applicationConfiguration;
public MessageController( ApplicationConfiguration applicationConfiguration)
{
this._applicationConfiguration = applicationConfiguration;
}
[HttpPost]
[Route("")]
public async Task<IActionResult> Create([FromBody] MessageViewModel message)
{
var res = await SendEmail(message);
return Ok(res.StatusCode == HttpStatusCode.Accepted);
}
protected async Task<Response> SendEmail(MessageViewModel message)
{
var client = new SendGridClient(_applicationConfiguration.SendGridApiKey);
var from = new EmailAddress(_applicationConfiguration.FromEmailAddress, "Portfolio");
var to = new EmailAddress(_applicationConfiguration.ToEmailAddress, "Mitchell");
var subject = "Portfolio: New Message";
var msg = MailHelper.CreateSingleEmail(from, to, subject, null, ConstructEmailBody(message));
return await client.SendEmailAsync(msg);
}
protected string ConstructEmailBody(MessageViewModel message)
{
var sb = new StringBuilder();
sb.Append("<p>").Append(message.Name).Append("</p>");
sb.Append("<p>").Append(message.Email).Append("</p>");
sb.Append("<p>").Append(message.Message).Append("</p>");
return sb.ToString();
}
}
}
| 33.423729 | 105 | 0.668864 | [
"MIT"
] | mwcaisse/portfolio | Portfolio/Portfolio.API/Controllers/MessageController.cs | 1,974 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Spettro.Models
{
public class Amplitude
{
public Amplitude(float[] values)
{
Values = values;
}
public float[] Values { get; }
public override string ToString()
{
var output = new string[Values.Length];
for (var i = 0; i < Values.Length; i++)
{
output[i] = Values[i].ToString("0.0'dB'");
}
return string.Join(",", output);
}
}
}
| 21.206897 | 58 | 0.525203 | [
"MIT"
] | BrightSoul/spectrum-analyzer | src/Models/Amplitude.cs | 617 | C# |
using System;
namespace zapnet
{
/// <summary>
/// For use in a bit field representing a selection of axes.
/// </summary>
[System.Serializable] [Flags]
public enum VectorAxes
{
/// <summary>
/// No axes are included in the set.
/// </summary>
None = 0,
/// <summary>
/// Whether the x axis is included in the set.
/// </summary>
X = 1,
/// <summary>
/// Whether the y axis is included in the set.
/// </summary>
Y = 2,
/// <summary>
/// Whether the z axis is included in the set.
/// </summary>
Z = 4
}
}
| 20.84375 | 64 | 0.478261 | [
"MIT"
] | BlackPhoenix134/zapnet | Solution/zapnet/Source/Utility/VectorAxes.cs | 669 | C# |
namespace HrdLib
{
public static class HrdElementExtension
{
//public static bool TryGetAttributeValue<T>(this HrdElement element, string attributeName, out T attrValue)
//{
// if (element == null || attributeName == null)
// {
// attrValue = default(T);
// return false;
// }
// var attr = element.GetElement<HrdAttribute>(attributeName);
// if (attr == null || attr.Value == null)
// {
// attrValue = default(T);
// return false;
// }
// if (attr.Value is T)
// {
// attrValue = (T)attr.Value;
// return true;
// }
// attrValue = default(T);
// return false;
//}
//public static bool TryGetArrayElement<T>(this HrdArray array, int index, out T value)
//{
// if (index < 0 || index >= array.Count)
// {
// value = default(T);
// return false;
// }
// var attr = array[index] as HrdAttribute;
// if (attr == null || attr.Value == null)
// {
// value = default(T);
// return false;
// }
// if (attr.Value is T)
// {
// value = (T)attr.Value;
// return true;
// }
// value = default(T);
// return false;
//}
}
}
| 26.719298 | 116 | 0.411687 | [
"MIT"
] | niello/deusexmachina | Tools/DialogEditor/HrdLib/HrdElementExtension.cs | 1,525 | C# |
//
// Copyright 2018-2019 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text.RegularExpressions;
using Carbonfrost.Commons.Spec.TestMatchers;
namespace Carbonfrost.Commons.Spec {
partial class Matchers {
public static MatchMatcher Match(string expected) {
return new MatchMatcher(new Regex(expected));
}
public static MatchMatcher Match(string expected, RegexOptions options) {
return new MatchMatcher(new Regex(expected, options));
}
public static MatchMatcher Match(Regex expected) {
return new MatchMatcher(expected);
}
}
static partial class Extensions {
public static void Match(this IExpectation<string> e, string expected) {
Match(e, expected, (string) null);
}
public static void Match(this IExpectation<string> e, string expected, RegexOptions options) {
Match(e, expected, options, (string) null);
}
public static void Match(this IExpectation<string> e, Regex expected) {
Match(e, expected, (string) null);
}
public static void Match(this IExpectation<string> e, string expected, string message, params object[] args) {
e.Like(Matchers.Match(expected), message, (object[]) args);
}
public static void Match(this IExpectation<string> e, string expected, RegexOptions options, string message, params object[] args) {
e.Like(Matchers.Match(expected, options), message, (object[]) args);
}
public static void Match(this IExpectation<string> e, Regex expected, string message, params object[] args) {
e.Like(Matchers.Match(expected), message, (object[]) args);
}
}
partial class Asserter {
public void Matches(string expected, string actual) {
Matches(expected, actual, (string) null);
}
public void Matches(string expected, RegexOptions options, string actual) {
Matches(expected, options, actual, (string) null);
}
public void Matches(Regex expected, string actual) {
Matches(expected, actual, (string) null);
}
public void Matches(string expected, string actual, string message, params object[] args) {
That(actual, Matchers.Match(expected), message, (object[]) args);
}
public void Matches(string expected, RegexOptions options, string actual, string message, params object[] args) {
That(actual, Matchers.Match(expected, options), message, (object[]) args);
}
public void Matches(Regex expected, string actual, string message, params object[] args) {
That(actual, Matchers.Match(expected), message, (object[]) args);
}
public void DoesNotMatch(string expected, string actual) {
DoesNotMatch(expected, actual, (string) null);
}
public void DoesNotMatch(string expected, RegexOptions options, string actual) {
DoesNotMatch(expected, options, actual, (string) null);
}
public void DoesNotMatch(Regex expected, string actual) {
DoesNotMatch(expected, actual, (string) null);
}
public void DoesNotMatch(string expected, string actual, string message, params object[] args) {
NotThat(actual, Matchers.Match(expected), message, (object[]) args);
}
public void DoesNotMatch(string expected, RegexOptions options, string actual, string message, params object[] args) {
NotThat(actual, Matchers.Match(expected, options), message, (object[]) args);
}
public void DoesNotMatch(Regex expected, string actual, string message, params object[] args) {
NotThat(actual, Matchers.Match(expected), message, (object[]) args);
}
}
partial class Assert {
public static void Matches(string expected, string actual) {
Global.Matches(expected, actual);
}
public static void Matches(string expected, RegexOptions options, string actual) {
Global.Matches(expected, options, actual);
}
public static void Matches(Regex expected, string actual) {
Global.Matches(expected, actual);
}
public static void Matches(string expected, string actual, string message, params object[] args) {
Global.Matches(expected, actual, message, (object[]) args);
}
public static void Matches(string expected, RegexOptions options, string actual, string message, params object[] args) {
Global.Matches(expected, options, actual, message, (object[]) args);
}
public static void Matches(Regex expected, string actual, string message, params object[] args) {
Global.Matches(expected, actual, message, (object[]) args);
}
public static void DoesNotMatch(string expected, string actual) {
Global.DoesNotMatch(expected, actual);
}
public static void DoesNotMatch(string expected, RegexOptions options, string actual) {
Global.DoesNotMatch(expected, options, actual);
}
public static void DoesNotMatch(Regex expected, string actual) {
Global.DoesNotMatch(expected, actual);
}
public static void DoesNotMatch(string expected, string actual, string message, params object[] args) {
Global.DoesNotMatch(expected, actual, message, (object[]) args);
}
public static void DoesNotMatch(string expected, RegexOptions options, string actual, string message, params object[] args) {
Global.DoesNotMatch(expected, options, actual, message, (object[]) args);
}
public static void DoesNotMatch(Regex expected, string actual, string message, params object[] args) {
Global.DoesNotMatch(expected, actual, message, (object[]) args);
}
}
partial class Assume {
public static void Matches(string expected, string actual) {
Global.Matches(expected, actual);
}
public static void Matches(string expected, RegexOptions options, string actual) {
Global.Matches(expected, options, actual);
}
public static void Matches(Regex expected, string actual) {
Global.Matches(expected, actual);
}
public static void Matches(string expected, string actual, string message, params object[] args) {
Global.Matches(expected, actual, message, (object[]) args);
}
public static void Matches(string expected, RegexOptions options, string actual, string message, params object[] args) {
Global.Matches(expected, options, actual, message, (object[]) args);
}
public static void Matches(Regex expected, string actual, string message, params object[] args) {
Global.Matches(expected, actual, message, (object[]) args);
}
public static void DoesNotMatch(string expected, string actual) {
Global.DoesNotMatch(expected, actual);
}
public static void DoesNotMatch(string expected, RegexOptions options, string actual) {
Global.DoesNotMatch(expected, options, actual);
}
public static void DoesNotMatch(Regex expected, string actual) {
Global.DoesNotMatch(expected, actual);
}
public static void DoesNotMatch(string expected, string actual, string message, params object[] args) {
Global.DoesNotMatch(expected, actual, message, (object[]) args);
}
public static void DoesNotMatch(string expected, RegexOptions options, string actual, string message, params object[] args) {
Global.DoesNotMatch(expected, options, actual, message, (object[]) args);
}
public static void DoesNotMatch(Regex expected, string actual, string message, params object[] args) {
Global.DoesNotMatch(expected, actual, message, (object[]) args);
}
}
namespace TestMatchers {
public class MatchMatcher : TestMatcher<string> {
public Regex Expected { get; private set; }
public MatchMatcher(Regex expected) {
if (expected == null) {
throw new ArgumentNullException("expected");
}
Expected = expected;
}
public override bool Matches(string actual) {
return Expected.IsMatch(actual);
}
}
}
}
| 37.236948 | 140 | 0.643982 | [
"Apache-2.0"
] | Carbonfrost/f-spec | dotnet/src/Carbonfrost.Commons.Spec/Src/Carbonfrost/Commons/Spec/Matchers/MatchMatcher.cs | 9,272 | C# |
using System;
using System.Threading.Tasks;
using System.Timers;
using System.Threading;
namespace AsyncAwait
{
class Program
{
private static System.Timers.Timer aTimer;
static async Task Main(string[] args)
{
AsyncMethods am = new AsyncMethods();
// var time1 = DateTime.Now;
// System.Console.WriteLine($"The first time is {time1}");
// Task m1 = am.Method1Async();
// Task m2 = am.Method2Async();
// Task m3 = am.Method3Async();
// Task m4 = am.Method4Async();
// Task m5 = am.Method5Async();
// time1 = DateTime.Now;
// System.Console.WriteLine($"The second time is {time1}");
// await m1;
// System.Console.WriteLine("M1 returned");
// await m2;
// System.Console.WriteLine("M2 returned");
// await m3;
// System.Console.WriteLine("M3 returned");
// await m4;
// System.Console.WriteLine("M4 returned");
// await m5;
// System.Console.WriteLine("M5 returned");
// time1 = DateTime.Now;
// System.Console.WriteLine($"The third time is {time1}");
//Thread.Sleep(15000);
//create a timer delegate to be raised every second.
// https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer.elapsed?view=netcore-3.1
aTimer = new System.Timers.Timer(); // create a timer
aTimer.Interval = 5; // set the timer interval to half a second
aTimer.Elapsed += OnTimedEvent; // subscribe the event to the timer
aTimer.AutoReset = true; // have the timer fire repeatedly
aTimer.Enabled = true; // start the timer
// Neither the class nor the methods are static so you can
// only access them through an instance of the class.
//AsyncMethods am = new AsyncMethods();
var time2 = DateTime.Now;
System.Console.WriteLine($"The first time is {time2}");
//call the methods the save the returned task into a Task.
Task m1Task = am.Method1Async();
var m2Task = am.Method2Async();
var m3Task = am.Method3Async();
var m4Task = am.Method4Async();
var m5Task = am.Method5Async();
//print the current time
time2 = DateTime.Now;
System.Console.WriteLine($"The second time is {time2}");
// now await the tasks.
await m1Task;
System.Console.WriteLine("M1 returned");
await m2Task;
System.Console.WriteLine("M2 returned");
await m3Task;
System.Console.WriteLine("M3 returned");
await m4Task;
System.Console.WriteLine("M4 returned");
await m5Task;
System.Console.WriteLine("M5 returned");
//wait 4 seconds to allow enough time for the methods to return
Task.Delay(4000).Wait();
// print the current time
var time3 = DateTime.Now;
System.Console.WriteLine($"The third time is {time3}");
}//end of Main()
// This event will fire based ont he trigger interal set above.
public static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
System.Console.WriteLine($"The time now is {e.SignalTime}");
}
}//end of Program
}//End of NameSpace | 35.97 | 103 | 0.554907 | [
"MIT"
] | 090820-dotnet-uta/curriculumTopics | Demos/AsyncAwait/Program.cs | 3,599 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.