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 |
|---|---|---|---|---|---|---|---|---|
namespace TodoWCF
{
public static class Constants
{
// URL of WCF service
public static string SoapUrl = "https://developer.xamarin.com:8081/TodoService.svc";
}
}
| 19 | 86 | 0.725146 | [
"Apache-2.0"
] | 4qu3l3c4r4/xamarin-forms-samples | WebServices/TodoWCF/TodoWCF/Constants.cs | 173 | C# |
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Web.LibraryManager.Vsix.UI.Models;
namespace Microsoft.Web.LibraryManager.Vsix.UI.Controls
{
/// <summary>
/// Interaction logic for PackageContentsTreeView.xaml
/// </summary>
public partial class PackageContentsTreeView
{
public PackageContentsTreeView()
{
InitializeComponent();
}
protected override AutomationPeer OnCreateAutomationPeer()
{
return new PackageContentsTreeViewAutomationPeer(this);
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
{
TreeView treeView = (TreeView)sender;
PackageItem packageItem = treeView.SelectedItem as PackageItem;
if (packageItem != null)
{
packageItem.IsChecked = !packageItem.IsChecked;
e.Handled = true;
}
}
else if (e.Key == Key.Tab)
{
TreeView treeView = (TreeView)sender;
TreeViewItem topTreeViewItem = treeView.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;
if (topTreeViewItem != null)
{
topTreeViewItem.IsSelected = true;
e.Handled = true;
}
}
}
}
}
| 30.08 | 117 | 0.55984 | [
"Apache-2.0"
] | aidmsu/LibraryManager | src/LibraryManager.Vsix/UI/Controls/PackageContentsTreeView.xaml.cs | 1,506 | C# |
using System.Diagnostics;
using System.Threading.Tasks;
using System.Collections.Generic;
using GitLabSharp.Entities;
using Version = GitLabSharp.Entities.Version;
using mrHelper.Common.Interfaces;
using mrHelper.Common.Constants;
namespace mrHelper.GitLabClient.Operators
{
/// <summary>
/// Implements DataCache-related interaction with GitLab
/// </summary>
internal class DataCacheOperator : BaseOperator
{
internal DataCacheOperator(string host, IHostProperties settings)
: base(host, settings)
{
}
internal Task<User> GetCurrentUserAsync()
{
return callWithSharedClient(
async (client) =>
await OperatorCallWrapper.Call(
() =>
CommonOperator.SearchCurrentUserAsync(client)));
}
internal Task<Project> GetProjectAsync(string projectName)
{
return callWithSharedClient(
async (client) =>
await OperatorCallWrapper.Call(
async () =>
(Project)await client.RunAsync(
async (gl) =>
await gl.Projects.Get(projectName).LoadTaskAsync())));
}
internal Task<IEnumerable<MergeRequest>> SearchMergeRequestsAsync(
SearchCriteria searchCriteria, int? maxResults, bool onlyOpen)
{
return callWithSharedClient(
async (client) =>
await OperatorCallWrapper.Call(
() =>
CommonOperator.SearchMergeRequestsAsync(client, searchCriteria, maxResults, onlyOpen)));
}
internal Task<IEnumerable<Commit>> GetCommitsAsync(string projectName, int iid)
{
// If MaxCommitsToLoad exceeds 100, need to call LoadAllTaskAsync() w/o PageFilter
Debug.Assert(Constants.MaxCommitsToLoad <= 100);
return callWithSharedClient(
async (client) =>
await OperatorCallWrapper.Call(
async () =>
(IEnumerable<Commit>)await client.RunAsync(
async (gl) =>
await gl.Projects.Get(projectName).MergeRequests.Get(iid).Commits.LoadTaskAsync(
new GitLabSharp.Accessors.PageFilter(Constants.MaxCommitsToLoad, 1)))));
}
internal Task<IEnumerable<Version>> GetVersionsAsync(string projectName, int iid)
{
return callWithSharedClient(
async (client) =>
await OperatorCallWrapper.Call(
async () =>
(IEnumerable<Version>)await client.RunAsync(
async (gl) =>
await gl.Projects.Get(projectName).MergeRequests.Get(iid).Versions.LoadAllTaskAsync())));
}
internal Task<Commit> GetCommitAsync(string projectName, string id)
{
return callWithSharedClient(
async (client) =>
await OperatorCallWrapper.Call(
async () =>
(Commit)await client.RunAsync(
async (gl) =>
await gl.Projects.Get(projectName).Repository.Commits.Get(id).LoadTaskAsync())));
}
internal Task<IEnumerable<Project>> GetProjects()
{
return callWithSharedClient(
async (client) =>
await OperatorCallWrapper.Call(
async () =>
(IEnumerable<Project>)await client.RunAsync(
async (gl) =>
await gl.Projects.LoadAllTaskAsync(
new GitLabSharp.Accessors.ProjectsFilter(false, true, true)))));
}
}
}
| 36.920792 | 113 | 0.570394 | [
"MIT"
] | BartWeyder/mrHelper | src/GitLabClient/src/Impl/Internal/Operators/DataCacheOperator.cs | 3,729 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Services;
namespace DF.WebUI.jqext.tests
{
/// <summary>
/// HttpUtility 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
public class HttpUtility : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string GetUrlResponse(string url)
{
string ret = null;
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
ret = reader.ReadToEnd();
return ret;
}
}
}
| 26.9 | 81 | 0.631041 | [
"Apache-2.0"
] | wolfchinaliu/gameCenter | jwx/src/main/webapp/easyui/tests/HttpUtility.asmx.cs | 1,138 | C# |
using System;
using BulletSharp.Math;
using static BulletSharp.UnsafeNativeMethods;
namespace BulletSharp
{
public enum BroadphaseNativeType
{
BoxShape,
TriangleShape,
TetrahedralShape,
ConvexTriangleMeshShape,
ConvexHullShape,
CONVEX_POINT_CLOUD_SHAPE_PROXYTYPE,
CUSTOM_POLYHEDRAL_SHAPE_TYPE,
IMPLICIT_CONVEX_SHAPES_START_HERE,
SphereShape,
MultiSphereShape,
CapsuleShape,
ConeShape,
ConvexShape,
CylinderShape,
UniformScalingShape,
MinkowskiSumShape,
MinkowskiDifferenceShape,
Box2DShape,
Convex2DShape,
CUSTOM_CONVEX_SHAPE_TYPE,
CONCAVE_SHAPES_START_HERE,
TriangleMeshShape,
ScaledTriangleMeshShape,
FAST_CONCAVE_MESH_PROXYTYPE,
TerrainShape,
GImpactShape,
MultiMaterialTriangleMesh,
EmptyShape,
StaticPlaneShape,
CUSTOM_CONCAVE_SHAPE_TYPE,
CONCAVE_SHAPES_END_HERE,
CompoundShape,
SoftBodyShape,
HFFLUID_SHAPE_PROXYTYPE,
HFFLUID_BUOYANT_CONVEX_SHAPE_PROXYTYPE,
INVALID_SHAPE_PROXYTYPE,
MAX_BROADPHASE_COLLISION_TYPES
}
[Flags]
public enum CollisionFilterGroups
{
None = 0,
DefaultFilter = 1,
StaticFilter = 2,
KinematicFilter = 4,
DebrisFilter = 8,
SensorTrigger = 16,
CharacterFilter = 32,
AllFilter = -1
}
public class BroadphaseProxy : BulletObject
{
private BulletObject _clientObject;
internal BroadphaseProxy(IntPtr native)
{
Initialize(native);
}
internal static BroadphaseProxy GetManaged(IntPtr native)
{
if (native == IntPtr.Zero)
{
return null;
}
IntPtr clientObjectPtr = btBroadphaseProxy_getClientObject(native);
if (clientObjectPtr != IntPtr.Zero) {
CollisionObject clientObject = CollisionObject.GetManaged(clientObjectPtr);
return clientObject.BroadphaseHandle;
}
throw new InvalidOperationException("Unknown broadphase proxy!");
//return new BroadphaseProxy(native);
}
public static bool IsCompound(BroadphaseNativeType proxyType)
{
return btBroadphaseProxy_isCompound(proxyType);
}
public static bool IsConcave(BroadphaseNativeType proxyType)
{
return btBroadphaseProxy_isConcave(proxyType);
}
public static bool IsConvex(BroadphaseNativeType proxyType)
{
return btBroadphaseProxy_isConvex(proxyType);
}
public static bool IsConvex2D(BroadphaseNativeType proxyType)
{
return btBroadphaseProxy_isConvex2d(proxyType);
}
public static bool IsInfinite(BroadphaseNativeType proxyType)
{
return btBroadphaseProxy_isInfinite(proxyType);
}
public static bool IsNonMoving(BroadphaseNativeType proxyType)
{
return btBroadphaseProxy_isNonMoving(proxyType);
}
public static bool IsPolyhedral(BroadphaseNativeType proxyType)
{
return btBroadphaseProxy_isPolyhedral(proxyType);
}
public static bool IsSoftBody(BroadphaseNativeType proxyType)
{
return btBroadphaseProxy_isSoftBody(proxyType);
}
public Vector3 AabbMax
{
get
{
Vector3 value;
btBroadphaseProxy_getAabbMax(Native, out value);
return value;
}
set => btBroadphaseProxy_setAabbMax(Native, ref value);
}
public Vector3 AabbMin
{
get
{
Vector3 value;
btBroadphaseProxy_getAabbMin(Native, out value);
return value;
}
set => btBroadphaseProxy_setAabbMin(Native, ref value);
}
public BulletObject ClientObject
{
get
{
IntPtr clientObjectPtr = btBroadphaseProxy_getClientObject(Native);
if (clientObjectPtr != IntPtr.Zero)
{
_clientObject = CollisionObject.GetManaged(clientObjectPtr);
}
return _clientObject;
}
set
{
var collisionObject = value as CollisionObject;
if (collisionObject != null)
{
btBroadphaseProxy_setClientObject(Native, collisionObject.Native);
}
else if (value == null)
{
btBroadphaseProxy_setClientObject(Native, IntPtr.Zero);
}
_clientObject = value;
}
}
public int CollisionFilterGroup
{
get => btBroadphaseProxy_getCollisionFilterGroup(Native);
set => btBroadphaseProxy_setCollisionFilterGroup(Native, value);
}
public int CollisionFilterMask
{
get => btBroadphaseProxy_getCollisionFilterMask(Native);
set => btBroadphaseProxy_setCollisionFilterMask(Native, value);
}
public int Uid => btBroadphaseProxy_getUid(Native);
public int UniqueId
{
get => btBroadphaseProxy_getUniqueId(Native);
set => btBroadphaseProxy_setUniqueId(Native, value);
}
}
public class BroadphasePair : BulletObject
{
internal BroadphasePair(IntPtr native)
{
Initialize(native);
}
public CollisionAlgorithm Algorithm
{
get
{
IntPtr valuePtr = btBroadphasePair_getAlgorithm(Native);
return (valuePtr == IntPtr.Zero) ? null : new CollisionAlgorithm(valuePtr, this);
}
set => btBroadphasePair_setAlgorithm(Native, (value.Native == IntPtr.Zero) ? IntPtr.Zero : value.Native);
}
public BroadphaseProxy Proxy0
{
get => BroadphaseProxy.GetManaged(btBroadphasePair_getPProxy0(Native));
set => btBroadphasePair_setPProxy0(Native, value.Native);
}
public BroadphaseProxy Proxy1
{
get => BroadphaseProxy.GetManaged(btBroadphasePair_getPProxy1(Native));
set => btBroadphasePair_setPProxy1(Native, value.Native);
}
}
}
| 22.853982 | 108 | 0.750048 | [
"Apache-2.0"
] | xtom0369/BulletPhysicsForUnity | BulletSharpPInvoke/BulletSharp/Collision/BroadphaseProxy.cs | 5,165 | C# |
/*
* Overture API
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Yaksa.OrckestraCommerce.Client.Client.OpenAPIDateConverter;
namespace Yaksa.OrckestraCommerce.Client.Model
{
/// <summary>
/// PaymentMethod
/// </summary>
[DataContract(Name = "PaymentMethod")]
public partial class PaymentMethod : IEquatable<PaymentMethod>, IValidatableObject
{
/// <summary>
/// The PaymentMethodType that is associated with this payment method.
/// </summary>
/// <value>The PaymentMethodType that is associated with this payment method.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TypeEnum
{
/// <summary>
/// Enum CreditCard for value: CreditCard
/// </summary>
[EnumMember(Value = "CreditCard")]
CreditCard = 1,
/// <summary>
/// Enum SavedCreditCard for value: SavedCreditCard
/// </summary>
[EnumMember(Value = "SavedCreditCard")]
SavedCreditCard = 2,
/// <summary>
/// Enum GiftCertificate for value: GiftCertificate
/// </summary>
[EnumMember(Value = "GiftCertificate")]
GiftCertificate = 3,
/// <summary>
/// Enum PurchaseOrder for value: PurchaseOrder
/// </summary>
[EnumMember(Value = "PurchaseOrder")]
PurchaseOrder = 4,
/// <summary>
/// Enum CashCard for value: CashCard
/// </summary>
[EnumMember(Value = "CashCard")]
CashCard = 5,
/// <summary>
/// Enum Cash for value: Cash
/// </summary>
[EnumMember(Value = "Cash")]
Cash = 6,
/// <summary>
/// Enum Debit for value: Debit
/// </summary>
[EnumMember(Value = "Debit")]
Debit = 7,
/// <summary>
/// Enum OnSiteCredit for value: OnSiteCredit
/// </summary>
[EnumMember(Value = "OnSiteCredit")]
OnSiteCredit = 8,
/// <summary>
/// Enum OnSiteDebit for value: OnSiteDebit
/// </summary>
[EnumMember(Value = "OnSiteDebit")]
OnSiteDebit = 9,
/// <summary>
/// Enum Cheque for value: Cheque
/// </summary>
[EnumMember(Value = "Cheque")]
Cheque = 10,
/// <summary>
/// Enum OnSiteUnspecified for value: OnSiteUnspecified
/// </summary>
[EnumMember(Value = "OnSiteUnspecified")]
OnSiteUnspecified = 11,
/// <summary>
/// Enum Paypal for value: Paypal
/// </summary>
[EnumMember(Value = "Paypal")]
Paypal = 12
}
/// <summary>
/// The PaymentMethodType that is associated with this payment method.
/// </summary>
/// <value>The PaymentMethodType that is associated with this payment method.</value>
[DataMember(Name = "type", EmitDefaultValue = false)]
public TypeEnum? Type { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="PaymentMethod" /> class.
/// </summary>
/// <param name="_default">Whether this payment method is used when none are specified.</param>
/// <param name="displayName">displayName.</param>
/// <param name="enabled">Whether this payment method is currently enabled and can be used..</param>
/// <param name="id">The unique identifier for this payment method..</param>
/// <param name="paymentProviderName">The name of the associated payment provider..</param>
/// <param name="propertyBag">propertyBag.</param>
/// <param name="type">The PaymentMethodType that is associated with this payment method..</param>
public PaymentMethod(bool _default = default(bool), Dictionary<string, string> displayName = default(Dictionary<string, string>), bool enabled = default(bool), string id = default(string), string paymentProviderName = default(string), Dictionary<string, Object> propertyBag = default(Dictionary<string, Object>), TypeEnum? type = default(TypeEnum?))
{
this.Default = _default;
this.DisplayName = displayName;
this.Enabled = enabled;
this.Id = id;
this.PaymentProviderName = paymentProviderName;
this.PropertyBag = propertyBag;
this.Type = type;
}
/// <summary>
/// Whether this payment method is used when none are specified
/// </summary>
/// <value>Whether this payment method is used when none are specified</value>
[DataMember(Name = "default", EmitDefaultValue = true)]
public bool Default { get; set; }
/// <summary>
/// Gets or Sets DisplayName
/// </summary>
[DataMember(Name = "displayName", EmitDefaultValue = false)]
public Dictionary<string, string> DisplayName { get; set; }
/// <summary>
/// Whether this payment method is currently enabled and can be used.
/// </summary>
/// <value>Whether this payment method is currently enabled and can be used.</value>
[DataMember(Name = "enabled", EmitDefaultValue = true)]
public bool Enabled { get; set; }
/// <summary>
/// The unique identifier for this payment method.
/// </summary>
/// <value>The unique identifier for this payment method.</value>
[DataMember(Name = "id", EmitDefaultValue = false)]
public string Id { get; set; }
/// <summary>
/// The name of the associated payment provider.
/// </summary>
/// <value>The name of the associated payment provider.</value>
[DataMember(Name = "paymentProviderName", EmitDefaultValue = false)]
public string PaymentProviderName { get; set; }
/// <summary>
/// Gets or Sets PropertyBag
/// </summary>
[DataMember(Name = "propertyBag", EmitDefaultValue = false)]
public Dictionary<string, Object> PropertyBag { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PaymentMethod {\n");
sb.Append(" Default: ").Append(Default).Append("\n");
sb.Append(" DisplayName: ").Append(DisplayName).Append("\n");
sb.Append(" Enabled: ").Append(Enabled).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" PaymentProviderName: ").Append(PaymentProviderName).Append("\n");
sb.Append(" PropertyBag: ").Append(PropertyBag).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as PaymentMethod);
}
/// <summary>
/// Returns true if PaymentMethod instances are equal
/// </summary>
/// <param name="input">Instance of PaymentMethod to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PaymentMethod input)
{
if (input == null)
return false;
return
(
this.Default == input.Default ||
this.Default.Equals(input.Default)
) &&
(
this.DisplayName == input.DisplayName ||
this.DisplayName != null &&
input.DisplayName != null &&
this.DisplayName.SequenceEqual(input.DisplayName)
) &&
(
this.Enabled == input.Enabled ||
this.Enabled.Equals(input.Enabled)
) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.PaymentProviderName == input.PaymentProviderName ||
(this.PaymentProviderName != null &&
this.PaymentProviderName.Equals(input.PaymentProviderName))
) &&
(
this.PropertyBag == input.PropertyBag ||
this.PropertyBag != null &&
input.PropertyBag != null &&
this.PropertyBag.SequenceEqual(input.PropertyBag)
) &&
(
this.Type == input.Type ||
this.Type.Equals(input.Type)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = hashCode * 59 + this.Default.GetHashCode();
if (this.DisplayName != null)
hashCode = hashCode * 59 + this.DisplayName.GetHashCode();
hashCode = hashCode * 59 + this.Enabled.GetHashCode();
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.PaymentProviderName != null)
hashCode = hashCode * 59 + this.PaymentProviderName.GetHashCode();
if (this.PropertyBag != null)
hashCode = hashCode * 59 + this.PropertyBag.GetHashCode();
hashCode = hashCode * 59 + this.Type.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 38.299342 | 357 | 0.548999 | [
"MIT"
] | Yaksa-ca/eShopOnWeb | src/Yaksa.OrckestraCommerce.Client/Model/PaymentMethod.cs | 11,643 | C# |
/* Copyright (c) 2006 Google Inc.
*
* 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.
*/
/*
* Created by Morten Christensen, http://blog.sitereactor.dk | http://twitter.com/sitereactor
*/
using Google.GData.Client;
namespace Google.GData.WebmasterTools
{
public class CrawlIssuesQuery : FeedQuery
{
/// <summary>
/// service url, http and https
/// </summary>
public const string HttpsFeedUrl = "https://www.google.com/webmasters/tools/feeds/siteID/crawlissues/";
/// <summary>
/// default constructor, does nothing
/// </summary>
public CrawlIssuesQuery()
: base(HttpsFeedUrl)
{
}
/// <summary>
/// base constructor, with initial queryUri
/// </summary>
/// <param name="queryUri">the query to use</param>
public CrawlIssuesQuery(string queryUri)
: base(queryUri)
{
}
/// <summary>
/// convienience method to create an URI based on a siteID
/// </summary>
/// <param name="siteID"></param>
/// <returns>string</returns>
public static string CreateCustomUri(string siteID)
{
return Utilities.EncodeSlugHeader(WebmasterToolsNameTable.BaseUserUri + siteID + "/crawlissues/");
}
}
}
| 32.20339 | 112 | 0.610526 | [
"Apache-2.0"
] | michael-jia-sage/libgoogle | src/webmastertools/crawlissuesquery.cs | 1,900 | C# |
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace NS_TestClass_compunit_04_second
{
using nanoFramework.TestFramework;
class NS_TestClass_compunit_04A
{
public void printClassName()
{
OutputHelper.WriteLine("Class B");
}
}
}
| 22.947368 | 70 | 0.688073 | [
"MIT"
] | Eclo/lib-CoreLibrary | Tests/NFUnitTestNamespace/NS_compunit_04B.cs | 436 | C# |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace DotNetNuke.Services.Authentication
{
public enum AuthMode
{
Login = 0,
Register = 1
}
}
| 22.461538 | 101 | 0.667808 | [
"MIT"
] | CMarius94/Dnn.Platform | DNN Platform/Library/Services/Authentication/AuthMode.cs | 294 | C# |
using AutoMapper;
using Outcompute.Trader.Data.Sql.Models;
using Outcompute.Trader.Models;
namespace Outcompute.Trader.Data.Sql;
internal class SqlTradingRepositoryProfile : Profile
{
public SqlTradingRepositoryProfile()
{
CreateMap<OrderQueryResult, OrderEntity>()
.ReverseMap();
CreateMap<AccountTrade, TradeEntity>()
.ReverseMap();
CreateMap<AccountTrade, TradeTableParameterEntity>()
.ForCtorParam(nameof(TradeTableParameterEntity.SymbolId), x => x.MapFrom((source, context) => ((IDictionary<string, int>)context.Items[nameof(TradeTableParameterEntity.SymbolId)])[source.Symbol]));
CreateMap<OrderQueryResult, OrderTableParameterEntity>()
.ForCtorParam(nameof(OrderTableParameterEntity.SymbolId), x => x.MapFrom((source, context) => ((IDictionary<string, int>)context.Items[nameof(OrderTableParameterEntity.SymbolId)])[source.Symbol]));
CreateMap<CancelStandardOrderResult, CancelOrderEntity>()
.ForCtorParam(nameof(CancelOrderEntity.SymbolId), x => x.MapFrom((source, context) => context.Items[nameof(CancelOrderEntity.SymbolId)]))
.ForCtorParam(nameof(CancelOrderEntity.ClientOrderId), x => x.MapFrom(y => y.OriginalClientOrderId));
CreateMap<Balance, BalanceTableParameterEntity>();
CreateMap<Balance, BalanceEntity>()
.ReverseMap();
CreateMap<MiniTicker, TickerEntity>()
.ReverseMap();
CreateMap<Kline, KlineTableParameterEntity>()
.ForCtorParam(nameof(KlineTableParameterEntity.SymbolId), x => x.MapFrom((source, context) => ((IDictionary<string, int>)context.Items[nameof(KlineTableParameterEntity.SymbolId)])[source.Symbol]));
CreateMap<Kline, KlineEntity>()
.ForCtorParam(nameof(KlineEntity.SymbolId), x => x.MapFrom((source, context) => context.Items[nameof(KlineEntity.SymbolId)]));
}
} | 46.926829 | 209 | 0.7079 | [
"MIT"
] | JorgeCandeias/Trader | Trader.Data.Sql/SqlTradingRepositoryProfile.cs | 1,926 | C# |
using System;
/*Problem 9. Forbidden words
We are given a string containing a list of forbidden words and a text containing some of these words.
Write a program that replaces the forbidden words with asterisks.
Example text: Microsoft announced its next generation PHP compiler today. It is based on .NET Framework 4.0
and is implemented as a dynamic language in CLR.
Forbidden words: PHP, CLR, Microsoft
The expected result: ********* announced its next generation *** compiler today.
It is based on .NET Framework 4.0 and is implemented as a dynamic language in ***.*/
namespace _09.Forbidden_words
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter text: ");
string text = Console.ReadLine();
Console.WriteLine("Enter a list of forbidden words, separated by space");
string[] forbiddenWords = Console.ReadLine().Trim().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < forbiddenWords.Length; i++)
{
text = text.Replace(forbiddenWords[i], new string('*', forbiddenWords[i].Length));
}
Console.WriteLine();
Console.WriteLine(text);
}
}
}
| 38.181818 | 122 | 0.652381 | [
"MIT"
] | VelislavLeonov/Telerik-Akademy | Homework Strings and Text Processing/09. Forbidden words/Forbidden words.cs | 1,262 | C# |
using System.ComponentModel.DataAnnotations;
using Monolith.Core.Attributes;
namespace Monolith.Foundation.Identity.Options
{
[Option("Foundation:Identity:JWT")]
public class JwtOptions
{
[Required]
public int ExpiresIn { get; set; }
[Required]
public string Audience { get; set; }
[Required]
public string Issuer { get; set; }
[Required]
[Environment("JWT_ISSUER_KEY")]
public string IssuerKey { get; set; }
}
}
| 21.956522 | 46 | 0.623762 | [
"MIT"
] | andrelom/monolith | src/Monolith.Foundation.Identity/Options/JwtOptions.cs | 505 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using Jinget.Core.Tests._BaseData;
namespace Jinget.Core.ExtensionMethods.Reflection.Tests
{
[TestClass()]
public class AssemblyExtensionsTests
{
[TestMethod()]
public void should_get_all_types_in_an_assembly()
{
var result = AssemblyExtensions.GetTypes(this.GetType().Assembly, typeof(NonGenericParent), normalizingPattern: @"Parent`1$");
Assert.IsNotNull(result);
Assert.IsTrue(result.Any());
Assert.IsTrue(result.All(x => x.Summary != string.Empty));
}
[TestMethod()]
public void should_get_all_authorized_methods_in_a_type()
{
var result = AssemblyExtensions.GetMethods(this.GetType().Assembly, typeof(NonGenericParent), typeof(Attributes.SummaryAttribute));
Assert.IsNotNull(result);
Assert.IsTrue(result.Any());
Assert.IsTrue(result.Any(x => x.MethodName!= "SampleMethod3"));
}
[TestMethod()]
public void should_get_all_methods_in_a_type()
{
var result = AssemblyExtensions.GetMethods(this.GetType().Assembly, typeof(NonGenericParent), typeof(Attributes.SummaryAttribute), onlyAuthorizedMethods: false);
Assert.IsNotNull(result);
Assert.IsTrue(result.Any());
Assert.IsTrue(result.Any(x => x.Summary != null));
}
}
} | 38.236842 | 173 | 0.651755 | [
"MIT"
] | VahidFarahmandian/Jinget | Jinget.Core.Tests/ExtensionMethods/Reflection/AssemblyExtensionsTests.cs | 1,455 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir & xuri 2021
//
// 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.
// This file was automatically generated and should not be edited directly.
using System.Runtime.InteropServices;
namespace SharpVk
{
/// <summary>
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct ProtectedSubmitInfo
{
/// <summary>
/// </summary>
public bool ProtectedSubmit
{
get;
set;
}
/// <summary>
/// </summary>
/// <param name="pointer">
/// </param>
internal unsafe void MarshalTo(SharpVk.Interop.ProtectedSubmitInfo* pointer)
{
pointer->SType = StructureType.ProtectedSubmitInfo;
pointer->Next = null;
pointer->ProtectedSubmit = ProtectedSubmit;
}
}
}
| 35.888889 | 84 | 0.679567 | [
"MIT"
] | xuri02/SharpVk | src/SharpVk/ProtectedSubmitInfo.gen.cs | 1,938 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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.
*/
using Python.Runtime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Util;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace QuantConnect.Python
{
/// <summary>
/// Organizes a list of data to create pandas.DataFrames
/// </summary>
public class PandasData
{
private static dynamic _pandas;
private readonly static HashSet<string> _baseDataProperties = typeof(BaseData).GetProperties().ToHashSet(x => x.Name.ToLowerInvariant());
private readonly static ConcurrentDictionary<Type, List<MemberInfo>> _membersByType = new ConcurrentDictionary<Type, List<MemberInfo>>();
private readonly Symbol _symbol;
private readonly Dictionary<string, Tuple<List<DateTime>, List<object>>> _series;
private readonly List<MemberInfo> _members;
/// <summary>
/// Gets true if this is a custom data request, false for normal QC data
/// </summary>
public bool IsCustomData { get; }
/// <summary>
/// Implied levels of a multi index pandas.Series (depends on the security type)
/// </summary>
public int Levels { get; } = 2;
/// <summary>
/// Initializes an instance of <see cref="PandasData"/>
/// </summary>
public PandasData(object data)
{
if (_pandas == null)
{
using (Py.GIL())
{
// this python Remapper class will work as a proxy and adjust the
// input to its methods using the provided 'mapper' callable object
_pandas = PythonEngine.ModuleFromString("remapper",
@"import pandas as pd
from pandas.core.resample import Resampler, DatetimeIndexResampler, PeriodIndexResampler, TimedeltaIndexResampler
from pandas.core.groupby.generic import DataFrameGroupBy, SeriesGroupBy
from pandas.core.indexes.frozen import FrozenList as pdFrozenList
from pandas.core.window import Expanding, EWM, Rolling, Window
from inspect import getmembers, isfunction, isgenerator
from functools import partial
from sys import modules
from clr import AddReference
AddReference(""QuantConnect.Common"")
from QuantConnect import *
def mapper(key):
'''Maps a Symbol object or a Symbol Ticker (string) to the string representation of
Symbol SecurityIdentifier. If cannot map, returns the object
'''
keyType = type(key)
if keyType is Symbol:
return str(key.ID)
if keyType is str:
kvp = SymbolCache.TryGetSymbol(key, None)
if kvp[0]:
return str(kvp[1].ID)
if keyType is tuple:
return tuple([mapper(x) for x in key])
if keyType is dict:
return {k:mapper(v) for k,v in key.items()}
return key
def try_wrap_as_index(obj):
'''Tries to wrap object if it is one of pandas' index objects.'''
objType = type(obj)
if objType is pd.Index:
return True, Index(obj)
if objType is pd.MultiIndex:
result = object.__new__(MultiIndex)
result._set_levels(obj.levels, copy=obj.copy, validate=False)
result._set_codes(obj.codes, copy=obj.copy, validate=False)
result._set_names(obj.names)
result.sortorder = obj.sortorder
return True, result
if objType is pdFrozenList:
return True, FrozenList(obj)
return False, obj
def try_wrap_as_pandas(obj):
'''Tries to wrap object if it is a pandas' object.'''
success, obj = try_wrap_as_index(obj)
if success:
return success, obj
objType = type(obj)
if objType is pd.DataFrame:
return True, DataFrame(data=obj)
if objType is pd.Series:
return True, Series(data=obj)
if objType is tuple:
anySuccess = False
results = list()
for item in obj:
success, result = try_wrap_as_pandas(item)
anySuccess |= success
results.append(result)
if anySuccess:
return True, tuple(results)
return False, obj
def try_wrap_resampler(obj, self):
'''Tries to wrap object if it is a pandas' Resampler object.'''
if not isinstance(obj, Resampler):
return False, obj
klass = CreateWrapperClass(type(obj))
return True, klass(self, groupby=obj.groupby, kind=obj.kind, axis=obj.axis)
def wrap_function(f):
'''Wraps function f with g.
Function g converts the args/kwargs to use alternative index keys
and the result of the f function call to the wrapper objects
'''
def g(*args, **kwargs):
if len(args) > 1:
args = mapper(args)
if len(kwargs) > 0:
kwargs = mapper(kwargs)
result = f(*args, **kwargs)
success, result = try_wrap_as_pandas(result)
if success:
return result
success, result = try_wrap_resampler(result, args[0])
if success:
return result
if isgenerator(result):
return ( (k, try_wrap_as_pandas(v)[1]) for k, v in result)
return result
g.__name__ = f.__name__
return g
def wrap_special_function(name, cls, fcls, gcls = None):
'''Replaces the special function of a given class by g that wraps fcls
This is how pandas implements them.
gcls represents an alternative for fcls
if the keyword argument has 'win_type' key for the Rolling/Window case
'''
fcls = CreateWrapperClass(fcls)
if gcls is not None:
gcls = CreateWrapperClass(fcls)
def g(*args, **kwargs):
if kwargs.get('win_type', None):
return gcls(*args, **kwargs)
return fcls(*args, **kwargs)
g.__name__ = name
setattr(cls, g.__name__, g)
def CreateWrapperClass(cls: type):
'''Creates wrapper classes.
Members of the original class are wrapped to allow alternative index look-up
'''
# Define a new class
klass = type(f'{cls.__name__}', (cls,) + cls.__bases__, dict(cls.__dict__))
def g(self, name):
'''Wrap '__getattribute__' to handle indices
Only need to wrap columns, index and levels attributes
'''
attr = object.__getattribute__(self, name)
if name in ['columns', 'index', 'levels']:
_, attr = try_wrap_as_index(attr)
return attr
g.__name__ = '__getattribute__'
g.__qualname__ = g.__name__
setattr(klass, g.__name__, g)
def wrap_union(f):
'''Wraps function f (union) with g.
Special case: The union method from index objects needs to
receive pandas' index objects to avoid infity recursion.
Function g converts the args/kwargs objects to one of pandas index objects
and the result of the f function call back to wrapper indexes objects
'''
def unwrap_index(obj):
'''Tries to unwrap object if it is one of this module wrapper's index objects.'''
objType = type(obj)
if objType is Index:
return pd.Index(obj)
if objType is MultiIndex:
result = object.__new__(pd.MultiIndex)
result._set_levels(obj.levels, copy=obj.copy, validate=False)
result._set_codes(obj.codes, copy=obj.copy, validate=False)
result._set_names(obj.names)
result.sortorder = obj.sortorder
return result
if objType is FrozenList:
return pdFrozenList(obj)
return obj
def g(*args, **kwargs):
args = tuple([unwrap_index(x) for x in args])
result = f(*args, **kwargs)
_, result = try_wrap_as_index(result)
return result
g.__name__ = f.__name__
return g
# We allow the wraopping of slot methods that are not inherited from object
# It will include operation methods like __add__ and __contains__
allow_list = set(x for x in dir(klass) if x.startswith('__')) - set(dir(object))
# Wrap class members of the newly created class
for name, member in getmembers(klass):
if name.startswith('_') and name not in allow_list:
continue
if isfunction(member):
if name == 'union':
member = wrap_union(member)
else:
member = wrap_function(member)
setattr(klass, name, member)
elif type(member) is property:
if type(member.fget) is partial:
func = CreateWrapperClass(member.fget.func)
fget = partial(func, name)
else:
fget = wrap_function(member.fget)
member = property(fget, member.fset, member.fdel, member.__doc__)
setattr(klass, name, member)
return klass
FrozenList = CreateWrapperClass(pdFrozenList)
Index = CreateWrapperClass(pd.Index)
MultiIndex = CreateWrapperClass(pd.MultiIndex)
Series = CreateWrapperClass(pd.Series)
DataFrame = CreateWrapperClass(pd.DataFrame)
wrap_special_function('groupby', Series, SeriesGroupBy)
wrap_special_function('groupby', DataFrame, DataFrameGroupBy)
wrap_special_function('ewm', Series, EWM)
wrap_special_function('ewm', DataFrame, EWM)
wrap_special_function('expanding', Series, Expanding)
wrap_special_function('expanding', DataFrame, Expanding)
wrap_special_function('rolling', Series, Rolling, Window)
wrap_special_function('rolling', DataFrame, Rolling, Window)
setattr(modules[__name__], 'concat', wrap_function(pd.concat))");
}
}
var enumerable = data as IEnumerable;
if (enumerable != null)
{
foreach (var item in enumerable)
{
data = item;
}
}
var type = data.GetType();
IsCustomData = type.Namespace != typeof(Bar).Namespace;
_members = new List<MemberInfo>();
_symbol = ((IBaseData)data).Symbol;
if (_symbol.SecurityType == SecurityType.Future) Levels = 3;
if (_symbol.SecurityType == SecurityType.Option) Levels = 5;
var columns = new HashSet<string>
{
"open", "high", "low", "close", "lastprice", "volume",
"askopen", "askhigh", "asklow", "askclose", "askprice", "asksize", "quantity", "suspicious",
"bidopen", "bidhigh", "bidlow", "bidclose", "bidprice", "bidsize", "exchange", "openinterest"
};
if (IsCustomData)
{
var keys = (data as DynamicData)?.GetStorageDictionary().ToHashSet(x => x.Key);
// C# types that are not DynamicData type
if (keys == null)
{
if (_membersByType.TryGetValue(type, out _members))
{
keys = _members.ToHashSet(x => x.Name.ToLowerInvariant());
}
else
{
var members = type.GetMembers().Where(x => x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property).ToList();
var duplicateKeys = members.GroupBy(x => x.Name.ToLowerInvariant()).Where(x => x.Count() > 1).Select(x => x.Key);
foreach (var duplicateKey in duplicateKeys)
{
throw new ArgumentException($"PandasData.ctor(): More than one \'{duplicateKey}\' member was found in \'{type.FullName}\' class.");
}
// If the custom data derives from a Market Data (e.g. Tick, TradeBar, QuoteBar), exclude its keys
keys = members.ToHashSet(x => x.Name.ToLowerInvariant());
keys.ExceptWith(_baseDataProperties);
keys.ExceptWith(GetPropertiesNames(typeof(QuoteBar), type));
keys.ExceptWith(GetPropertiesNames(typeof(TradeBar), type));
keys.ExceptWith(GetPropertiesNames(typeof(Tick), type));
keys.Add("value");
_members = members.Where(x => keys.Contains(x.Name.ToLowerInvariant())).ToList();
_membersByType.TryAdd(type, _members);
}
}
columns.Add("value");
columns.UnionWith(keys);
}
_series = columns.ToDictionary(k => k, v => Tuple.Create(new List<DateTime>(), new List<object>()));
}
/// <summary>
/// Adds security data object to the end of the lists
/// </summary>
/// <param name="baseData"><see cref="IBaseData"/> object that contains security data</param>
public void Add(object baseData)
{
foreach (var member in _members)
{
var key = member.Name.ToLowerInvariant();
var endTime = ((IBaseData) baseData).EndTime;
AddToSeries(key, endTime, (member as FieldInfo)?.GetValue(baseData));
AddToSeries(key, endTime, (member as PropertyInfo)?.GetValue(baseData));
}
var storage = (baseData as DynamicData)?.GetStorageDictionary();
if (storage != null)
{
var endTime = ((IBaseData) baseData).EndTime;
var value = ((IBaseData) baseData).Value;
AddToSeries("value", endTime, value);
foreach (var kvp in storage)
{
AddToSeries(kvp.Key, endTime, kvp.Value);
}
}
else
{
var ticks = new List<Tick> { baseData as Tick };
var tradeBar = baseData as TradeBar;
var quoteBar = baseData as QuoteBar;
Add(ticks, tradeBar, quoteBar);
}
}
/// <summary>
/// Adds Lean data objects to the end of the lists
/// </summary>
/// <param name="ticks">List of <see cref="Tick"/> object that contains tick information of the security</param>
/// <param name="tradeBar"><see cref="TradeBar"/> object that contains trade bar information of the security</param>
/// <param name="quoteBar"><see cref="QuoteBar"/> object that contains quote bar information of the security</param>
public void Add(IEnumerable<Tick> ticks, TradeBar tradeBar, QuoteBar quoteBar)
{
if (tradeBar != null)
{
var time = tradeBar.EndTime;
AddToSeries("open", time, tradeBar.Open);
AddToSeries("high", time, tradeBar.High);
AddToSeries("low", time, tradeBar.Low);
AddToSeries("close", time, tradeBar.Close);
AddToSeries("volume", time, tradeBar.Volume);
}
if (quoteBar != null)
{
var time = quoteBar.EndTime;
if (tradeBar == null)
{
AddToSeries("open", time, quoteBar.Open);
AddToSeries("high", time, quoteBar.High);
AddToSeries("low", time, quoteBar.Low);
AddToSeries("close", time, quoteBar.Close);
}
if (quoteBar.Ask != null)
{
AddToSeries("askopen", time, quoteBar.Ask.Open);
AddToSeries("askhigh", time, quoteBar.Ask.High);
AddToSeries("asklow", time, quoteBar.Ask.Low);
AddToSeries("askclose", time, quoteBar.Ask.Close);
AddToSeries("asksize", time, quoteBar.LastAskSize);
}
if (quoteBar.Bid != null)
{
AddToSeries("bidopen", time, quoteBar.Bid.Open);
AddToSeries("bidhigh", time, quoteBar.Bid.High);
AddToSeries("bidlow", time, quoteBar.Bid.Low);
AddToSeries("bidclose", time, quoteBar.Bid.Close);
AddToSeries("bidsize", time, quoteBar.LastBidSize);
}
}
if (ticks != null)
{
foreach (var tick in ticks)
{
if (tick == null) continue;
var time = tick.EndTime;
var column = tick.TickType == TickType.OpenInterest
? "openinterest"
: "lastprice";
if (tick.TickType == TickType.Quote)
{
AddToSeries("askprice", time, tick.AskPrice);
AddToSeries("asksize", time, tick.AskSize);
AddToSeries("bidprice", time, tick.BidPrice);
AddToSeries("bidsize", time, tick.BidSize);
}
AddToSeries("exchange", time, tick.Exchange);
AddToSeries("suspicious", time, tick.Suspicious);
AddToSeries("quantity", time, tick.Quantity);
AddToSeries(column, time, tick.LastPrice);
}
}
}
/// <summary>
/// Get the pandas.DataFrame of the current <see cref="PandasData"/> state
/// </summary>
/// <param name="levels">Number of levels of the multi index</param>
/// <returns>pandas.DataFrame object</returns>
public PyObject ToPandasDataFrame(int levels = 2)
{
var empty = new PyString(string.Empty);
var list = Enumerable.Repeat<PyObject>(empty, 5).ToList();
list[3] = _symbol.ID.ToString().ToPython();
if (_symbol.SecurityType == SecurityType.Future)
{
list[0] = _symbol.ID.Date.ToPython();
list[3] = _symbol.ID.ToString().ToPython();
}
if (_symbol.SecurityType == SecurityType.Option)
{
list[0] = _symbol.ID.Date.ToPython();
list[1] = _symbol.ID.StrikePrice.ToPython();
list[2] = _symbol.ID.OptionRight.ToString().ToPython();
list[3] = _symbol.ID.ToString().ToPython();
}
// Create the index labels
var names = "expiry,strike,type,symbol,time";
if (levels == 2)
{
names = "symbol,time";
list.RemoveRange(0, 3);
}
if (levels == 3)
{
names = "expiry,symbol,time";
list.RemoveRange(1, 2);
}
Func<object, bool> filter = x =>
{
var isNaNOrZero = x is double && ((double)x).IsNaNOrZero();
var isNullOrWhiteSpace = x is string && string.IsNullOrWhiteSpace((string)x);
var isFalse = x is bool && !(bool)x;
return x == null || isNaNOrZero || isNullOrWhiteSpace || isFalse;
};
Func<DateTime, PyTuple> selector = x =>
{
list[list.Count - 1] = x.ToPython();
return new PyTuple(list.ToArray());
};
// creating the pandas MultiIndex is expensive so we keep a cash
var indexCache = new Dictionary<List<DateTime>, dynamic>(new ListComparer<DateTime>());
using (Py.GIL())
{
// Returns a dictionary keyed by column name where values are pandas.Series objects
var pyDict = new PyDict();
var splitNames = names.Split(',');
foreach (var kvp in _series)
{
var values = kvp.Value.Item2;
if (values.All(filter)) continue;
dynamic index;
if (!indexCache.TryGetValue(kvp.Value.Item1, out index))
{
var tuples = kvp.Value.Item1.Select(selector).ToArray();
index = _pandas.MultiIndex.from_tuples(tuples, names: splitNames);
indexCache[kvp.Value.Item1] = index;
}
pyDict.SetItem(kvp.Key, _pandas.Series(values, index));
}
_series.Clear();
return _pandas.DataFrame(pyDict);
}
}
/// <summary>
/// Adds data to dictionary
/// </summary>
/// <param name="key">The key of the value to get</param>
/// <param name="time"><see cref="DateTime"/> object to add to the value associated with the specific key</param>
/// <param name="input"><see cref="Object"/> to add to the value associated with the specific key</param>
private void AddToSeries(string key, DateTime time, object input)
{
if (input == null) return;
Tuple<List<DateTime>, List<object>> value;
if (_series.TryGetValue(key, out value))
{
value.Item1.Add(time);
value.Item2.Add(input is decimal ? input.ConvertInvariant<double>() : input);
}
else
{
throw new ArgumentException($"PandasData.AddToSeries(): {key} key does not exist in series dictionary.");
}
}
/// <summary>
/// Get the lower-invariant name of properties of the type that a another type is assignable from
/// </summary>
/// <param name="baseType">The type that is assignable from</param>
/// <param name="type">The type that is assignable by</param>
/// <returns>List of string. Empty list if not assignable from</returns>
private static IEnumerable<string> GetPropertiesNames(Type baseType, Type type)
{
return baseType.IsAssignableFrom(type)
? baseType.GetProperties().Select(x => x.Name.ToLowerInvariant())
: Enumerable.Empty<string>();
}
}
} | 39.142612 | 159 | 0.567315 | [
"Apache-2.0"
] | kumacapitalllc/Lean | Common/Python/PandasData.cs | 22,783 | C# |
#if UTC
namespace Piksel.HockeyApp.Extensibility.Implementation.External
{
/// <summary>
/// Partial class to add the EventData attribute and any additional customizations to the generated type.
/// </summary>
[System.Diagnostics.Tracing.EventData(Name = "PartB_ExceptionData")]
internal partial class ExceptionData
{
}
}
#endif | 29.75 | 109 | 0.722689 | [
"MIT"
] | piksel/HockeySDK-Windows | Src/Kit.Core45/Extensibility/Implementation/External/ExceptionData.cs | 359 | C# |
using Avalonia.Markup.Xaml;
using CANShark.Desktop.Views.Core;
namespace CANShark.Desktop.Views.Setup
{
public class SetupView : BaseControl
{
public SetupView()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| 18.421053 | 42 | 0.591429 | [
"MIT"
] | CANBusAutomotive/CANShark | Src/CANShark.Desktop/Views/Setup/SetupView.xaml.cs | 352 | C# |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using d60.Cirqus.Events;
using d60.Cirqus.Extensions;
namespace d60.Cirqus.Views.ViewManagers
{
/// <summary>
/// Simple implementation of <see cref="IViewManagerProfiler"/> that sums up totals of time spent qualified by view manager instance
/// and domain event type. Collected stats can be had by calling <see cref="GetStats"/> which yields the collected stats and resets
/// the profiler. The profiler is reentrant in the sense that it does not break if called concurrently, but the results of
/// <see cref="GetStats"/> definitely make the most sense when called periodically by one single thread.
/// </summary>
public class StandardViewManagerProfiler : IViewManagerProfiler
{
class Tracking
{
public Tracking(TimeSpan initialDuration)
{
Total = initialDuration;
Updates = 1;
}
public TimeSpan Total { get; private set; }
public int Updates { get; private set; }
public Tracking Update(TimeSpan duration)
{
Total += duration;
Updates++;
return this;
}
}
readonly ConcurrentDictionary<IViewManager, ConcurrentDictionary<Type, Tracking>>
_timeSpent = new ConcurrentDictionary<IViewManager, ConcurrentDictionary<Type, Tracking>>();
public void RegisterTimeSpent(IViewManager viewManager, DomainEvent domainEvent, TimeSpan duration)
{
_timeSpent.GetOrAdd(viewManager, vm => new ConcurrentDictionary<Type, Tracking>())
.AddOrUpdate(domainEvent.GetType(), type => new Tracking(duration), (type, tracking) => tracking.Update(duration));
}
public ViewManagerStatsResult GetStats()
{
var viewManagers = _timeSpent.Keys.ToList();
var collectedStats = new List<ViewManagerStats>();
foreach (var viewManager in viewManagers)
{
ConcurrentDictionary<Type, Tracking> trackings;
if (!_timeSpent.TryRemove(viewManager, out trackings)) continue;
collectedStats.Add(new ViewManagerStats(viewManager, trackings.Select(kvp => new DomainEventStats(kvp.Key, kvp.Value.Total, kvp.Value.Updates))));
}
return new ViewManagerStatsResult(collectedStats);
}
public class ViewManagerStatsResult : IEnumerable<ViewManagerStats>
{
readonly List<ViewManagerStats> _stats;
public ViewManagerStatsResult(IEnumerable<ViewManagerStats> stats)
{
_stats = stats.ToList();
}
public IEnumerator<ViewManagerStats> GetEnumerator()
{
return _stats.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class ViewManagerStats : IEnumerable<DomainEventStats>
{
readonly List<DomainEventStats> _eventStats;
public ViewManagerStats(IViewManager viewManager, IEnumerable<DomainEventStats> eventStats)
{
_eventStats = eventStats.ToList();
ViewManager = viewManager;
}
public IViewManager ViewManager { get; private set; }
public IEnumerator<DomainEventStats> GetEnumerator()
{
return _eventStats.GetEnumerator();
}
public override string ToString()
{
return string.Format(@"{0}:
{1}", ViewManager.GetType().GetPrettyName(), string.Join(Environment.NewLine, this.Select(s => s.ToString()).Indented()));
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class DomainEventStats
{
public DomainEventStats(Type domainEventType, TimeSpan elapsed, int numberOfOccurrences)
{
DomainEventType = domainEventType;
Elapsed = elapsed;
NumberOfOccurrences = numberOfOccurrences;
}
public Type DomainEventType { get; private set; }
public TimeSpan Elapsed { get; private set; }
public int NumberOfOccurrences { get; private set; }
public override string ToString()
{
return string.Format("{0}: {1:0.0} s ({2})", DomainEventType.Name, Elapsed.TotalSeconds, NumberOfOccurrences);
}
}
}
} | 36.549618 | 162 | 0.600459 | [
"MIT"
] | brettwinters/Cirqus | src/d60.Cirqus/Views/ViewManagers/StandardViewManagerProfiler.cs | 4,790 | C# |
namespace MooVC.Architecture.Ddd.AggregateReferenceMismatchExceptionTests
{
using System;
using Xunit;
public sealed class WhenAggregateReferenceMismatchExceptionIsConstructed
{
[Fact]
public void GivenAReferenceThenAnInstanceIsReturnedWithAllPropertiesSet()
{
var reference = Guid.NewGuid().ToReference<AggregateRoot>();
var original = new AggregateReferenceMismatchException<EventCentricAggregateRoot>(reference);
Assert.Equal(reference, original.Reference);
}
[Fact]
public void GivenANullReferenceThenAnArgumentNullExceptionIsThrown()
{
Reference? reference = default;
ArgumentNullException exception = Assert.Throws<ArgumentNullException>(
() => new AggregateReferenceMismatchException<EventCentricAggregateRoot>(reference!));
Assert.Equal(nameof(reference), exception.ParamName);
}
}
} | 34.607143 | 105 | 0.692466 | [
"MIT"
] | MooVC/MooVC.Architecture | src/MooVC.Architecture.Tests/Ddd/AggregateReferenceMismatchExceptionTests/WhenAggregateReferenceMismatchExceptionIsConstructed.cs | 971 | C# |
using Business.ConstructiveHeuristics;
using Contracts.Interfaces.Business;
using Contracts.Interfaces.Repository.Instances;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Repository.Instances;
namespace RMCDP.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddScoped<IDeliveryOrderRepository, DeliveryOrderRepository>();
services.AddScoped<ILoadPlacesRepository, LoadPlacesRepository>();
services.AddScoped<IBestLoadPlaceFit, BestLoadPlaceFit>();
services.AddScoped<IBehrouzAlireza, BehrouzAlireza>();
}
// 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.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
}
}
}
| 32.117647 | 106 | 0.668498 | [
"MIT"
] | RichardSobreiro/RMCDP | RMCDP/RMCDP.Api/Startup.cs | 1,640 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Cake.Core.Configuration;
using Cake.Core.IO;
namespace Cake.Core.Tooling
{
/// <summary>
/// Implementation of the default tool resolution strategy.
/// </summary>
public sealed class ToolResolutionStrategy : IToolResolutionStrategy
{
private readonly IFileSystem _fileSystem;
private readonly ICakeEnvironment _environment;
private readonly IGlobber _globber;
private readonly ICakeConfiguration _configuration;
private readonly object _lock;
private List<DirectoryPath> _path;
/// <summary>
/// Initializes a new instance of the <see cref="ToolResolutionStrategy"/> class.
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="environment">The environment.</param>
/// <param name="globber">The globber.</param>
/// <param name="configuration">The configuration.</param>
public ToolResolutionStrategy(
IFileSystem fileSystem,
ICakeEnvironment environment,
IGlobber globber,
ICakeConfiguration configuration)
{
if (fileSystem == null)
{
throw new ArgumentNullException(nameof(fileSystem));
}
if (environment == null)
{
throw new ArgumentNullException(nameof(environment));
}
if (globber == null)
{
throw new ArgumentNullException(nameof(globber));
}
_fileSystem = fileSystem;
_environment = environment;
_globber = globber;
_configuration = configuration;
_lock = new object();
}
/// <summary>
/// Resolves the specified tool using the specified tool repository.
/// </summary>
/// <param name="repository">The tool repository.</param>
/// <param name="tool">The tool.</param>
/// <returns>
/// The path to the tool; otherwise <c>null</c>.
/// </returns>
public FilePath Resolve(IToolRepository repository, string tool)
{
if (repository == null)
{
throw new ArgumentNullException(nameof(repository));
}
if (tool == null)
{
throw new ArgumentNullException(nameof(tool));
}
if (string.IsNullOrWhiteSpace(tool))
{
throw new ArgumentException("Tool name cannot be empty.", nameof(tool));
}
// Does this file already have registrations?
var resolve = LookInRegistrations(repository, tool);
if (resolve == null)
{
// Look in ./tools/
resolve = LookInToolsDirectory(tool);
if (resolve == null)
{
// Look in the path environment variable.
resolve = LookInPath(tool);
}
}
return resolve;
}
private static FilePath LookInRegistrations(IToolRepository repository, string tool)
{
return repository.Resolve(tool).LastOrDefault();
}
private FilePath LookInToolsDirectory(string tool)
{
var pattern = string.Concat(GetToolsDirectory().FullPath, "/**/", tool);
var toolPath = _globber.GetFiles(pattern).FirstOrDefault();
return toolPath?.MakeAbsolute(_environment);
}
private FilePath LookInPath(string tool)
{
lock (_lock)
{
if (_path == null)
{
_path = GetPathDirectories();
}
foreach (var pathDir in _path)
{
var file = pathDir.CombineWithFilePath(tool);
if (_fileSystem.Exist(file))
{
return file.MakeAbsolute(_environment);
}
}
return null;
}
}
private DirectoryPath GetToolsDirectory()
{
var toolPath = _configuration.GetValue(Constants.Paths.Tools);
if (!string.IsNullOrWhiteSpace(toolPath))
{
return new DirectoryPath(toolPath);
}
return new DirectoryPath("./tools");
}
private List<DirectoryPath> GetPathDirectories()
{
var result = new List<DirectoryPath>();
var path = _environment.GetEnvironmentVariable("PATH");
if (!string.IsNullOrEmpty(path))
{
var separator = new[] { _environment.Platform.IsUnix() ? ':' : ';' };
var paths = path.Split(separator, StringSplitOptions.RemoveEmptyEntries);
result.AddRange(paths.Select(p => new DirectoryPath(p)));
}
return result;
}
}
} | 33.858974 | 92 | 0.542598 | [
"MIT"
] | cpx86/cake | src/Cake.Core/Tooling/ToolResolutionStrategy.cs | 5,284 | C# |
using Abp.Dependency;
using Abp.Extensions;
using Microsoft.Extensions.Configuration;
using TakTikan.Tailor.Configuration;
namespace TakTikan.Tailor.Net.Sms
{
public class TwilioSmsSenderConfiguration : ITransientDependency
{
private readonly IConfigurationRoot _appConfiguration;
public string AccountSid => _appConfiguration["Twilio:AccountSid"];
public string AuthToken => _appConfiguration["Twilio:AuthToken"];
public string SenderNumber => _appConfiguration["Twilio:SenderNumber"];
public TwilioSmsSenderConfiguration(IAppConfigurationAccessor configurationAccessor)
{
_appConfiguration = configurationAccessor.Configuration;
}
}
}
| 30.125 | 92 | 0.748271 | [
"MIT"
] | vahidsaberi/TakTikan-Tailor | aspnet-core/src/TakTikan.Tailor.Core/Net/Sms/TwilioSmsSenderConfiguration.cs | 725 | C# |
using System.Runtime.InteropServices;
namespace THNETII.WinApi.Native.WinNT
{
// C:\Program Files (x86)\Windows Kits\10\Include\10.0.17134.0\um\winnt.h, line 15344
/// <summary>
/// Session RIT State
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct POWER_SESSION_RIT_STATE
{
private byte ActiveField;
/// <value>
/// <see langword="true"/> - RIT input received,
/// <see langword="false"/> - RIT timeout
/// </value>
public bool Active
{
get => ActiveField != 0;
set => ActiveField = (byte)(value ? 1 : 0);
}
/// <summary>
/// last input time held for this session
/// </summary>
public int LastInputTime;
}
}
| 27.892857 | 89 | 0.558259 | [
"MIT"
] | couven92/thnetii-windows-api | src-native/THNETII.WinApi.Headers.WinNT/POWER_SESSION_RIT_STATE.cs | 781 | C# |
using Cotorra.Core.Utils;
using Cotorra.Core.Validator;
using Cotorra.Schema;
using Cotorra.Schema.Calculation;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace Cotorra.Core.Managers.Calculation
{
public class OverdraftCalculationManager : CalculationBase, ICalculationManager
{
/// <summary>
/// sumConceptsAccumulatedByDetail
/// </summary>
/// <param name="overdraftDetail"></param>
/// <param name="conceptPaymentRelationship"></param>
/// <param name="conceptType"></param>
/// <returns></returns>
private decimal sumConceptsAccumulatedByDetail(OverdraftDetail overdraftDetail,
ConceptPaymentRelationship conceptPaymentRelationship, ConceptType conceptType,
ConceptPaymentType conceptPaymentType)
{
var sumconceptsToAccumulate = 0M;
if (conceptPaymentRelationship.ConceptPaymentType == ConceptPaymentType.TotalAmount &&
conceptPaymentRelationship.ConceptPaymentType == conceptPaymentType)
{
if (overdraftDetail.ConceptPayment.ConceptType == conceptType && overdraftDetail.ConceptPaymentID == conceptPaymentRelationship.ConceptPaymentID)
{
sumconceptsToAccumulate += overdraftDetail.Amount;
}
}
else if (conceptPaymentRelationship.ConceptPaymentType == ConceptPaymentType.Amount1 &&
conceptPaymentRelationship.ConceptPaymentType == conceptPaymentType)
{
if (overdraftDetail.ConceptPayment.ConceptType == conceptType &&
overdraftDetail.ConceptPaymentID == conceptPaymentRelationship.ConceptPaymentID)
{
sumconceptsToAccumulate += overdraftDetail.Taxed;
}
}
else if (conceptPaymentRelationship.ConceptPaymentType == ConceptPaymentType.Amount2 &&
conceptPaymentRelationship.ConceptPaymentType == conceptPaymentType)
{
if (overdraftDetail.ConceptPayment.ConceptType == conceptType &&
overdraftDetail.ConceptPaymentID == conceptPaymentRelationship.ConceptPaymentID)
{
sumconceptsToAccumulate += overdraftDetail.Exempt;
}
}
else if (conceptPaymentRelationship.ConceptPaymentType == ConceptPaymentType.Amount3 &&
conceptPaymentRelationship.ConceptPaymentType == conceptPaymentType)
{
if (overdraftDetail.ConceptPayment.ConceptType == conceptType &&
overdraftDetail.ConceptPaymentID == conceptPaymentRelationship.ConceptPaymentID)
{
sumconceptsToAccumulate += overdraftDetail.IMSSTaxed;
}
}
else if (conceptPaymentRelationship.ConceptPaymentType == ConceptPaymentType.Amount4 &&
conceptPaymentRelationship.ConceptPaymentType == conceptPaymentType)
{
if (overdraftDetail.ConceptPayment.ConceptType == conceptType &&
overdraftDetail.ConceptPaymentID == conceptPaymentRelationship.ConceptPaymentID)
{
sumconceptsToAccumulate += overdraftDetail.IMSSExempt;
}
}
return sumconceptsToAccumulate;
}
/// <summary>
/// Templeate para crear los acumulados
/// </summary>
/// <param name="conceptPaymentRelationship"></param>
/// <param name="overdraft"></param>
/// <param name="periodFiscalYear"></param>
/// <param name="identityWorkID"></param>
/// <param name="instanceID"></param>
/// <param name="userID"></param>
/// <returns></returns>
private AccumulatedEmployee createDefault(ConceptPaymentRelationship conceptPaymentRelationship,
Guid employeeID, int periodFiscalYear,
Guid identityWorkID, Guid instanceID, Guid userID)
{
var accumulatedEmployee = new AccumulatedEmployee()
{
ID = Guid.NewGuid(),
Active = true,
AccumulatedTypeID = conceptPaymentRelationship.AccumulatedTypeID,
company = identityWorkID,
EmployeeID = employeeID,
CreationDate = DateTime.UtcNow,
DeleteDate = null,
user = userID,
InstanceID = instanceID,
Description = String.Empty,
Name = String.Empty,
Timestamp = DateTime.UtcNow,
StatusID = 1,
ExerciseFiscalYear = periodFiscalYear,
};
return accumulatedEmployee;
}
/// <summary>
/// Acumulados a partir de los cálculos en los conceptos
/// </summary>
/// <param name="overdraft"></param>
/// <param name="instanceID"></param>
/// <param name="identityWorkID"></param>
/// <param name="userID"></param>
/// <param name="conceptPaymentRelationships"></param>
/// <param name="conceptType"></param>
/// <param name="totalAmount"></param>
/// <param name="accumulatedEmployeesToCreateUpdate"></param>
/// <returns></returns>
private async Task<ConcurrentBag<AccumulatedEmployee>> accumulatesConceptsLocalAsync(
OverdraftDetail overdraftDetail,
Guid employeeID,
int periodFiscalYear,
int month,
Guid instanceID, Guid identityWorkID, Guid userID,
ConcurrentBag<ConceptPaymentRelationship> conceptPaymentRelationships,
ConceptType conceptType,
ConceptPaymentType conceptPaymentType,
ConcurrentBag<AccumulatedEmployee> accumulatedEmployeesToCreateUpdate = null)
{
if (null == accumulatedEmployeesToCreateUpdate)
{
accumulatedEmployeesToCreateUpdate = new ConcurrentBag<AccumulatedEmployee>(new List<AccumulatedEmployee>());
}
var conceptPaymentsRelationSubList =
conceptPaymentRelationships.Where(p =>
p.ConceptPaymentID == overdraftDetail.ConceptPaymentID);
//acumular montos por conceptos
Parallel.ForEach(conceptPaymentsRelationSubList, cpr =>
{
var conceptPaymentRelationship = cpr;
var sumconceptsToAccumulate = 0M;
sumconceptsToAccumulate = sumConceptsAccumulatedByDetail(
overdraftDetail, conceptPaymentRelationship,
conceptType, conceptPaymentType);
var accumulatedEmployee = default(AccumulatedEmployee);
bool isNew = false;
//si existe en las listas ya no se agrega
var accuList = accumulatedEmployeesToCreateUpdate.FirstOrDefault(p =>
p.InstanceID == instanceID &&
p.AccumulatedTypeID == conceptPaymentRelationship.AccumulatedTypeID &&
p.EmployeeID == employeeID &&
p.ExerciseFiscalYear == periodFiscalYear);
if (accuList == null || accuList == default(AccumulatedEmployee))
{
//Create entity
accumulatedEmployee = createDefault(conceptPaymentRelationship,
employeeID,
periodFiscalYear,
identityWorkID,
instanceID,
userID);
accumulatedEmployee.AccumulatedType = conceptPaymentRelationship.AccumulatedType;
isNew = true;
}
else
{
accumulatedEmployee = accuList;
accumulatedEmployee.AccumulatedType = conceptPaymentRelationship.AccumulatedType;
}
if (month == 1) accumulatedEmployee.January = accumulatedEmployee.January + sumconceptsToAccumulate;
else if (month == 2) accumulatedEmployee.February = accumulatedEmployee.February + sumconceptsToAccumulate;
else if (month == 3) accumulatedEmployee.March = accumulatedEmployee.March + sumconceptsToAccumulate;
else if (month == 4) accumulatedEmployee.April = accumulatedEmployee.April + sumconceptsToAccumulate;
else if (month == 5) accumulatedEmployee.May = accumulatedEmployee.May + sumconceptsToAccumulate;
else if (month == 6) accumulatedEmployee.June = accumulatedEmployee.June + sumconceptsToAccumulate;
else if (month == 7) accumulatedEmployee.July = accumulatedEmployee.July + sumconceptsToAccumulate;
else if (month == 8) accumulatedEmployee.August = accumulatedEmployee.August + sumconceptsToAccumulate;
else if (month == 9) accumulatedEmployee.September = accumulatedEmployee.September + sumconceptsToAccumulate;
else if (month == 10) accumulatedEmployee.October = accumulatedEmployee.October + sumconceptsToAccumulate;
else if (month == 11) accumulatedEmployee.November = accumulatedEmployee.November + sumconceptsToAccumulate;
else if (month == 12) accumulatedEmployee.December = accumulatedEmployee.December + sumconceptsToAccumulate;
if (isNew)
{
accumulatedEmployeesToCreateUpdate.Add(accumulatedEmployee);
}
});
return accumulatedEmployeesToCreateUpdate;
}
/// <summary>
/// Calcula todos los conceptos por tipo de concepto
/// </summary>
/// <param name="calculationBaseResult"></param>
/// <param name="conceptType"></param>
/// <param name="calculateOverdraftParams"></param>
/// <param name="accumulatedEmployees"></param>
/// <returns></returns>
internal async Task<(Overdraft, List<AccumulatedEmployee>)> CalculateByConceptAsync(
CalculationBaseResult calculationBaseResult,
ConceptType conceptType,
CalculateOverdraftParams calculateOverdraftParams,
ConcurrentBag<AccumulatedEmployee> accumulatedEmployees)
{
//1. calculate perceptions
var overdraftDetailsToIterate = calculationBaseResult.Overdraft.OverdraftDetails
.AsParallel()
.Where(p => p.ConceptPayment.ConceptType == conceptType)
.OrderBy(p => p.ConceptPayment.Code);
var employeeID = calculationBaseResult.Overdraft.EmployeeID;
var year = calculationBaseResult.Overdraft.PeriodDetail.FinalDate.Year;
var month = calculationBaseResult.Overdraft.PeriodDetail.FinalDate.Month;
foreach (var overdraftDetail in overdraftDetailsToIterate)
{
var formula = overdraftDetail.ConceptPayment.Formula;
var formulaValue = overdraftDetail.ConceptPayment.FormulaValue;
var formula1 = overdraftDetail.ConceptPayment.Formula1;
var formula2 = overdraftDetail.ConceptPayment.Formula2;
var formula3 = overdraftDetail.ConceptPayment.Formula3;
var formula4 = overdraftDetail.ConceptPayment.Formula4;
//Valor / Dias / etc
if (!String.IsNullOrEmpty(formulaValue) && !overdraftDetail.IsValueCapturedByUser)
{
var calculateResultValueLocal = base.Calculate(formulaValue);
overdraftDetail.Value = calculateResultValueLocal.Result;
}
if (!String.IsNullOrEmpty(formula) && !overdraftDetail.IsTotalAmountCapturedByUser)
{
//Monto / Total
var calculateResultLocal = base.Calculate(formula);
overdraftDetail.Amount = calculateResultLocal.Result;
}
//Calculate the accumulates for perceptions of the period
accumulatedEmployees = await accumulatesConceptsLocalAsync(
overdraftDetail,
employeeID,
year,
month,
calculateOverdraftParams.InstanceID,
calculateOverdraftParams.IdentityWorkID,
calculateOverdraftParams.UserID,
new ConcurrentBag<ConceptPaymentRelationship>(
calculationBaseResult.ConceptPaymentRelationships),
conceptType,
ConceptPaymentType.TotalAmount,
accumulatedEmployees
);
////Refresh accumulates for calculation
base.ReplaceAccumulates(accumulatedEmployees);
if (!String.IsNullOrEmpty(formula1) && !overdraftDetail.IsAmount1CapturedByUser)
{
var calculateResultLocal1 = base.Calculate(formula1);
overdraftDetail.Taxed = calculateResultLocal1.Result;
}
//Calculate the accumulates for perceptions of the period
accumulatedEmployees = await accumulatesConceptsLocalAsync(
overdraftDetail,
employeeID,
year,
month,
calculateOverdraftParams.InstanceID,
calculateOverdraftParams.IdentityWorkID,
calculateOverdraftParams.UserID,
new ConcurrentBag<ConceptPaymentRelationship>(
calculationBaseResult.ConceptPaymentRelationships),
conceptType,
ConceptPaymentType.Amount1,
accumulatedEmployees
);
////Refresh accumulates for calculation
base.ReplaceAccumulates(accumulatedEmployees);
if (!String.IsNullOrEmpty(formula2) && !overdraftDetail.IsAmount2CapturedByUser)
{
var calculateResultLocal2 = base.Calculate(formula2);
overdraftDetail.Exempt = calculateResultLocal2.Result;
}
//Calculate the accumulates for perceptions of the period
accumulatedEmployees = await accumulatesConceptsLocalAsync(
overdraftDetail,
employeeID,
year,
month,
calculateOverdraftParams.InstanceID,
calculateOverdraftParams.IdentityWorkID,
calculateOverdraftParams.UserID,
new ConcurrentBag<ConceptPaymentRelationship>(
calculationBaseResult.ConceptPaymentRelationships),
conceptType,
ConceptPaymentType.Amount2,
accumulatedEmployees
);
////Refresh accumulates for calculation
base.ReplaceAccumulates(accumulatedEmployees);
if (!String.IsNullOrEmpty(formula3) && !overdraftDetail.IsAmount3CapturedByUser)
{
var calculateResultLocal3 = base.Calculate(formula3);
overdraftDetail.IMSSTaxed = calculateResultLocal3.Result;
}
//Calculate the accumulates for perceptions of the period
accumulatedEmployees = await accumulatesConceptsLocalAsync(
overdraftDetail,
employeeID,
year,
month,
calculateOverdraftParams.InstanceID,
calculateOverdraftParams.IdentityWorkID,
calculateOverdraftParams.UserID,
new ConcurrentBag<ConceptPaymentRelationship>(
calculationBaseResult.ConceptPaymentRelationships),
conceptType,
ConceptPaymentType.Amount3,
accumulatedEmployees
);
////Refresh accumulates for calculation
base.ReplaceAccumulates(accumulatedEmployees);
if (!String.IsNullOrEmpty(formula4) && !overdraftDetail.IsAmount4CapturedByUser)
{
var calculateResultLocal4 = base.Calculate(formula4);
overdraftDetail.IMSSExempt = calculateResultLocal4.Result;
}
//Calculate the accumulates for perceptions of the period
accumulatedEmployees = await accumulatesConceptsLocalAsync(
overdraftDetail,
employeeID,
year,
month,
calculateOverdraftParams.InstanceID,
calculateOverdraftParams.IdentityWorkID,
calculateOverdraftParams.UserID,
new ConcurrentBag<ConceptPaymentRelationship>(
calculationBaseResult.ConceptPaymentRelationships),
conceptType,
ConceptPaymentType.Amount4,
accumulatedEmployees
);
////Refresh accumulates for calculation
base.ReplaceAccumulates(accumulatedEmployees);
}
return (calculationBaseResult.Overdraft, accumulatedEmployees.ToList());
}
/// <summary>
/// Saves overdraft and overdraft details, and the accumulates for employee
/// </summary>
/// <param name="overdraftToSave"></param>
/// <param name="accumulatedEmployees"></param>
/// <param name="identityWorkID"></param>
/// <returns></returns>
private async Task saveOverdraft(Overdraft overdraftToSave,
CalculateOverdraftParams calculateOverdraftParams)
{
//Prepare datatable to save
DataTable dtOverdraftGuidList = new DataTable();
dtOverdraftGuidList.Columns.Add("ID", typeof(Guid));
dtOverdraftGuidList.Columns.Add("OverdraftID", typeof(Guid));
dtOverdraftGuidList.Columns.Add("ConceptPaymentID", typeof(Guid));
dtOverdraftGuidList.Columns.Add("Value", typeof(decimal));
dtOverdraftGuidList.Columns.Add("Amount", typeof(decimal));
dtOverdraftGuidList.Columns.Add("Taxed", typeof(decimal));
dtOverdraftGuidList.Columns.Add("Exempt", typeof(decimal));
dtOverdraftGuidList.Columns.Add("IMSSTaxed", typeof(decimal));
dtOverdraftGuidList.Columns.Add("IMSSExempt", typeof(decimal));
dtOverdraftGuidList.Columns.Add("IsGeneratedByPermanentMovement", typeof(bool));
overdraftToSave.OverdraftDetails.ForEach(detail =>
{
dtOverdraftGuidList.Rows.Add(
detail.ID,
detail.OverdraftID,
detail.ConceptPaymentID,
detail.Value,
detail.Amount,
detail.Taxed,
detail.Exempt,
detail.IMSSTaxed,
detail.IMSSExempt,
detail.IsGeneratedByPermanentMovement);
});
//connection
using (var connection = new SqlConnection(ConnectionManager.ConfigConnectionString))
{
if (connection.State != ConnectionState.Open)
{
await connection.OpenAsync();
}
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "CalculousOverdraft";
//OverdraftDetails Parameter
SqlParameter paramOverdraftIdsTable = new SqlParameter("@OverdraftDetails", SqlDbType.Structured)
{
TypeName = "dbo.stampoverdraftdetailtabletype",
Value = dtOverdraftGuidList
};
command.Parameters.Add(paramOverdraftIdsTable);
command.Parameters.AddWithValue("@InstanceId", calculateOverdraftParams.InstanceID);
command.Parameters.AddWithValue("@company", calculateOverdraftParams.IdentityWorkID);
command.Parameters.AddWithValue("@user", calculateOverdraftParams.UserID);
//Execute SP de autorización
await command.ExecuteNonQueryAsync();
}
}
}
/// <summary>
/// Create Or Update ConceptPayment
/// </summary>
/// <param name="overdraftID"></param>
/// <param name="conceptPaymentID"></param>
/// <param name="amount"></param>
/// <param name="instanceID"></param>
/// <param name="identityWorkID"></param>
/// <param name="user"></param>
/// <returns></returns>
private async Task<Guid> createUpdateConceptPayment(
Guid overdraftID, Guid conceptPaymentID,
decimal amount, Guid instanceID,
Guid identityWorkID, Guid user
)
{
Guid ID = Guid.Empty;
using (var connection = new SqlConnection(ConnectionManager.ConfigConnectionString))
{
if (connection.State != ConnectionState.Open)
{
await connection.OpenAsync();
}
using (var command = connection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "CreateUpdateConceptPayment";
//@Amount
command.Parameters.AddWithValue("@OverdraftId", overdraftID);
command.Parameters.AddWithValue("@ConceptPaymentId", conceptPaymentID);
command.Parameters.AddWithValue("@Amount", amount);
command.Parameters.AddWithValue("@InstanceId", instanceID);
command.Parameters.AddWithValue("@company", identityWorkID);
command.Parameters.AddWithValue("@user", user);
//Execute SP de autorización
var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
ID = Guid.Parse(reader[0].ToString());
}
await reader.CloseAsync();
}
}
return ID;
}
/// <summary>
/// Ajuste al neto
/// </summary>
/// <param name="overdraftFinal"></param>
/// <param name="calculateOverdraftParams"></param>
/// <param name="dataResponse"></param>
/// <returns></returns>
internal async Task<Overdraft> amountAdjustmentAsync(Overdraft overdraftFinal,
CalculateOverdraftParams calculateOverdraftParams, CalculationBaseResult dataResponse)
{
//Ajuste al neto o ajuste en sueldos
const int BASE_ROUND_RATE = 10;
const int BASE_PERCENTAGE = 100;
const int AMOUNT_ADJUSTMENT_CODE = 99;
var overdraftManager = new OverdraftManager();
var totals = overdraftManager.GetTotals(overdraftFinal, new RoundUtil("MXN"));
//neto
var perceptions = totals.TotalSalaryTotals;
var deductions = totals.TotalDeductionPayments;
var neto = perceptions - deductions;
var netoCents = ((neto * BASE_ROUND_RATE) - Math.Truncate(neto * BASE_ROUND_RATE)) / BASE_ROUND_RATE;
var perceptionsCents = ((perceptions * BASE_ROUND_RATE) - Math.Truncate(perceptions * BASE_ROUND_RATE)) / BASE_ROUND_RATE;
var deductionsCents = ((deductions * BASE_ROUND_RATE) - Math.Truncate(deductions * BASE_ROUND_RATE)) / BASE_ROUND_RATE;
//calculate difference
var difference = 0M;
if ((netoCents * BASE_PERCENTAGE) % BASE_ROUND_RATE != 0)
{
difference = Math.Abs(netoCents - (BASE_ROUND_RATE / BASE_PERCENTAGE));
if (difference != 0)
{
difference = -1 * Math.Abs(0.1M - difference);
}
}
var detail = overdraftFinal.OverdraftDetails.FirstOrDefault(
p => p.ConceptPayment.Code == AMOUNT_ADJUSTMENT_CODE &&
p.ConceptPayment.ConceptType == ConceptType.DeductionPayment);
//connection
var conceptPayment = dataResponse.ConceptPayments.FirstOrDefault(p =>
p.Code == 99 &&
p.ConceptType == ConceptType.DeductionPayment);
var overdraftID = overdraftFinal.ID;
var conceptPaymentID = conceptPayment.ID;
//Create or Update ConceptPayment Neto Adjustment
var ID = Guid.NewGuid();
if (calculateOverdraftParams.SaveOverdraft)
{
ID = await createUpdateConceptPayment(overdraftID, conceptPaymentID, difference,
calculateOverdraftParams.InstanceID, calculateOverdraftParams.IdentityWorkID,
calculateOverdraftParams.UserID);
}
if (detail == null)
{
var overdraftDetail = new OverdraftDetail()
{
Active = true,
Amount = difference,
company = calculateOverdraftParams.IdentityWorkID,
ConceptPaymentID = conceptPayment.ID,
ConceptPayment = null,
CreationDate = DateTime.UtcNow,
DeleteDate = null,
Description = "Ajuste al neto (autogenerado)",
Name = "Ajuste al neto (autogenerado)",
ID = ID,
InstanceID = calculateOverdraftParams.InstanceID,
OverdraftID = overdraftFinal.ID,
user = calculateOverdraftParams.UserID,
Timestamp = DateTime.UtcNow,
StatusID = 1,
Label1 = "Gravado",
Label2 = "Exento",
Label3 = "IMSS Gravado",
Label4 = "IMSS Exento",
};
//add to overdraftFinal
overdraftDetail.ConceptPayment = conceptPayment;
overdraftFinal.OverdraftDetails.Add(overdraftDetail);
}
else
{
detail.Amount = difference;
}
return overdraftFinal;
}
/// <summary>
/// Do parallel calculation and deletes accumulates
/// </summary>
/// <param name="overdrafts"></param>
/// <param name="identityWorkID"></param>
/// <param name="instanceID"></param>
/// <param name="userID"></param>
/// <returns></returns>
private async Task doParallelCalculationAsync(IEnumerable<Overdraft> overdrafts, Guid identityWorkID, Guid instanceID, Guid userID)
{
//10. Calcula los Overdraft de todos los empleados de ese periodo
foreach (var overdraftToCalculate in overdrafts)
{
ICalculationManager calculationManager = new OverdraftCalculationManager();
CalculateOverdraftParams calculateOverdraftParams = new CalculateOverdraftParams()
{
IdentityWorkID = identityWorkID,
InstanceID = instanceID,
OverdraftID = overdraftToCalculate.ID,
ResetCalculation = false,
DeleteAccumulates = false,
UserID = userID
};
calculationManager.CalculateAsync(calculateOverdraftParams);
}
}
private async Task doCalculationAsync(IEnumerable<Overdraft> overdrafts, Guid identityWorkID, Guid instanceID, Guid userID)
{
//10. Calcula los Overdraft de todos los empleados de ese periodo
foreach (var overdraftToCalculate in overdrafts)
{
ICalculationManager calculationManager = new OverdraftCalculationManager();
CalculateOverdraftParams calculateOverdraftParams = new CalculateOverdraftParams()
{
IdentityWorkID = identityWorkID,
InstanceID = instanceID,
OverdraftID = overdraftToCalculate.ID,
ResetCalculation = false,
DeleteAccumulates = false,
UserID = userID
};
await calculationManager.CalculateAsync(calculateOverdraftParams);
}
}
/// <summary>
/// Calculation for overdraftsIds
/// </summary>
/// <param name="overdraftsIds"></param>
/// <param name="identityWorkID"></param>
/// <param name="instanceID"></param>
/// <param name="userID"></param>
/// <returns></returns>
private async Task doParallelCalculationAsync(IEnumerable<Guid> overdraftsIds, Guid identityWorkID, Guid instanceID, Guid userID)
{
//10. Calcula los Overdraft de todos los empleados de ese periodo
foreach (var overdraftToCalculate in overdraftsIds)
{
ICalculationManager calculationManager = new OverdraftCalculationManager();
CalculateOverdraftParams calculateOverdraftParams = new CalculateOverdraftParams()
{
IdentityWorkID = identityWorkID,
InstanceID = instanceID,
OverdraftID = overdraftToCalculate,
ResetCalculation = false,
DeleteAccumulates = false,
UserID = userID
};
calculationManager.CalculateAsync(calculateOverdraftParams);
}
}
private EmployeeConceptsRelationDetail getDefaultEmployeeConceptRelation(Guid instanceID, Guid companyID, Guid user,
decimal amountApplied, Overdraft overdraft, Guid employeeConceptRelationID)
{
var employeeConceptRelationDetail = new EmployeeConceptsRelationDetail()
{
Active = true,
AmountApplied = amountApplied,
company = companyID,
ConceptsRelationPaymentStatus = ConceptsRelationPaymentStatus.Pending,
CreationDate = DateTime.Now,
CompanyID = companyID,
DeleteDate = null,
Description = "",
EmployeeConceptsRelationID = employeeConceptRelationID,
ID = Guid.NewGuid(),
IdentityID = user,
InstanceID = instanceID,
Name = "",
OverdraftID = overdraft.ID,
PaymentDate = overdraft.PeriodDetail.InitialDate,
StatusID = 1,
Timestamp = DateTime.Now,
ValueApplied = 0,
IsAmountAppliedCapturedByUser = false
};
return employeeConceptRelationDetail;
}
private async Task<List<EmployeeConceptsRelationDetail>> getConceptRelated(
Overdraft overdraft,
int code,
ConceptType conceptType)
{
var lstDetails = new List<EmployeeConceptsRelationDetail>();
var companyID = overdraft.company;
var instanceID = overdraft.InstanceID;
var user = overdraft.user;
var middlewareManager = new MiddlewareManager<EmployeeConceptsRelation>(new BaseRecordManager<EmployeeConceptsRelation>(),
new EmployeeConceptsRelationValidator());
var overdraftDetail = overdraft.OverdraftDetails
.FirstOrDefault(p =>
p.ConceptPayment.Code == code &&
p.ConceptPayment.ConceptType == conceptType);
if (null != overdraftDetail)
{
var employeeConceptsRelations = await middlewareManager.FindByExpressionAsync(p =>
p.ConceptPaymentID == overdraftDetail.ConceptPaymentID &&
p.InstanceID == instanceID &&
p.EmployeeID == overdraft.EmployeeID &&
p.ConceptPaymentStatus == ConceptPaymentStatus.Active, companyID);
if (employeeConceptsRelations.Any())
{
lstDetails.Add(getDefaultEmployeeConceptRelation(
instanceID,
companyID,
user,
overdraftDetail.Amount,
overdraft,
employeeConceptsRelations.FirstOrDefault().ID
));
}
}
return lstDetails;
}
private async Task<List<EmployeeConceptsRelationDetail>> getInfonavitConceptRelated(
Overdraft overdraft,
InfonavitCreditType infonavitCreditType,
ConceptType conceptType)
{
var code = infonavitCreditType switch
{
InfonavitCreditType.FixQuota_D16 => 16,
InfonavitCreditType.DiscountFactor_D15 => 15,
InfonavitCreditType.Percentage_D59 => 59,
InfonavitCreditType.HomeInsurance_D14 => 14,
_ => throw new NotImplementedException("Tipo de retención infonavit inexistente"),
};
return await getConceptRelated(overdraft, code, conceptType);
}
private async Task saveConceptRelations(FunctionParams functionParams,
CalculateOverdraftParams calculateOverdraftParams, Overdraft overdraft)
{
var details = functionParams.EmployeeConceptsRelationDetails;
var identityWorkID = calculateOverdraftParams.IdentityWorkID;
var middlewareManager = new MiddlewareManager<EmployeeConceptsRelationDetail>(new BaseRecordManager<EmployeeConceptsRelationDetail>(),
new EmployeeConceptsRelationDetailValidator());
var toCreate = new List<EmployeeConceptsRelationDetail>();
var toUpdate = new List<EmployeeConceptsRelationDetail>();
//get infonavit movements
details.AddRange(await getInfonavitConceptRelated(overdraft, InfonavitCreditType.Percentage_D59, ConceptType.DeductionPayment));
details.AddRange(await getInfonavitConceptRelated(overdraft, InfonavitCreditType.FixQuota_D16, ConceptType.DeductionPayment));
details.AddRange(await getInfonavitConceptRelated(overdraft, InfonavitCreditType.DiscountFactor_D15, ConceptType.DeductionPayment));
details.AddRange(await getInfonavitConceptRelated(overdraft, InfonavitCreditType.HomeInsurance_D14, ConceptType.DeductionPayment));
//Consultar a BD todos los EmployeeConceptsRelationID
if (details.Any())
{
var ids = details.Select(p => p.EmployeeConceptsRelationID);
var detailsFound = await middlewareManager.FindByExpressionAsync(p =>
ids.Contains(p.EmployeeConceptsRelationID), identityWorkID);
//Ver si existen en BD o no
details.ForEach(detail =>
{
//Encontrar el EmployeeConceptsRelation correspondiente para ver si es create or update
var detailInListFound = detailsFound.Where(p =>
p.OverdraftID == detail.OverdraftID &&
p.EmployeeConceptsRelationID == detail.EmployeeConceptsRelationID &&
p.InstanceID == detail.InstanceID);
if (detailInListFound.Any())
{
detailInListFound.FirstOrDefault().AmountApplied = detail.AmountApplied;
detailInListFound.FirstOrDefault().Timestamp = DateTime.Now;
toUpdate.Add(detailInListFound.FirstOrDefault());
}
else
{
toCreate.Add(detail);
}
});
//Escribir a BD
if (toCreate.Any())
{
await middlewareManager.CreateAsync(toCreate, identityWorkID);
}
if (toUpdate.Any())
{
await middlewareManager.UpdateAsync(toUpdate, identityWorkID);
}
}
}
/// <summary>
/// Calculates the formula by overdraft
/// </summary>
/// <param name="calculateByOverdraftIDParams"></param>
/// <returns></returns>
public async Task<ICalculateResult> CalculateAsync(ICalculateParams calculateParams)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//result instance
var calculateResult = new CalculateOverdraftResult();
var calculateOverdraftParams = calculateParams as CalculateOverdraftParams;
//Functions params // Para inyectarle a las formulas los datos necesarios para el calculo (1 sola llamada a BD)
var dataResponse = await GetDataAsync(
calculateOverdraftParams.OverdraftID,
calculateOverdraftParams.InstanceID,
calculateOverdraftParams.IdentityWorkID);
//Poner en 0 todos los amounts / previous calculation
dataResponse.Overdraft.OverdraftDetails.ForEach(p =>
{
p.Taxed = 0M;
p.Exempt = 0M;
p.IMSSTaxed = 0M;
p.IMSSExempt = 0M;
if (calculateOverdraftParams.ResetCalculation)
{
p.IsAmount1CapturedByUser = false;
p.IsAmount2CapturedByUser = false;
p.IsAmount3CapturedByUser = false;
p.IsAmount4CapturedByUser = false;
p.IsTotalAmountCapturedByUser = false;
p.IsValueCapturedByUser = false;
p.Value = 0M;
p.Amount = 0M;
}
});
FunctionParams functionParams = new FunctionParams();
functionParams.CalculationBaseResult = dataResponse;
functionParams.IdentityWorkID = calculateOverdraftParams.IdentityWorkID;
functionParams.InstanceID = calculateOverdraftParams.InstanceID;
//Initializate data, arguments, and functions
base.Initializate(functionParams);
//overdraftDetails - All Perceptions, Deductions and Obligations
List<AccumulatedEmployee> accumulatedEmployees = null;
//Perceptions
(var overdraft, var employeeAccumulates) = await CalculateByConceptAsync(dataResponse, ConceptType.SalaryPayment,
calculateOverdraftParams, null);
accumulatedEmployees = employeeAccumulates;
dataResponse.Overdraft = overdraft;
//Deductions
(overdraft, employeeAccumulates) = await CalculateByConceptAsync(dataResponse, ConceptType.DeductionPayment,
calculateOverdraftParams, new ConcurrentBag<AccumulatedEmployee>(accumulatedEmployees));
accumulatedEmployees = employeeAccumulates;
dataResponse.Overdraft = overdraft;
//Liabilities
//Liability
dataResponse.IsLiability = true;
(overdraft, employeeAccumulates) = await CalculateByConceptAsync(dataResponse, ConceptType.LiabilityPayment,
calculateOverdraftParams, new ConcurrentBag<AccumulatedEmployee>(accumulatedEmployees));
dataResponse.Overdraft = overdraft;
dataResponse.IsLiability = false;
//Ajuste al neto
var overdraftFinal = await amountAdjustmentAsync(dataResponse.Overdraft, calculateOverdraftParams, dataResponse);
//Prepare data to result
calculateResult.OverdraftResult = overdraftFinal;
//Afecta el sobrerecibo y sus acumulados del periodo en cálculo
if (calculateOverdraftParams.SaveOverdraft)
{
//save conceptRelations - fonacot, infonavit, etc.
await saveConceptRelations(functionParams, calculateOverdraftParams, overdraftFinal);
//save overdraft and details
await saveOverdraft(overdraftFinal, calculateOverdraftParams);
}
stopwatch.Stop();
Trace.WriteLine($"Time elapsed in the overdraft calculation {stopwatch.Elapsed}");
//return the result
return calculateResult;
}
/// <summary>
/// calculate single formula
/// </summary>
/// <param name="formula"></param>
/// <returns></returns>
public CalculateResult CalculateFormula(string formula)
{
return base.Calculate(formula, true);
}
/// <summary>
/// do the calculation for each overdraft per employee in the new period
/// </summary>
/// <param name="newOverdrafts"></param>
/// <param name="authorizationParams"></param>
public async Task CalculationFireAndForgetAsync(IEnumerable<Overdraft> overdrafts, Guid identityWorkID, Guid instanceID, Guid userID)
{
Task.Run(async () =>
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
if (overdrafts.Any())
{
await doParallelCalculationAsync(overdrafts, identityWorkID, instanceID, userID);
}
stopwatch.Stop();
Trace.WriteLine($"Time elapsed in the fire and forget calculation {stopwatch.Elapsed} for {overdrafts.Count()} overdrafts");
});
}
/// <summary>
/// do the calculation for each overdraft per employee in the new period
/// </summary>
/// <param name="newOverdrafts"></param>
/// <param name="authorizationParams"></param>
public async Task CalculationFireAndForgetAsync(IEnumerable<Guid> overdraftsIds, Guid identityWorkID, Guid instanceID, Guid userID)
{
Task.Run(async () =>
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
if (overdraftsIds.Any())
{
await doParallelCalculationAsync(overdraftsIds, identityWorkID, instanceID, userID);
}
stopwatch.Stop();
Trace.WriteLine($"Time elapsed in the fire and forget calculation {stopwatch.Elapsed} for {overdraftsIds.Count()} overdrafts");
});
}
/// <summary>
/// do the calculation for each overdraft per employee in the new period by employees Ids
/// </summary>
/// <param name="employeeIds"></param>
/// <param name="identityWorkID"></param>
/// <param name="instanceID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public async Task CalculationFireAndForgetByEmployeesAsync(IEnumerable<Guid> employeeIds, Guid identityWorkID, Guid instanceID, Guid userID)
{
Task.Run(async () =>
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//Get overdrafts to do calculation
var middlewareOverdraft = new MiddlewareManager<Overdraft>(
new BaseRecordManager<Overdraft>(), new OverdraftValidator());
var overdrafts = await middlewareOverdraft.FindByExpressionAsync(p =>
p.InstanceID == instanceID &&
employeeIds.Contains(p.EmployeeID) &&
p.OverdraftStatus == OverdraftStatus.None
, identityWorkID);
await doParallelCalculationAsync(overdrafts, identityWorkID, instanceID, userID);
stopwatch.Stop();
Trace.WriteLine($"Time elapsed in the fire and forget calculation {stopwatch.Elapsed} for {overdrafts.Count()} overdrafts");
});
}
/// <summary>
/// do the calculation for each overdraft per employee in the new period by employees Ids
/// </summary>
/// <param name="employeeIds"></param>
/// <param name="identityWorkID"></param>
/// <param name="instanceID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public async Task CalculationByEmployeesAsync(IEnumerable<Guid> employeeIds, Guid identityWorkID, Guid instanceID, Guid userID)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//Get overdrafts to do calculation
var middlewareOverdraft = new MiddlewareManager<Overdraft>(
new BaseRecordManager<Overdraft>(), new OverdraftValidator());
var overdrafts = await middlewareOverdraft.FindByExpressionAsync(p =>
p.InstanceID == instanceID &&
employeeIds.Contains(p.EmployeeID) &&
p.OverdraftStatus == OverdraftStatus.None
, identityWorkID);
await doCalculationAsync(overdrafts, identityWorkID, instanceID, userID);
stopwatch.Stop();
Trace.WriteLine($"Time elapsed in calculation by employees {stopwatch.Elapsed} for {overdrafts.Count()} overdrafts");
}
/// <summary>
/// do the calculation for each overdraft per employee in the new period by employees Ids
/// </summary>
/// <param name="employeeIds"></param>
/// <param name="identityWorkID"></param>
/// <param name="instanceID"></param>
/// <param name="userID"></param>
/// <returns></returns>
public async Task CalculationFireAndForgetByPeriodIdsAsync(IEnumerable<Guid> periodIds, Guid identityWorkID, Guid instanceID, Guid userID)
{
Task.Run(async () =>
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//Get overdrafts to do calculation
var middlewareOverdraft = new MiddlewareManager<Overdraft>(
new BaseRecordManager<Overdraft>(), new OverdraftValidator());
var overdrafts = await middlewareOverdraft.FindByExpressionAsync(p =>
p.InstanceID == instanceID &&
periodIds.Contains(p.PeriodDetail.PeriodID) &&
p.PeriodDetail.PeriodStatus == PeriodStatus.Calculating &&
p.OverdraftStatus == OverdraftStatus.None
, identityWorkID, new string[] { "PeriodDetail" });
await doParallelCalculationAsync(overdrafts, identityWorkID, instanceID, userID);
stopwatch.Stop();
Trace.WriteLine($"Time elapsed in the fire and forget calculation {stopwatch.Elapsed} for {overdrafts.Count()} overdrafts");
});
}
}
}
| 45.196613 | 161 | 0.58051 | [
"MIT"
] | CotorraProject/Cotorra | Cotorra.Core/Managers/Calculation/Calc/OverdraftCalculationManager.cs | 48,051 | C# |
using System;
using System.Linq;
using SQLEngine.SqlServer;
using Xunit;
namespace SQLEngine.Tests.SqlServer
{
public partial class AllTests
{
private readonly IExpressionCompiler _compiler=new SqlExpressionCompiler();
#region Equals
[Fact]
public void Test_Expression_Compiler_Simple_Equal_Integer()
{
var expected = $"{nameof(UserTable.IdInteger)} = 1";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger == 1);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Equal_Integer_1()
{
var expected = $"{nameof(UserTable.IdInteger)} = 10";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger == 10L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Equal_Long()
{
var expected = $"{nameof(UserTable.IdLong)} = 2";
var actual = _compiler.Compile<UserTable>(x => x.IdLong == 2L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Equal_Long_1()
{
var expected = $"{nameof(UserTable.IdLong)} = 3";
var actual = _compiler.Compile<UserTable>(x => x.IdLong == (int)3);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Equal_Short_1()
{
var expected = $"{nameof(UserTable.IdShort)} = 3";
var actual = _compiler.Compile<UserTable>(x => x.IdShort == (short)3);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Equal_Byte_1()
{
byte b = 3;
var expected = $"{nameof(UserTable.IdByte)} = {b}";
var actual = _compiler.Compile<UserTable>(x => x.IdByte == b);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Equal_Guid()
{
var guid = Guid.NewGuid();
var expected = $"{nameof(UserTable.IdGuid)} = '{guid}'";
var actual = _compiler.Compile<UserTable>(x => x.IdGuid == guid);
Assert.Equal(expected, actual);
}
#endregion
#region Not Equals
[Fact]
public void Test_Expression_Compiler_Simple_NotEqual_Integer()
{
var expected = $"{nameof(UserTable.IdInteger)} <> 1";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger != 1);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_NotEqual_Integer_1()
{
var expected = $"{nameof(UserTable.IdInteger)} <> 10";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger != 10L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_NotEqual_Long()
{
var expected = $"{nameof(UserTable.IdLong)} <> 2";
var actual = _compiler.Compile<UserTable>(x => x.IdLong != 2L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_NotEqual_Long_1()
{
var expected = $"{nameof(UserTable.IdLong)} <> 3";
var actual = _compiler.Compile<UserTable>(x => x.IdLong != (int)3);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_NotEqual_Guid()
{
var guid = Guid.NewGuid();
var expected = $"{nameof(UserTable.IdGuid)} <> '{guid}'";
var actual = _compiler.Compile<UserTable>(x => x.IdGuid != guid);
Assert.Equal(expected, actual);
}
#endregion
#region Greater
[Fact]
public void Test_Expression_Compiler_Simple_Greater_Integer()
{
var expected = $"{nameof(UserTable.IdInteger)} > 1";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger > 1);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Greater_Integer_1()
{
var expected = $"{nameof(UserTable.IdInteger)} > 10";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger > 10L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Greater_Long()
{
var expected = $"{nameof(UserTable.IdLong)} > 2";
var actual = _compiler.Compile<UserTable>(x => x.IdLong > 2L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Greater_Long_1()
{
var expected = $"{nameof(UserTable.IdLong)} > 3";
var actual = _compiler.Compile<UserTable>(x => x.IdLong > (int)3);
Assert.Equal(expected, actual);
}
//[Fact]
//public void Test_Expression_Compiler_Simple_Greater_Guid()
//{
// var guid = Guid.NewGuid();
// var expected = $"{nameof(UserTable.IdGuid)} > '{guid}'";
// var actual = _compiler.Compile<UserTable>(x => x.IdGuid > guid);
// Assert.Equal(expected, actual);
//}
#endregion
#region GreaterEqual
[Fact]
public void Test_Expression_Compiler_Simple_GreaterEqual_Integer()
{
var expected = $"{nameof(UserTable.IdInteger)} >= 1";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger >= 1);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_GreaterEqual_Integer_1()
{
var expected = $"{nameof(UserTable.IdInteger)} >= 10";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger >= 10L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_GreaterEqual_Long()
{
var expected = $"{nameof(UserTable.IdLong)} >= 2";
var actual = _compiler.Compile<UserTable>(x => x.IdLong >= 2L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_GreaterEqual_Long_1()
{
var expected = $"{nameof(UserTable.IdLong)} >= 3";
var actual = _compiler.Compile<UserTable>(x => x.IdLong >= (int)3);
Assert.Equal(expected, actual);
}
//[Fact]
//public void Test_Expression_Compiler_Simple_GreaterEqual_Guid()
//{
// var guid = Guid.NewGuid();
// var expected = $"{nameof(UserTable.IdGuid)} >= '{guid}'";
// var actual = _compiler.Compile<UserTable>(x => x.IdGuid >= guid);
// Assert.Equal(expected, actual);
//}
#endregion
#region Less
[Fact]
public void Test_Expression_Compiler_Simple_Less_Integer()
{
var expected = $"{nameof(UserTable.IdInteger)} < 1";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger < 1);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Less_Integer_1()
{
var expected = $"{nameof(UserTable.IdInteger)} < 10";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger < 10L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Less_Long()
{
var expected = $"{nameof(UserTable.IdLong)} < 2";
var actual = _compiler.Compile<UserTable>(x => x.IdLong < 2L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Less_Long_1()
{
var expected = $"{nameof(UserTable.IdLong)} < 3";
var actual = _compiler.Compile<UserTable>(x => x.IdLong < (int)3);
Assert.Equal(expected, actual);
}
//[Fact]
//public void Test_Expression_Compiler_Simple_Less_Guid()
//{
// var guid = Guid.NewGuid();
// var expected = $"{nameof(UserTable.IdGuid)} < '{guid}'";
// var actual = _compiler.Compile<UserTable>(x => x.IdGuid < guid);
// Assert.Equal(expected, actual);
//}
#endregion
#region LessEqual
[Fact]
public void Test_Expression_Compiler_Simple_LessEqual_Integer()
{
var expected = $"{nameof(UserTable.IdInteger)} <= 1";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger <= 1);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_LessEqual_Integer_1()
{
var expected = $"{nameof(UserTable.IdInteger)} <= 10";
var actual = _compiler.Compile<UserTable>(x => x.IdInteger <= 10L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_LessEqual_Long()
{
var expected = $"{nameof(UserTable.IdLong)} <= 2";
var actual = _compiler.Compile<UserTable>(x => x.IdLong <= 2L);
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_LessEqual_Long_1()
{
var expected = $"{nameof(UserTable.IdLong)} <= 3";
var actual = _compiler.Compile<UserTable>(x => x.IdLong <= (int)3);
Assert.Equal(expected, actual);
}
//[Fact]
//public void Test_Expression_Compiler_Simple_LessEqual_Guid()
//{
// var guid = Guid.NewGuid();
// var expected = $"{nameof(UserTable.IdGuid)} <= '{guid}'";
// var actual = _compiler.Compile<UserTable>(x => x.IdGuid > guid);
// Assert.Equal(expected, actual);
//}
#endregion
#region Integer Contains
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Integer_1()
{
var expected = $"{nameof(UserTable.IdInteger)} IN (1,2,3)";
var arr = new [] {1, 2, 3};
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdInteger));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Integer_2()
{
var expected = $"CAST({nameof(UserTable.IdInteger)} AS bigint) IN (1,2,3)";
var arr = new long[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdInteger));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Integer_3()
{
var expected = $"CAST({nameof(UserTable.IdInteger)} AS double) IN (1,2,3)";
var arr = new double[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdInteger));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Integer_4()
{
var expected = $"CAST({nameof(UserTable.IdInteger)} AS float) IN (1,2,3)";
var arr = new float[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdInteger));
Assert.Equal(expected, actual);
}
//[Fact]
//public void Test_Expression_Compiler_Simple_Contains_Integer_5()
//{
// var expected = $"{nameof(UserTable.IdInteger)} IN (1,2,3)";
// var arr = new decimal[ { 1, 2, 3 };
// var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdInteger));
// Assert.Equal(expected, actual);
//}
#endregion
#region Short Contains
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Short_1()
{
var expected = $"CAST({nameof(UserTable.IdShort)} AS int) IN (1,2,3)";
var arr = new [] {1, 2, 3};
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdShort));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Short_1_1()
{
var expected = $"{nameof(UserTable.IdShort)} IN (1,2,3)";
var arr = new short[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdShort));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Short_2()
{
var expected = $"CAST({nameof(UserTable.IdShort)} AS bigint) IN (1,2,3)";
var arr = new long[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdShort));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Short_3()
{
var expected = $"CAST({nameof(UserTable.IdShort)} AS double) IN (1,2,3)";
var arr = new double[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdShort));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Short_4()
{
var expected = $"CAST({nameof(UserTable.IdShort)} AS float) IN (1,2,3)";
var arr = new float[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdShort));
Assert.Equal(expected, actual);
}
//[Fact]
//public void Test_Expression_Compiler_Simple_Contains_Short_5()
//{
// var expected = $"{nameof(UserTable.IdShort)} IN (1,2,3)";
// var arr = new decimal[ { 1, 2, 3 };
// var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdShort));
// Assert.Equal(expected, actual);
//}
#endregion
#region Byte Contains
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Byte_1()
{
var expected = $"CAST({nameof(UserTable.IdByte)} AS int) IN (1,2,3)";
var arr = new [] {1, 2, 3};
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdByte));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Byte_1_1()
{
var expected = $"{nameof(UserTable.IdByte)} IN (1,2,3)";
var arr = new byte[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdByte));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Byte_1_3()
{
var expected = $"CAST({nameof(UserTable.IdByte)} AS smallint) IN (1,2,3)";
var arr = new short[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdByte));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Byte_2()
{
var expected = $"CAST({nameof(UserTable.IdByte)} AS bigint) IN (1,2,3)";
var arr = new long[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdByte));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Byte_3()
{
var expected = $"CAST({nameof(UserTable.IdByte)} AS double) IN (1,2,3)";
var arr = new double[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdByte));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Byte_4()
{
var expected = $"CAST({nameof(UserTable.IdByte)} AS float) IN (1,2,3)";
var arr = new float[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdByte));
Assert.Equal(expected, actual);
}
//[Fact]
//public void Test_Expression_Compiler_Simple_Contains_Byte_5()
//{
// var expected = $"CAST({nameof(UserTable.IdByte)} AS double) IN (1,2,3)";
// var arr = new decimal[ { 1, 2, 3 };
// var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdByte));
// Assert.Equal(expected, actual);
//}
#endregion
#region Long Contains
//[Fact]
//public void Test_Expression_Compiler_Simple_Contains_Long_1()
//{
// var expected = $"{nameof(UserTable.IdLong)} IN (1,2,3)";
// var arr = new [ {1, 2, 3};
// var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdLong));
// Assert.Equal(expected, actual);
//}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Long_2()
{
var expected = $"{nameof(UserTable.IdLong)} IN (1,2,3)";
var arr = new long[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdLong));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Long_3()
{
var expected = $"CAST({nameof(UserTable.IdLong)} AS double) IN (1,2,3)";
var arr = new double[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdLong));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Long_4()
{
var expected = $"CAST({nameof(UserTable.IdLong)} AS float) IN (1,2,3)";
var arr = new float[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdLong));
Assert.Equal(expected, actual);
}
[Fact]
public void Test_Expression_Compiler_Simple_Contains_Long_5()
{
var expected = $"CAST({nameof(UserTable.IdLong)} AS decimal(19,4)) IN (1,2,3)";
var arr = new decimal[] { 1, 2, 3 };
var actual = _compiler.Compile<UserTable>(x => arr.Contains(x.IdLong));
Assert.Equal(expected, actual);
}
#endregion
}
}
| 39.701903 | 91 | 0.561851 | [
"Apache-2.0"
] | raminrahimzada/SQLEngine | SQLEngine.Tests/SqlServer/ExpressionCompilerTests.cs | 18,781 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Dyvmsapi.Transform;
using Aliyun.Acs.Dyvmsapi.Transform.V20170525;
namespace Aliyun.Acs.Dyvmsapi.Model.V20170525
{
public class SubmitHotlineTransferRegisterRequest : RpcAcsRequest<SubmitHotlineTransferRegisterResponse>
{
public SubmitHotlineTransferRegisterRequest()
: base("Dyvmsapi", "2017-05-25", "SubmitHotlineTransferRegister", "dyvms", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.Dyvmsapi.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.Dyvmsapi.Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private string operatorIdentityCard;
private long? resourceOwnerId;
private string operatorMail;
private string hotlineNumber;
private List<TransferPhoneNumberInfos> transferPhoneNumberInfoss = new List<TransferPhoneNumberInfos>(){ };
private string operatorMobileVerifyCode;
private string agreement;
private string qualificationId;
private string resourceOwnerAccount;
private long? ownerId;
private string operatorMobile;
private string operatorMailVerifyCode;
private string operatorName;
public string OperatorIdentityCard
{
get
{
return operatorIdentityCard;
}
set
{
operatorIdentityCard = value;
DictionaryUtil.Add(QueryParameters, "OperatorIdentityCard", value);
}
}
public long? ResourceOwnerId
{
get
{
return resourceOwnerId;
}
set
{
resourceOwnerId = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString());
}
}
public string OperatorMail
{
get
{
return operatorMail;
}
set
{
operatorMail = value;
DictionaryUtil.Add(QueryParameters, "OperatorMail", value);
}
}
public string HotlineNumber
{
get
{
return hotlineNumber;
}
set
{
hotlineNumber = value;
DictionaryUtil.Add(QueryParameters, "HotlineNumber", value);
}
}
public List<TransferPhoneNumberInfos> TransferPhoneNumberInfoss
{
get
{
return transferPhoneNumberInfoss;
}
set
{
transferPhoneNumberInfoss = value;
for (int i = 0; i < transferPhoneNumberInfoss.Count; i++)
{
DictionaryUtil.Add(QueryParameters,"TransferPhoneNumberInfos." + (i + 1) + ".PhoneNumber", transferPhoneNumberInfoss[i].PhoneNumber);
DictionaryUtil.Add(QueryParameters,"TransferPhoneNumberInfos." + (i + 1) + ".PhoneNumberOwnerName", transferPhoneNumberInfoss[i].PhoneNumberOwnerName);
DictionaryUtil.Add(QueryParameters,"TransferPhoneNumberInfos." + (i + 1) + ".IdentityCard", transferPhoneNumberInfoss[i].IdentityCard);
}
}
}
public string OperatorMobileVerifyCode
{
get
{
return operatorMobileVerifyCode;
}
set
{
operatorMobileVerifyCode = value;
DictionaryUtil.Add(QueryParameters, "OperatorMobileVerifyCode", value);
}
}
public string Agreement
{
get
{
return agreement;
}
set
{
agreement = value;
DictionaryUtil.Add(QueryParameters, "Agreement", value);
}
}
public string QualificationId
{
get
{
return qualificationId;
}
set
{
qualificationId = value;
DictionaryUtil.Add(QueryParameters, "QualificationId", value);
}
}
public string ResourceOwnerAccount
{
get
{
return resourceOwnerAccount;
}
set
{
resourceOwnerAccount = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public string OperatorMobile
{
get
{
return operatorMobile;
}
set
{
operatorMobile = value;
DictionaryUtil.Add(QueryParameters, "OperatorMobile", value);
}
}
public string OperatorMailVerifyCode
{
get
{
return operatorMailVerifyCode;
}
set
{
operatorMailVerifyCode = value;
DictionaryUtil.Add(QueryParameters, "OperatorMailVerifyCode", value);
}
}
public string OperatorName
{
get
{
return operatorName;
}
set
{
operatorName = value;
DictionaryUtil.Add(QueryParameters, "OperatorName", value);
}
}
public class TransferPhoneNumberInfos
{
private string phoneNumber;
private string phoneNumberOwnerName;
private string identityCard;
public string PhoneNumber
{
get
{
return phoneNumber;
}
set
{
phoneNumber = value;
}
}
public string PhoneNumberOwnerName
{
get
{
return phoneNumberOwnerName;
}
set
{
phoneNumberOwnerName = value;
}
}
public string IdentityCard
{
get
{
return identityCard;
}
set
{
identityCard = value;
}
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override SubmitHotlineTransferRegisterResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return SubmitHotlineTransferRegisterResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 22.10299 | 157 | 0.657598 | [
"Apache-2.0"
] | aliyun/aliyun-openapi-net-sdk | aliyun-net-sdk-dyvmsapi/Dyvmsapi/Model/V20170525/SubmitHotlineTransferRegisterRequest.cs | 6,653 | C# |
namespace PnP.Core.Model.SharePoint
{
/// <summary>
/// Site Logo aspect ratio
/// </summary>
internal enum SiteLogoAspect
{
/// <summary>
/// Square logo
/// </summary>
Square = 0,
/// <summary>
/// Rectangular logo
/// </summary>
Rectangular = 1
}
}
| 18 | 36 | 0.473684 | [
"MIT"
] | MathijsVerbeeck/pnpcore | src/sdk/PnP.Core/Model/SharePoint/Branding/Internal/Enums/SiteLogoAspect.cs | 344 | C# |
namespace PetClinic.Application.Common
{
public static class ApplicationConstants
{
public static class Roles
{
public const string Client = "Client";
public const string Doctor = "Doctor";
}
public static class InvalidMessages
{
public const string NullCommand = "Invalid request";
public const string Client = "Invalid member client.";
public const string Doctor = "Invalid member doc.";
public const string Pet = "Invalid pet.";
public const string UnavailableAppointment = "The selected date/room/doctor/client is unavailable.";
public const string UnavailableAppointmentDate = "The selected date is unavailable.";
public const string ExistingMember = "There is already an existing member with this account!";
public const string InvalidAppointment = "Invalid selected appointment.";
}
public static class Validations
{
public const int ZeroNumber = 0;
}
}
}
| 37.310345 | 112 | 0.62939 | [
"MIT"
] | stefanMinch3v/DomainDrivenDesignArchitecture | src/PetClinic/PetClinic.Application/Common/ApplicationConstants.cs | 1,084 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MonthPrinter")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MonthPrinter")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e248b33e-6dc9-4db4-8c2c-299e1a059f2d")]
// 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.583333 | 84 | 0.744272 | [
"MIT"
] | pirocorp/Programming-Basics | CsharpBasicProblems/MonthPrinter/Properties/AssemblyInfo.cs | 1,356 | 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("Demo.DBTimeouts")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Demo.DBTimeouts")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7bfd7856-f666-487e-be62-d2b92229641f")]
// 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.918919 | 84 | 0.744833 | [
"Apache-2.0"
] | toddmeinershagen/Demo.DbTimeouts | src/Demo.DBTimeouts/Demo.DBTimeouts/Properties/AssemblyInfo.cs | 1,406 | C# |
using Ryujinx.Common.Logging;
using Ryujinx.Graphics.Gpu.Memory;
using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostAsGpu.Types;
using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostChannel;
using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvMap;
using Ryujinx.Memory;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostAsGpu
{
class NvHostAsGpuDeviceFile : NvDeviceFile
{
private const uint SmallPageSize = 0x1000;
private const uint BigPageSize = 0x10000;
private static readonly uint[] _pageSizes = new uint[] { SmallPageSize, BigPageSize };
private const ulong SmallRegionLimit = 0x400000000UL; // 16 GB
private const ulong DefaultUserSize = 1UL << 37;
private struct VmRegion
{
public ulong Start { get; }
public ulong Limit { get; }
public VmRegion(ulong start, ulong limit)
{
Start = start;
Limit = limit;
}
}
private static readonly VmRegion[] _vmRegions = new VmRegion[]
{
new VmRegion((ulong)BigPageSize << 16, SmallRegionLimit),
new VmRegion(SmallRegionLimit, DefaultUserSize)
};
private readonly AddressSpaceContext _asContext;
private readonly NvMemoryAllocator _memoryAllocator;
public NvHostAsGpuDeviceFile(ServiceCtx context, IVirtualMemoryManager memory, long owner) : base(context, owner)
{
_asContext = new AddressSpaceContext(context.Device.Gpu.CreateMemoryManager(owner));
_memoryAllocator = new NvMemoryAllocator();
}
public override NvInternalResult Ioctl(NvIoctl command, Span<byte> arguments)
{
NvInternalResult result = NvInternalResult.NotImplemented;
if (command.Type == NvIoctl.NvGpuAsMagic)
{
switch (command.Number)
{
case 0x01:
result = CallIoctlMethod<BindChannelArguments>(BindChannel, arguments);
break;
case 0x02:
result = CallIoctlMethod<AllocSpaceArguments>(AllocSpace, arguments);
break;
case 0x03:
result = CallIoctlMethod<FreeSpaceArguments>(FreeSpace, arguments);
break;
case 0x05:
result = CallIoctlMethod<UnmapBufferArguments>(UnmapBuffer, arguments);
break;
case 0x06:
result = CallIoctlMethod<MapBufferExArguments>(MapBufferEx, arguments);
break;
case 0x08:
result = CallIoctlMethod<GetVaRegionsArguments>(GetVaRegions, arguments);
break;
case 0x09:
result = CallIoctlMethod<InitializeExArguments>(InitializeEx, arguments);
break;
case 0x14:
result = CallIoctlMethod<RemapArguments>(Remap, arguments);
break;
}
}
return result;
}
public override NvInternalResult Ioctl3(NvIoctl command, Span<byte> arguments, Span<byte> inlineOutBuffer)
{
NvInternalResult result = NvInternalResult.NotImplemented;
if (command.Type == NvIoctl.NvGpuAsMagic)
{
switch (command.Number)
{
case 0x08:
// This is the same as the one in ioctl as inlineOutBuffer is empty.
result = CallIoctlMethod<GetVaRegionsArguments>(GetVaRegions, arguments);
break;
}
}
return result;
}
private NvInternalResult BindChannel(ref BindChannelArguments arguments)
{
var channelDeviceFile = INvDrvServices.DeviceFileIdRegistry.GetData<NvHostChannelDeviceFile>(arguments.Fd);
if (channelDeviceFile == null)
{
// TODO: Return invalid Fd error.
}
channelDeviceFile.Channel.BindMemory(_asContext.Gmm);
return NvInternalResult.Success;
}
private NvInternalResult AllocSpace(ref AllocSpaceArguments arguments)
{
ulong size = (ulong)arguments.Pages * (ulong)arguments.PageSize;
NvInternalResult result = NvInternalResult.Success;
lock (_asContext)
{
// Note: When the fixed offset flag is not set,
// the Offset field holds the alignment size instead.
if ((arguments.Flags & AddressSpaceFlags.FixedOffset) != 0)
{
bool regionInUse = _memoryAllocator.IsRegionInUse(arguments.Offset, size, out ulong freeAddressStartPosition);
ulong address;
if (!regionInUse)
{
_memoryAllocator.AllocateRange(arguments.Offset, size, freeAddressStartPosition);
address = freeAddressStartPosition;
}
else
{
address = NvMemoryAllocator.PteUnmapped;
}
arguments.Offset = address;
}
else
{
ulong address = _memoryAllocator.GetFreeAddress(size, out ulong freeAddressStartPosition, arguments.Offset);
if (address != NvMemoryAllocator.PteUnmapped)
{
_memoryAllocator.AllocateRange(address, size, freeAddressStartPosition);
}
arguments.Offset = address;
}
if (arguments.Offset == NvMemoryAllocator.PteUnmapped)
{
arguments.Offset = 0;
Logger.Warning?.Print(LogClass.ServiceNv, $"Failed to allocate size {size:x16}!");
result = NvInternalResult.OutOfMemory;
}
else
{
_asContext.AddReservation(arguments.Offset, size);
}
}
return result;
}
private NvInternalResult FreeSpace(ref FreeSpaceArguments arguments)
{
ulong size = (ulong)arguments.Pages * (ulong)arguments.PageSize;
NvInternalResult result = NvInternalResult.Success;
lock (_asContext)
{
if (_asContext.RemoveReservation(arguments.Offset))
{
_memoryAllocator.DeallocateRange(arguments.Offset, size);
_asContext.Gmm.Unmap(arguments.Offset, size);
}
else
{
Logger.Warning?.Print(LogClass.ServiceNv,
$"Failed to free offset 0x{arguments.Offset:x16} size 0x{size:x16}!");
result = NvInternalResult.InvalidInput;
}
}
return result;
}
private NvInternalResult UnmapBuffer(ref UnmapBufferArguments arguments)
{
lock (_asContext)
{
if (_asContext.RemoveMap(arguments.Offset, out ulong size))
{
if (size != 0)
{
_memoryAllocator.DeallocateRange(arguments.Offset, size);
_asContext.Gmm.Unmap(arguments.Offset, size);
}
}
else
{
Logger.Warning?.Print(LogClass.ServiceNv, $"Invalid buffer offset {arguments.Offset:x16}!");
}
}
return NvInternalResult.Success;
}
private NvInternalResult MapBufferEx(ref MapBufferExArguments arguments)
{
const string MapErrorMsg = "Failed to map fixed buffer with offset 0x{0:x16}, size 0x{1:x16} and alignment 0x{2:x16}!";
ulong physicalAddress;
if ((arguments.Flags & AddressSpaceFlags.RemapSubRange) != 0)
{
lock (_asContext)
{
if (_asContext.TryGetMapPhysicalAddress(arguments.Offset, out physicalAddress))
{
ulong virtualAddress = arguments.Offset + arguments.BufferOffset;
physicalAddress += arguments.BufferOffset;
_asContext.Gmm.Map(physicalAddress, virtualAddress, arguments.MappingSize);
return NvInternalResult.Success;
}
else
{
Logger.Warning?.Print(LogClass.ServiceNv, $"Address 0x{arguments.Offset:x16} not mapped!");
return NvInternalResult.InvalidInput;
}
}
}
NvMapHandle map = NvMapDeviceFile.GetMapFromHandle(Owner, arguments.NvMapHandle);
if (map == null)
{
Logger.Warning?.Print(LogClass.ServiceNv, $"Invalid NvMap handle 0x{arguments.NvMapHandle:x8}!");
return NvInternalResult.InvalidInput;
}
ulong pageSize = (ulong)arguments.PageSize;
if (pageSize == 0)
{
pageSize = (ulong)map.Align;
}
physicalAddress = map.Address + arguments.BufferOffset;
ulong size = arguments.MappingSize;
if (size == 0)
{
size = (uint)map.Size;
}
NvInternalResult result = NvInternalResult.Success;
lock (_asContext)
{
// Note: When the fixed offset flag is not set,
// the Offset field holds the alignment size instead.
bool virtualAddressAllocated = (arguments.Flags & AddressSpaceFlags.FixedOffset) == 0;
if (!virtualAddressAllocated)
{
if (_asContext.ValidateFixedBuffer(arguments.Offset, size, pageSize))
{
_asContext.Gmm.Map(physicalAddress, arguments.Offset, size);
}
else
{
string message = string.Format(MapErrorMsg, arguments.Offset, size, pageSize);
Logger.Warning?.Print(LogClass.ServiceNv, message);
result = NvInternalResult.InvalidInput;
}
}
else
{
ulong va = _memoryAllocator.GetFreeAddress(size, out ulong freeAddressStartPosition, pageSize);
if (va != NvMemoryAllocator.PteUnmapped)
{
_memoryAllocator.AllocateRange(va, size, freeAddressStartPosition);
}
_asContext.Gmm.Map(physicalAddress, va, size);
arguments.Offset = va;
}
if (arguments.Offset == NvMemoryAllocator.PteUnmapped)
{
arguments.Offset = 0;
Logger.Warning?.Print(LogClass.ServiceNv, $"Failed to map size 0x{size:x16}!");
result = NvInternalResult.InvalidInput;
}
else
{
_asContext.AddMap(arguments.Offset, size, physicalAddress, virtualAddressAllocated);
}
}
return result;
}
private NvInternalResult GetVaRegions(ref GetVaRegionsArguments arguments)
{
int vaRegionStructSize = Unsafe.SizeOf<VaRegion>();
Debug.Assert(vaRegionStructSize == 0x18);
Debug.Assert(_pageSizes.Length == 2);
uint writeEntries = (uint)(arguments.BufferSize / vaRegionStructSize);
if (writeEntries > _pageSizes.Length)
{
writeEntries = (uint)_pageSizes.Length;
}
for (uint i = 0; i < writeEntries; i++)
{
ref var region = ref arguments.Regions[(int)i];
var vmRegion = _vmRegions[i];
uint pageSize = _pageSizes[i];
region.PageSize = pageSize;
region.Offset = vmRegion.Start;
region.Pages = (vmRegion.Limit - vmRegion.Start) / pageSize;
region.Padding = 0;
}
arguments.BufferSize = (uint)(_pageSizes.Length * vaRegionStructSize);
return NvInternalResult.Success;
}
private NvInternalResult InitializeEx(ref InitializeExArguments arguments)
{
Logger.Stub?.PrintStub(LogClass.ServiceNv);
return NvInternalResult.Success;
}
private NvInternalResult Remap(Span<RemapArguments> arguments)
{
MemoryManager gmm = _asContext.Gmm;
for (int index = 0; index < arguments.Length; index++)
{
ulong mapOffs = (ulong)arguments[index].MapOffset << 16;
ulong gpuVa = (ulong)arguments[index].GpuOffset << 16;
ulong size = (ulong)arguments[index].Pages << 16;
if (arguments[index].NvMapHandle == 0)
{
gmm.Unmap(gpuVa, size);
}
else
{
NvMapHandle map = NvMapDeviceFile.GetMapFromHandle(Owner, arguments[index].NvMapHandle);
if (map == null)
{
Logger.Warning?.Print(LogClass.ServiceNv, $"Invalid NvMap handle 0x{arguments[index].NvMapHandle:x8}!");
return NvInternalResult.InvalidInput;
}
gmm.Map(mapOffs + map.Address, gpuVa, size);
}
}
return NvInternalResult.Success;
}
public override void Close() { }
}
}
| 35.984925 | 131 | 0.524089 | [
"MIT"
] | AcK77/Ryujinx | Ryujinx.HLE/HOS/Services/Nv/NvDrvServices/NvHostAsGpu/NvHostAsGpuDeviceFile.cs | 14,324 | C# |
/*
* THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.Json.Serialization;
namespace Plotly.Blazor.Traces.HistogramLib
{
/// <summary>
/// The Unselected class.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")]
[Serializable]
public class Unselected : IEquatable<Unselected>
{
/// <summary>
/// Gets or sets the Marker.
/// </summary>
[JsonPropertyName(@"marker")]
public Plotly.Blazor.Traces.HistogramLib.UnselectedLib.Marker Marker { get; set;}
/// <summary>
/// Gets or sets the TextFont.
/// </summary>
[JsonPropertyName(@"textfont")]
public Plotly.Blazor.Traces.HistogramLib.UnselectedLib.TextFont TextFont { get; set;}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (!(obj is Unselected other)) return false;
return ReferenceEquals(this, obj) || Equals(other);
}
/// <inheritdoc />
public bool Equals([AllowNull] Unselected other)
{
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
return
(
Marker == other.Marker ||
Marker != null &&
Marker.Equals(other.Marker)
) &&
(
TextFont == other.TextFont ||
TextFont != null &&
TextFont.Equals(other.TextFont)
);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
var hashCode = 41;
if (Marker != null) hashCode = hashCode * 59 + Marker.GetHashCode();
if (TextFont != null) hashCode = hashCode * 59 + TextFont.GetHashCode();
return hashCode;
}
}
/// <summary>
/// Checks for equality of the left Unselected and the right Unselected.
/// </summary>
/// <param name="left">Left Unselected.</param>
/// <param name="right">Right Unselected.</param>
/// <returns>Boolean</returns>
public static bool operator == (Unselected left, Unselected right)
{
return Equals(left, right);
}
/// <summary>
/// Checks for inequality of the left Unselected and the right Unselected.
/// </summary>
/// <param name="left">Left Unselected.</param>
/// <param name="right">Right Unselected.</param>
/// <returns>Boolean</returns>
public static bool operator != (Unselected left, Unselected right)
{
return !Equals(left, right);
}
/// <summary>
/// Gets a deep copy of this instance.
/// </summary>
/// <returns>Unselected</returns>
public Unselected DeepClone()
{
return this.Copy();
}
}
} | 31.666667 | 94 | 0.531889 | [
"MIT"
] | BenSzuszkiewicz/Plotly.Blazor | Plotly.Blazor/Traces/HistogramLib/Unselected.cs | 3,230 | C# |
using AutoMapper;
namespace ChallengeAccepted.Api.Mapping
{
public interface IHaveCustomMappings
{
void CreateMappings(IConfiguration configuration);
}
}
| 17.6 | 58 | 0.738636 | [
"MIT"
] | NativeScriptHybrids/ChallengeAccepted | ChallengeAccepted.Service/ChallengeAccepted.Api/Mapping/IHaveCustomMappings.cs | 178 | 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 Cake.Common.Tests.Fixtures.Tools.TextTransform;
using Cake.Common.Tools.TextTransform;
using Cake.Core;
using NSubstitute;
using Xunit;
namespace Cake.Common.Tests.Unit.Tools.TextTransform;
public sealed class TextTransformAliasTests
{
public sealed class TheTransformTemplateMethod
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given
var fixture = new TextTransformFixture();
// When
var result = Record.Exception(() => TextTransformAliases.TransformTemplate(null, fixture.SourceFile));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Source_File_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
// When
var result = Record.Exception(() => TextTransformAliases.TransformTemplate(context, null));
// Then
AssertEx.IsArgumentNullException(result, "sourceFile");
}
}
} | 29.906977 | 114 | 0.650078 | [
"MIT"
] | ecampidoglio/cake | src/Cake.Common.Tests/Unit/Tools/TextTransform/TextTemplateAliasTests.cs | 1,288 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006-2019, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.472)
// Version 5.472.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using ComponentFactory.Krypton.Navigator;
namespace ComponentFactory.Krypton.Workspace
{
/// <summary>
/// Data associated with a change in the active page.
/// </summary>
public class ActivePageChangedEventArgs : EventArgs
{
#region Instance Fields
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ActivePageChangedEventArgs class.
/// </summary>
/// <param name="oldPage">Previous active page value.</param>
/// <param name="newPage">New active page value.</param>
public ActivePageChangedEventArgs(KryptonPage oldPage,
KryptonPage newPage)
{
OldPage = oldPage;
NewPage = newPage;
}
#endregion
#region Public
/// <summary>
/// Gets the old page reference.
/// </summary>
public KryptonPage OldPage { get; }
/// <summary>
/// Gets the new page reference.
/// </summary>
public KryptonPage NewPage { get; }
#endregion
}
}
| 35.12963 | 157 | 0.5767 | [
"BSD-3-Clause"
] | dave-w-au/Krypton-NET-5.472 | Source/Krypton Components/ComponentFactory.Krypton.Workspace/EventArgs/ActivePageChangedEventArgs.cs | 1,900 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using ModelService;
using SendGrid;
using SendGrid.Helpers.Mail;
using Serilog;
namespace FunctionalService
{
public class FunctionalSvc : IFunctionalSvc
{
private readonly AdminUserOptions _adminUserOptions;
private readonly AppUserOptions _appUserOptions;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IHostingEnvironment _env;
public FunctionalSvc(IOptions<AppUserOptions> appUserOptions,
IOptions<AdminUserOptions> adminUserOptions,
UserManager<ApplicationUser> userManager, IHostingEnvironment env)
{
_adminUserOptions = adminUserOptions.Value;
_appUserOptions = appUserOptions.Value;
_userManager = userManager;
_env = env;
}
public async Task CreateDefaultAdminUser()
{
try
{
var adminUser = new ApplicationUser
{
Email = _adminUserOptions.Email,
UserName = _adminUserOptions.Username,
EmailConfirmed = true,
ProfilePic = await GetDefaultProfilePic(),
PhoneNumber = "1234567890",
PhoneNumberConfirmed = true,
Firstname = _adminUserOptions.Firstname,
Lastname = _adminUserOptions.Lastname,
UserRole = "Administrator",
IsActive = true,
UserAddresses = new List<AddressModel>
{
new AddressModel {Country = _adminUserOptions.Country, Type = "Billing"},
new AddressModel {Country = _adminUserOptions.Country, Type = "Shipping"}
}
};
var result = await _userManager.CreateAsync(adminUser, _adminUserOptions.Password);
if (result.Succeeded)
{
await _userManager.AddToRoleAsync(adminUser, "Administrator");
Log.Information("Admin User Created {UserName}", adminUser.UserName);
}
else
{
var errorString = string.Join(",", result.Errors);
Log.Error("Error while creating user {Error}", errorString);
}
}
catch (Exception ex)
{
Log.Error("Error while creating user {Error} {StackTrace} {InnerException} {Source}",
ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
}
}
public async Task CreateDefaultUser()
{
try
{
var appUser = new ApplicationUser
{
Email = _appUserOptions.Email,
UserName = _appUserOptions.Username,
EmailConfirmed = true,
ProfilePic = await GetDefaultProfilePic(),
PhoneNumber = "1234567890",
PhoneNumberConfirmed = true,
Firstname = _appUserOptions.Firstname,
Lastname = _appUserOptions.Lastname,
UserRole = "Customer",
IsActive = true,
UserAddresses = new List<AddressModel>
{
new AddressModel {Country = _appUserOptions.Country, Type = "Billing"},
new AddressModel {Country = _appUserOptions.Country, Type = "Shipping"}
}
};
var result = await _userManager.CreateAsync(appUser, _appUserOptions.Password);
if (result.Succeeded)
{
await _userManager.AddToRoleAsync(appUser, "Customer");
Log.Information("App User Created {UserName}", appUser.UserName);
}
else
{
var errorString = string.Join(",", result.Errors);
Log.Error("Error while creating user {Error}", errorString);
}
}
catch (Exception ex)
{
Log.Error("Error while creating user {Error} {StackTrace} {InnerException} {Source}",
ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
}
}
public async Task SendEmailByGmailAsync(string fromEmail, string fromFullName, string subject, string messageBody, string toEmail, string toFullName, string smtpUser, string smtpPassword, string smtpHost, int smtpPort, bool smtpSSL)
{
try
{
var body = messageBody;
var message = new MailMessage();
message.To.Add(new MailAddress(toEmail, toFullName));
message.From = new MailAddress(fromEmail, fromFullName);
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
using var smtp = new SmtpClient();
var credential = new NetworkCredential
{
UserName = smtpUser,
Password = smtpPassword
};
smtp.Credentials = credential;
smtp.Host = smtpHost;
smtp.Port = smtpPort;
smtp.EnableSsl = smtpSSL;
await smtp.SendMailAsync(message);
}
catch (Exception ex)
{
Log.Error("An error occurred while seeding the database {Error} {StackTrace} {InnerException} {Source}",
ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
}
}
public async Task SendEmailBySendGridAsync(string apiKey, string fromEmail, string fromFullName, string subject, string message, string email)
{
try
{
await Execute(apiKey, fromEmail, fromFullName, subject, message, email);
}
catch (Exception ex)
{
Log.Error("Error while creating user {Error} {StackTrace} {InnerException} {Source}",
ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
}
}
static async Task<Response> Execute(string apiKey, string fromEmail, string fromFullName, string subject, string message, string email)
{
var client = new SendGridClient(apiKey);
var from = new EmailAddress(fromEmail, fromFullName);
var to = new EmailAddress(email);
var plainTextContent = message;
var htmlContent = message;
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
return response;
}
private async Task<string> GetDefaultProfilePic()
{
try
{
// Default Profile pic path
// Create the Profile Image Path
var profPicPath = _env.WebRootPath + $"{Path.DirectorySeparatorChar}uploads{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}profile{Path.DirectorySeparatorChar}";
var defaultPicPath = _env.WebRootPath + $"{Path.DirectorySeparatorChar}uploads{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}profile{Path.DirectorySeparatorChar}default{Path.DirectorySeparatorChar}profile.jpeg";
var extension = Path.GetExtension(defaultPicPath);
var filename = DateTime.Now.ToString("yymmssfff");
var path = Path.Combine(profPicPath, filename) + extension;
var dbImagePath = Path.Combine($"{Path.DirectorySeparatorChar}uploads{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}profile{Path.DirectorySeparatorChar}", filename) + extension;
await using (Stream source = new FileStream(defaultPicPath, FileMode.Open))
{
await using Stream destination = new FileStream(path, FileMode.Create);
await source.CopyToAsync(destination);
}
return dbImagePath;
}
catch (Exception ex)
{
Log.Error("{Error}", ex.Message);
}
return string.Empty;
}
}
}
| 41.303318 | 242 | 0.559839 | [
"MIT",
"Unlicense"
] | bishoe/CMS_CORE_NG | FunctionalService/FunctionalSvc.cs | 8,717 | C# |
using Microsoft.EntityFrameworkCore;
namespace Capstone.Models
{
public class CapstoneContext : DbContext // these will become tables in the database
{
public DbSet<Actor> Actors { get; set; }
public DbSet<Show> Shows { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<ActingCredit> ActingCredit { get; set; }
public DbSet<GenreShow> GenreShow { get; set; }
public CapstoneContext(DbContextOptions options) : base(options) { }
// protected override void OnModelCreating(ModelBuilder modelBuilder)
// {
// modelBuilder.Entity<ActingCredit>()
// .HasKey(ac => new { ac.ActorId, ac.ShowId });
// modelBuilder.Entity<ActingCredit>()
// .HasOne(ac => ac.Show)
// .WithMany(s => s.JoinActingCredit)
// .HasForeignKey(ac => ac.ShowId);
// modelBuilder.Entity<ActingCredit>()
// .HasOne(ac => ac.Actor)
// .WithMany(a => a.JoinActingCredit)
// .HasForeignKey(ac => ac.ActorId);
// }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLazyLoadingProxies(); // proxies are needed to use lazy loading
}
}
} | 35.205882 | 87 | 0.6533 | [
"MIT"
] | ericamarroquin/capstone | Capstone/Models/CapstoneContext.cs | 1,197 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class ITypeSymbolExtensions
{
/// <summary>
/// Returns the corresponding symbol in this type or a base type that implements
/// interfaceMember (either implicitly or explicitly), or null if no such symbol exists
/// (which might be either because this type doesn't implement the container of
/// interfaceMember, or this type doesn't supply a member that successfully implements
/// interfaceMember).
/// </summary>
public static async Task<ImmutableArray<ISymbol>> FindImplementationsForInterfaceMemberAsync(
this ITypeSymbol typeSymbol,
ISymbol interfaceMember,
Solution solution,
CancellationToken cancellationToken)
{
// This method can return multiple results. Consider the case of:
//
// interface IGoo<X> { void Goo(X x); }
//
// class C : IGoo<int>, IGoo<string> { void Goo(int x); void Goo(string x); }
//
// If you're looking for the implementations of IGoo<X>.Goo then you want to find both
// results in C.
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var builder);
// TODO(cyrusn): Implement this using the actual code for
// TypeSymbol.FindImplementationForInterfaceMember
if (typeSymbol == null || interfaceMember == null)
return ImmutableArray<ISymbol>.Empty;
if (interfaceMember.Kind != SymbolKind.Event &&
interfaceMember.Kind != SymbolKind.Method &&
interfaceMember.Kind != SymbolKind.Property)
{
return ImmutableArray<ISymbol>.Empty;
}
// WorkItem(4843)
//
// 'typeSymbol' has to at least implement the interface containing the member. note:
// this just means that the interface shows up *somewhere* in the inheritance chain of
// this type. However, this type may not actually say that it implements it. For
// example:
//
// interface I { void Goo(); }
//
// class B { }
//
// class C : B, I { }
//
// class D : C { }
//
// D does implement I transitively through C. However, even if D has a "Goo" method, it
// won't be an implementation of I.Goo. The implementation of I.Goo must be from a type
// that actually has I in it's direct interface chain, or a type that's a base type of
// that. in this case, that means only classes C or B.
var interfaceType = interfaceMember.ContainingType;
if (!typeSymbol.ImplementsIgnoringConstruction(interfaceType))
return ImmutableArray<ISymbol>.Empty;
// We've ascertained that the type T implements some constructed type of the form I<X>.
// However, we're not precisely sure which constructions of I<X> are being used. For
// example, a type C might implement I<int> and I<string>. If we're searching for a
// method from I<X> we might need to find several methods that implement different
// instantiations of that method.
var originalInterfaceType = interfaceMember.ContainingType.OriginalDefinition;
var originalInterfaceMember = interfaceMember.OriginalDefinition;
var constructedInterfaces = typeSymbol.AllInterfaces.Where(i =>
SymbolEquivalenceComparer.Instance.Equals(i.OriginalDefinition, originalInterfaceType));
foreach (var constructedInterface in constructedInterfaces)
{
cancellationToken.ThrowIfCancellationRequested();
// OriginalSymbolMatch allows types to be matched across different assemblies if they are considered to
// be the same type, which provides a more accurate implementations list for interfaces.
var constructedInterfaceMember =
await constructedInterface.GetMembers(interfaceMember.Name).FirstOrDefaultAsync(
typeSymbol => SymbolFinder.OriginalSymbolsMatchAsync(solution, typeSymbol, interfaceMember, cancellationToken)).ConfigureAwait(false);
if (constructedInterfaceMember == null)
{
continue;
}
// Now we need to walk the base type chain, but we start at the first type that actually
// has the interface directly in its interface hierarchy.
var seenTypeDeclaringInterface = false;
for (var currentType = typeSymbol; currentType != null; currentType = currentType.BaseType)
{
seenTypeDeclaringInterface = seenTypeDeclaringInterface ||
currentType.GetOriginalInterfacesAndTheirBaseInterfaces().Contains(interfaceType.OriginalDefinition);
if (seenTypeDeclaringInterface)
{
var result = currentType.FindImplementations(constructedInterfaceMember, solution.Workspace);
if (result != null)
{
builder.Add(result);
break;
}
}
}
}
return builder.ToImmutable();
}
public static ISymbol? FindImplementations(this ITypeSymbol typeSymbol, ISymbol constructedInterfaceMember, Workspace workspace)
=> constructedInterfaceMember switch
{
IEventSymbol eventSymbol => typeSymbol.FindImplementations(eventSymbol, workspace),
IMethodSymbol methodSymbol => typeSymbol.FindImplementations(methodSymbol, workspace),
IPropertySymbol propertySymbol => typeSymbol.FindImplementations(propertySymbol, workspace),
_ => null,
};
private static ISymbol? FindImplementations<TSymbol>(
this ITypeSymbol typeSymbol,
TSymbol constructedInterfaceMember,
Workspace workspace) where TSymbol : class, ISymbol
{
// Check the current type for explicit interface matches. Otherwise, check
// the current type and base types for implicit matches.
var explicitMatches =
from member in typeSymbol.GetMembers().OfType<TSymbol>()
from explicitInterfaceMethod in member.ExplicitInterfaceImplementations()
where SymbolEquivalenceComparer.Instance.Equals(explicitInterfaceMethod, constructedInterfaceMember)
select member;
var provider = workspace.Services.GetLanguageServices(typeSymbol.Language);
var semanticFacts = provider.GetRequiredService<ISemanticFactsService>();
// Even if a language only supports explicit interface implementation, we
// can't enforce it for types from metadata. For example, a VB symbol
// representing System.Xml.XmlReader will say it implements IDisposable, but
// the XmlReader.Dispose() method will not be an explicit implementation of
// IDisposable.Dispose()
if ((!semanticFacts.SupportsImplicitInterfaceImplementation &&
typeSymbol.Locations.Any(location => location.IsInSource)) ||
typeSymbol.TypeKind == TypeKind.Interface)
{
return explicitMatches.FirstOrDefault();
}
var syntaxFacts = provider.GetRequiredService<ISyntaxFactsService>();
var implicitMatches =
from baseType in typeSymbol.GetBaseTypesAndThis()
from member in baseType.GetMembers(constructedInterfaceMember.Name).OfType<TSymbol>()
where member.DeclaredAccessibility == Accessibility.Public &&
!member.IsStatic &&
SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(member, constructedInterfaceMember, syntaxFacts.IsCaseSensitive)
select member;
return explicitMatches.FirstOrDefault() ?? implicitMatches.FirstOrDefault();
}
[return: NotNullIfNotNull(parameterName: "type")]
public static ITypeSymbol? RemoveUnavailableTypeParameters(
this ITypeSymbol? type,
Compilation compilation,
IEnumerable<ITypeParameterSymbol> availableTypeParameters)
{
return type?.RemoveUnavailableTypeParameters(compilation, availableTypeParameters.Select(t => t.Name).ToSet());
}
[return: NotNullIfNotNull(parameterName: "type")]
private static ITypeSymbol? RemoveUnavailableTypeParameters(
this ITypeSymbol? type,
Compilation compilation,
ISet<string> availableTypeParameterNames)
{
return type?.Accept(new UnavailableTypeParameterRemover(compilation, availableTypeParameterNames));
}
[return: NotNullIfNotNull(parameterName: "type")]
public static ITypeSymbol? RemoveAnonymousTypes(
this ITypeSymbol? type,
Compilation compilation)
{
return type?.Accept(new AnonymousTypeRemover(compilation));
}
[return: NotNullIfNotNull(parameterName: "type")]
public static ITypeSymbol? RemoveUnnamedErrorTypes(
this ITypeSymbol? type,
Compilation compilation)
{
return type?.Accept(new UnnamedErrorTypeRemover(compilation));
}
public static IList<ITypeParameterSymbol> GetReferencedMethodTypeParameters(
this ITypeSymbol? type, IList<ITypeParameterSymbol>? result = null)
{
result ??= new List<ITypeParameterSymbol>();
type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: true));
return result;
}
public static IList<ITypeParameterSymbol> GetReferencedTypeParameters(
this ITypeSymbol? type, IList<ITypeParameterSymbol>? result = null)
{
result ??= new List<ITypeParameterSymbol>();
type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: false));
return result;
}
[return: NotNullIfNotNull(parameterName: "type")]
public static ITypeSymbol? SubstituteTypes<TType1, TType2>(
this ITypeSymbol? type,
IDictionary<TType1, TType2> mapping,
Compilation compilation)
where TType1 : ITypeSymbol
where TType2 : ITypeSymbol
{
return type.SubstituteTypes(mapping, new CompilationTypeGenerator(compilation));
}
[return: NotNullIfNotNull(parameterName: "type")]
public static ITypeSymbol? SubstituteTypes<TType1, TType2>(
this ITypeSymbol? type,
IDictionary<TType1, TType2> mapping,
ITypeGenerator typeGenerator)
where TType1 : ITypeSymbol
where TType2 : ITypeSymbol
{
return type?.Accept(new SubstituteTypesVisitor<TType1, TType2>(mapping, typeGenerator));
}
}
}
| 47.857708 | 170 | 0.6333 | [
"MIT"
] | Acidburn0zzz/roslyn | src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.cs | 12,110 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace ConnectFour.AI.AI_Torgo
{
public class AI_Torgo : MonoBehaviour, IBrain
{
private BoardPosition[,] _currentBoard;
private List<Target> _myTargets = new List<Target>();
private List<Target> _enemyTargets = new List<Target>();
private List<BoardPosition> _moves = new List<BoardPosition>();
private List<BoardPosition> _enemyMoves = new List<BoardPosition>();
private Target _selectedTarget;
private Target _enemySelectedTarget;
private TeamName _myTeam;
private TeamName _enemyTeam;
public ColumnNumber ChooseColumnIndex(GameState gameState)
{
InitGameState(gameState);
UpdateEnemyMoves();
PickMyBestTarget();
PickEnemyBestTarget();
ColumnNumber index = PickRandomMoveBaseOnBestTarget(gameState);
UpdateMovesList(index);
return index;
}
private ColumnNumber PickRandomMoveBaseOnBestTarget(GameState gameState)
{
if (_enemySelectedTarget != null)
{
if (_enemySelectedTarget.GetFourCost(_currentBoard,_enemyTeam) < 2 )
{
if (_selectedTarget != null && _selectedTarget.GetFourCost(_currentBoard, _myTeam) > 1)
{
return _enemySelectedTarget.GetNextPosition(_currentBoard).XIndex;
}
}
}
if (_selectedTarget != null)
{
int requiredMovesCount = _selectedTarget.MovesRequiredToFillPath.Count;
if (requiredMovesCount > 0)
{
BoardPosition pos = _selectedTarget.MovesRequiredToFillPath[0];
return pos.XIndex;
}
else
{
try
{
ColumnNumber column = _selectedTarget.GetNextPosition(_currentBoard).XIndex;
if (column != null)
{
return column;
}
}
catch
{
//I am so good at coding
}
}
}
return ChooseRandomMove(gameState);
}
private ColumnNumber ChooseRandomMove(GameState gameState)
{
int index = UnityEngine.Random.Range(0, gameState.AvailableMoves.Count);
ColumnNumber randomColumn = gameState.AvailableMoves[index].XIndex;
return randomColumn;
}
private void PickEnemyBestTarget()
{
List<Option> options = BuildOptionList(_enemyMoves, _enemyTargets, _enemyTeam);
_enemyTargets = BuildTargetLists(options, _enemyTeam);
_enemySelectedTarget = BestTargetFromList(_enemyTargets,_enemyTeam);
}
private void PickMyBestTarget()
{
List<Option> options = BuildOptionList(_moves, _myTargets, _myTeam);
_myTargets = BuildTargetLists(options, _myTeam);
_selectedTarget = BestTargetFromList(_myTargets, _myTeam);
}
private List<Option> BuildOptionList(List<BoardPosition> moves, List<Target> oldTargets , TeamName teamName)
{
OptionBuilder builder = new OptionBuilder(teamName);
List<Option> options = new List<Option>();
moves.ForEach(x => options.Add(builder.BuildOption(x, _currentBoard, oldTargets)));
return options;
}
private List<Target> BuildTargetLists(List<Option> options, TeamName teamName)
{
List<Target> targets = new List<Target>();
foreach (Option o in options)
{
foreach (Target t in o.Targets)
{
if (t.CheckIfTargetValid(_currentBoard, teamName))
{
targets.Add(t);
}
}
}
return targets;
}
private Target BestTargetFromList(List<Target> targets, TeamName teamName)
{
Target selectedTarget = null;
targets = targets.OrderBy(x => x.GetFourCost(_currentBoard, teamName)).ToList();
if (targets.Count > 0)
{
selectedTarget = targets[0];
}
return selectedTarget;
}
private void UpdateMovesList(ColumnNumber chosenColumn)
{
for (int i = 0; i < 6; i++)
{
if (!_currentBoard[(int)chosenColumn, i].IsOccupied)
{
_moves.Add(_currentBoard[(int)chosenColumn, i]);
break;
}
}
}
private void InitGameState(GameState gameState)
{
_currentBoard = gameState.CurrentBoardState;
}
private void UpdateEnemyMoves()
{
List<BoardPosition> enemyMoves = new List<BoardPosition>();
foreach (BoardPosition bp in _currentBoard)
{
if (bp.Owner == _enemyTeam)
{
enemyMoves.Add(bp);
}
}
_enemyMoves = enemyMoves;
}
void OnDrawGizmos()
{
if (_moves != null)
{
OptionBuilder builder = new OptionBuilder(_myTeam);
foreach (BoardPosition bp in _moves)
{
Option option = builder.BuildOption(bp, _currentBoard, _myTargets);
foreach (Target t in option.Targets)
{
Gizmos.DrawCube(t.TargetPosition.Position, new Vector2(.25f, .25f));
Vector2 labelPos = new Vector2(t.TargetPosition.Position.x, t.TargetPosition.Position.y + .75f);
GUIStyle style = new GUIStyle();
Handles.Label(labelPos, t.GetFourCost(_currentBoard, _myTeam).ToString(), style);
Gizmos.color = Color.gray;
t.MovesRequiredToFillPath.ForEach(x => Gizmos.DrawSphere(x.Position, .25f));
Gizmos.color = Color.green;
t.Path.ForEach(x => Gizmos.DrawSphere(x.Position, .15f));
}
}
}
if (_selectedTarget != null)
{
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(_selectedTarget.TargetPosition.Position, .25f);
}
if (_enemySelectedTarget != null)
{
Gizmos.color = Color.magenta;
Gizmos.DrawWireSphere(_enemySelectedTarget.TargetPosition.Position, .45f);
}
if (_enemyTargets != null && _enemyTargets.Count > 0)
{
Gizmos.color = Color.red;
_enemyTargets.ForEach(x => Gizmos.DrawWireSphere(x.TargetPosition.Position, .25f));
}
}
public void SetTeam(TeamName teamName)
{
switch(teamName)
{
case TeamName.BlackTeam:
_myTeam = TeamName.BlackTeam;
_enemyTeam = TeamName.RedTeam;
break;
case TeamName.RedTeam:
_myTeam = TeamName.RedTeam;
_enemyTeam = TeamName.BlackTeam;
break;
}
}
public void OnRoundCompletion()
{
_currentBoard = null;
_moves.Clear();
_selectedTarget = null;
_myTargets = null;
_enemyMoves.Clear();
_enemySelectedTarget = null;
_enemyTargets = null;
}
}
}
| 34.147679 | 120 | 0.512418 | [
"MIT"
] | eamonn-keogh/CoderDojo2019-ConnectFour | Connect-Four-master/Connect-Four-master/Assets/Scripts/AI/AI_Torgo/AI_Torgo.cs | 8,095 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Xaml.Input
{
// Skipping already declared delegate Windows.UI.Xaml.Input.ManipulationStartingEventHandler
}
| 32.857143 | 93 | 0.808696 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Input/ManipulationStartingEventHandler.cs | 230 | C# |
namespace Caliburn.PresentationFramework.RoutedMessaging
{
using System;
/// <summary>
/// The outcome of processing a message.
/// </summary>
public class MessageProcessingOutcome
{
/// <summary>
/// Initializes a new instance of the <see cref="MessageProcessingOutcome"/> class.
/// </summary>
/// <param name="result">The result.</param>
/// <param name="resultType">Type of the result.</param>
/// <param name="wasCancelled">if set to <c>true</c> [was cancelled].</param>
public MessageProcessingOutcome(object result, Type resultType, bool wasCancelled)
{
Result = result;
ResultType = resultType;
WasCancelled = wasCancelled;
}
/// <summary>
/// Gets or sets a value indicating whether message processing was cancelled.
/// </summary>
/// <value><c>true</c> if cancelled; otherwise, <c>false</c>.</value>
public bool WasCancelled { get; private set; }
/// <summary>
/// Gets or sets the type of the result.
/// </summary>
/// <value>The type of the result.</value>
public Type ResultType { get; set; }
/// <summary>
/// Gets or sets the result.
/// </summary>
/// <value>The result.</value>
public object Result { get; set; }
}
} | 35 | 92 | 0.55331 | [
"MIT"
] | CaliburnFx/Caliburn | src/Caliburn/PresentationFramework/RoutedMessaging/MessageProcessingOutcome.cs | 1,435 | C# |
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MetroEXControls {
public partial class ImagePanel : UserControl {
private Brush mBackgroundBrush = null;
private Image mImage = null;
private Point mStartMousePos;
private Point mStartScrollPosition;
private bool mPanning = false;
private bool mTransparencyEnabled = true;
#region Delegates
public delegate void OnPreDrawDelegate(System.Drawing.Graphics g);
public delegate void OnPostDrawDelegate(System.Drawing.Graphics g);
public OnPreDrawDelegate OnPreDraw { get; set; } = null;
public OnPostDrawDelegate OnPostDraw { get; set; } = null;
#endregion
public Image Image {
get {
return this.mImage;
}
set {
this.mImage = value;
this.AdjustScrolling();
this.Invalidate();
}
}
public bool TransparencyEnabled {
get {
return mTransparencyEnabled;
}
set {
if (mTransparencyEnabled != value) {
mTransparencyEnabled = value;
this.Invalidate();
}
}
}
public ImagePanel() {
Bitmap bmp = new Bitmap(16, 16);
for (int y = 0; y < bmp.Height; ++y) {
for (int x = 0; x < bmp.Width; ++x) {
bool isWhite = (x < 8 && y < 8) || (x >= 8 && y >= 8);
bmp.SetPixel(x, y, isWhite ? Color.LightGray : Color.DarkGray);
}
}
mBackgroundBrush = new TextureBrush(bmp);
InitializeComponent();
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.Selectable, false);
this.UpdateStyles();
}
public int GetDrawOffsetX() {
int leftWithOffset = this.Padding.Left;
if (this.AutoScroll) {
leftWithOffset += this.AutoScrollPosition.X;
}
return leftWithOffset;
}
public int GetDrawOffsetY() {
int topWithOffset = this.Padding.Top;
if (this.AutoScroll) {
topWithOffset += this.AutoScrollPosition.Y;
}
return topWithOffset;
}
protected override void OnPaint(PaintEventArgs e) {
this.OnPreDraw?.Invoke(e.Graphics);
int left = this.Padding.Left;
int top = this.Padding.Top;
int leftWithOffset = left;
int topWithOffset = top;
if (this.AutoScroll) {
leftWithOffset += this.AutoScrollPosition.X;
topWithOffset += this.AutoScrollPosition.Y;
}
// background
if (mImage != null && mTransparencyEnabled) {
int width = Math.Min(mImage.Width, this.ClientRectangle.Width);
int height = Math.Min(mImage.Height, this.ClientRectangle.Height);
e.Graphics.FillRectangle(mBackgroundBrush, left, top, width, height);
} else {
e.Graphics.FillRectangle(Brushes.White, this.ClientRectangle);
}
// image
if (mImage != null) {
if (!mTransparencyEnabled) {
e.Graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
} else {
e.Graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
}
e.Graphics.DrawImageUnscaled(mImage, leftWithOffset, topWithOffset);
}
this.OnPostDraw?.Invoke(e.Graphics);
// borders
ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, this.ForeColor, ButtonBorderStyle.Solid);
}
protected override void OnScroll(ScrollEventArgs e) {
base.OnScroll(e);
this.Invalidate();
}
protected override void OnMouseMove(MouseEventArgs e) {
base.OnMouseMove(e);
if (e.Button == MouseButtons.Left) {
if (!mPanning) {
mStartMousePos = e.Location;
this.SwitchPanning(true);
}
if (mPanning) {
int x = -(mStartScrollPosition.X - (mStartMousePos.X - e.Location.X));
int y = -(mStartScrollPosition.Y - (mStartMousePos.Y - e.Location.Y));
this.UpdateScrollPosition(new Point(x, y));
}
}
}
protected override void OnMouseUp(MouseEventArgs e) {
base.OnMouseUp(e);
if (mPanning) {
this.SwitchPanning(false);
}
}
private void SwitchPanning(bool isPanning) {
if (isPanning != mPanning) {
mPanning = isPanning;
mStartScrollPosition = this.AutoScrollPosition;
this.Cursor = isPanning ? Cursors.SizeAll : Cursors.Default;
}
}
private void UpdateScrollPosition(Point position) {
this.AutoScrollPosition = position;
this.OnScroll(new ScrollEventArgs(ScrollEventType.ThumbPosition, 0));
this.Invalidate();
}
private void AdjustLayout() {
if (this.AutoSize) {
this.AdjustSize();
} else if (this.AutoScroll) {
this.AdjustScrolling();
}
}
private void AdjustSize() {
if (this.AutoSize && this.Dock == DockStyle.None) {
this.Size = this.PreferredSize;
}
}
private void AdjustScrolling() {
if (this.AutoScroll && mImage != null) {
this.AutoScrollMinSize = mImage.Size;
}
}
}
}
| 32.657754 | 161 | 0.529393 | [
"MIT"
] | D-AIRY/MetroEX | libs/MetroEXControls/src/ImagePanel.cs | 6,109 | C# |
using System;
using System.Collections.Generic;
namespace MsSql.Context_For_Scaffolding.Models
{
public partial class UserEntities
{
public int UserId { get; set; }
public int EntityId { get; set; }
public bool IsOwner { get; set; }
public DateTime CreateDate { get; set; }
public virtual Entities Entity { get; set; }
public virtual Users User { get; set; }
}
}
| 25.058824 | 52 | 0.63615 | [
"MIT"
] | Magicianred/base-webapi-accounts-network | MsSql.Context_For_Scaffolding/Models/UserEntities.cs | 428 | C# |
using SimpleArchitecture.Application.Common.Interfaces;
using SimpleArchitecture.Infrastructure.Identity;
using SimpleArchitecture.Infrastructure.Persistence;
using SimpleArchitecture.WebUI;
using MediatR;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using NUnit.Framework;
using Respawn;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
[SetUpFixture]
public class Testing
{
private static IConfigurationRoot _configuration;
private static IServiceScopeFactory _scopeFactory;
private static Checkpoint _checkpoint;
private static string _currentUserId;
[OneTimeSetUp]
public void RunBeforeAnyTests()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
.AddEnvironmentVariables();
_configuration = builder.Build();
var startup = new Startup(_configuration);
var services = new ServiceCollection();
services.AddSingleton(Mock.Of<IWebHostEnvironment>(w =>
w.EnvironmentName == "Development" &&
w.ApplicationName == "SimpleArchitecture.WebUI"));
services.AddLogging();
startup.ConfigureServices(services);
// Replace service registration for ICurrentUserService
// Remove existing registration
var currentUserServiceDescriptor = services.FirstOrDefault(d =>
d.ServiceType == typeof(ICurrentUserService));
services.Remove(currentUserServiceDescriptor);
// Register testing version
services.AddTransient(provider =>
Mock.Of<ICurrentUserService>(s => s.UserId == _currentUserId));
_scopeFactory = services.BuildServiceProvider().GetService<IServiceScopeFactory>();
_checkpoint = new Checkpoint
{
TablesToIgnore = new[] { "__EFMigrationsHistory" }
};
EnsureDatabase();
}
private static void EnsureDatabase()
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
context.Database.Migrate();
}
public static async Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request)
{
using var scope = _scopeFactory.CreateScope();
var mediator = scope.ServiceProvider.GetService<ISender>();
return await mediator.Send(request);
}
public static async Task<string> RunAsDefaultUserAsync()
{
return await RunAsUserAsync("test@local", "Testing1234!", new string[] { });
}
public static async Task<string> RunAsAdministratorAsync()
{
return await RunAsUserAsync("administrator@local", "Administrator1234!", new[] { "Administrator" });
}
public static async Task<string> RunAsUserAsync(string userName, string password, string[] roles)
{
using var scope = _scopeFactory.CreateScope();
var userManager = scope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
var user = new ApplicationUser { UserName = userName, Email = userName };
var result = await userManager.CreateAsync(user, password);
if (roles.Any())
{
var roleManager = scope.ServiceProvider.GetService<RoleManager<IdentityRole>>();
foreach (var role in roles)
{
await roleManager.CreateAsync(new IdentityRole(role));
}
await userManager.AddToRolesAsync(user, roles);
}
if (result.Succeeded)
{
_currentUserId = user.Id;
return _currentUserId;
}
var errors = string.Join(Environment.NewLine, result.ToApplicationResult().Errors);
throw new Exception($"Unable to create {userName}.{Environment.NewLine}{errors}");
}
public static async Task ResetState()
{
await _checkpoint.Reset(_configuration.GetConnectionString("DefaultConnection"));
_currentUserId = null;
}
public static async Task<TEntity> FindAsync<TEntity>(params object[] keyValues)
where TEntity : class
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
return await context.FindAsync<TEntity>(keyValues);
}
public static async Task AddAsync<TEntity>(TEntity entity)
where TEntity : class
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
context.Add(entity);
await context.SaveChangesAsync();
}
public static async Task<int> CountAsync<TEntity>() where TEntity : class
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
return await context.Set<TEntity>().CountAsync();
}
[OneTimeTearDown]
public void RunAfterAnyTests()
{
}
}
| 29.954023 | 108 | 0.677475 | [
"MIT"
] | mehdyHD/SimpleArchitecture | tests/Application.IntegrationTests/Testing.cs | 5,214 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MFiles.VAF.Extensions.ExtensionMethods
{
public static class DictionaryExtensionMethods
{
/// <summary>
/// Adds or updates an item in a dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the key in the dictionary.</typeparam>
/// <typeparam name="TValue">The type of the value in the dictionary.</typeparam>
/// <param name="dictionary">The dictionary to update.</param>
/// <param name="key">The key of the item.</param>
/// <param name="value">The value for the item.</param>
public static void AddOrUpdate<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
// Sanity.
if (null == dictionary)
throw new ArgumentNullException(nameof(dictionary));
if (null == key)
throw new ArgumentNullException(nameof(key));
if (dictionary.ContainsKey(key))
dictionary[key] = value;
else
dictionary.Add(key, value);
}
}
}
| 32.454545 | 113 | 0.681606 | [
"MIT"
] | M-Files/VAF.Extensions.Community | MFiles.VAF.Extensions/ExtensionMethods/DictionaryExtensionMethods.cs | 1,073 | C# |
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Atn
{
/// <summary>
/// Executes a custom lexer action by calling
/// <see cref="Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)"/>
/// with the
/// rule and action indexes assigned to the custom action. The implementation of
/// a custom action is added to the generated code for the lexer in an override
/// of
/// <see cref="Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)"/>
/// when the grammar is compiled.
/// <p>This class may represent embedded actions created with the <code>{...}</code>
/// syntax in ANTLR 4, as well as actions created for lexer commands where the
/// command argument could not be evaluated when the grammar was compiled.</p>
/// </summary>
/// <author>Sam Harwell</author>
/// <since>4.2</since>
public sealed class LexerCustomAction : ILexerAction
{
private readonly int ruleIndex;
private readonly int actionIndex;
/// <summary>
/// Constructs a custom lexer action with the specified rule and action
/// indexes.
/// </summary>
/// <remarks>
/// Constructs a custom lexer action with the specified rule and action
/// indexes.
/// </remarks>
/// <param name="ruleIndex">
/// The rule index to use for calls to
/// <see cref="Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)"/>
/// .
/// </param>
/// <param name="actionIndex">
/// The action index to use for calls to
/// <see cref="Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)"/>
/// .
/// </param>
public LexerCustomAction(int ruleIndex, int actionIndex)
{
this.ruleIndex = ruleIndex;
this.actionIndex = actionIndex;
}
/// <summary>
/// Gets the rule index to use for calls to
/// <see cref="Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)"/>
/// .
/// </summary>
/// <returns>The rule index for the custom action.</returns>
public int RuleIndex
{
get
{
return ruleIndex;
}
}
/// <summary>
/// Gets the action index to use for calls to
/// <see cref="Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)"/>
/// .
/// </summary>
/// <returns>The action index for the custom action.</returns>
public int ActionIndex
{
get
{
return actionIndex;
}
}
/// <summary><inheritDoc/></summary>
/// <returns>
/// This method returns
/// <see cref="LexerActionType.Custom"/>
/// .
/// </returns>
public LexerActionType ActionType
{
get
{
return LexerActionType.Custom;
}
}
/// <summary>Gets whether the lexer action is position-dependent.</summary>
/// <remarks>
/// Gets whether the lexer action is position-dependent. Position-dependent
/// actions may have different semantics depending on the
/// <see cref="Antlr4.Runtime.ICharStream"/>
/// index at the time the action is executed.
/// <p>Custom actions are position-dependent since they may represent a
/// user-defined embedded action which makes calls to methods like
/// <see cref="Antlr4.Runtime.Lexer.Text()"/>
/// .</p>
/// </remarks>
/// <returns>
/// This method returns
/// <see langword="true"/>
/// .
/// </returns>
public bool IsPositionDependent
{
get
{
return true;
}
}
/// <summary>
/// <inheritDoc/>
/// <p>Custom actions are implemented by calling
/// <see cref="Antlr4.Runtime.Recognizer{Symbol, ATNInterpreter}.Action(Antlr4.Runtime.RuleContext, int, int)"/>
/// with the
/// appropriate rule and action indexes.</p>
/// </summary>
public void Execute(Lexer lexer)
{
lexer.Action(null, ruleIndex, actionIndex);
}
public override int GetHashCode()
{
int hash = MurmurHash.Initialize();
hash = MurmurHash.Update(hash, (int)(ActionType));
hash = MurmurHash.Update(hash, ruleIndex);
hash = MurmurHash.Update(hash, actionIndex);
return MurmurHash.Finish(hash, 3);
}
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
else
{
if (!(obj is Antlr4.Runtime.Atn.LexerCustomAction))
{
return false;
}
}
Antlr4.Runtime.Atn.LexerCustomAction other = (Antlr4.Runtime.Atn.LexerCustomAction)obj;
return ruleIndex == other.ruleIndex && actionIndex == other.actionIndex;
}
}
}
| 35.08642 | 120 | 0.561928 | [
"BSD-3-Clause"
] | charwliu/antlr4 | runtime/CSharp/runtime/CSharp/Antlr4.Runtime/Atn/LexerCustomAction.cs | 5,684 | 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("TakiApp.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TakiApp.UWP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 35.827586 | 84 | 0.739172 | [
"MIT"
] | samuelarbibe/Taki | Client/Client/TakiApp/TakiApp.UWP/Properties/AssemblyInfo.cs | 1,042 | C# |
using System;
using System.Diagnostics;
namespace Handyman.Azure.Cosmos.Table.Internals
{
[DebuggerDisplay("{Build()}")]
internal class RootTableQueryFilterNode : ITableQueryFilterNode
{
private ITableQueryFilterNode _child;
public void Add(ITableQueryFilterNode node)
{
if (_child != null)
throw new InvalidOperationException();
_child = node;
}
public string Build()
{
return _child?.Build() ?? throw new InvalidOperationException();
}
}
} | 23.75 | 76 | 0.608772 | [
"MIT"
] | JonasSamuelsson/Handyman | src/Handyman.Azure.Cosmos.Table/src/Internals/RootTableQueryFilterNode.cs | 572 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
namespace System
{
public partial class String
{
public bool Contains(string value)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
return SpanHelpers.IndexOf(ref _firstChar, Length, ref value._firstChar, value.Length)
>= 0;
}
public bool Contains(string value, StringComparison comparisonType)
{
#pragma warning disable CA2249 // Consider using 'string.Contains' instead of 'string.IndexOf'... this is the implementation of Contains!
return IndexOf(value, comparisonType) >= 0;
#pragma warning restore CA2249
}
public bool Contains(char value) => SpanHelpers.Contains(ref _firstChar, value, Length);
public bool Contains(char value, StringComparison comparisonType)
{
return IndexOf(value, comparisonType) != -1;
}
// Returns the index of the first occurrence of a specified character in the current instance.
// The search starts at startIndex and runs thorough the next count characters.
//
public int IndexOf(char value) => SpanHelpers.IndexOf(ref _firstChar, value, Length);
public int IndexOf(char value, int startIndex)
{
return IndexOf(value, startIndex, this.Length - startIndex);
}
public int IndexOf(char value, StringComparison comparisonType)
{
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(
this,
value,
GetCaseCompareOfComparisonCulture(comparisonType)
);
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IndexOf(
this,
value,
GetCaseCompareOfComparisonCulture(comparisonType)
);
case StringComparison.Ordinal:
return IndexOf(value);
case StringComparison.OrdinalIgnoreCase:
return CompareInfo.Invariant.IndexOf(
this,
value,
CompareOptions.OrdinalIgnoreCase
);
default:
throw new ArgumentException(
SR.NotSupported_StringComparison,
nameof(comparisonType)
);
}
}
public unsafe int IndexOf(char value, int startIndex, int count)
{
if ((uint)startIndex > (uint)Length)
throw new ArgumentOutOfRangeException(
nameof(startIndex),
SR.ArgumentOutOfRange_Index
);
if ((uint)count > (uint)(Length - startIndex))
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
int result = SpanHelpers.IndexOf(
ref Unsafe.Add(ref _firstChar, startIndex),
value,
count
);
return result == -1 ? result : result + startIndex;
}
// Returns the index of the first occurrence of any specified character in the current instance.
// The search starts at startIndex and runs to startIndex + count - 1.
//
public int IndexOfAny(char[] anyOf)
{
return IndexOfAny(anyOf, 0, this.Length);
}
public int IndexOfAny(char[] anyOf, int startIndex)
{
return IndexOfAny(anyOf, startIndex, this.Length - startIndex);
}
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
if (anyOf == null)
throw new ArgumentNullException(nameof(anyOf));
if ((uint)startIndex > (uint)Length)
throw new ArgumentOutOfRangeException(
nameof(startIndex),
SR.ArgumentOutOfRange_Index
);
if ((uint)count > (uint)(Length - startIndex))
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (anyOf.Length > 0 && anyOf.Length <= 5)
{
// The ReadOnlySpan.IndexOfAny extension is vectorized for values of 1 - 5 in length
int result = new ReadOnlySpan<char>(
ref Unsafe.Add(ref _firstChar, startIndex),
count
).IndexOfAny(anyOf);
return result == -1 ? result : result + startIndex;
}
else if (anyOf.Length > 5)
{
// Use Probabilistic Map
return IndexOfCharArray(anyOf, startIndex, count);
}
else // anyOf.Length == 0
{
return -1;
}
}
private unsafe int IndexOfCharArray(char[] anyOf, int startIndex, int count)
{
// use probabilistic map, see InitializeProbabilisticMap
ProbabilisticMap map = default;
uint* charMap = (uint*)↦
InitializeProbabilisticMap(charMap, anyOf);
fixed (char* pChars = &_firstChar)
{
char* pCh = pChars + startIndex;
while (count > 0)
{
int thisChar = *pCh;
if (
IsCharBitSet(charMap, (byte)thisChar)
&& IsCharBitSet(charMap, (byte)(thisChar >> 8))
&& ArrayContains((char)thisChar, anyOf)
)
{
return (int)(pCh - pChars);
}
count--;
pCh++;
}
return -1;
}
}
private const int PROBABILISTICMAP_BLOCK_INDEX_MASK = 0x7;
private const int PROBABILISTICMAP_BLOCK_INDEX_SHIFT = 0x3;
private const int PROBABILISTICMAP_SIZE = 0x8;
// A probabilistic map is an optimization that is used in IndexOfAny/
// LastIndexOfAny methods. The idea is to create a bit map of the characters we
// are searching for and use this map as a "cheap" check to decide if the
// current character in the string exists in the array of input characters.
// There are 256 bits in the map, with each character mapped to 2 bits. Every
// character is divided into 2 bytes, and then every byte is mapped to 1 bit.
// The character map is an array of 8 integers acting as map blocks. The 3 lsb
// in each byte in the character is used to index into this map to get the
// right block, the value of the remaining 5 msb are used as the bit position
// inside this block.
private static unsafe void InitializeProbabilisticMap(
uint* charMap,
ReadOnlySpan<char> anyOf
)
{
bool hasAscii = false;
uint* charMapLocal = charMap; // https://github.com/dotnet/runtime/issues/9040
for (int i = 0; i < anyOf.Length; ++i)
{
int c = anyOf[i];
// Map low bit
SetCharBit(charMapLocal, (byte)c);
// Map high bit
c >>= 8;
if (c == 0)
{
hasAscii = true;
}
else
{
SetCharBit(charMapLocal, (byte)c);
}
}
if (hasAscii)
{
// Common to search for ASCII symbols. Just set the high value once.
charMapLocal[0] |= 1u;
}
}
private static bool ArrayContains(char searchChar, char[] anyOf)
{
for (int i = 0; i < anyOf.Length; i++)
{
if (anyOf[i] == searchChar)
return true;
}
return false;
}
private static unsafe bool IsCharBitSet(uint* charMap, byte value)
{
return (
charMap[value & PROBABILISTICMAP_BLOCK_INDEX_MASK]
& (1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT))
) != 0;
}
private static unsafe void SetCharBit(uint* charMap, byte value)
{
charMap[value & PROBABILISTICMAP_BLOCK_INDEX_MASK] |=
1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT);
}
/*
* IndexOf, LastIndexOf, Contains, StartsWith, and EndsWith
* ========================================================
*
* Given a search string 'searchString', a target string 'value' to locate within the search string, and a comparer
* 'comparer', we ask the comparer to generate a set S of tuples '(startPos, endPos)' for which the below expression
* returns true:
*
* >> bool result = searchString.Substring(startPos, endPos - startPos).Equals(value, comparer);
*
* If the generated set S is empty (i.e., there is no combination of values 'startPos' and 'endPos' which makes the
* above expression evaluate to true), then we say "'searchString' does not contain 'value'", and the expression
* "searchString.Contains(value, comparer)" should evaluate to false. If the set S is non-empty, then we say
* "'searchString' contains 'value'", and the expression "searchString.Contains(value, comparer)" should
* evaluate to true.
*
* n.b. There may be other tuples '(startPos, endPos)' *not* present in the generated set S for which the above
* expression evaluates to true. We discount the existence of these values. Allowing any such values to factor
* into the logic below could result in splitting the search string in a manner inappropriate for the culture
* rules of the specified comparer. For the remainder of this discussion, when we refer to 'startPos' and
* 'endPos', we consider only tuples '(startPos, endPos)' as they may be present in the generated set S.
*
* Given a 'searchString', 'value', and 'comparer', the behavior of the IndexOf method is that it finds the
* smallest possible 'endPos' for which there exists any corresponding 'startPos' which makes the above
* expression evaluate to true, then it returns any 'startPos' within that subset. For example:
*
* let searchString = "<ZWJ><ZWJ>hihi" (where <ZWJ> = U+200D ZERO WIDTH JOINER, a weightless code point)
* let value = "hi"
* let comparer = a linguistic culture-invariant comparer (e.g., StringComparison.InvariantCulture)
* then S = { (0, 4), (1, 4), (2, 4), (4, 6) }
* so the expression "<ZWJ><ZWJ>hihi".IndexOf("hi", comparer) can evaluate to any of { 0, 1, 2 }.
*
* n.b. ordinal comparers (e.g., StringComparison.Ordinal and StringComparison.OrdinalIgnoreCase) do not
* exhibit this ambiguity, as any given 'startPos' or 'endPos' will appear at most exactly once across
* all entries from set S. With the above example, S = { (2, 4), (4, 6) }, so IndexOf = 2 unambiguously.
*
* There exists a relationship between IndexOf and StartsWith. If there exists in set S any entry with
* the tuple values (startPos = 0, endPos = <anything>), we say "'searchString' starts with 'value'", and
* the expression "searchString.StartsWith(value, comparer)" should evaluate to true. If there exists
* no such entry in set S, then we say "'searchString' does not start with 'value'", and the expression
* "searchString.StartsWith(value, comparer)" should evaluate to false.
*
* LastIndexOf and EndsWith have a similar relationship as IndexOf and StartsWith. The behavior of the
* LastIndexOf method is that it finds the largest possible 'endPos' for which there exists any corresponding
* 'startPos' which makes the expression evaluate to true, then it returns any 'startPos' within that
* subset. For example:
*
* let searchString = "hi<ZWJ><ZWJ>hi" (this is slightly modified from the earlier example)
* let value = "hi"
* let comparer = StringComparison.InvariantCulture
* then S = { (0, 2), (0, 3), (0, 4), (2, 6), (3, 6), (4, 6) }
* so the expression "hi<ZWJ><ZWJ>hi".LastIndexOf("hi", comparer) can evaluate to any of { 2, 3, 4 }.
*
* If there exists in set S any entry with the tuple values (startPos = <anything>, endPos = searchString.Length),
* we say "'searchString' ends with 'value'", and the expression "searchString.EndsWith(value, comparer)"
* should evaluate to true. If there exists no such entry in set S, then we say "'searchString' does not
* start with 'value'", and the expression "searchString.EndsWith(value, comparer)" should evaluate to false.
*
* There are overloads of IndexOf and LastIndexOf which take an offset and length in order to constrain the
* search space to a substring of the original search string.
*
* For LastIndexOf specifially, overloads which take a 'startIndex' and 'count' behave differently
* than their IndexOf counterparts. 'startIndex' is the index of the last char element that should
* be considered when performing the search. For example, if startIndex = 4, then the caller is
* indicating "when finding the match I want you to include the char element at index 4, but not
* any char elements past that point."
*
* idx = 0123456 ("abcdefg".Length = 7)
* So, if the search string is "abcdefg", startIndex = 5 and count = 3, then the search space will
* ~~~ be the substring "def", as highlighted to the left.
* Essentially: "the search space should be of length 3 chars and should end *just after* the char
* element at index 5."
*
* Since this behavior can introduce off-by-one errors in the boundary cases, we allow startIndex = -1
* with a zero-length 'searchString' (treated as equivalent to startIndex = 0), and we allow
* startIndex = searchString.Length (treated as equivalent to startIndex = searchString.Length - 1).
*
* Note also that this behavior can introduce errors when dealing with UTF-16 surrogate pairs.
* If the search string is the 3 chars "[BMP][HI][LO]", startIndex = 1 and count = 2, then the
* ~~~~~~~~~ search space wil be the substring "[BMP][ HI]".
* This means that the char [HI] is incorrectly seen as a standalone high surrogate, which could
* lead to incorrect matching behavior, or it could cause LastIndexOf to incorrectly report that
* a zero-weight character could appear between the [HI] and [LO] chars.
*/
public int IndexOf(string value)
{
return IndexOf(value, StringComparison.CurrentCulture);
}
public int IndexOf(string value, int startIndex)
{
return IndexOf(value, startIndex, StringComparison.CurrentCulture);
}
public int IndexOf(string value, int startIndex, int count)
{
return IndexOf(value, startIndex, count, StringComparison.CurrentCulture);
}
public int IndexOf(string value, StringComparison comparisonType)
{
return IndexOf(value, 0, this.Length, comparisonType);
}
public int IndexOf(string value, int startIndex, StringComparison comparisonType)
{
return IndexOf(value, startIndex, this.Length - startIndex, comparisonType);
}
public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType)
{
// Parameter checking will be done by CompareInfo.IndexOf.
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(
this,
value,
startIndex,
count,
GetCaseCompareOfComparisonCulture(comparisonType)
);
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IndexOf(
this,
value,
startIndex,
count,
GetCaseCompareOfComparisonCulture(comparisonType)
);
case StringComparison.Ordinal:
case StringComparison.OrdinalIgnoreCase:
return Ordinal.IndexOf(
this,
value,
startIndex,
count,
comparisonType == StringComparison.OrdinalIgnoreCase
);
default:
throw (value is null)
? new ArgumentNullException(nameof(value))
: new ArgumentException(
SR.NotSupported_StringComparison,
nameof(comparisonType)
);
}
}
// Returns the index of the last occurrence of a specified character in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
public int LastIndexOf(char value) =>
SpanHelpers.LastIndexOf(ref _firstChar, value, Length);
public int LastIndexOf(char value, int startIndex)
{
return LastIndexOf(value, startIndex, startIndex + 1);
}
public unsafe int LastIndexOf(char value, int startIndex, int count)
{
if (Length == 0)
return -1;
if ((uint)startIndex >= (uint)Length)
throw new ArgumentOutOfRangeException(
nameof(startIndex),
SR.ArgumentOutOfRange_Index
);
if ((uint)count > (uint)startIndex + 1)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
int startSearchAt = startIndex + 1 - count;
int result = SpanHelpers.LastIndexOf(
ref Unsafe.Add(ref _firstChar, startSearchAt),
value,
count
);
return result == -1 ? result : result + startSearchAt;
}
// Returns the index of the last occurrence of any specified character in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
public int LastIndexOfAny(char[] anyOf)
{
return LastIndexOfAny(anyOf, this.Length - 1, this.Length);
}
public int LastIndexOfAny(char[] anyOf, int startIndex)
{
return LastIndexOfAny(anyOf, startIndex, startIndex + 1);
}
public unsafe int LastIndexOfAny(char[] anyOf, int startIndex, int count)
{
if (anyOf == null)
throw new ArgumentNullException(nameof(anyOf));
if (Length == 0)
return -1;
if ((uint)startIndex >= (uint)Length)
{
throw new ArgumentOutOfRangeException(
nameof(startIndex),
SR.ArgumentOutOfRange_Index
);
}
if ((count < 0) || ((count - 1) > startIndex))
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
}
if (anyOf.Length > 1)
{
return LastIndexOfCharArray(anyOf, startIndex, count);
}
else if (anyOf.Length == 1)
{
return LastIndexOf(anyOf[0], startIndex, count);
}
else // anyOf.Length == 0
{
return -1;
}
}
private unsafe int LastIndexOfCharArray(char[] anyOf, int startIndex, int count)
{
// use probabilistic map, see InitializeProbabilisticMap
ProbabilisticMap map = default;
uint* charMap = (uint*)↦
InitializeProbabilisticMap(charMap, anyOf);
fixed (char* pChars = &_firstChar)
{
char* pCh = pChars + startIndex;
while (count > 0)
{
int thisChar = *pCh;
if (
IsCharBitSet(charMap, (byte)thisChar)
&& IsCharBitSet(charMap, (byte)(thisChar >> 8))
&& ArrayContains((char)thisChar, anyOf)
)
{
return (int)(pCh - pChars);
}
count--;
pCh--;
}
return -1;
}
}
// Returns the index of the last occurrence of any character in value in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
public int LastIndexOf(string value)
{
return LastIndexOf(
value,
this.Length - 1,
this.Length,
StringComparison.CurrentCulture
);
}
public int LastIndexOf(string value, int startIndex)
{
return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture);
}
public int LastIndexOf(string value, int startIndex, int count)
{
return LastIndexOf(value, startIndex, count, StringComparison.CurrentCulture);
}
public int LastIndexOf(string value, StringComparison comparisonType)
{
return LastIndexOf(value, this.Length - 1, this.Length, comparisonType);
}
public int LastIndexOf(string value, int startIndex, StringComparison comparisonType)
{
return LastIndexOf(value, startIndex, startIndex + 1, comparisonType);
}
public int LastIndexOf(
string value,
int startIndex,
int count,
StringComparison comparisonType
)
{
// Parameter checking will be done by CompareInfo.LastIndexOf.
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(
this,
value,
startIndex,
count,
GetCaseCompareOfComparisonCulture(comparisonType)
);
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.LastIndexOf(
this,
value,
startIndex,
count,
GetCaseCompareOfComparisonCulture(comparisonType)
);
case StringComparison.Ordinal:
case StringComparison.OrdinalIgnoreCase:
return CompareInfo.Invariant.LastIndexOf(
this,
value,
startIndex,
count,
GetCompareOptionsFromOrdinalStringComparison(comparisonType)
);
default:
throw (value is null)
? new ArgumentNullException(nameof(value))
: new ArgumentException(
SR.NotSupported_StringComparison,
nameof(comparisonType)
);
}
}
[StructLayout(LayoutKind.Explicit, Size = PROBABILISTICMAP_SIZE * sizeof(uint))]
private struct ProbabilisticMap { }
}
}
| 41.960848 | 137 | 0.554273 | [
"MIT"
] | belav/runtime | src/libraries/System.Private.CoreLib/src/System/String.Searching.cs | 25,722 | C# |
using UnityEngine;
using UnityEditor;
namespace InspectorAttribute
{
[CustomPropertyDrawer(typeof(ConditionalHideAttribute))]
public class ConditionalHideDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
ConditionalHideAttribute condHAtt = (ConditionalHideAttribute)attribute;
bool show = GetConditionalHideAttributeResult(condHAtt, property);
bool readOnly = condHAtt.hideType == HideType.HideOrReadonly || !show;
bool hide = condHAtt.hideType != HideType.Readonly && !show;
if (!hide)
{
bool wasGuiEnabled = GUI.enabled;
GUI.enabled = !readOnly;
EditorGUI.PropertyField(position, property, label, true);
GUI.enabled = wasGuiEnabled;
}
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
ConditionalHideAttribute condHAtt = (ConditionalHideAttribute)attribute;
bool show = GetConditionalHideAttributeResult(condHAtt, property);
bool readOnly = condHAtt.hideType == HideType.HideOrReadonly || !show;
bool hide = condHAtt.hideType != HideType.Readonly && !show;
if (!hide)
return EditorGUI.GetPropertyHeight(property, label);
else // (hide)
return -EditorGUIUtility.standardVerticalSpacing;
}
private bool GetConditionalHideAttributeResult(ConditionalHideAttribute condHAtt, SerializedProperty property)
{
switch (condHAtt.type)
{
case HideCondition.Boolean:
case HideCondition.Enum:
break;
case HideCondition.IsPlaying:
return !Application.isPlaying;
case HideCondition.IsntPlaying:
return Application.isPlaying;
default:
Debug.LogError("You forgot a type in ConditionalHideDrawer !");
return true;
}
string propertyName = condHAtt.ConditionalSourceField;
bool invert = false;
bool bitmaskAnd = false;
if ((propertyName[0] == ConditionalHideAttribute.invertChar && propertyName[1] == ConditionalHideAttribute.bitmaskAndChar)
|| (propertyName[1] == ConditionalHideAttribute.invertChar && propertyName[0] == ConditionalHideAttribute.bitmaskAndChar))
{
invert = true;
bitmaskAnd = true;
propertyName = propertyName.Substring(2);
}
else if (propertyName[0] == ConditionalHideAttribute.invertChar)
{
invert = true;
propertyName = propertyName.Substring(1);
}
else if (propertyName[0] == ConditionalHideAttribute.bitmaskAndChar)
{
bitmaskAnd = true;
propertyName = propertyName.Substring(1);
}
SerializedProperty sourcePropertyValue;
if (this.RepresentAnArray())
sourcePropertyValue = property.serializedObject.FindProperty(propertyName);
else
{
string propertyPath = property.propertyPath; //returns the property path of the property we want to apply the attribute to
string conditionPath = propertyPath.Replace(property.name, propertyName); //changes the path to the conditionalsource property path
sourcePropertyValue = property.serializedObject.FindProperty(conditionPath);
}
if (sourcePropertyValue != null)
{
if (condHAtt.type == HideCondition.Enum && bitmaskAnd)
{
if (invert)
return (sourcePropertyValue.intValue & condHAtt.enumValue) != 0;
else
return (sourcePropertyValue.intValue & condHAtt.enumValue) == 0;
}
else if (condHAtt.type == HideCondition.Enum) // (&& !bitmaskAnd)
{
if (invert)
return sourcePropertyValue.intValue == condHAtt.enumValue;
else
return sourcePropertyValue.intValue != condHAtt.enumValue;
}
else // (condHAtt.type == HideCondition.Boolean)
{
if (invert)
return sourcePropertyValue.boolValue;
else
return !(sourcePropertyValue.boolValue);
}
}
else
Debug.LogError("Attempting to use a ConditionalHideAttribute but no matching " +
"SourcePropertyValue found in object: " + propertyName);
return true;
}
}
} | 43.389831 | 148 | 0.554883 | [
"CC0-1.0"
] | Slyp05/Unity-Inspector-Attributes-Collection | Inspector Attributes Collection/Editor/ConditionalHideDrawer.cs | 5,122 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using OnlineBookStoreDemo.Data.Common.Models;
namespace OnlineBookStoreDemo.Data.Models
{
public class Subscriber : BaseDeletableModel<int>
{
[Required(ErrorMessage = "Please enter your email address here.")]
[EmailAddress(ErrorMessage = "Please enter valid email address.")]
public string Email { get; set; }
}
}
| 29 | 74 | 0.734914 | [
"MIT"
] | Pivchev/OnlineBookStoreDemo | src/Data/OnlineBookStoreDemo.Data.Models/Subscriber.cs | 466 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticloadbalancing-2012-06-01.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.ElasticLoadBalancing.Model
{
///<summary>
/// ElasticLoadBalancing exception
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public class AccessPointNotFoundException : AmazonElasticLoadBalancingException
{
/// <summary>
/// Constructs a new AccessPointNotFoundException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public AccessPointNotFoundException(string message)
: base(message) {}
/// <summary>
/// Construct instance of AccessPointNotFoundException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public AccessPointNotFoundException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of AccessPointNotFoundException
/// </summary>
/// <param name="innerException"></param>
public AccessPointNotFoundException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of AccessPointNotFoundException
/// </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 AccessPointNotFoundException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of AccessPointNotFoundException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public AccessPointNotFoundException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the AccessPointNotFoundException 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 AccessPointNotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 44.010309 | 178 | 0.657063 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/ElasticLoadBalancing/Generated/Model/AccessPointNotFoundException.cs | 4,269 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetCoreIdentity.Domain.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace DotNetCoreIdentity.Web.Areas.Identity.Pages.Account.Manage
{
public class GenerateRecoveryCodesModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger<GenerateRecoveryCodesModel> _logger;
public GenerateRecoveryCodesModel(
UserManager<ApplicationUser> userManager,
ILogger<GenerateRecoveryCodesModel> logger)
{
_userManager = userManager;
_logger = logger;
}
[TempData]
public string[] RecoveryCodes { get; set; }
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
if (!isTwoFactorEnabled)
{
var userId = await _userManager.GetUserIdAsync(user);
throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' because they do not have 2FA enabled.");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user);
var userId = await _userManager.GetUserIdAsync(user);
if (!isTwoFactorEnabled)
{
throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' as they do not have 2FA enabled.");
}
var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
RecoveryCodes = recoveryCodes.ToArray();
_logger.LogInformation("User with ID '{UserId}' has generated new 2FA recovery codes.", userId);
StatusMessage = "You have generated new recovery codes.";
return RedirectToPage("./ShowRecoveryCodes");
}
}
} | 37.123288 | 153 | 0.638007 | [
"MIT"
] | nyf16/Bootcamp-Repeat- | DotNetCoreIdentity/src/DotNetCoreIdentity.Web/Areas/Identity/Pages/Account/Manage/GenerateRecoveryCodes.cshtml.cs | 2,712 | C# |
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Dhgms.GripeWithRoslyn.Analyzer.CodeCracker.Extensions
{
public static class CSharpGeneratedCodeAnalysisExtensions
{
public static bool IsGenerated(this SyntaxNodeAnalysisContext context) => (context.SemanticModel?.SyntaxTree?.IsGenerated() ?? false) || (context.Node?.IsGenerated() ?? false);
private static readonly string[] generatedCodeAttributes = new string[] { "DebuggerNonUserCode", "GeneratedCode", "DebuggerNonUserCodeAttribute", "GeneratedCodeAttribute" };
public static bool IsGenerated(this SyntaxNode node) => node.HasAttributeOnAncestorOrSelf(generatedCodeAttributes);
public static bool IsGenerated(this SyntaxTreeAnalysisContext context) => context.Tree?.IsGenerated() ?? false;
public static bool IsGenerated(this SymbolAnalysisContext context)
{
if (context.Symbol == null) return false;
foreach (var syntaxReference in context.Symbol.DeclaringSyntaxReferences)
{
if (syntaxReference.SyntaxTree.IsGenerated()) return true;
var root = syntaxReference.SyntaxTree.GetRoot();
var node = root?.FindNode(syntaxReference.Span);
if (node.IsGenerated()) return true;
}
return false;
}
public static bool IsGenerated(this SyntaxTree tree) => (tree.FilePath?.IsOnGeneratedFile() ?? false) || tree.HasAutoGeneratedComment();
public static bool HasAutoGeneratedComment(this SyntaxTree tree)
{
var root = tree.GetRoot();
if (root == null) return false;
var firstToken = root.GetFirstToken();
SyntaxTriviaList trivia;
if (firstToken == default(SyntaxToken))
{
var token = ((CompilationUnitSyntax)root).EndOfFileToken;
if (!token.HasLeadingTrivia) return false;
trivia = token.LeadingTrivia;
}
else
{
if (!firstToken.HasLeadingTrivia) return false;
trivia = firstToken.LeadingTrivia;
}
var comments = trivia.Where(t => t.IsKind(SyntaxKind.SingleLineCommentTrivia) || t.IsKind(SyntaxKind.MultiLineCommentTrivia));
return comments.Any(t =>
{
var s = t.ToString();
return s.Contains("<auto-generated") || s.Contains("<autogenerated");
});
}
}
} | 43.966667 | 184 | 0.639879 | [
"MIT"
] | DHGMS-Solutions/gripewithroslyn | src/Dhgms.GripeWithRoslyn.Analyzer/CodeCracker/Extensions/CSharpGeneratedCodeAnalysisExtensions.cs | 2,640 | C# |
namespace IonCLI.PackageManagement
{
public enum DependencySourceType
{
/// <summary>
/// A project hosted on GitHub.
/// </summary>
GitHub,
/// <summary>
/// A project hosted on a Git URL.
/// </summary>
Git,
/// <summary>
/// A project hosted locally in the file system.
/// </summary>
Local
}
public abstract class DependencySource
{
public DependencySourceType Type { get; set; }
public string URL { get; set; }
}
}
| 20 | 56 | 0.519643 | [
"MIT"
] | IonLanguage/CLI | IonCLI/PackageManagement/DependencySource.cs | 560 | C# |
/*
* Apteco API
*
* An API to allow access to Apteco Marketing Suite resources
*
* OpenAPI spec version: v2
* Contact: support@apteco.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SwaggerDateConverter = Apteco.OrbitDashboardRefresher.APIClient.Client.SwaggerDateConverter;
namespace Apteco.OrbitDashboardRefresher.APIClient.Model
{
/// <summary>
/// Summary details for a user
/// </summary>
[DataContract]
public partial class PagedResultsFileSystemSummary : IEquatable<PagedResultsFileSystemSummary>
{
/// <summary>
/// Initializes a new instance of the <see cref="PagedResultsFileSystemSummary" /> class.
/// </summary>
[JsonConstructorAttribute]
protected PagedResultsFileSystemSummary() { }
/// <summary>
/// Initializes a new instance of the <see cref="PagedResultsFileSystemSummary" /> class.
/// </summary>
/// <param name="offset">The number of items that were skipped over from the (potentially filtered) result set (required).</param>
/// <param name="count">The number of items returned in this page of the result set (required).</param>
/// <param name="totalCount">The total number of items available in the (potentially filtered) result set (required).</param>
/// <param name="list">The list of results (required).</param>
public PagedResultsFileSystemSummary(int? offset = default(int?), int? count = default(int?), int? totalCount = default(int?), List<FileSystemSummary> list = default(List<FileSystemSummary>))
{
// to ensure "offset" is required (not null)
if (offset == null)
{
throw new InvalidDataException("offset is a required property for PagedResultsFileSystemSummary and cannot be null");
}
else
{
this.Offset = offset;
}
// to ensure "count" is required (not null)
if (count == null)
{
throw new InvalidDataException("count is a required property for PagedResultsFileSystemSummary and cannot be null");
}
else
{
this.Count = count;
}
// to ensure "totalCount" is required (not null)
if (totalCount == null)
{
throw new InvalidDataException("totalCount is a required property for PagedResultsFileSystemSummary and cannot be null");
}
else
{
this.TotalCount = totalCount;
}
// to ensure "list" is required (not null)
if (list == null)
{
throw new InvalidDataException("list is a required property for PagedResultsFileSystemSummary and cannot be null");
}
else
{
this.List = list;
}
}
/// <summary>
/// The number of items that were skipped over from the (potentially filtered) result set
/// </summary>
/// <value>The number of items that were skipped over from the (potentially filtered) result set</value>
[DataMember(Name="offset", EmitDefaultValue=false)]
public int? Offset { get; set; }
/// <summary>
/// The number of items returned in this page of the result set
/// </summary>
/// <value>The number of items returned in this page of the result set</value>
[DataMember(Name="count", EmitDefaultValue=false)]
public int? Count { get; set; }
/// <summary>
/// The total number of items available in the (potentially filtered) result set
/// </summary>
/// <value>The total number of items available in the (potentially filtered) result set</value>
[DataMember(Name="totalCount", EmitDefaultValue=false)]
public int? TotalCount { get; set; }
/// <summary>
/// The list of results
/// </summary>
/// <value>The list of results</value>
[DataMember(Name="list", EmitDefaultValue=false)]
public List<FileSystemSummary> List { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PagedResultsFileSystemSummary {\n");
sb.Append(" Offset: ").Append(Offset).Append("\n");
sb.Append(" Count: ").Append(Count).Append("\n");
sb.Append(" TotalCount: ").Append(TotalCount).Append("\n");
sb.Append(" List: ").Append(List).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as PagedResultsFileSystemSummary);
}
/// <summary>
/// Returns true if PagedResultsFileSystemSummary instances are equal
/// </summary>
/// <param name="input">Instance of PagedResultsFileSystemSummary to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PagedResultsFileSystemSummary input)
{
if (input == null)
return false;
return
(
this.Offset == input.Offset ||
(this.Offset != null &&
this.Offset.Equals(input.Offset))
) &&
(
this.Count == input.Count ||
(this.Count != null &&
this.Count.Equals(input.Count))
) &&
(
this.TotalCount == input.TotalCount ||
(this.TotalCount != null &&
this.TotalCount.Equals(input.TotalCount))
) &&
(
this.List == input.List ||
this.List != null &&
this.List.SequenceEqual(input.List)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Offset != null)
hashCode = hashCode * 59 + this.Offset.GetHashCode();
if (this.Count != null)
hashCode = hashCode * 59 + this.Count.GetHashCode();
if (this.TotalCount != null)
hashCode = hashCode * 59 + this.TotalCount.GetHashCode();
if (this.List != null)
hashCode = hashCode * 59 + this.List.GetHashCode();
return hashCode;
}
}
}
}
| 38.559406 | 199 | 0.555142 | [
"Apache-2.0"
] | Apteco/OrbitDashboardRefresher | Apteco.OrbitDashboardRefresher.APIClient/Model/PagedResultsFileSystemSummary.cs | 7,789 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Question_07_06_Jigsaw
{
public class Piece
{
// Always ordered in Left, Top, Bottom, Right
protected List<Edge> orderedEdges;
int numberOfFlatEdges = 0;
public Piece()
{
orderedEdges = new List<Edge>();
}
public Piece(int data, List<Edge> edges)
{
if (edges.Count != 4) throw new ArgumentException();
orderedEdges = edges;
LeftEdge = CheckEdge(orderedEdges[0]);
TopEdge = CheckEdge(orderedEdges[1]);
RightEdge = CheckEdge(orderedEdges[2]);
BottomEdge = CheckEdge(orderedEdges[3]);
Data = data;
}
private Edge CheckEdge(Edge value)
{
if (value.Type == EdgeType.Flat)
{
numberOfFlatEdges++;
}
return value;
}
public int Data
{
get;
protected set;
}
public Edge LeftEdge
{
get;
protected set;
}
public Edge TopEdge
{
get;
protected set;
}
public Edge RightEdge
{
get;
protected set;
}
public Edge BottomEdge
{
get;
protected set;
}
public bool IsCorner
{
get
{
return numberOfFlatEdges == 2;
}
}
public bool Rotate()
{
var temp = BottomEdge;
BottomEdge = RightEdge;
RightEdge = TopEdge;
TopEdge = LeftEdge;
LeftEdge = temp;
return true;
}
}
}
| 20.23913 | 64 | 0.465091 | [
"Apache-2.0"
] | qulia/CrackingTheCodingInterview | Question_07_06_Jigsaw/Piece.cs | 1,864 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type Data Source.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class DataSource : Entity
{
///<summary>
/// The internal DataSource constructor
///</summary>
protected internal DataSource()
{
// Don't allow initialization of abstract entity types
}
/// <summary>
/// Gets or sets created by.
/// The user who created the dataSource.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "createdBy", Required = Newtonsoft.Json.Required.Default)]
public IdentitySet CreatedBy { get; set; }
/// <summary>
/// Gets or sets created date time.
/// The date and time the dataSource was created.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "createdDateTime", Required = Newtonsoft.Json.Required.Default)]
public DateTimeOffset? CreatedDateTime { get; set; }
/// <summary>
/// Gets or sets display name.
/// The display name of the dataSource. This will be the name of the SharePoint site.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "displayName", Required = Newtonsoft.Json.Required.Default)]
public string DisplayName { get; set; }
}
}
| 36.894737 | 153 | 0.600095 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/model/DataSource.cs | 2,103 | C# |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Ocelot.OrleansHttpGateway.Infrastructure
{
/// <summary>
/// LateBoundMethod is a generic method signature that is passed an instance
/// and an array of parameters and returns an object. It basically can be
/// used to call any method.
///
/// </summary>
/// <param name="target">The instance that the dynamic method is called on</param>
/// <param name="arguments"></param>
/// <returns></returns>
internal delegate object LateBoundMethod(object target, object[] arguments);
/// <summary>
/// This class creates a generic method delegate from a MethodInfo signature
/// converting the method call into a LateBoundMethod delegate call. Using
/// this class allows making repeated calls very quickly.
///
/// Note: this class will be very inefficient for individual dynamic method
/// calls - compilation of the expression is very expensive up front, so using
/// this delegate factory makes sense only if you re-use and cache the dynamicly
/// loaded method repeatedly.
///
/// Entirely based on Nate Kohari's blog post:
/// http://kohari.org/2009/03/06/fast-late-bound-invocation-with-expression-trees/
/// </summary>
internal static class DelegateFactory
{
/// <summary>
/// Creates a LateBoundMethod delegate from a MethodInfo structure
/// Basically creates a dynamic delegate on the fly.
/// </summary>
/// <param name="method"></param>
/// <returns></returns>
public static LateBoundMethod Create(MethodInfo method)
{
ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "target");
ParameterExpression argumentsParameter = Expression.Parameter(typeof(object[]), "arguments");
MethodCallExpression call = Expression.Call(
Expression.Convert(instanceParameter, method.DeclaringType),
method,
CreateParameterExpressions(method, argumentsParameter));
Expression<LateBoundMethod> lambda = Expression.Lambda<LateBoundMethod>(
Expression.Convert(call, typeof(object)),
instanceParameter,
argumentsParameter);
return lambda.Compile();
}
/// <summary>
/// Creates a LateBoundMethod from type methodname and parameter signature that
/// is turned into a MethodInfo structure and then parsed into a dynamic delegate
/// </summary>
/// <param name="type"></param>
/// <param name="methodName"></param>
/// <param name="parameterTypes"></param>
/// <returns></returns>
public static LateBoundMethod Create(Type type, string methodName, params Type[] parameterTypes)
{
return Create(type.GetMethod(methodName, parameterTypes));
}
private static Expression[] CreateParameterExpressions(MethodInfo method, Expression argumentsParameter)
{
return method.GetParameters().Select((parameter, index) =>
Expression.Convert(
Expression.ArrayIndex(argumentsParameter, Expression.Constant(index)),
parameter.ParameterType)).ToArray();
}
}
} | 41.280488 | 112 | 0.647563 | [
"Apache-2.0"
] | AClumsy/Ocelot.OrleansHttpGateway | src/Ocelot.OrleansHttpGateway/Infrastructure/DelegateFactory.cs | 3,387 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class PanzerSmartWeaponTargetController : inkWidgetLogicController
{
[Ordinal(0)] [RED("distanceText")] public inkTextWidgetReference DistanceText { get; set; }
[Ordinal(1)] [RED("lockingAnimationProxy")] public CHandle<inkanimProxy> LockingAnimationProxy { get; set; }
public PanzerSmartWeaponTargetController(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 33.294118 | 120 | 0.749117 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/PanzerSmartWeaponTargetController.cs | 550 | C# |
// Copyright (C) 2012 Xtensive LLC.
// All rights reserved.
// For conditions of distribution and use, see license.
// Created by: Denis Krjuchkov
// Created: 2012.03.16
namespace Xtensive.Orm.Tests.Storage.Multimapping.CrossRenameModel.Version1.Namespace2
{
[HierarchyRoot]
public class Renamed2 : Entity
{
[Key, Field]
public int Id { get; set; }
[Field]
public string Name { get; set; }
}
} | 24.444444 | 87 | 0.661364 | [
"MIT"
] | SergeiPavlov/dataobjects-net | Orm/Xtensive.Orm.Tests/Storage/Multimapping/CrossRenameModel/Version1/Namespace2/Renamed2.cs | 442 | 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 iot1click-devices-2018-05-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.IoT1ClickDevicesService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.IoT1ClickDevicesService.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GetDeviceMethods operation
/// </summary>
public class GetDeviceMethodsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
GetDeviceMethodsResponse response = new GetDeviceMethodsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("deviceMethods", targetDepth))
{
var unmarshaller = new ListUnmarshaller<DeviceMethod, DeviceMethodUnmarshaller>(DeviceMethodUnmarshaller.Instance);
response.DeviceMethods = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalFailureException"))
{
return InternalFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException"))
{
return InvalidRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonIoT1ClickDevicesServiceException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static GetDeviceMethodsResponseUnmarshaller _instance = new GetDeviceMethodsResponseUnmarshaller();
internal static GetDeviceMethodsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetDeviceMethodsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.567797 | 206 | 0.654316 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/IoT1ClickDevicesService/Generated/Model/Internal/MarshallTransformations/GetDeviceMethodsResponseUnmarshaller.cs | 4,669 | C# |
#if UNITY_EDITOR && ODIN_INSPECTOR
namespace UniTween.Editor
{
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities;
using Sirenix.Utilities.Editor;
using System.Collections.Generic;
using System.Linq;
using UniTween.Core;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public class UniTweenSequenceExplorer : OdinMenuEditorWindow
{
public static List<UniTweenSequencePlayer> sequences = new List<UniTweenSequencePlayer>();
protected override OdinMenuTree BuildMenuTree()
{
OdinMenuTree tree = new OdinMenuTree(true);
tree.DefaultMenuStyle.IconSize = 28.00f;
tree.Config.DrawSearchToolbar = true;
var evs = GetSequences();
Dictionary<string, int> sqAmount = new Dictionary<string, int>();
for (int i = 0; i < evs.Count; i++)
{
string sqName = evs[i].DisplayName != "" ? evs[i].name + ": " + evs[i].DisplayName : evs[i].name;
if (sqAmount.ContainsKey(sqName))
{
sqAmount[sqName] += 1;
}
else
{
sqAmount.Add(sqName, 0);
}
if (sqAmount[sqName] != 0)
tree.Add(sqName + " (" + sqAmount[sqName] + ")", evs[i]);
else
tree.Add(sqName, evs[i]);
}
tree.SortMenuItemsByName();
return tree;
}
public List<UniTweenSequencePlayer> GetSequences()
{
var evs = CustomFindObjectsOfTypeAll<UniTweenSequencePlayer>();
sequences.Clear();
for (int i = 0; i < evs.Count; i++)
{
sequences.Add(evs[i]);
}
return sequences;
}
protected override void OnBeginDrawEditors()
{
OdinMenuItem selected = null;
if (MenuTree != null)
{
if (MenuTree.MenuItems.Count > 0)
{
selected = this.MenuTree.Selection.FirstOrDefault();
}
var toolbarHeight = this.MenuTree.Config.SearchToolbarHeight;
SirenixEditorGUI.BeginHorizontalToolbar(toolbarHeight);
{
if (selected != null)
{
if (SirenixEditorGUI.ToolbarButton(new GUIContent("Select GameObject")))
{
Selection.activeGameObject = (((UniTweenSequencePlayer)selected.Value).gameObject);
EditorGUIUtility.PingObject(Selection.activeGameObject);
}
}
if (SirenixEditorGUI.ToolbarButton(new GUIContent("Reload Tree")))
{
ForceMenuTreeRebuild();
}
}
SirenixEditorGUI.EndHorizontalToolbar();
}
else
{
if (SirenixEditorGUI.ToolbarButton(new GUIContent("Reload Tree")))
{
ForceMenuTreeRebuild();
}
}
}
[MenuItem("Tools/UniTween/Sequence Explorer")]
private static void OpenWindow()
{
var window = GetWindow<UniTweenSequenceExplorer>();
window.titleContent.text = "Sequences";
window.position = GUIHelper.GetEditorWindowRect().AlignCenter(800, 500);
}
protected override void DrawEditor(int index)
{
UniTweenSequencePlayer obj = (UniTweenSequencePlayer)CurrentDrawingTargets[index];
if (obj != null)
{
SirenixEditorGUI.BeginBox($"{obj.gameObject.name} : {obj.DisplayName}");
{
base.DrawEditor(index);
}
SirenixEditorGUI.EndBox();
}
}
public static List<T> CustomFindObjectsOfTypeAll<T>()
{
List<T> results = new List<T>();
for (int i = 0; i < SceneManager.sceneCount; i++)
{
var s = SceneManager.GetSceneAt(i);
if (s.isLoaded)
{
var allGameObjects = s.GetRootGameObjects();
for (int j = 0; j < allGameObjects.Length; j++)
{
var go = allGameObjects[j];
results.AddRange(go.GetComponentsInChildren<T>(true));
}
}
}
return results;
}
}
}
#endif | 32.805556 | 113 | 0.491956 | [
"MIT"
] | Funbites-Game-Studio/com.funbites.unitween | Editor/UniTweenSequenceExplorer.cs | 4,726 | C# |
using System;
namespace IPA.App.ThinControllerApp.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; } = null!;
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
| 19.5 | 70 | 0.666667 | [
"Apache-2.0"
] | IPA-CyberLab/IPA-DN-ThinController-Private | ThinControllerApp/Models/ErrorViewModel.cs | 236 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Debug = System.Diagnostics.Debug;
using IEnumerable = System.Collections.IEnumerable;
using StringBuilder = System.Text.StringBuilder;
using Interlocked = System.Threading.Interlocked;
using System.Diagnostics.CodeAnalysis;
namespace System.Xml.Linq
{
/// <summary>
/// Represents a node that can contain other nodes.
/// </summary>
/// <remarks>
/// The two classes that derive from <see cref="XContainer"/> are
/// <see cref="XDocument"/> and <see cref="XElement"/>.
/// </remarks>
public abstract class XContainer : XNode
{
internal object? content;
internal XContainer() { }
internal XContainer(XContainer other!!)
{
if (other.content is string)
{
this.content = other.content;
}
else
{
XNode? n = (XNode?)other.content;
if (n != null)
{
do
{
n = n.next!;
AppendNodeSkipNotify(n.CloneNode());
} while (n != other.content);
}
}
}
/// <summary>
/// Get the first child node of this node.
/// </summary>
public XNode? FirstNode
{
get
{
XNode? last = LastNode;
return last != null ? last.next : null;
}
}
/// <summary>
/// Get the last child node of this node.
/// </summary>
public XNode? LastNode
{
get
{
if (content == null) return null;
XNode? n = content as XNode;
if (n != null) return n;
string? s = content as string;
if (s != null)
{
if (s.Length == 0) return null;
XText t = new XText(s);
t.parent = this;
t.next = t;
Interlocked.CompareExchange<object>(ref content, t, s);
}
return (XNode)content;
}
}
/// <overloads>
/// Adds the specified content as a child (or as children) to this <see cref="XContainer"/>. The
/// content can be simple content, a collection of content objects, a parameter list
/// of content objects, or null.
/// </overloads>
/// <summary>
/// Adds the specified content as a child (or children) of this <see cref="XContainer"/>.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// to be added.
/// </param>
/// <remarks>
/// When adding simple content, a number of types may be passed to this method.
/// Valid types include:
/// <list>
/// <item>string</item>
/// <item>double</item>
/// <item>float</item>
/// <item>decimal</item>
/// <item>bool</item>
/// <item>DateTime</item>
/// <item>DateTimeOffset</item>
/// <item>TimeSpan</item>
/// <item>Any type implementing ToString()</item>
/// <item>Any type implementing IEnumerable</item>
///
/// </list>
/// When adding complex content, a number of types may be passed to this method.
/// <list>
/// <item>XObject</item>
/// <item>XNode</item>
/// <item>XAttribute</item>
/// <item>Any type implementing IEnumerable</item>
/// </list>
///
/// If an object implements IEnumerable, then the collection in the object is enumerated,
/// and all items in the collection are added. If the collection contains simple content,
/// then the simple content in the collection is concatenated and added as a single
/// string of simple content. If the collection contains complex content, then each item
/// in the collection is added separately.
///
/// If content is null, nothing is added. This allows the results of a query to be passed
/// as content. If the query returns null, no contents are added, and this method does not
/// throw a NullReferenceException.
///
/// Attributes and simple content can't be added to a document.
///
/// An added attribute must have a unique name within the element to
/// which it is being added.
/// </remarks>
public void Add(object? content)
{
if (SkipNotify())
{
AddContentSkipNotify(content);
return;
}
if (content == null) return;
XNode? n = content as XNode;
if (n != null)
{
AddNode(n);
return;
}
string? s = content as string;
if (s != null)
{
AddString(s);
return;
}
XAttribute? a = content as XAttribute;
if (a != null)
{
AddAttribute(a);
return;
}
XStreamingElement? x = content as XStreamingElement;
if (x != null)
{
AddNode(new XElement(x));
return;
}
object?[]? o = content as object?[];
if (o != null)
{
foreach (object? obj in o) Add(obj);
return;
}
IEnumerable? e = content as IEnumerable;
if (e != null)
{
foreach (object? obj in e) Add(obj);
return;
}
AddString(GetStringValue(content));
}
/// <summary>
/// Adds the specified content as a child (or children) of this <see cref="XContainer"/>.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void Add(params object?[] content)
{
Add((object)content);
}
/// <overloads>
/// Adds the specified content as the first child (or children) of this document or element. The
/// content can be simple content, a collection of content objects, a parameter
/// list of content objects, or null.
/// </overloads>
/// <summary>
/// Adds the specified content as the first child (or children) of this document or element.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// to be added.
/// </param>
/// <remarks>
/// See <see cref="XContainer.Add(object)"/> for details about the content that can be added
/// using this method.
/// </remarks>
public void AddFirst(object? content)
{
new Inserter(this, null).Add(content);
}
/// <summary>
/// Adds the specified content as the first children of this document or element.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
public void AddFirst(params object?[] content)
{
AddFirst((object)content);
}
/// <summary>
/// Creates an <see cref="XmlWriter"/> used to add either nodes
/// or attributes to the <see cref="XContainer"/>. The later option
/// applies only for <see cref="XElement"/>.
/// </summary>
/// <returns>An <see cref="XmlWriter"/></returns>
public XmlWriter CreateWriter()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = this is XDocument ? ConformanceLevel.Document : ConformanceLevel.Fragment;
return XmlWriter.Create(new XNodeBuilder(this), settings);
}
/// <summary>
/// Get descendant elements plus leaf nodes contained in an <see cref="XContainer"/>
/// </summary>
/// <returns><see cref="IEnumerable{XNode}"/> over all descendants</returns>
public IEnumerable<XNode> DescendantNodes()
{
return GetDescendantNodes(false);
}
/// <summary>
/// Returns the descendant <see cref="XElement"/>s of this <see cref="XContainer"/>. Note this method will
/// not return itself in the resulting IEnumerable. See <see cref="XElement.DescendantsAndSelf()"/> if you
/// need to include the current <see cref="XElement"/> in the results.
/// <seealso cref="XElement.DescendantsAndSelf()"/>
/// </summary>
/// <returns>
/// An IEnumerable of <see cref="XElement"/> with all of the descendants below this <see cref="XContainer"/> in the XML tree.
/// </returns>
public IEnumerable<XElement> Descendants()
{
return GetDescendants(null, false);
}
/// <summary>
/// Returns the Descendant <see cref="XElement"/>s with the passed in <see cref="XName"/> as an IEnumerable
/// of XElement.
/// </summary>
/// <param name="name">The <see cref="XName"/> to match against descendant <see cref="XElement"/>s.</param>
/// <returns>An <see cref="IEnumerable"/> of <see cref="XElement"/></returns>
public IEnumerable<XElement> Descendants(XName? name)
{
return name != null ? GetDescendants(name, false) : XElement.EmptySequence;
}
/// <summary>
/// Returns the child element with this <see cref="XName"/> or null if there is no child element
/// with a matching <see cref="XName"/>.
/// <seealso cref="XContainer.Elements()"/>
/// </summary>
/// <param name="name">
/// The <see cref="XName"/> to match against this <see cref="XContainer"/>s child elements.
/// </param>
/// <returns>
/// An <see cref="XElement"/> child that matches the <see cref="XName"/> passed in, or null.
/// </returns>
public XElement? Element(XName name)
{
XNode? n = content as XNode;
if (n != null)
{
do
{
n = n.next!;
XElement? e = n as XElement;
if (e != null && e.name == name) return e;
} while (n != content);
}
return null;
}
///<overloads>
/// Returns the child <see cref="XElement"/>s of this <see cref="XContainer"/>.
/// </overloads>
/// <summary>
/// Returns all of the child elements of this <see cref="XContainer"/>.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable"/> over all of this <see cref="XContainer"/>'s child <see cref="XElement"/>s.
/// </returns>
public IEnumerable<XElement> Elements()
{
return GetElements(null);
}
/// <summary>
/// Returns the child elements of this <see cref="XContainer"/> that match the <see cref="XName"/> passed in.
/// </summary>
/// <param name="name">
/// The <see cref="XName"/> to match against the <see cref="XElement"/> children of this <see cref="XContainer"/>.
/// </param>
/// <returns>
/// An <see cref="IEnumerable"/> of <see cref="XElement"/> children of this <see cref="XContainer"/> that have
/// a matching <see cref="XName"/>.
/// </returns>
public IEnumerable<XElement> Elements(XName? name)
{
return name != null ? GetElements(name) : XElement.EmptySequence;
}
///<overloads>
/// Returns the content of this <see cref="XContainer"/>. Note that the content does not
/// include <see cref="XAttribute"/>s.
/// <seealso cref="XElement.Attributes()"/>
/// </overloads>
/// <summary>
/// Returns the content of this <see cref="XContainer"/> as an <see cref="IEnumerable"/> of <see cref="object"/>. Note
/// that the content does not include <see cref="XAttribute"/>s.
/// <seealso cref="XElement.Attributes()"/>
/// </summary>
/// <returns>The contents of this <see cref="XContainer"/></returns>
public IEnumerable<XNode> Nodes()
{
XNode? n = LastNode;
if (n != null)
{
do
{
n = n.next!;
yield return n;
} while (n.parent == this && n != content);
}
}
/// <summary>
/// Removes the nodes from this <see cref="XContainer"/>. Note this
/// methods does not remove attributes. See <see cref="XElement.RemoveAttributes()"/>.
/// <seealso cref="XElement.RemoveAttributes()"/>
/// </summary>
public void RemoveNodes()
{
if (SkipNotify())
{
RemoveNodesSkipNotify();
return;
}
while (content != null)
{
string? s = content as string;
if (s != null)
{
if (s.Length > 0)
{
ConvertTextToNode();
}
else
{
if (this is XElement)
{
// Change in the serialization of an empty element:
// from start/end tag pair to empty tag
NotifyChanging(this, XObjectChangeEventArgs.Value);
if ((object)s != (object)content) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
content = null;
NotifyChanged(this, XObjectChangeEventArgs.Value);
}
else
{
content = null;
}
}
}
XNode? last = content as XNode;
if (last != null)
{
XNode n = last.next!;
NotifyChanging(n, XObjectChangeEventArgs.Remove);
if (last != content || n != last.next) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
if (n != last)
{
last.next = n.next;
}
else
{
content = null;
}
n.parent = null;
n.next = null;
NotifyChanged(n, XObjectChangeEventArgs.Remove);
}
}
}
/// <overloads>
/// Replaces the children nodes of this document or element with the specified content. The
/// content can be simple content, a collection of content objects, a parameter
/// list of content objects, or null.
/// </overloads>
/// <summary>
/// Replaces the children nodes of this document or element with the specified content.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// that replace the children nodes.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void ReplaceNodes(object? content)
{
content = GetContentSnapshot(content);
RemoveNodes();
Add(content);
}
/// <summary>
/// Replaces the children nodes of this document or element with the specified content.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void ReplaceNodes(params object?[] content)
{
ReplaceNodes((object)content);
}
internal virtual void AddAttribute(XAttribute a)
{
}
internal virtual void AddAttributeSkipNotify(XAttribute a)
{
}
internal void AddContentSkipNotify(object? content)
{
if (content == null) return;
XNode? n = content as XNode;
if (n != null)
{
AddNodeSkipNotify(n);
return;
}
string? s = content as string;
if (s != null)
{
AddStringSkipNotify(s);
return;
}
XAttribute? a = content as XAttribute;
if (a != null)
{
AddAttributeSkipNotify(a);
return;
}
XStreamingElement? x = content as XStreamingElement;
if (x != null)
{
AddNodeSkipNotify(new XElement(x));
return;
}
object?[]? o = content as object?[];
if (o != null)
{
foreach (object? obj in o) AddContentSkipNotify(obj);
return;
}
IEnumerable? e = content as IEnumerable;
if (e != null)
{
foreach (object? obj in e) AddContentSkipNotify(obj);
return;
}
AddStringSkipNotify(GetStringValue(content));
}
internal void AddNode(XNode n)
{
ValidateNode(n, this);
if (n.parent != null)
{
n = n.CloneNode();
}
else
{
XNode p = this;
while (p.parent != null) p = p.parent;
if (n == p) n = n.CloneNode();
}
ConvertTextToNode();
AppendNode(n);
}
internal void AddNodeSkipNotify(XNode n)
{
ValidateNode(n, this);
if (n.parent != null)
{
n = n.CloneNode();
}
else
{
XNode p = this;
while (p.parent != null) p = p.parent;
if (n == p) n = n.CloneNode();
}
ConvertTextToNode();
AppendNodeSkipNotify(n);
}
internal void AddString(string s)
{
ValidateString(s);
if (content == null)
{
if (s.Length > 0)
{
AppendNode(new XText(s));
}
else
{
if (this is XElement)
{
// Change in the serialization of an empty element:
// from empty tag to start/end tag pair
NotifyChanging(this, XObjectChangeEventArgs.Value);
if (content != null) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
content = s;
NotifyChanged(this, XObjectChangeEventArgs.Value);
}
else
{
content = s;
}
}
}
else if (s.Length > 0)
{
ConvertTextToNode();
XText? tn = content as XText;
if (tn != null && !(tn is XCData))
{
tn.Value += s;
}
else
{
AppendNode(new XText(s));
}
}
}
internal void AddStringSkipNotify(string s)
{
ValidateString(s);
if (content == null)
{
content = s;
}
else if (s.Length > 0)
{
string? stringContent = content as string;
if (stringContent != null)
{
content = stringContent + s;
}
else
{
XText? tn = content as XText;
if (tn != null && !(tn is XCData))
{
tn.text += s;
}
else
{
AppendNodeSkipNotify(new XText(s));
}
}
}
}
internal void AppendNode(XNode n)
{
bool notify = NotifyChanging(n, XObjectChangeEventArgs.Add);
if (n.parent != null) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
AppendNodeSkipNotify(n);
if (notify) NotifyChanged(n, XObjectChangeEventArgs.Add);
}
internal void AppendNodeSkipNotify(XNode n)
{
n.parent = this;
if (content == null || content is string)
{
n.next = n;
}
else
{
XNode x = (XNode)content;
n.next = x.next;
x.next = n;
}
content = n;
}
internal override void AppendText(StringBuilder sb)
{
string? s = content as string;
if (s != null)
{
sb.Append(s);
}
else
{
XNode? n = (XNode?)content;
if (n != null)
{
do
{
n = n.next!;
n.AppendText(sb);
} while (n != content);
}
}
}
private string? GetTextOnly()
{
if (content == null) return null;
string? s = content as string;
if (s == null)
{
XNode n = (XNode)content;
do
{
n = n.next!;
if (n.NodeType != XmlNodeType.Text) return null;
s += ((XText)n).Value;
} while (n != content);
}
return s;
}
private string CollectText(ref XNode? n)
{
string s = "";
while (n != null && n.NodeType == XmlNodeType.Text)
{
s += ((XText)n).Value;
n = n != content ? n.next : null;
}
return s;
}
internal bool ContentsEqual(XContainer e)
{
if (content == e.content) return true;
string? s = GetTextOnly();
if (s != null) return s == e.GetTextOnly();
XNode? n1 = content as XNode;
XNode? n2 = e.content as XNode;
if (n1 != null && n2 != null)
{
n1 = n1.next;
n2 = n2.next;
while (true)
{
if (CollectText(ref n1) != e.CollectText(ref n2)) break;
if (n1 == null && n2 == null) return true;
if (n1 == null || n2 == null || !n1.DeepEquals(n2)) break;
n1 = n1 != content ? n1.next : null;
n2 = n2 != e.content ? n2.next : null;
}
}
return false;
}
internal int ContentsHashCode()
{
string? s = GetTextOnly();
if (s != null) return s.GetHashCode();
int h = 0;
XNode? n = content as XNode;
if (n != null)
{
do
{
n = n.next;
string text = CollectText(ref n);
if (text.Length > 0)
{
h ^= text.GetHashCode();
}
if (n == null) break;
h ^= n.GetDeepHashCode();
} while (n != content);
}
return h;
}
internal void ConvertTextToNode()
{
string? s = content as string;
if (!string.IsNullOrEmpty(s))
{
XText t = new XText(s);
t.parent = this;
t.next = t;
content = t;
}
}
internal IEnumerable<XNode> GetDescendantNodes(bool self)
{
if (self) yield return this;
XNode n = this;
while (true)
{
XContainer? c = n as XContainer;
XNode? first;
if (c != null && (first = c.FirstNode) != null)
{
n = first;
}
else
{
while (n != null && n != this && n == n.parent!.content) n = n.parent;
if (n == null || n == this) break;
n = n.next!;
}
yield return n;
}
}
internal IEnumerable<XElement> GetDescendants(XName? name, bool self)
{
if (self)
{
XElement e = (XElement)this;
if (name == null || e.name == name) yield return e;
}
XNode n = this;
XContainer? c = this;
while (true)
{
if (c != null && c.content is XNode)
{
n = ((XNode)c.content).next!;
}
else
{
while (n != this && n == n.parent!.content) n = n.parent;
if (n == this) break;
n = n.next!;
}
XElement? e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
c = e;
}
}
private IEnumerable<XElement> GetElements(XName? name)
{
XNode? n = content as XNode;
if (n != null)
{
do
{
n = n.next!;
XElement? e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
} while (n.parent == this && n != content);
}
}
internal static string GetStringValue(object value)
{
string? s = value switch
{
string stringValue => stringValue,
int intValue => XmlConvert.ToString(intValue),
double doubleValue => XmlConvert.ToString(doubleValue),
long longValue => XmlConvert.ToString(longValue),
float floatValue => XmlConvert.ToString(floatValue),
decimal decimalValue => XmlConvert.ToString(decimalValue),
short shortValue => XmlConvert.ToString(shortValue),
sbyte sbyteValue => XmlConvert.ToString(sbyteValue),
bool boolValue => XmlConvert.ToString(boolValue),
DateTime dtValue => XmlConvert.ToString(dtValue, XmlDateTimeSerializationMode.RoundtripKind),
DateTimeOffset dtoValue => XmlConvert.ToString(dtoValue),
TimeSpan tsValue => XmlConvert.ToString(tsValue),
XObject => throw new ArgumentException(SR.Argument_XObjectValue),
_ => value.ToString()
};
if (s == null) throw new ArgumentException(SR.Argument_ConvertToString);
return s;
}
internal void ReadContentFrom(XmlReader r)
{
if (r.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
ContentReader cr = new ContentReader(this);
while (cr.ReadContentFrom(this, r) && r.Read()) ;
}
internal void ReadContentFrom(XmlReader r, LoadOptions o)
{
if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0)
{
ReadContentFrom(r);
return;
}
if (r.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
ContentReader cr = new ContentReader(this, r, o);
while (cr.ReadContentFrom(this, r, o) && r.Read()) ;
}
internal async Task ReadContentFromAsync(XmlReader r, CancellationToken cancellationToken)
{
if (r.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
ContentReader cr = new ContentReader(this);
do
{
cancellationToken.ThrowIfCancellationRequested();
}
while (await cr.ReadContentFromAsync(this, r).ConfigureAwait(false) && await r.ReadAsync().ConfigureAwait(false));
}
internal async Task ReadContentFromAsync(XmlReader r, LoadOptions o, CancellationToken cancellationToken)
{
if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0)
{
await ReadContentFromAsync(r, cancellationToken).ConfigureAwait(false);
return;
}
if (r.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
ContentReader cr = new ContentReader(this, r, o);
do
{
cancellationToken.ThrowIfCancellationRequested();
}
while (await cr.ReadContentFromAsync(this, r, o).ConfigureAwait(false) && await r.ReadAsync().ConfigureAwait(false));
}
private sealed class ContentReader
{
private readonly NamespaceCache _eCache;
private readonly NamespaceCache _aCache;
private readonly IXmlLineInfo? _lineInfo;
private XContainer _currentContainer;
private string? _baseUri;
public ContentReader(XContainer rootContainer)
{
_currentContainer = rootContainer;
}
public ContentReader(XContainer rootContainer, XmlReader r, LoadOptions o)
{
_currentContainer = rootContainer;
_baseUri = (o & LoadOptions.SetBaseUri) != 0 ? r.BaseURI : null;
_lineInfo = (o & LoadOptions.SetLineInfo) != 0 ? r as IXmlLineInfo : null;
}
public bool ReadContentFrom(XContainer rootContainer, XmlReader r)
{
switch (r.NodeType)
{
case XmlNodeType.Element:
XElement e = new XElement(_eCache.Get(r.NamespaceURI).GetName(r.LocalName));
if (r.MoveToFirstAttribute())
{
do
{
e.AppendAttributeSkipNotify(new XAttribute(_aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value));
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
_currentContainer.AddNodeSkipNotify(e);
if (!r.IsEmptyElement)
{
_currentContainer = e;
}
break;
case XmlNodeType.EndElement:
if (_currentContainer.content == null)
{
_currentContainer.content = string.Empty;
}
if (_currentContainer == rootContainer) return false;
_currentContainer = _currentContainer.parent!;
break;
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
_currentContainer.AddStringSkipNotify(r.Value);
break;
case XmlNodeType.CDATA:
_currentContainer.AddNodeSkipNotify(new XCData(r.Value));
break;
case XmlNodeType.Comment:
_currentContainer.AddNodeSkipNotify(new XComment(r.Value));
break;
case XmlNodeType.ProcessingInstruction:
_currentContainer.AddNodeSkipNotify(new XProcessingInstruction(r.Name, r.Value));
break;
case XmlNodeType.DocumentType:
_currentContainer.AddNodeSkipNotify(new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value));
break;
case XmlNodeType.EntityReference:
if (!r.CanResolveEntity) throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
r.ResolveEntity();
break;
case XmlNodeType.EndEntity:
break;
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
}
return true;
}
public async ValueTask<bool> ReadContentFromAsync(XContainer rootContainer, XmlReader r)
{
switch (r.NodeType)
{
case XmlNodeType.Element:
XElement e = new XElement(_eCache.Get(r.NamespaceURI).GetName(r.LocalName));
if (r.MoveToFirstAttribute())
{
do
{
e.AppendAttributeSkipNotify(new XAttribute(
_aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName),
await r.GetValueAsync().ConfigureAwait(false)));
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
_currentContainer.AddNodeSkipNotify(e);
if (!r.IsEmptyElement)
{
_currentContainer = e;
}
break;
case XmlNodeType.EndElement:
if (_currentContainer.content == null)
{
_currentContainer.content = string.Empty;
}
if (_currentContainer == rootContainer) return false;
_currentContainer = _currentContainer.parent!;
break;
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
_currentContainer.AddStringSkipNotify(await r.GetValueAsync().ConfigureAwait(false));
break;
case XmlNodeType.CDATA:
_currentContainer.AddNodeSkipNotify(new XCData(await r.GetValueAsync().ConfigureAwait(false)));
break;
case XmlNodeType.Comment:
_currentContainer.AddNodeSkipNotify(new XComment(await r.GetValueAsync().ConfigureAwait(false)));
break;
case XmlNodeType.ProcessingInstruction:
_currentContainer.AddNodeSkipNotify(new XProcessingInstruction(r.Name, await r.GetValueAsync().ConfigureAwait(false)));
break;
case XmlNodeType.DocumentType:
_currentContainer.AddNodeSkipNotify(new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), await r.GetValueAsync().ConfigureAwait(false)));
break;
case XmlNodeType.EntityReference:
if (!r.CanResolveEntity) throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
r.ResolveEntity();
break;
case XmlNodeType.EndEntity:
break;
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
}
return true;
}
public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o)
{
XNode? newNode = null;
string baseUri = r.BaseURI;
switch (r.NodeType)
{
case XmlNodeType.Element:
{
XElement e = new XElement(_eCache.Get(r.NamespaceURI).GetName(r.LocalName));
if (_baseUri != null && _baseUri != baseUri)
{
e.SetBaseUri(baseUri);
}
if (_lineInfo != null && _lineInfo.HasLineInfo())
{
e.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
}
if (r.MoveToFirstAttribute())
{
do
{
XAttribute a = new XAttribute(_aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value);
if (_lineInfo != null && _lineInfo.HasLineInfo())
{
a.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
}
e.AppendAttributeSkipNotify(a);
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
_currentContainer.AddNodeSkipNotify(e);
if (!r.IsEmptyElement)
{
_currentContainer = e;
if (_baseUri != null)
{
_baseUri = baseUri;
}
}
break;
}
case XmlNodeType.EndElement:
{
if (_currentContainer.content == null)
{
_currentContainer.content = string.Empty;
}
// Store the line info of the end element tag.
// Note that since we've got EndElement the current container must be an XElement
XElement? e = _currentContainer as XElement;
Debug.Assert(e != null, "EndElement received but the current container is not an element.");
if (e != null && _lineInfo != null && _lineInfo.HasLineInfo())
{
e.SetEndElementLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
}
if (_currentContainer == rootContainer) return false;
if (_baseUri != null && _currentContainer.HasBaseUri)
{
_baseUri = _currentContainer.parent!.BaseUri;
}
_currentContainer = _currentContainer.parent!;
break;
}
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
if ((_baseUri != null && _baseUri != baseUri) ||
(_lineInfo != null && _lineInfo.HasLineInfo()))
{
newNode = new XText(r.Value);
}
else
{
_currentContainer.AddStringSkipNotify(r.Value);
}
break;
case XmlNodeType.CDATA:
newNode = new XCData(r.Value);
break;
case XmlNodeType.Comment:
newNode = new XComment(r.Value);
break;
case XmlNodeType.ProcessingInstruction:
newNode = new XProcessingInstruction(r.Name, r.Value);
break;
case XmlNodeType.DocumentType:
newNode = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value);
break;
case XmlNodeType.EntityReference:
if (!r.CanResolveEntity) throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
r.ResolveEntity();
break;
case XmlNodeType.EndEntity:
break;
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
}
if (newNode != null)
{
if (_baseUri != null && _baseUri != baseUri)
{
newNode.SetBaseUri(baseUri);
}
if (_lineInfo != null && _lineInfo.HasLineInfo())
{
newNode.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
}
_currentContainer.AddNodeSkipNotify(newNode);
}
return true;
}
public async ValueTask<bool> ReadContentFromAsync(XContainer rootContainer, XmlReader r, LoadOptions o)
{
XNode? newNode = null;
string baseUri = r.BaseURI!;
switch (r.NodeType)
{
case XmlNodeType.Element:
{
XElement e = new XElement(_eCache.Get(r.NamespaceURI).GetName(r.LocalName));
if (_baseUri != null && _baseUri != baseUri)
{
e.SetBaseUri(baseUri);
}
if (_lineInfo != null && _lineInfo.HasLineInfo())
{
e.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
}
if (r.MoveToFirstAttribute())
{
do
{
XAttribute a = new XAttribute(
_aCache.Get(r.Prefix.Length == 0 ? string.Empty : r.NamespaceURI).GetName(r.LocalName),
await r.GetValueAsync().ConfigureAwait(false));
if (_lineInfo != null && _lineInfo.HasLineInfo())
{
a.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
}
e.AppendAttributeSkipNotify(a);
} while (r.MoveToNextAttribute());
r.MoveToElement();
}
_currentContainer.AddNodeSkipNotify(e);
if (!r.IsEmptyElement)
{
_currentContainer = e;
if (_baseUri != null)
{
_baseUri = baseUri;
}
}
break;
}
case XmlNodeType.EndElement:
{
if (_currentContainer.content == null)
{
_currentContainer.content = string.Empty;
}
// Store the line info of the end element tag.
// Note that since we've got EndElement the current container must be an XElement
XElement? e = _currentContainer as XElement;
Debug.Assert(e != null, "EndElement received but the current container is not an element.");
if (e != null && _lineInfo != null && _lineInfo.HasLineInfo())
{
e.SetEndElementLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
}
if (_currentContainer == rootContainer) return false;
if (_baseUri != null && _currentContainer.HasBaseUri)
{
_baseUri = _currentContainer.parent!.BaseUri;
}
_currentContainer = _currentContainer.parent!;
break;
}
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
if ((_baseUri != null && _baseUri != baseUri) ||
(_lineInfo != null && _lineInfo.HasLineInfo()))
{
newNode = new XText(await r.GetValueAsync().ConfigureAwait(false));
}
else
{
_currentContainer.AddStringSkipNotify(await r.GetValueAsync().ConfigureAwait(false));
}
break;
case XmlNodeType.CDATA:
newNode = new XCData(await r.GetValueAsync().ConfigureAwait(false));
break;
case XmlNodeType.Comment:
newNode = new XComment(await r.GetValueAsync().ConfigureAwait(false));
break;
case XmlNodeType.ProcessingInstruction:
newNode = new XProcessingInstruction(r.Name, await r.GetValueAsync().ConfigureAwait(false));
break;
case XmlNodeType.DocumentType:
newNode = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), await r.GetValueAsync().ConfigureAwait(false));
break;
case XmlNodeType.EntityReference:
if (!r.CanResolveEntity) throw new InvalidOperationException(SR.InvalidOperation_UnresolvedEntityReference);
r.ResolveEntity();
break;
case XmlNodeType.EndEntity:
break;
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, r.NodeType));
}
if (newNode != null)
{
if (_baseUri != null && _baseUri != baseUri)
{
newNode.SetBaseUri(baseUri);
}
if (_lineInfo != null && _lineInfo.HasLineInfo())
{
newNode.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
}
_currentContainer.AddNodeSkipNotify(newNode);
}
return true;
}
}
internal void RemoveNode(XNode n)
{
bool notify = NotifyChanging(n, XObjectChangeEventArgs.Remove);
if (n.parent != this) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
Debug.Assert(content != null);
XNode p = (XNode)content;
while (p.next != n) p = p.next!;
if (p == n)
{
content = null;
}
else
{
if (content == n) content = p;
p.next = n.next;
}
n.parent = null;
n.next = null;
if (notify) NotifyChanged(n, XObjectChangeEventArgs.Remove);
}
private void RemoveNodesSkipNotify()
{
XNode? n = content as XNode;
if (n != null)
{
do
{
XNode next = n.next!;
n.parent = null;
n.next = null;
n = next;
} while (n != content);
}
content = null;
}
// Validate insertion of the given node. previous is the node after which insertion
// will occur. previous == null means at beginning, previous == this means at end.
internal virtual void ValidateNode(XNode node, XNode? previous)
{
}
internal virtual void ValidateString(string s)
{
}
internal void WriteContentTo(XmlWriter writer)
{
if (content != null)
{
string? stringContent = content as string;
if (stringContent != null)
{
if (this is XDocument)
{
writer.WriteWhitespace(stringContent);
}
else
{
writer.WriteString(stringContent);
}
}
else
{
XNode n = (XNode)content;
do
{
n = n.next!;
n.WriteTo(writer);
} while (n != content);
}
}
}
internal async Task WriteContentToAsync(XmlWriter writer, CancellationToken cancellationToken)
{
if (content != null)
{
string? stringContent = content as string;
if (stringContent != null)
{
cancellationToken.ThrowIfCancellationRequested();
Task tWrite;
if (this is XDocument)
{
tWrite = writer.WriteWhitespaceAsync(stringContent);
}
else
{
tWrite = writer.WriteStringAsync(stringContent);
}
await tWrite.ConfigureAwait(false);
}
else
{
XNode n = (XNode)content;
do
{
n = n.next!;
await n.WriteToAsync(writer, cancellationToken).ConfigureAwait(false);
} while (n != content);
}
}
}
private static void AddContentToList(List<object?> list, object? content)
{
IEnumerable? e = content is string ? null : content as IEnumerable;
if (e == null)
{
list.Add(content);
}
else
{
foreach (object? obj in e)
{
if (obj != null) AddContentToList(list, obj);
}
}
}
[return: NotNullIfNotNull("content")]
internal static object? GetContentSnapshot(object? content)
{
if (content is string || !(content is IEnumerable)) return content;
List<object?> list = new List<object?>();
AddContentToList(list, content);
return list;
}
}
}
| 38.859094 | 191 | 0.454443 | [
"MIT"
] | AUTOMATE-2001/runtime | src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs | 54,053 | C# |
// <auto-generated />
using System;
using IdentityServer4.EntityFramework.DbContexts;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.Internal;
namespace Api.Auth.Data.Migrations.IdentityServer.PersistedGrantDb
{
[DbContext(typeof(PersistedGrantDbContext))]
[Migration("20180408112409_Grants")]
partial class Grants
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.0-preview1-28290")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("IdentityServer4.EntityFramework.Entities.PersistedGrant", b =>
{
b.Property<string>("Key")
.HasMaxLength(200);
b.Property<string>("ClientId")
.IsRequired()
.HasMaxLength(200);
b.Property<DateTime>("CreationTime");
b.Property<string>("Data")
.IsRequired()
.HasMaxLength(50000);
b.Property<DateTime?>("Expiration");
b.Property<string>("SubjectId")
.HasMaxLength(200);
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(50);
b.HasKey("Key");
b.HasIndex("SubjectId", "ClientId", "Type");
b.ToTable("PersistedGrants");
});
#pragma warning restore 612, 618
}
}
}
| 33.534483 | 117 | 0.583033 | [
"MIT"
] | Kosat/SimpleForumSPA | Api.Auth/Data/Migrations/IdentityServer/PersistedGrantDb/20180408112409_Grants.Designer.cs | 1,947 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Xunit.Abstractions;
namespace Microsoft.EntityFrameworkCore.Query
{
public class ManyToManyNoTrackingQuerySqlServerTest
: ManyToManyNoTrackingQueryRelationalTestBase<ManyToManyQuerySqlServerFixture>
{
public ManyToManyNoTrackingQuerySqlServerTest(ManyToManyQuerySqlServerFixture fixture, ITestOutputHelper testOutputHelper)
: base(fixture)
{
Fixture.TestSqlLoggerFactory.Clear();
//Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper);
}
protected override bool CanExecuteQueryString
=> true;
public override async Task Skip_navigation_all(bool async)
{
await base.Skip_navigation_all(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name]
FROM [EntityOnes] AS [e]
WHERE NOT EXISTS (
SELECT 1
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
WHERE ([e].[Id] = [j].[OneId]) AND NOT ([e0].[Name] LIKE N'%B%'))");
}
public override async Task Skip_navigation_any_without_predicate(bool async)
{
await base.Skip_navigation_any_without_predicate(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name]
FROM [EntityOnes] AS [e]
WHERE EXISTS (
SELECT 1
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityThrees] AS [e0] ON [j].[ThreeId] = [e0].[Id]
WHERE ([e].[Id] = [j].[OneId]) AND ([e0].[Name] LIKE N'%B%'))");
}
public override async Task Skip_navigation_any_with_predicate(bool async)
{
await base.Skip_navigation_any_with_predicate(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name]
FROM [EntityOnes] AS [e]
WHERE EXISTS (
SELECT 1
FROM [EntityOneEntityTwo] AS [e0]
INNER JOIN [EntityTwos] AS [e1] ON [e0].[EntityTwoId] = [e1].[Id]
WHERE ([e].[Id] = [e0].[EntityOneId]) AND ([e1].[Name] LIKE N'%B%'))");
}
public override async Task Skip_navigation_contains(bool async)
{
await base.Skip_navigation_contains(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name]
FROM [EntityOnes] AS [e]
WHERE EXISTS (
SELECT 1
FROM [JoinOneToThreePayloadFullShared] AS [j]
INNER JOIN [EntityThrees] AS [e0] ON [j].[ThreeId] = [e0].[Id]
WHERE ([e].[Id] = [j].[OneId]) AND ([e0].[Id] = 1))");
}
public override async Task Skip_navigation_count_without_predicate(bool async)
{
await base.Skip_navigation_count_without_predicate(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name]
FROM [EntityOnes] AS [e]
WHERE (
SELECT COUNT(*)
FROM [JoinOneSelfPayload] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[LeftId] = [e0].[Id]
WHERE [e].[Id] = [j].[RightId]) > 0");
}
public override async Task Skip_navigation_count_with_predicate(bool async)
{
await base.Skip_navigation_count_with_predicate(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name]
FROM [EntityOnes] AS [e]
ORDER BY (
SELECT COUNT(*)
FROM [JoinOneToBranch] AS [j]
INNER JOIN (
SELECT [e0].[Id], [e0].[Discriminator], [e0].[Name], [e0].[Number], [e0].[IsGreen]
FROM [EntityRoots] AS [e0]
WHERE [e0].[Discriminator] IN (N'EntityBranch', N'EntityLeaf')
) AS [t] ON [j].[EntityBranchId] = [t].[Id]
WHERE ([e].[Id] = [j].[EntityOneId]) AND ([t].[Name] IS NOT NULL AND ([t].[Name] LIKE N'L%'))), [e].[Id]");
}
public override async Task Skip_navigation_long_count_without_predicate(bool async)
{
await base.Skip_navigation_long_count_without_predicate(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId]
FROM [EntityTwos] AS [e]
WHERE (
SELECT COUNT_BIG(*)
FROM [JoinTwoToThree] AS [j]
INNER JOIN [EntityThrees] AS [e0] ON [j].[ThreeId] = [e0].[Id]
WHERE [e].[Id] = [j].[TwoId]) > CAST(0 AS bigint)");
}
public override async Task Skip_navigation_long_count_with_predicate(bool async)
{
await base.Skip_navigation_long_count_with_predicate(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId]
FROM [EntityTwos] AS [e]
ORDER BY (
SELECT COUNT_BIG(*)
FROM [JoinTwoSelfShared] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[LeftId] = [e0].[Id]
WHERE ([e].[Id] = [j].[RightId]) AND ([e0].[Name] IS NOT NULL AND ([e0].[Name] LIKE N'L%'))) DESC, [e].[Id]");
}
public override async Task Skip_navigation_select_many_average(bool async)
{
await base.Skip_navigation_select_many_average(async);
AssertSql(
@"SELECT AVG(CAST([t].[Key1] AS float))
FROM [EntityTwos] AS [e]
INNER JOIN (
SELECT [e0].[Key1], [j].[TwoId]
FROM [JoinTwoToCompositeKeyShared] AS [j]
INNER JOIN [EntityCompositeKeys] AS [e0] ON (([j].[CompositeId1] = [e0].[Key1]) AND ([j].[CompositeId2] = [e0].[Key2])) AND ([j].[CompositeId3] = [e0].[Key3])
) AS [t] ON [e].[Id] = [t].[TwoId]");
}
public override async Task Skip_navigation_select_many_max(bool async)
{
await base.Skip_navigation_select_many_max(async);
AssertSql(
@"SELECT MAX([t].[Key1])
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [e0].[Key1], [j].[ThreeId]
FROM [JoinThreeToCompositeKeyFull] AS [j]
INNER JOIN [EntityCompositeKeys] AS [e0] ON (([j].[CompositeId1] = [e0].[Key1]) AND ([j].[CompositeId2] = [e0].[Key2])) AND ([j].[CompositeId3] = [e0].[Key3])
) AS [t] ON [e].[Id] = [t].[ThreeId]");
}
public override async Task Skip_navigation_select_many_min(bool async)
{
await base.Skip_navigation_select_many_min(async);
AssertSql(
@"SELECT MIN([t].[Id])
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [e1].[Id], [e0].[EntityThreeId]
FROM [EntityRootEntityThree] AS [e0]
INNER JOIN [EntityRoots] AS [e1] ON [e0].[EntityRootId] = [e1].[Id]
) AS [t] ON [e].[Id] = [t].[EntityThreeId]");
}
public override async Task Skip_navigation_select_many_sum(bool async)
{
await base.Skip_navigation_select_many_sum(async);
AssertSql(
@"SELECT COALESCE(SUM([t].[Key1]), 0)
FROM [EntityRoots] AS [e]
INNER JOIN (
SELECT [e0].[Key1], [j].[RootId]
FROM [JoinCompositeKeyToRootShared] AS [j]
INNER JOIN [EntityCompositeKeys] AS [e0] ON (([j].[CompositeId1] = [e0].[Key1]) AND ([j].[CompositeId2] = [e0].[Key2])) AND ([j].[CompositeId3] = [e0].[Key3])
) AS [t] ON [e].[Id] = [t].[RootId]");
}
public override async Task Skip_navigation_select_subquery_average(bool async)
{
await base.Skip_navigation_select_subquery_average(async);
AssertSql(
@"SELECT (
SELECT AVG(CAST([e].[Key1] AS float))
FROM [JoinCompositeKeyToLeaf] AS [j]
INNER JOIN [EntityCompositeKeys] AS [e] ON (([j].[CompositeId1] = [e].[Key1]) AND ([j].[CompositeId2] = [e].[Key2])) AND ([j].[CompositeId3] = [e].[Key3])
WHERE [e0].[Id] = [j].[LeafId])
FROM [EntityRoots] AS [e0]
WHERE [e0].[Discriminator] = N'EntityLeaf'");
}
public override async Task Skip_navigation_select_subquery_max(bool async)
{
await base.Skip_navigation_select_subquery_max(async);
AssertSql(
@"SELECT (
SELECT MAX([e].[Id])
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityOnes] AS [e] ON [j].[OneId] = [e].[Id]
WHERE [e0].[Id] = [j].[TwoId])
FROM [EntityTwos] AS [e0]");
}
public override async Task Skip_navigation_select_subquery_min(bool async)
{
await base.Skip_navigation_select_subquery_min(async);
AssertSql(
@"SELECT (
SELECT MIN([e].[Id])
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityOnes] AS [e] ON [j].[OneId] = [e].[Id]
WHERE [e0].[Id] = [j].[ThreeId])
FROM [EntityThrees] AS [e0]");
}
public override async Task Skip_navigation_select_subquery_sum(bool async)
{
await base.Skip_navigation_select_subquery_sum(async);
AssertSql(
@"SELECT (
SELECT COALESCE(SUM([e0].[Id]), 0)
FROM [EntityOneEntityTwo] AS [e]
INNER JOIN [EntityOnes] AS [e0] ON [e].[EntityOneId] = [e0].[Id]
WHERE [e1].[Id] = [e].[EntityTwoId])
FROM [EntityTwos] AS [e1]");
}
public override async Task Skip_navigation_order_by_first_or_default(bool async)
{
await base.Skip_navigation_order_by_first_or_default(async);
AssertSql(
@"SELECT [t0].[Id], [t0].[Name]
FROM [EntityThrees] AS [e]
LEFT JOIN (
SELECT [t].[Id], [t].[Name], [t].[ThreeId]
FROM (
SELECT [e0].[Id], [e0].[Name], [j].[ThreeId], ROW_NUMBER() OVER(PARTITION BY [j].[ThreeId] ORDER BY [e0].[Id]) AS [row]
FROM [JoinOneToThreePayloadFullShared] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
) AS [t]
WHERE [t].[row] <= 1
) AS [t0] ON [e].[Id] = [t0].[ThreeId]");
}
public override async Task Skip_navigation_order_by_single_or_default(bool async)
{
await base.Skip_navigation_order_by_single_or_default(async);
AssertSql(
@"SELECT [t0].[Id], [t0].[Name]
FROM [EntityOnes] AS [e]
OUTER APPLY (
SELECT TOP(1) [t].[Id], [t].[Name]
FROM (
SELECT TOP(1) [e0].[Id], [e0].[Name]
FROM [JoinOneSelfPayload] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[RightId] = [e0].[Id]
WHERE [e].[Id] = [j].[LeftId]
ORDER BY [e0].[Id]
) AS [t]
ORDER BY [t].[Id]
) AS [t0]");
}
public override async Task Skip_navigation_order_by_last_or_default(bool async)
{
await base.Skip_navigation_order_by_last_or_default(async);
AssertSql(
@"SELECT [t0].[Id], [t0].[Name]
FROM [EntityRoots] AS [e]
LEFT JOIN (
SELECT [t].[Id], [t].[Name], [t].[EntityBranchId]
FROM (
SELECT [e0].[Id], [e0].[Name], [j].[EntityBranchId], ROW_NUMBER() OVER(PARTITION BY [j].[EntityBranchId] ORDER BY [e0].[Id] DESC) AS [row]
FROM [JoinOneToBranch] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[EntityOneId] = [e0].[Id]
) AS [t]
WHERE [t].[row] <= 1
) AS [t0] ON [e].[Id] = [t0].[EntityBranchId]
WHERE [e].[Discriminator] IN (N'EntityBranch', N'EntityLeaf')");
}
public override async Task Skip_navigation_order_by_reverse_first_or_default(bool async)
{
await base.Skip_navigation_order_by_reverse_first_or_default(async);
AssertSql(
@"SELECT [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId]
FROM [EntityThrees] AS [e]
LEFT JOIN (
SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[ThreeId]
FROM (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [j].[ThreeId], ROW_NUMBER() OVER(PARTITION BY [j].[ThreeId] ORDER BY [e0].[Id] DESC) AS [row]
FROM [JoinTwoToThree] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
) AS [t]
WHERE [t].[row] <= 1
) AS [t0] ON [e].[Id] = [t0].[ThreeId]");
}
public override async Task Skip_navigation_cast(bool async)
{
await base.Skip_navigation_cast(async);
AssertSql(
@"SELECT [e].[Key1], [e].[Key2], [e].[Key3], [t0].[Id], [t0].[Discriminator], [t0].[Name], [t0].[Number], [t0].[IsGreen], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[LeafId]
FROM [EntityCompositeKeys] AS [e]
LEFT JOIN (
SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t].[Number], [t].[IsGreen], [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[LeafId]
FROM [JoinCompositeKeyToLeaf] AS [j]
INNER JOIN (
SELECT [e0].[Id], [e0].[Discriminator], [e0].[Name], [e0].[Number], [e0].[IsGreen]
FROM [EntityRoots] AS [e0]
WHERE [e0].[Discriminator] = N'EntityLeaf'
) AS [t] ON [j].[LeafId] = [t].[Id]
) AS [t0] ON (([e].[Key1] = [t0].[CompositeId1]) AND ([e].[Key2] = [t0].[CompositeId2])) AND ([e].[Key3] = [t0].[CompositeId3])
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[LeafId], [t0].[Id]");
}
public override async Task Skip_navigation_of_type(bool async)
{
await base.Skip_navigation_of_type(async);
AssertSql(
@"SELECT [e].[Key1], [e].[Key2], [e].[Key3], [t].[Id], [t].[Discriminator], [t].[Name], [t].[Number], [t].[IsGreen], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[RootId]
FROM [EntityCompositeKeys] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[Discriminator], [e0].[Name], [e0].[Number], [e0].[IsGreen], [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[RootId]
FROM [JoinCompositeKeyToRootShared] AS [j]
INNER JOIN [EntityRoots] AS [e0] ON [j].[RootId] = [e0].[Id]
WHERE [e0].[Discriminator] = N'EntityLeaf'
) AS [t] ON (([e].[Key1] = [t].[CompositeId1]) AND ([e].[Key2] = [t].[CompositeId2])) AND ([e].[Key3] = [t].[CompositeId3])
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[RootId], [t].[Id]");
}
public override async Task Join_with_skip_navigation(bool async)
{
await base.Join_with_skip_navigation(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId], [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId]
FROM [EntityTwos] AS [e]
INNER JOIN [EntityTwos] AS [e0] ON [e].[Id] = (
SELECT TOP(1) [e1].[Id]
FROM [JoinTwoSelfShared] AS [j]
INNER JOIN [EntityTwos] AS [e1] ON [j].[RightId] = [e1].[Id]
WHERE [e0].[Id] = [j].[LeftId]
ORDER BY [e1].[Id])");
}
public override async Task Left_join_with_skip_navigation(bool async)
{
await base.Left_join_with_skip_navigation(async);
AssertSql(
@"SELECT [e].[Key1], [e].[Key2], [e].[Key3], [e].[Name], [e0].[Key1], [e0].[Key2], [e0].[Key3], [e0].[Name]
FROM [EntityCompositeKeys] AS [e]
LEFT JOIN [EntityCompositeKeys] AS [e0] ON (
SELECT TOP(1) [e1].[Id]
FROM [JoinTwoToCompositeKeyShared] AS [j]
INNER JOIN [EntityTwos] AS [e1] ON [j].[TwoId] = [e1].[Id]
WHERE (([e].[Key1] = [j].[CompositeId1]) AND ([e].[Key2] = [j].[CompositeId2])) AND ([e].[Key3] = [j].[CompositeId3])
ORDER BY [e1].[Id]) = (
SELECT TOP(1) [e2].[Id]
FROM [JoinThreeToCompositeKeyFull] AS [j0]
INNER JOIN [EntityThrees] AS [e2] ON [j0].[ThreeId] = [e2].[Id]
WHERE (([e0].[Key1] = [j0].[CompositeId1]) AND ([e0].[Key2] = [j0].[CompositeId2])) AND ([e0].[Key3] = [j0].[CompositeId3])
ORDER BY [e2].[Id])
ORDER BY [e].[Key1], [e0].[Key1], [e].[Key2], [e0].[Key2]");
}
public override async Task Select_many_over_skip_navigation(bool async)
{
await base.Select_many_over_skip_navigation(async);
AssertSql(
@"SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId]
FROM [EntityRoots] AS [e]
INNER JOIN (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], [e0].[EntityRootId]
FROM [EntityRootEntityThree] AS [e0]
INNER JOIN [EntityThrees] AS [e1] ON [e0].[EntityThreeId] = [e1].[Id]
) AS [t] ON [e].[Id] = [t].[EntityRootId]");
}
public override async Task Select_many_over_skip_navigation_where(bool async)
{
await base.Select_many_over_skip_navigation_where(async);
AssertSql(
@"SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId]
FROM [EntityOnes] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [j].[OneId]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
) AS [t] ON [e].[Id] = [t].[OneId]");
}
public override async Task Select_many_over_skip_navigation_order_by_skip(bool async)
{
await base.Select_many_over_skip_navigation_order_by_skip(async);
AssertSql(
@"SELECT [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId]
FROM [EntityOnes] AS [e]
INNER JOIN (
SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[OneId]
FROM (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [j].[OneId], ROW_NUMBER() OVER(PARTITION BY [j].[OneId] ORDER BY [e0].[Id]) AS [row]
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityThrees] AS [e0] ON [j].[ThreeId] = [e0].[Id]
) AS [t]
WHERE 2 < [t].[row]
) AS [t0] ON [e].[Id] = [t0].[OneId]");
}
public override async Task Select_many_over_skip_navigation_order_by_take(bool async)
{
await base.Select_many_over_skip_navigation_order_by_take(async);
AssertSql(
@"SELECT [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId]
FROM [EntityOnes] AS [e]
INNER JOIN (
SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[EntityOneId]
FROM (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], [e0].[EntityOneId], ROW_NUMBER() OVER(PARTITION BY [e0].[EntityOneId] ORDER BY [e1].[Id]) AS [row]
FROM [EntityOneEntityTwo] AS [e0]
INNER JOIN [EntityTwos] AS [e1] ON [e0].[EntityTwoId] = [e1].[Id]
) AS [t]
WHERE [t].[row] <= 2
) AS [t0] ON [e].[Id] = [t0].[EntityOneId]");
}
public override async Task Select_many_over_skip_navigation_order_by_skip_take(bool async)
{
await base.Select_many_over_skip_navigation_order_by_skip_take(async);
AssertSql(
@"SELECT [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId]
FROM [EntityOnes] AS [e]
INNER JOIN (
SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[OneId]
FROM (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [j].[OneId], ROW_NUMBER() OVER(PARTITION BY [j].[OneId] ORDER BY [e0].[Id]) AS [row]
FROM [JoinOneToThreePayloadFullShared] AS [j]
INNER JOIN [EntityThrees] AS [e0] ON [j].[ThreeId] = [e0].[Id]
) AS [t]
WHERE (2 < [t].[row]) AND ([t].[row] <= 5)
) AS [t0] ON [e].[Id] = [t0].[OneId]");
}
public override async Task Select_many_over_skip_navigation_of_type(bool async)
{
await base.Select_many_over_skip_navigation_of_type(async);
AssertSql(
@"SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t].[Number], [t].[IsGreen]
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [e1].[Id], [e1].[Discriminator], [e1].[Name], [e1].[Number], [e1].[IsGreen], [e0].[EntityThreeId]
FROM [EntityRootEntityThree] AS [e0]
INNER JOIN [EntityRoots] AS [e1] ON [e0].[EntityRootId] = [e1].[Id]
WHERE [e1].[Discriminator] IN (N'EntityBranch', N'EntityLeaf')
) AS [t] ON [e].[Id] = [t].[EntityThreeId]");
}
public override async Task Select_many_over_skip_navigation_cast(bool async)
{
await base.Select_many_over_skip_navigation_cast(async);
AssertSql(
@"SELECT [t0].[Id], [t0].[Discriminator], [t0].[Name], [t0].[Number], [t0].[IsGreen]
FROM [EntityOnes] AS [e]
INNER JOIN (
SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t].[Number], [t].[IsGreen], [j].[EntityOneId]
FROM [JoinOneToBranch] AS [j]
INNER JOIN (
SELECT [e0].[Id], [e0].[Discriminator], [e0].[Name], [e0].[Number], [e0].[IsGreen]
FROM [EntityRoots] AS [e0]
WHERE [e0].[Discriminator] IN (N'EntityBranch', N'EntityLeaf')
) AS [t] ON [j].[EntityBranchId] = [t].[Id]
) AS [t0] ON [e].[Id] = [t0].[EntityOneId]");
}
public override async Task Select_skip_navigation(bool async)
{
await base.Select_skip_navigation(async);
AssertSql(
@"SELECT [e].[Id], [t].[Id], [t].[Name], [t].[LeftId], [t].[RightId]
FROM [EntityOnes] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[Name], [j].[LeftId], [j].[RightId]
FROM [JoinOneSelfPayload] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[LeftId] = [e0].[Id]
) AS [t] ON [e].[Id] = [t].[RightId]
ORDER BY [e].[Id], [t].[LeftId], [t].[RightId], [t].[Id]");
}
public override async Task Select_skip_navigation_multiple(bool async)
{
await base.Select_skip_navigation_multiple(async);
AssertSql(
@"SELECT [e].[Id], [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[ThreeId], [t].[TwoId], [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [t0].[LeftId], [t0].[RightId], [t1].[Key1], [t1].[Key2], [t1].[Key3], [t1].[Name], [t1].[TwoId], [t1].[CompositeId1], [t1].[CompositeId2], [t1].[CompositeId3]
FROM [EntityTwos] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [j].[ThreeId], [j].[TwoId]
FROM [JoinTwoToThree] AS [j]
INNER JOIN [EntityThrees] AS [e0] ON [j].[ThreeId] = [e0].[Id]
) AS [t] ON [e].[Id] = [t].[TwoId]
LEFT JOIN (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], [j0].[LeftId], [j0].[RightId]
FROM [JoinTwoSelfShared] AS [j0]
INNER JOIN [EntityTwos] AS [e1] ON [j0].[LeftId] = [e1].[Id]
) AS [t0] ON [e].[Id] = [t0].[RightId]
LEFT JOIN (
SELECT [e2].[Key1], [e2].[Key2], [e2].[Key3], [e2].[Name], [j1].[TwoId], [j1].[CompositeId1], [j1].[CompositeId2], [j1].[CompositeId3]
FROM [JoinTwoToCompositeKeyShared] AS [j1]
INNER JOIN [EntityCompositeKeys] AS [e2] ON (([j1].[CompositeId1] = [e2].[Key1]) AND ([j1].[CompositeId2] = [e2].[Key2])) AND ([j1].[CompositeId3] = [e2].[Key3])
) AS [t1] ON [e].[Id] = [t1].[TwoId]
ORDER BY [e].[Id], [t].[ThreeId], [t].[TwoId], [t].[Id], [t0].[LeftId], [t0].[RightId], [t0].[Id], [t1].[TwoId], [t1].[CompositeId1], [t1].[CompositeId2], [t1].[CompositeId3], [t1].[Key1], [t1].[Key2], [t1].[Key3]");
}
public override async Task Select_skip_navigation_first_or_default(bool async)
{
await base.Select_skip_navigation_first_or_default(async);
AssertSql(
@"SELECT [t0].[Key1], [t0].[Key2], [t0].[Key3], [t0].[Name]
FROM [EntityThrees] AS [e]
LEFT JOIN (
SELECT [t].[Key1], [t].[Key2], [t].[Key3], [t].[Name], [t].[ThreeId]
FROM (
SELECT [e0].[Key1], [e0].[Key2], [e0].[Key3], [e0].[Name], [j].[ThreeId], ROW_NUMBER() OVER(PARTITION BY [j].[ThreeId] ORDER BY [e0].[Key1], [e0].[Key2]) AS [row]
FROM [JoinThreeToCompositeKeyFull] AS [j]
INNER JOIN [EntityCompositeKeys] AS [e0] ON (([j].[CompositeId1] = [e0].[Key1]) AND ([j].[CompositeId2] = [e0].[Key2])) AND ([j].[CompositeId3] = [e0].[Key3])
) AS [t]
WHERE [t].[row] <= 1
) AS [t0] ON [e].[Id] = [t0].[ThreeId]
ORDER BY [e].[Id]");
}
public override async Task Include_skip_navigation(bool async)
{
await base.Include_skip_navigation(async);
AssertSql(
@"SELECT [e].[Key1], [e].[Key2], [e].[Key3], [e].[Name], [t].[Id], [t].[Discriminator], [t].[Name], [t].[Number], [t].[IsGreen], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[RootId]
FROM [EntityCompositeKeys] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[Discriminator], [e0].[Name], [e0].[Number], [e0].[IsGreen], [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[RootId]
FROM [JoinCompositeKeyToRootShared] AS [j]
INNER JOIN [EntityRoots] AS [e0] ON [j].[RootId] = [e0].[Id]
) AS [t] ON (([e].[Key1] = [t].[CompositeId1]) AND ([e].[Key2] = [t].[CompositeId2])) AND ([e].[Key3] = [t].[CompositeId3])
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[RootId], [t].[Id]");
}
public override async Task Include_skip_navigation_then_reference(bool async)
{
await base.Include_skip_navigation_then_reference(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId], [t].[Id], [t].[Name], [t].[Id0], [t].[CollectionInverseId], [t].[Name0], [t].[ReferenceInverseId], [t].[OneId], [t].[TwoId]
FROM [EntityTwos] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[Name], [e1].[Id] AS [Id0], [e1].[CollectionInverseId], [e1].[Name] AS [Name0], [e1].[ReferenceInverseId], [j].[OneId], [j].[TwoId]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
LEFT JOIN [EntityTwos] AS [e1] ON [e0].[Id] = [e1].[ReferenceInverseId]
) AS [t] ON [e].[Id] = [t].[TwoId]
ORDER BY [e].[Id], [t].[OneId], [t].[TwoId], [t].[Id], [t].[Id0]");
}
public override async Task Include_skip_navigation_then_include_skip_navigation(bool async)
{
await base.Include_skip_navigation_then_include_skip_navigation(async);
AssertSql(
@"SELECT [e].[Key1], [e].[Key2], [e].[Key3], [e].[Name], [t1].[Id], [t1].[Discriminator], [t1].[Name], [t1].[Number], [t1].[IsGreen], [t1].[CompositeId1], [t1].[CompositeId2], [t1].[CompositeId3], [t1].[LeafId], [t1].[Id0], [t1].[Name0], [t1].[EntityBranchId], [t1].[EntityOneId]
FROM [EntityCompositeKeys] AS [e]
LEFT JOIN (
SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t].[Number], [t].[IsGreen], [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[LeafId], [t0].[Id] AS [Id0], [t0].[Name] AS [Name0], [t0].[EntityBranchId], [t0].[EntityOneId]
FROM [JoinCompositeKeyToLeaf] AS [j]
INNER JOIN (
SELECT [e0].[Id], [e0].[Discriminator], [e0].[Name], [e0].[Number], [e0].[IsGreen]
FROM [EntityRoots] AS [e0]
WHERE [e0].[Discriminator] = N'EntityLeaf'
) AS [t] ON [j].[LeafId] = [t].[Id]
LEFT JOIN (
SELECT [e1].[Id], [e1].[Name], [j0].[EntityBranchId], [j0].[EntityOneId]
FROM [JoinOneToBranch] AS [j0]
INNER JOIN [EntityOnes] AS [e1] ON [j0].[EntityOneId] = [e1].[Id]
) AS [t0] ON [t].[Id] = [t0].[EntityBranchId]
) AS [t1] ON (([e].[Key1] = [t1].[CompositeId1]) AND ([e].[Key2] = [t1].[CompositeId2])) AND ([e].[Key3] = [t1].[CompositeId3])
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3], [t1].[CompositeId1], [t1].[CompositeId2], [t1].[CompositeId3], [t1].[LeafId], [t1].[Id], [t1].[EntityBranchId], [t1].[EntityOneId], [t1].[Id0]");
}
public override async Task Include_skip_navigation_then_include_reference_and_skip_navigation(bool async)
{
await base.Include_skip_navigation_then_include_reference_and_skip_navigation(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId], [t0].[Id], [t0].[Name], [t0].[Id0], [t0].[CollectionInverseId], [t0].[Name0], [t0].[ReferenceInverseId], [t0].[OneId], [t0].[ThreeId], [t0].[Id1], [t0].[Name1], [t0].[LeftId], [t0].[RightId]
FROM [EntityThrees] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[Name], [e1].[Id] AS [Id0], [e1].[CollectionInverseId], [e1].[Name] AS [Name0], [e1].[ReferenceInverseId], [j].[OneId], [j].[ThreeId], [t].[Id] AS [Id1], [t].[Name] AS [Name1], [t].[LeftId], [t].[RightId]
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
LEFT JOIN [EntityTwos] AS [e1] ON [e0].[Id] = [e1].[ReferenceInverseId]
LEFT JOIN (
SELECT [e2].[Id], [e2].[Name], [j0].[LeftId], [j0].[RightId]
FROM [JoinOneSelfPayload] AS [j0]
INNER JOIN [EntityOnes] AS [e2] ON [j0].[RightId] = [e2].[Id]
) AS [t] ON [e0].[Id] = [t].[LeftId]
) AS [t0] ON [e].[Id] = [t0].[ThreeId]
ORDER BY [e].[Id], [t0].[OneId], [t0].[ThreeId], [t0].[Id], [t0].[Id0], [t0].[LeftId], [t0].[RightId], [t0].[Id1]");
}
public override async Task Include_skip_navigation_and_reference(bool async)
{
await base.Include_skip_navigation_and_reference(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId], [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [t].[Id], [t].[Name], [t].[EntityOneId], [t].[EntityTwoId]
FROM [EntityTwos] AS [e]
LEFT JOIN [EntityThrees] AS [e0] ON [e].[Id] = [e0].[ReferenceInverseId]
LEFT JOIN (
SELECT [e2].[Id], [e2].[Name], [e1].[EntityOneId], [e1].[EntityTwoId]
FROM [EntityOneEntityTwo] AS [e1]
INNER JOIN [EntityOnes] AS [e2] ON [e1].[EntityOneId] = [e2].[Id]
) AS [t] ON [e].[Id] = [t].[EntityTwoId]
ORDER BY [e].[Id], [e0].[Id], [t].[EntityOneId], [t].[EntityTwoId], [t].[Id]");
}
public override async Task Filtered_include_skip_navigation_where(bool async)
{
await base.Filtered_include_skip_navigation_where(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId], [t].[Id], [t].[Name], [t].[OneId], [t].[ThreeId]
FROM [EntityThrees] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[Name], [j].[OneId], [j].[ThreeId]
FROM [JoinOneToThreePayloadFullShared] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
WHERE [e0].[Id] < 10
) AS [t] ON [e].[Id] = [t].[ThreeId]
ORDER BY [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id]");
}
public override async Task Filtered_include_skip_navigation_order_by(bool async)
{
await base.Filtered_include_skip_navigation_order_by(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId], [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[ThreeId], [t].[TwoId]
FROM [EntityThrees] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [j].[ThreeId], [j].[TwoId]
FROM [JoinTwoToThree] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
) AS [t] ON [e].[Id] = [t].[ThreeId]
ORDER BY [e].[Id], [t].[Id], [t].[ThreeId], [t].[TwoId]");
}
public override async Task Filtered_include_skip_navigation_order_by_skip(bool async)
{
await base.Filtered_include_skip_navigation_order_by_skip(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId], [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [t0].[LeftId], [t0].[RightId]
FROM [EntityTwos] AS [e]
LEFT JOIN (
SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[LeftId], [t].[RightId]
FROM (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [j].[LeftId], [j].[RightId], ROW_NUMBER() OVER(PARTITION BY [j].[LeftId] ORDER BY [e0].[Id]) AS [row]
FROM [JoinTwoSelfShared] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[RightId] = [e0].[Id]
) AS [t]
WHERE 2 < [t].[row]
) AS [t0] ON [e].[Id] = [t0].[LeftId]
ORDER BY [e].[Id], [t0].[LeftId], [t0].[Id], [t0].[RightId]");
}
public override async Task Filtered_include_skip_navigation_order_by_take(bool async)
{
await base.Filtered_include_skip_navigation_order_by_take(async);
AssertSql(
@"SELECT [e].[Key1], [e].[Key2], [e].[Key3], [e].[Name], [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [t0].[TwoId], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3]
FROM [EntityCompositeKeys] AS [e]
LEFT JOIN (
SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[TwoId], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3]
FROM (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [j].[TwoId], [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], ROW_NUMBER() OVER(PARTITION BY [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3] ORDER BY [e0].[Id]) AS [row]
FROM [JoinTwoToCompositeKeyShared] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
) AS [t]
WHERE [t].[row] <= 2
) AS [t0] ON (([e].[Key1] = [t0].[CompositeId1]) AND ([e].[Key2] = [t0].[CompositeId2])) AND ([e].[Key3] = [t0].[CompositeId3])
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[Id], [t0].[TwoId]");
}
public override async Task Filtered_include_skip_navigation_order_by_skip_take(bool async)
{
await base.Filtered_include_skip_navigation_order_by_skip_take(async);
AssertSql(
@"SELECT [e].[Key1], [e].[Key2], [e].[Key3], [e].[Name], [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [t0].[Id0]
FROM [EntityCompositeKeys] AS [e]
LEFT JOIN (
SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[Id0], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3]
FROM (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [j].[Id] AS [Id0], [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], ROW_NUMBER() OVER(PARTITION BY [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3] ORDER BY [e0].[Id]) AS [row]
FROM [JoinThreeToCompositeKeyFull] AS [j]
INNER JOIN [EntityThrees] AS [e0] ON [j].[ThreeId] = [e0].[Id]
) AS [t]
WHERE (1 < [t].[row]) AND ([t].[row] <= 3)
) AS [t0] ON (([e].[Key1] = [t0].[CompositeId1]) AND ([e].[Key2] = [t0].[CompositeId2])) AND ([e].[Key3] = [t0].[CompositeId3])
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[Id], [t0].[Id0]");
}
public override async Task Filtered_then_include_skip_navigation_where(bool async)
{
await base.Filtered_then_include_skip_navigation_where(async);
AssertSql(
@"SELECT [e].[Id], [e].[Discriminator], [e].[Name], [e].[Number], [e].[IsGreen], [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [t0].[EntityRootId], [t0].[EntityThreeId], [t0].[Id0], [t0].[Name0], [t0].[OneId], [t0].[ThreeId]
FROM [EntityRoots] AS [e]
LEFT JOIN (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], [e0].[EntityRootId], [e0].[EntityThreeId], [t].[Id] AS [Id0], [t].[Name] AS [Name0], [t].[OneId], [t].[ThreeId]
FROM [EntityRootEntityThree] AS [e0]
INNER JOIN [EntityThrees] AS [e1] ON [e0].[EntityThreeId] = [e1].[Id]
LEFT JOIN (
SELECT [e2].[Id], [e2].[Name], [j].[OneId], [j].[ThreeId]
FROM [JoinOneToThreePayloadFullShared] AS [j]
INNER JOIN [EntityOnes] AS [e2] ON [j].[OneId] = [e2].[Id]
WHERE [e2].[Id] < 10
) AS [t] ON [e1].[Id] = [t].[ThreeId]
) AS [t0] ON [e].[Id] = [t0].[EntityRootId]
ORDER BY [e].[Id], [t0].[EntityRootId], [t0].[EntityThreeId], [t0].[Id], [t0].[OneId], [t0].[ThreeId], [t0].[Id0]");
}
public override async Task Filtered_then_include_skip_navigation_order_by_skip_take(bool async)
{
await base.Filtered_then_include_skip_navigation_order_by_skip_take(async);
AssertSql(
@"SELECT [e].[Id], [e].[Discriminator], [e].[Name], [e].[Number], [e].[IsGreen], [t1].[Key1], [t1].[Key2], [t1].[Key3], [t1].[Name], [t1].[CompositeId1], [t1].[CompositeId2], [t1].[CompositeId3], [t1].[RootId], [t1].[Id], [t1].[CollectionInverseId], [t1].[Name0], [t1].[ReferenceInverseId], [t1].[Id0]
FROM [EntityRoots] AS [e]
LEFT JOIN (
SELECT [e0].[Key1], [e0].[Key2], [e0].[Key3], [e0].[Name], [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[RootId], [t0].[Id], [t0].[CollectionInverseId], [t0].[Name] AS [Name0], [t0].[ReferenceInverseId], [t0].[Id0], [t0].[CompositeId1] AS [CompositeId10], [t0].[CompositeId2] AS [CompositeId20], [t0].[CompositeId3] AS [CompositeId30]
FROM [JoinCompositeKeyToRootShared] AS [j]
INNER JOIN [EntityCompositeKeys] AS [e0] ON (([j].[CompositeId1] = [e0].[Key1]) AND ([j].[CompositeId2] = [e0].[Key2])) AND ([j].[CompositeId3] = [e0].[Key3])
LEFT JOIN (
SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[Id0], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3]
FROM (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], [j0].[Id] AS [Id0], [j0].[CompositeId1], [j0].[CompositeId2], [j0].[CompositeId3], ROW_NUMBER() OVER(PARTITION BY [j0].[CompositeId1], [j0].[CompositeId2], [j0].[CompositeId3] ORDER BY [e1].[Id]) AS [row]
FROM [JoinThreeToCompositeKeyFull] AS [j0]
INNER JOIN [EntityThrees] AS [e1] ON [j0].[ThreeId] = [e1].[Id]
) AS [t]
WHERE (1 < [t].[row]) AND ([t].[row] <= 3)
) AS [t0] ON (([e0].[Key1] = [t0].[CompositeId1]) AND ([e0].[Key2] = [t0].[CompositeId2])) AND ([e0].[Key3] = [t0].[CompositeId3])
) AS [t1] ON [e].[Id] = [t1].[RootId]
ORDER BY [e].[Id], [t1].[CompositeId1], [t1].[CompositeId2], [t1].[CompositeId3], [t1].[RootId], [t1].[Key1], [t1].[Key2], [t1].[Key3], [t1].[CompositeId10], [t1].[CompositeId20], [t1].[CompositeId30], [t1].[Id], [t1].[Id0]");
}
public override async Task Filtered_include_skip_navigation_where_then_include_skip_navigation(bool async)
{
await base.Filtered_include_skip_navigation_where_then_include_skip_navigation(async);
AssertSql(
@"SELECT [e].[Id], [e].[Discriminator], [e].[Name], [e].[Number], [e].[IsGreen], [t0].[Key1], [t0].[Key2], [t0].[Key3], [t0].[Name], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[LeafId], [t0].[Id], [t0].[CollectionInverseId], [t0].[Name0], [t0].[ReferenceInverseId], [t0].[TwoId], [t0].[CompositeId10], [t0].[CompositeId20], [t0].[CompositeId30]
FROM [EntityRoots] AS [e]
LEFT JOIN (
SELECT [e0].[Key1], [e0].[Key2], [e0].[Key3], [e0].[Name], [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[LeafId], [t].[Id], [t].[CollectionInverseId], [t].[Name] AS [Name0], [t].[ReferenceInverseId], [t].[TwoId], [t].[CompositeId1] AS [CompositeId10], [t].[CompositeId2] AS [CompositeId20], [t].[CompositeId3] AS [CompositeId30]
FROM [JoinCompositeKeyToLeaf] AS [j]
INNER JOIN [EntityCompositeKeys] AS [e0] ON (([j].[CompositeId1] = [e0].[Key1]) AND ([j].[CompositeId2] = [e0].[Key2])) AND ([j].[CompositeId3] = [e0].[Key3])
LEFT JOIN (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], [j0].[TwoId], [j0].[CompositeId1], [j0].[CompositeId2], [j0].[CompositeId3]
FROM [JoinTwoToCompositeKeyShared] AS [j0]
INNER JOIN [EntityTwos] AS [e1] ON [j0].[TwoId] = [e1].[Id]
) AS [t] ON (([e0].[Key1] = [t].[CompositeId1]) AND ([e0].[Key2] = [t].[CompositeId2])) AND ([e0].[Key3] = [t].[CompositeId3])
WHERE [e0].[Key1] < 5
) AS [t0] ON [e].[Id] = [t0].[LeafId]
WHERE [e].[Discriminator] = N'EntityLeaf'
ORDER BY [e].[Id], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[LeafId], [t0].[Key1], [t0].[Key2], [t0].[Key3], [t0].[TwoId], [t0].[CompositeId10], [t0].[CompositeId20], [t0].[CompositeId30], [t0].[Id]");
}
public override async Task Filtered_include_skip_navigation_order_by_skip_take_then_include_skip_navigation_where(bool async)
{
await base.Filtered_include_skip_navigation_order_by_skip_take_then_include_skip_navigation_where(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name], [t1].[Id], [t1].[CollectionInverseId], [t1].[Name], [t1].[ReferenceInverseId], [t1].[OneId], [t1].[TwoId], [t1].[Id0], [t1].[CollectionInverseId0], [t1].[Name0], [t1].[ReferenceInverseId0], [t1].[ThreeId], [t1].[TwoId0]
FROM [EntityOnes] AS [e]
OUTER APPLY (
SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[OneId], [t].[TwoId], [t0].[Id] AS [Id0], [t0].[CollectionInverseId] AS [CollectionInverseId0], [t0].[Name] AS [Name0], [t0].[ReferenceInverseId] AS [ReferenceInverseId0], [t0].[ThreeId], [t0].[TwoId] AS [TwoId0]
FROM (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [j].[OneId], [j].[TwoId]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
WHERE [e].[Id] = [j].[OneId]
ORDER BY [e0].[Id]
OFFSET 1 ROWS FETCH NEXT 2 ROWS ONLY
) AS [t]
LEFT JOIN (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], [j0].[ThreeId], [j0].[TwoId]
FROM [JoinTwoToThree] AS [j0]
INNER JOIN [EntityThrees] AS [e1] ON [j0].[ThreeId] = [e1].[Id]
WHERE [e1].[Id] < 10
) AS [t0] ON [t].[Id] = [t0].[TwoId]
) AS [t1]
ORDER BY [e].[Id], [t1].[Id], [t1].[OneId], [t1].[TwoId], [t1].[ThreeId], [t1].[TwoId0], [t1].[Id0]");
}
public override async Task Filtered_include_skip_navigation_where_then_include_skip_navigation_order_by_skip_take(bool async)
{
await base.Filtered_include_skip_navigation_where_then_include_skip_navigation_order_by_skip_take(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name], [t1].[Id], [t1].[CollectionInverseId], [t1].[Name], [t1].[ReferenceInverseId], [t1].[OneId], [t1].[TwoId], [t1].[Id0], [t1].[CollectionInverseId0], [t1].[Name0], [t1].[ReferenceInverseId0], [t1].[ThreeId], [t1].[TwoId0]
FROM [EntityOnes] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [j].[OneId], [j].[TwoId], [t0].[Id] AS [Id0], [t0].[CollectionInverseId] AS [CollectionInverseId0], [t0].[Name] AS [Name0], [t0].[ReferenceInverseId] AS [ReferenceInverseId0], [t0].[ThreeId], [t0].[TwoId] AS [TwoId0]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
LEFT JOIN (
SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[ThreeId], [t].[TwoId]
FROM (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], [j0].[ThreeId], [j0].[TwoId], ROW_NUMBER() OVER(PARTITION BY [j0].[TwoId] ORDER BY [e1].[Id]) AS [row]
FROM [JoinTwoToThree] AS [j0]
INNER JOIN [EntityThrees] AS [e1] ON [j0].[ThreeId] = [e1].[Id]
) AS [t]
WHERE (1 < [t].[row]) AND ([t].[row] <= 3)
) AS [t0] ON [e0].[Id] = [t0].[TwoId]
WHERE [e0].[Id] < 10
) AS [t1] ON [e].[Id] = [t1].[OneId]
ORDER BY [e].[Id], [t1].[OneId], [t1].[TwoId], [t1].[Id], [t1].[TwoId0], [t1].[Id0], [t1].[ThreeId]");
}
public override async Task Filter_include_on_skip_navigation_combined(bool async)
{
await base.Filter_include_on_skip_navigation_combined(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId], [t].[Id], [t].[Name], [t].[Id0], [t].[CollectionInverseId], [t].[Name0], [t].[ReferenceInverseId], [t].[OneId], [t].[TwoId], [t].[Id1], [t].[CollectionInverseId0], [t].[Name1], [t].[ReferenceInverseId0]
FROM [EntityTwos] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[Name], [e1].[Id] AS [Id0], [e1].[CollectionInverseId], [e1].[Name] AS [Name0], [e1].[ReferenceInverseId], [j].[OneId], [j].[TwoId], [e2].[Id] AS [Id1], [e2].[CollectionInverseId] AS [CollectionInverseId0], [e2].[Name] AS [Name1], [e2].[ReferenceInverseId] AS [ReferenceInverseId0]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
LEFT JOIN [EntityTwos] AS [e1] ON [e0].[Id] = [e1].[ReferenceInverseId]
LEFT JOIN [EntityTwos] AS [e2] ON [e0].[Id] = [e2].[CollectionInverseId]
WHERE [e0].[Id] < 10
) AS [t] ON [e].[Id] = [t].[TwoId]
ORDER BY [e].[Id], [t].[OneId], [t].[TwoId], [t].[Id], [t].[Id0], [t].[Id1]");
}
public override async Task Filter_include_on_skip_navigation_combined_with_filtered_then_includes(bool async)
{
await base.Filter_include_on_skip_navigation_combined_with_filtered_then_includes(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId], [t3].[Id], [t3].[Name], [t3].[OneId], [t3].[ThreeId], [t3].[Id0], [t3].[CollectionInverseId], [t3].[Name0], [t3].[ReferenceInverseId], [t3].[OneId0], [t3].[TwoId], [t3].[Id1], [t3].[Discriminator], [t3].[Name1], [t3].[Number], [t3].[IsGreen], [t3].[EntityBranchId], [t3].[EntityOneId]
FROM [EntityThrees] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[Name], [j].[OneId], [j].[ThreeId], [t0].[Id] AS [Id0], [t0].[CollectionInverseId], [t0].[Name] AS [Name0], [t0].[ReferenceInverseId], [t0].[OneId] AS [OneId0], [t0].[TwoId], [t2].[Id] AS [Id1], [t2].[Discriminator], [t2].[Name] AS [Name1], [t2].[Number], [t2].[IsGreen], [t2].[EntityBranchId], [t2].[EntityOneId]
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
LEFT JOIN (
SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [t].[OneId], [t].[TwoId]
FROM (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], [j0].[OneId], [j0].[TwoId], ROW_NUMBER() OVER(PARTITION BY [j0].[OneId] ORDER BY [e1].[Id]) AS [row]
FROM [JoinOneToTwo] AS [j0]
INNER JOIN [EntityTwos] AS [e1] ON [j0].[TwoId] = [e1].[Id]
) AS [t]
WHERE (1 < [t].[row]) AND ([t].[row] <= 3)
) AS [t0] ON [e0].[Id] = [t0].[OneId]
LEFT JOIN (
SELECT [t1].[Id], [t1].[Discriminator], [t1].[Name], [t1].[Number], [t1].[IsGreen], [j1].[EntityBranchId], [j1].[EntityOneId]
FROM [JoinOneToBranch] AS [j1]
INNER JOIN (
SELECT [e2].[Id], [e2].[Discriminator], [e2].[Name], [e2].[Number], [e2].[IsGreen]
FROM [EntityRoots] AS [e2]
WHERE [e2].[Discriminator] IN (N'EntityBranch', N'EntityLeaf')
) AS [t1] ON [j1].[EntityBranchId] = [t1].[Id]
WHERE [t1].[Id] < 20
) AS [t2] ON [e0].[Id] = [t2].[EntityOneId]
WHERE [e0].[Id] < 10
) AS [t3] ON [e].[Id] = [t3].[ThreeId]
ORDER BY [e].[Id], [t3].[OneId], [t3].[ThreeId], [t3].[Id], [t3].[OneId0], [t3].[Id0], [t3].[TwoId], [t3].[EntityBranchId], [t3].[EntityOneId], [t3].[Id1]");
}
public override async Task Filtered_include_on_skip_navigation_then_filtered_include_on_navigation(bool async)
{
await base.Filtered_include_on_skip_navigation_then_filtered_include_on_navigation(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId], [t0].[Id], [t0].[Name], [t0].[OneId], [t0].[ThreeId], [t0].[Id0], [t0].[CollectionInverseId], [t0].[Name0], [t0].[ReferenceInverseId]
FROM [EntityThrees] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[Name], [j].[OneId], [j].[ThreeId], [t].[Id] AS [Id0], [t].[CollectionInverseId], [t].[Name] AS [Name0], [t].[ReferenceInverseId]
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
LEFT JOIN (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId]
FROM [EntityTwos] AS [e1]
WHERE [e1].[Id] < 5
) AS [t] ON [e0].[Id] = [t].[CollectionInverseId]
WHERE [e0].[Id] > 15
) AS [t0] ON [e].[Id] = [t0].[ThreeId]
ORDER BY [e].[Id], [t0].[OneId], [t0].[ThreeId], [t0].[Id], [t0].[Id0]");
}
public override async Task Filtered_include_on_navigation_then_filtered_include_on_skip_navigation(bool async)
{
await base.Filtered_include_on_navigation_then_filtered_include_on_skip_navigation(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name], [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [t0].[Id0], [t0].[CollectionInverseId0], [t0].[Name0], [t0].[ReferenceInverseId0], [t0].[ThreeId], [t0].[TwoId]
FROM [EntityOnes] AS [e]
LEFT JOIN (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], [t].[Id] AS [Id0], [t].[CollectionInverseId] AS [CollectionInverseId0], [t].[Name] AS [Name0], [t].[ReferenceInverseId] AS [ReferenceInverseId0], [t].[ThreeId], [t].[TwoId]
FROM [EntityTwos] AS [e0]
LEFT JOIN (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], [j].[ThreeId], [j].[TwoId]
FROM [JoinTwoToThree] AS [j]
INNER JOIN [EntityThrees] AS [e1] ON [j].[ThreeId] = [e1].[Id]
WHERE [e1].[Id] < 5
) AS [t] ON [e0].[Id] = [t].[TwoId]
WHERE [e0].[Id] > 15
) AS [t0] ON [e].[Id] = [t0].[CollectionInverseId]
ORDER BY [e].[Id], [t0].[Id], [t0].[ThreeId], [t0].[TwoId], [t0].[Id0]");
}
public override async Task Includes_accessed_via_different_path_are_merged(bool async)
{
await base.Includes_accessed_via_different_path_are_merged(async);
AssertSql(" ");
}
public override async Task Filered_includes_accessed_via_different_path_are_merged(bool async)
{
await base.Filered_includes_accessed_via_different_path_are_merged(async);
AssertSql(" ");
}
public override async Task Include_skip_navigation_split(bool async)
{
await base.Include_skip_navigation_split(async);
AssertSql(
@"SELECT [e].[Key1], [e].[Key2], [e].[Key3], [e].[Name]
FROM [EntityCompositeKeys] AS [e]
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3]",
//
@"SELECT [t].[Id], [t].[Discriminator], [t].[Name], [t].[Number], [t].[IsGreen], [e].[Key1], [e].[Key2], [e].[Key3]
FROM [EntityCompositeKeys] AS [e]
INNER JOIN (
SELECT [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [e0].[Id], [e0].[Discriminator], [e0].[Name], [e0].[Number], [e0].[IsGreen]
FROM [JoinCompositeKeyToRootShared] AS [j]
INNER JOIN [EntityRoots] AS [e0] ON [j].[RootId] = [e0].[Id]
) AS [t] ON (([e].[Key1] = [t].[CompositeId1]) AND ([e].[Key2] = [t].[CompositeId2])) AND ([e].[Key3] = [t].[CompositeId3])
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3]");
}
public override async Task Include_skip_navigation_then_reference_split(bool async)
{
await base.Include_skip_navigation_then_reference_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId]
FROM [EntityTwos] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t].[Id], [t].[Name], [t].[Id0], [t].[CollectionInverseId], [t].[Name0], [t].[ReferenceInverseId], [e].[Id]
FROM [EntityTwos] AS [e]
INNER JOIN (
SELECT [j].[TwoId], [e0].[Id], [e0].[Name], [e1].[Id] AS [Id0], [e1].[CollectionInverseId], [e1].[Name] AS [Name0], [e1].[ReferenceInverseId]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
LEFT JOIN [EntityTwos] AS [e1] ON [e0].[Id] = [e1].[ReferenceInverseId]
) AS [t] ON [e].[Id] = [t].[TwoId]
ORDER BY [e].[Id]");
}
public override async Task Include_skip_navigation_then_include_skip_navigation_split(bool async)
{
await base.Include_skip_navigation_then_include_skip_navigation_split(async);
AssertSql(
@"SELECT [e].[Key1], [e].[Key2], [e].[Key3], [e].[Name]
FROM [EntityCompositeKeys] AS [e]
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3]",
//
@"SELECT [t0].[Id], [t0].[Discriminator], [t0].[Name], [t0].[Number], [t0].[IsGreen], [e].[Key1], [e].[Key2], [e].[Key3], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[LeafId]
FROM [EntityCompositeKeys] AS [e]
INNER JOIN (
SELECT [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[LeafId], [t].[Id], [t].[Discriminator], [t].[Name], [t].[Number], [t].[IsGreen]
FROM [JoinCompositeKeyToLeaf] AS [j]
INNER JOIN (
SELECT [e0].[Id], [e0].[Discriminator], [e0].[Name], [e0].[Number], [e0].[IsGreen]
FROM [EntityRoots] AS [e0]
WHERE [e0].[Discriminator] = N'EntityLeaf'
) AS [t] ON [j].[LeafId] = [t].[Id]
) AS [t0] ON (([e].[Key1] = [t0].[CompositeId1]) AND ([e].[Key2] = [t0].[CompositeId2])) AND ([e].[Key3] = [t0].[CompositeId3])
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[LeafId], [t0].[Id]",
//
@"SELECT [t1].[Id], [t1].[Name], [e].[Key1], [e].[Key2], [e].[Key3], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[LeafId], [t0].[Id]
FROM [EntityCompositeKeys] AS [e]
INNER JOIN (
SELECT [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[LeafId], [t].[Id]
FROM [JoinCompositeKeyToLeaf] AS [j]
INNER JOIN (
SELECT [e0].[Id]
FROM [EntityRoots] AS [e0]
WHERE [e0].[Discriminator] = N'EntityLeaf'
) AS [t] ON [j].[LeafId] = [t].[Id]
) AS [t0] ON (([e].[Key1] = [t0].[CompositeId1]) AND ([e].[Key2] = [t0].[CompositeId2])) AND ([e].[Key3] = [t0].[CompositeId3])
INNER JOIN (
SELECT [j0].[EntityBranchId], [e1].[Id], [e1].[Name]
FROM [JoinOneToBranch] AS [j0]
INNER JOIN [EntityOnes] AS [e1] ON [j0].[EntityOneId] = [e1].[Id]
) AS [t1] ON [t0].[Id] = [t1].[EntityBranchId]
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[LeafId], [t0].[Id]");
}
public override async Task Include_skip_navigation_then_include_reference_and_skip_navigation_split(bool async)
{
await base.Include_skip_navigation_then_include_reference_and_skip_navigation_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId]
FROM [EntityThrees] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t].[Id], [t].[Name], [t].[Id0], [t].[CollectionInverseId], [t].[Name0], [t].[ReferenceInverseId], [e].[Id], [t].[OneId], [t].[ThreeId]
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [j].[OneId], [j].[ThreeId], [e0].[Id], [e0].[Name], [e1].[Id] AS [Id0], [e1].[CollectionInverseId], [e1].[Name] AS [Name0], [e1].[ReferenceInverseId]
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
LEFT JOIN [EntityTwos] AS [e1] ON [e0].[Id] = [e1].[ReferenceInverseId]
) AS [t] ON [e].[Id] = [t].[ThreeId]
ORDER BY [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id], [t].[Id0]",
//
@"SELECT [t0].[Id], [t0].[Name], [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id], [t].[Id0]
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [j].[OneId], [j].[ThreeId], [e0].[Id], [e1].[Id] AS [Id0]
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
LEFT JOIN [EntityTwos] AS [e1] ON [e0].[Id] = [e1].[ReferenceInverseId]
) AS [t] ON [e].[Id] = [t].[ThreeId]
INNER JOIN (
SELECT [j0].[LeftId], [e2].[Id], [e2].[Name]
FROM [JoinOneSelfPayload] AS [j0]
INNER JOIN [EntityOnes] AS [e2] ON [j0].[RightId] = [e2].[Id]
) AS [t0] ON [t].[Id] = [t0].[LeftId]
ORDER BY [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id], [t].[Id0]");
}
public override async Task Include_skip_navigation_and_reference_split(bool async)
{
await base.Include_skip_navigation_and_reference_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId], [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId]
FROM [EntityTwos] AS [e]
LEFT JOIN [EntityThrees] AS [e0] ON [e].[Id] = [e0].[ReferenceInverseId]
ORDER BY [e].[Id], [e0].[Id]",
//
@"SELECT [t].[Id], [t].[Name], [e].[Id], [e0].[Id]
FROM [EntityTwos] AS [e]
LEFT JOIN [EntityThrees] AS [e0] ON [e].[Id] = [e0].[ReferenceInverseId]
INNER JOIN (
SELECT [e1].[EntityTwoId], [e2].[Id], [e2].[Name]
FROM [EntityOneEntityTwo] AS [e1]
INNER JOIN [EntityOnes] AS [e2] ON [e1].[EntityOneId] = [e2].[Id]
) AS [t] ON [e].[Id] = [t].[EntityTwoId]
ORDER BY [e].[Id], [e0].[Id]");
}
public override async Task Filtered_include_skip_navigation_where_split(bool async)
{
await base.Filtered_include_skip_navigation_where_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId]
FROM [EntityThrees] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t].[Id], [t].[Name], [e].[Id]
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [j].[ThreeId], [e0].[Id], [e0].[Name]
FROM [JoinOneToThreePayloadFullShared] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
WHERE [e0].[Id] < 10
) AS [t] ON [e].[Id] = [t].[ThreeId]
ORDER BY [e].[Id]");
}
public override async Task Filtered_include_skip_navigation_order_by_split(bool async)
{
await base.Filtered_include_skip_navigation_order_by_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId]
FROM [EntityThrees] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [e].[Id]
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [t].[ThreeId], [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId]
FROM (
SELECT [j].[ThreeId], [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], ROW_NUMBER() OVER(PARTITION BY [j].[ThreeId] ORDER BY [e0].[Id]) AS [row]
FROM [JoinTwoToThree] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
) AS [t]
WHERE 0 < [t].[row]
) AS [t0] ON [e].[Id] = [t0].[ThreeId]
ORDER BY [e].[Id], [t0].[ThreeId], [t0].[Id]");
}
public override async Task Filtered_include_skip_navigation_order_by_skip_split(bool async)
{
await base.Filtered_include_skip_navigation_order_by_skip_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId]
FROM [EntityTwos] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [e].[Id]
FROM [EntityTwos] AS [e]
INNER JOIN (
SELECT [t].[LeftId], [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId]
FROM (
SELECT [j].[LeftId], [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], ROW_NUMBER() OVER(PARTITION BY [j].[LeftId] ORDER BY [e0].[Id]) AS [row]
FROM [JoinTwoSelfShared] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[RightId] = [e0].[Id]
) AS [t]
WHERE 2 < [t].[row]
) AS [t0] ON [e].[Id] = [t0].[LeftId]
ORDER BY [e].[Id], [t0].[LeftId], [t0].[Id]");
}
public override async Task Filtered_include_skip_navigation_order_by_take_split(bool async)
{
await base.Filtered_include_skip_navigation_order_by_take_split(async);
AssertSql(
@"SELECT [e].[Key1], [e].[Key2], [e].[Key3], [e].[Name]
FROM [EntityCompositeKeys] AS [e]
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3]",
//
@"SELECT [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [e].[Key1], [e].[Key2], [e].[Key3]
FROM [EntityCompositeKeys] AS [e]
INNER JOIN (
SELECT [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId]
FROM (
SELECT [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], ROW_NUMBER() OVER(PARTITION BY [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3] ORDER BY [e0].[Id]) AS [row]
FROM [JoinTwoToCompositeKeyShared] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
) AS [t]
WHERE [t].[row] <= 2
) AS [t0] ON (([e].[Key1] = [t0].[CompositeId1]) AND ([e].[Key2] = [t0].[CompositeId2])) AND ([e].[Key3] = [t0].[CompositeId3])
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[Id]");
}
public override async Task Filtered_include_skip_navigation_order_by_skip_take_split(bool async)
{
await base.Filtered_include_skip_navigation_order_by_skip_take_split(async);
AssertSql(
@"SELECT [e].[Key1], [e].[Key2], [e].[Key3], [e].[Name]
FROM [EntityCompositeKeys] AS [e]
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3]",
//
@"SELECT [t0].[Id0], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [e].[Key1], [e].[Key2], [e].[Key3]
FROM [EntityCompositeKeys] AS [e]
INNER JOIN (
SELECT [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[Id0], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId]
FROM (
SELECT [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [e0].[Id] AS [Id0], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], ROW_NUMBER() OVER(PARTITION BY [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3] ORDER BY [e0].[Id]) AS [row]
FROM [JoinThreeToCompositeKeyFull] AS [j]
INNER JOIN [EntityThrees] AS [e0] ON [j].[ThreeId] = [e0].[Id]
) AS [t]
WHERE (1 < [t].[row]) AND ([t].[row] <= 3)
) AS [t0] ON (([e].[Key1] = [t0].[CompositeId1]) AND ([e].[Key2] = [t0].[CompositeId2])) AND ([e].[Key3] = [t0].[CompositeId3])
ORDER BY [e].[Key1], [e].[Key2], [e].[Key3], [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[Id0]");
}
public override async Task Filtered_then_include_skip_navigation_where_split(bool async)
{
await base.Filtered_then_include_skip_navigation_where_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[Discriminator], [e].[Name], [e].[Number], [e].[IsGreen]
FROM [EntityRoots] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [e].[Id], [t].[EntityRootId], [t].[EntityThreeId]
FROM [EntityRoots] AS [e]
INNER JOIN (
SELECT [e0].[EntityRootId], [e0].[EntityThreeId], [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId]
FROM [EntityRootEntityThree] AS [e0]
INNER JOIN [EntityThrees] AS [e1] ON [e0].[EntityThreeId] = [e1].[Id]
) AS [t] ON [e].[Id] = [t].[EntityRootId]
ORDER BY [e].[Id], [t].[EntityRootId], [t].[EntityThreeId], [t].[Id]",
//
@"SELECT [t0].[Id], [t0].[Name], [e].[Id], [t].[EntityRootId], [t].[EntityThreeId], [t].[Id]
FROM [EntityRoots] AS [e]
INNER JOIN (
SELECT [e0].[EntityRootId], [e0].[EntityThreeId], [e1].[Id]
FROM [EntityRootEntityThree] AS [e0]
INNER JOIN [EntityThrees] AS [e1] ON [e0].[EntityThreeId] = [e1].[Id]
) AS [t] ON [e].[Id] = [t].[EntityRootId]
INNER JOIN (
SELECT [j].[ThreeId], [e2].[Id], [e2].[Name]
FROM [JoinOneToThreePayloadFullShared] AS [j]
INNER JOIN [EntityOnes] AS [e2] ON [j].[OneId] = [e2].[Id]
WHERE [e2].[Id] < 10
) AS [t0] ON [t].[Id] = [t0].[ThreeId]
ORDER BY [e].[Id], [t].[EntityRootId], [t].[EntityThreeId], [t].[Id]");
}
public override async Task Filtered_then_include_skip_navigation_order_by_skip_take_split(bool async)
{
await base.Filtered_then_include_skip_navigation_order_by_skip_take_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[Discriminator], [e].[Name], [e].[Number], [e].[IsGreen]
FROM [EntityRoots] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t].[Key1], [t].[Key2], [t].[Key3], [t].[Name], [e].[Id], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[RootId]
FROM [EntityRoots] AS [e]
INNER JOIN (
SELECT [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[RootId], [e0].[Key1], [e0].[Key2], [e0].[Key3], [e0].[Name]
FROM [JoinCompositeKeyToRootShared] AS [j]
INNER JOIN [EntityCompositeKeys] AS [e0] ON (([j].[CompositeId1] = [e0].[Key1]) AND ([j].[CompositeId2] = [e0].[Key2])) AND ([j].[CompositeId3] = [e0].[Key3])
) AS [t] ON [e].[Id] = [t].[RootId]
ORDER BY [e].[Id], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[RootId], [t].[Key1], [t].[Key2], [t].[Key3]",
//
@"SELECT [t1].[Id0], [t1].[CollectionInverseId], [t1].[Name], [t1].[ReferenceInverseId], [e].[Id], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[RootId], [t].[Key1], [t].[Key2], [t].[Key3]
FROM [EntityRoots] AS [e]
INNER JOIN (
SELECT [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[RootId], [e0].[Key1], [e0].[Key2], [e0].[Key3]
FROM [JoinCompositeKeyToRootShared] AS [j]
INNER JOIN [EntityCompositeKeys] AS [e0] ON (([j].[CompositeId1] = [e0].[Key1]) AND ([j].[CompositeId2] = [e0].[Key2])) AND ([j].[CompositeId3] = [e0].[Key3])
) AS [t] ON [e].[Id] = [t].[RootId]
INNER JOIN (
SELECT [t0].[CompositeId1], [t0].[CompositeId2], [t0].[CompositeId3], [t0].[Id0], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId]
FROM (
SELECT [j0].[CompositeId1], [j0].[CompositeId2], [j0].[CompositeId3], [e1].[Id] AS [Id0], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], ROW_NUMBER() OVER(PARTITION BY [j0].[CompositeId1], [j0].[CompositeId2], [j0].[CompositeId3] ORDER BY [e1].[Id]) AS [row]
FROM [JoinThreeToCompositeKeyFull] AS [j0]
INNER JOIN [EntityThrees] AS [e1] ON [j0].[ThreeId] = [e1].[Id]
) AS [t0]
WHERE (1 < [t0].[row]) AND ([t0].[row] <= 3)
) AS [t1] ON (([t].[Key1] = [t1].[CompositeId1]) AND ([t].[Key2] = [t1].[CompositeId2])) AND ([t].[Key3] = [t1].[CompositeId3])
ORDER BY [e].[Id], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[RootId], [t].[Key1], [t].[Key2], [t].[Key3], [t1].[CompositeId1], [t1].[CompositeId2], [t1].[CompositeId3], [t1].[Id0]");
}
public override async Task Filtered_include_skip_navigation_where_then_include_skip_navigation_split(bool async)
{
await base.Filtered_include_skip_navigation_where_then_include_skip_navigation_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[Discriminator], [e].[Name], [e].[Number], [e].[IsGreen]
FROM [EntityRoots] AS [e]
WHERE [e].[Discriminator] = N'EntityLeaf'
ORDER BY [e].[Id]",
//
@"SELECT [t].[Key1], [t].[Key2], [t].[Key3], [t].[Name], [e].[Id], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[LeafId]
FROM [EntityRoots] AS [e]
INNER JOIN (
SELECT [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[LeafId], [e0].[Key1], [e0].[Key2], [e0].[Key3], [e0].[Name]
FROM [JoinCompositeKeyToLeaf] AS [j]
INNER JOIN [EntityCompositeKeys] AS [e0] ON (([j].[CompositeId1] = [e0].[Key1]) AND ([j].[CompositeId2] = [e0].[Key2])) AND ([j].[CompositeId3] = [e0].[Key3])
WHERE [e0].[Key1] < 5
) AS [t] ON [e].[Id] = [t].[LeafId]
WHERE [e].[Discriminator] = N'EntityLeaf'
ORDER BY [e].[Id], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[LeafId], [t].[Key1], [t].[Key2], [t].[Key3]",
//
@"SELECT [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [e].[Id], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[LeafId], [t].[Key1], [t].[Key2], [t].[Key3]
FROM [EntityRoots] AS [e]
INNER JOIN (
SELECT [j].[CompositeId1], [j].[CompositeId2], [j].[CompositeId3], [j].[LeafId], [e0].[Key1], [e0].[Key2], [e0].[Key3]
FROM [JoinCompositeKeyToLeaf] AS [j]
INNER JOIN [EntityCompositeKeys] AS [e0] ON (([j].[CompositeId1] = [e0].[Key1]) AND ([j].[CompositeId2] = [e0].[Key2])) AND ([j].[CompositeId3] = [e0].[Key3])
WHERE [e0].[Key1] < 5
) AS [t] ON [e].[Id] = [t].[LeafId]
INNER JOIN (
SELECT [j0].[CompositeId1], [j0].[CompositeId2], [j0].[CompositeId3], [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId]
FROM [JoinTwoToCompositeKeyShared] AS [j0]
INNER JOIN [EntityTwos] AS [e1] ON [j0].[TwoId] = [e1].[Id]
) AS [t0] ON (([t].[Key1] = [t0].[CompositeId1]) AND ([t].[Key2] = [t0].[CompositeId2])) AND ([t].[Key3] = [t0].[CompositeId3])
WHERE [e].[Discriminator] = N'EntityLeaf'
ORDER BY [e].[Id], [t].[CompositeId1], [t].[CompositeId2], [t].[CompositeId3], [t].[LeafId], [t].[Key1], [t].[Key2], [t].[Key3]");
}
public override async Task Filtered_include_skip_navigation_order_by_skip_take_then_include_skip_navigation_where_split(bool async)
{
await base.Filtered_include_skip_navigation_order_by_skip_take_then_include_skip_navigation_where_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name]
FROM [EntityOnes] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [e].[Id], [t0].[OneId], [t0].[TwoId]
FROM [EntityOnes] AS [e]
INNER JOIN (
SELECT [t].[OneId], [t].[TwoId], [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId]
FROM (
SELECT [j].[OneId], [j].[TwoId], [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId], ROW_NUMBER() OVER(PARTITION BY [j].[OneId] ORDER BY [e0].[Id]) AS [row]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
) AS [t]
WHERE (1 < [t].[row]) AND ([t].[row] <= 3)
) AS [t0] ON [e].[Id] = [t0].[OneId]
ORDER BY [e].[Id], [t0].[OneId], [t0].[TwoId], [t0].[Id]",
//
@"SELECT [t1].[Id], [t1].[CollectionInverseId], [t1].[Name], [t1].[ReferenceInverseId], [e].[Id], [t0].[OneId], [t0].[TwoId], [t0].[Id]
FROM [EntityOnes] AS [e]
INNER JOIN (
SELECT [t].[OneId], [t].[TwoId], [t].[Id]
FROM (
SELECT [j].[OneId], [j].[TwoId], [e0].[Id], ROW_NUMBER() OVER(PARTITION BY [j].[OneId] ORDER BY [e0].[Id]) AS [row]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
) AS [t]
WHERE (1 < [t].[row]) AND ([t].[row] <= 3)
) AS [t0] ON [e].[Id] = [t0].[OneId]
INNER JOIN (
SELECT [j0].[TwoId], [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId]
FROM [JoinTwoToThree] AS [j0]
INNER JOIN [EntityThrees] AS [e1] ON [j0].[ThreeId] = [e1].[Id]
WHERE [e1].[Id] < 10
) AS [t1] ON [t0].[Id] = [t1].[TwoId]
ORDER BY [e].[Id], [t0].[OneId], [t0].[TwoId], [t0].[Id]");
}
public override async Task Filtered_include_skip_navigation_where_then_include_skip_navigation_order_by_skip_take_split(bool async)
{
await base.Filtered_include_skip_navigation_where_then_include_skip_navigation_order_by_skip_take_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name]
FROM [EntityOnes] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [e].[Id], [t].[OneId], [t].[TwoId]
FROM [EntityOnes] AS [e]
INNER JOIN (
SELECT [j].[OneId], [j].[TwoId], [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
WHERE [e0].[Id] < 10
) AS [t] ON [e].[Id] = [t].[OneId]
ORDER BY [e].[Id], [t].[OneId], [t].[TwoId], [t].[Id]",
//
@"SELECT [t1].[Id], [t1].[CollectionInverseId], [t1].[Name], [t1].[ReferenceInverseId], [e].[Id], [t].[OneId], [t].[TwoId], [t].[Id]
FROM [EntityOnes] AS [e]
INNER JOIN (
SELECT [j].[OneId], [j].[TwoId], [e0].[Id]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityTwos] AS [e0] ON [j].[TwoId] = [e0].[Id]
WHERE [e0].[Id] < 10
) AS [t] ON [e].[Id] = [t].[OneId]
INNER JOIN (
SELECT [t0].[TwoId], [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId]
FROM (
SELECT [j0].[TwoId], [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], ROW_NUMBER() OVER(PARTITION BY [j0].[TwoId] ORDER BY [e1].[Id]) AS [row]
FROM [JoinTwoToThree] AS [j0]
INNER JOIN [EntityThrees] AS [e1] ON [j0].[ThreeId] = [e1].[Id]
) AS [t0]
WHERE (1 < [t0].[row]) AND ([t0].[row] <= 3)
) AS [t1] ON [t].[Id] = [t1].[TwoId]
ORDER BY [e].[Id], [t].[OneId], [t].[TwoId], [t].[Id], [t1].[TwoId], [t1].[Id]");
}
public override async Task Filter_include_on_skip_navigation_combined_split(bool async)
{
await base.Filter_include_on_skip_navigation_combined_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId]
FROM [EntityTwos] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t].[Id], [t].[Name], [t].[Id0], [t].[CollectionInverseId], [t].[Name0], [t].[ReferenceInverseId], [e].[Id], [t].[OneId], [t].[TwoId]
FROM [EntityTwos] AS [e]
INNER JOIN (
SELECT [j].[OneId], [j].[TwoId], [e0].[Id], [e0].[Name], [e1].[Id] AS [Id0], [e1].[CollectionInverseId], [e1].[Name] AS [Name0], [e1].[ReferenceInverseId]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
LEFT JOIN [EntityTwos] AS [e1] ON [e0].[Id] = [e1].[ReferenceInverseId]
WHERE [e0].[Id] < 10
) AS [t] ON [e].[Id] = [t].[TwoId]
ORDER BY [e].[Id], [t].[OneId], [t].[TwoId], [t].[Id], [t].[Id0]",
//
@"SELECT [e2].[Id], [e2].[CollectionInverseId], [e2].[Name], [e2].[ReferenceInverseId], [e].[Id], [t].[OneId], [t].[TwoId], [t].[Id], [t].[Id0]
FROM [EntityTwos] AS [e]
INNER JOIN (
SELECT [j].[OneId], [j].[TwoId], [e0].[Id], [e1].[Id] AS [Id0]
FROM [JoinOneToTwo] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
LEFT JOIN [EntityTwos] AS [e1] ON [e0].[Id] = [e1].[ReferenceInverseId]
WHERE [e0].[Id] < 10
) AS [t] ON [e].[Id] = [t].[TwoId]
INNER JOIN [EntityTwos] AS [e2] ON [t].[Id] = [e2].[CollectionInverseId]
ORDER BY [e].[Id], [t].[OneId], [t].[TwoId], [t].[Id], [t].[Id0]");
}
public override async Task Filter_include_on_skip_navigation_combined_with_filtered_then_includes_split(bool async)
{
await base.Filter_include_on_skip_navigation_combined_with_filtered_then_includes_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId]
FROM [EntityThrees] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t].[Id], [t].[Name], [e].[Id], [t].[OneId], [t].[ThreeId]
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [j].[OneId], [j].[ThreeId], [e0].[Id], [e0].[Name]
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
WHERE [e0].[Id] < 10
) AS [t] ON [e].[Id] = [t].[ThreeId]
ORDER BY [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id]",
//
@"SELECT [t1].[Id], [t1].[CollectionInverseId], [t1].[Name], [t1].[ReferenceInverseId], [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id]
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [j].[OneId], [j].[ThreeId], [e0].[Id]
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
WHERE [e0].[Id] < 10
) AS [t] ON [e].[Id] = [t].[ThreeId]
INNER JOIN (
SELECT [t0].[OneId], [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId]
FROM (
SELECT [j0].[OneId], [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId], ROW_NUMBER() OVER(PARTITION BY [j0].[OneId] ORDER BY [e1].[Id]) AS [row]
FROM [JoinOneToTwo] AS [j0]
INNER JOIN [EntityTwos] AS [e1] ON [j0].[TwoId] = [e1].[Id]
) AS [t0]
WHERE (1 < [t0].[row]) AND ([t0].[row] <= 3)
) AS [t1] ON [t].[Id] = [t1].[OneId]
ORDER BY [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id], [t1].[OneId], [t1].[Id]",
//
@"SELECT [t1].[Id], [t1].[Discriminator], [t1].[Name], [t1].[Number], [t1].[IsGreen], [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id]
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [j].[OneId], [j].[ThreeId], [e0].[Id]
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
WHERE [e0].[Id] < 10
) AS [t] ON [e].[Id] = [t].[ThreeId]
INNER JOIN (
SELECT [j0].[EntityOneId], [t0].[Id], [t0].[Discriminator], [t0].[Name], [t0].[Number], [t0].[IsGreen]
FROM [JoinOneToBranch] AS [j0]
INNER JOIN (
SELECT [e1].[Id], [e1].[Discriminator], [e1].[Name], [e1].[Number], [e1].[IsGreen]
FROM [EntityRoots] AS [e1]
WHERE [e1].[Discriminator] IN (N'EntityBranch', N'EntityLeaf')
) AS [t0] ON [j0].[EntityBranchId] = [t0].[Id]
WHERE [t0].[Id] < 20
) AS [t1] ON [t].[Id] = [t1].[EntityOneId]
ORDER BY [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id]");
}
public override async Task Filtered_include_on_skip_navigation_then_filtered_include_on_navigation_split(bool async)
{
await base.Filtered_include_on_skip_navigation_then_filtered_include_on_navigation_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[CollectionInverseId], [e].[Name], [e].[ReferenceInverseId]
FROM [EntityThrees] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t].[Id], [t].[Name], [e].[Id], [t].[OneId], [t].[ThreeId]
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [j].[OneId], [j].[ThreeId], [e0].[Id], [e0].[Name]
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
WHERE [e0].[Id] > 15
) AS [t] ON [e].[Id] = [t].[ThreeId]
ORDER BY [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id]",
//
@"SELECT [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id]
FROM [EntityThrees] AS [e]
INNER JOIN (
SELECT [j].[OneId], [j].[ThreeId], [e0].[Id]
FROM [JoinOneToThreePayloadFull] AS [j]
INNER JOIN [EntityOnes] AS [e0] ON [j].[OneId] = [e0].[Id]
WHERE [e0].[Id] > 15
) AS [t] ON [e].[Id] = [t].[ThreeId]
INNER JOIN (
SELECT [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId]
FROM [EntityTwos] AS [e1]
WHERE [e1].[Id] < 5
) AS [t0] ON [t].[Id] = [t0].[CollectionInverseId]
ORDER BY [e].[Id], [t].[OneId], [t].[ThreeId], [t].[Id]");
}
public override async Task Filtered_include_on_navigation_then_filtered_include_on_skip_navigation_split(bool async)
{
await base.Filtered_include_on_navigation_then_filtered_include_on_skip_navigation_split(async);
AssertSql(
@"SELECT [e].[Id], [e].[Name]
FROM [EntityOnes] AS [e]
ORDER BY [e].[Id]",
//
@"SELECT [t].[Id], [t].[CollectionInverseId], [t].[Name], [t].[ReferenceInverseId], [e].[Id]
FROM [EntityOnes] AS [e]
INNER JOIN (
SELECT [e0].[Id], [e0].[CollectionInverseId], [e0].[Name], [e0].[ReferenceInverseId]
FROM [EntityTwos] AS [e0]
WHERE [e0].[Id] > 15
) AS [t] ON [e].[Id] = [t].[CollectionInverseId]
ORDER BY [e].[Id], [t].[Id]",
//
@"SELECT [t0].[Id], [t0].[CollectionInverseId], [t0].[Name], [t0].[ReferenceInverseId], [e].[Id], [t].[Id]
FROM [EntityOnes] AS [e]
INNER JOIN (
SELECT [e0].[Id], [e0].[CollectionInverseId]
FROM [EntityTwos] AS [e0]
WHERE [e0].[Id] > 15
) AS [t] ON [e].[Id] = [t].[CollectionInverseId]
INNER JOIN (
SELECT [j].[TwoId], [e1].[Id], [e1].[CollectionInverseId], [e1].[Name], [e1].[ReferenceInverseId]
FROM [JoinTwoToThree] AS [j]
INNER JOIN [EntityThrees] AS [e1] ON [j].[ThreeId] = [e1].[Id]
WHERE [e1].[Id] < 5
) AS [t0] ON [t].[Id] = [t0].[TwoId]
ORDER BY [e].[Id], [t].[Id]");
}
private void AssertSql(params string[] expected)
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);
}
}
| 51.866286 | 385 | 0.580536 | [
"Apache-2.0"
] | 0b01/efcore | test/EFCore.SqlServer.FunctionalTests/Query/ManyToManyNoTrackingQuerySqlServerTest.cs | 81,845 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[assembly: global::Xamarin.Forms.Xaml.XamlResourceIdAttribute("Market_Application.Views.GetStarted.xaml", "Views/GetStarted.xaml", typeof(global::Market_Application.Views.Page1))]
namespace Market_Application.Views {
[global::Xamarin.Forms.Xaml.XamlFilePathAttribute("Views\\GetStarted.xaml")]
public partial class Page1 : global::Xamarin.Forms.ContentPage {
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")]
private void InitializeComponent() {
global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(Page1));
}
}
}
| 41.72 | 179 | 0.594439 | [
"MIT"
] | Chanyx666/Market-Application- | Market Application/obj/Debug/netstandard2.0/Views/GetStarted.xaml.g.cs | 1,043 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
#if DEBUG
using System.Reflection;
using System.Diagnostics;
#endif
namespace JSLOL.Parser
{
/// <summary>
/// Base class for evry parsing object that provides basic set of tools.
/// </summary>
public abstract class CodeElement
{
protected Code _code;
protected int _indentLevel;
protected String _indention;
abstract protected int[] _allowedCodeElements { get; }
/// <summary>
/// Variable to store starting point of the parsed expression
/// </summary>
protected int _startOffset = 0;
/// <summary>
/// Variable to store ending point of the parsed expression
/// </summary>
protected int _stopOffset = 0;
/// <summary>
/// List of code element objects found inside.
/// </summary>
protected List <CodeElement> codeElements = new List<CodeElement>();
/// <summary>
/// Current code offset for regex matching
/// </summary>
protected int _offset = 0 ;
/// <summary>
/// offset used to parse code
/// </summary>
public int offset {
get { return this._offset; }
protected set{ this._offset = value; }
}
/// <summary>
///
/// </summary>
/// <param name="code">The Code object</param>
/// <param name="offset">Number of chars that has been alreadey parsed</param>
/// <param name="indentionLevel">Code indention level aka. number of '\t'</param>
public CodeElement(Code code, int offset, int indentionLevel)
{
this._code = code;
this._offset = offset;
this._startOffset = offset;
this._indentLevel = indentionLevel;
this._indention = new String('\t', this._indentLevel);
this.Parse(); //throws CodeElementNotFound exception
this._stopOffset = this._offset;
#if DEBUG
String codeFragment ;
if (this._stopOffset - this._startOffset > 30)
codeFragment = this._code.source.Substring(this._startOffset, 15) + " (...) " + this._code.source.Substring(this._stopOffset - 8, 8);
else
codeFragment = this._code.source.Substring(this._startOffset, this._stopOffset - this._startOffset);
codeFragment = codeFragment.Replace("\r\n","\\n");
Debug.WriteLine(String.Format("offset : {0} to {1} :: Found {2} : '{3:20}'",
this._startOffset,
this._stopOffset,
this.GetType().Name,
codeFragment
));
#endif
}
/// <summary>
/// Match selected CodeElement indentified by eID When successfull add it to codeElements list and icrease parsing offset
/// </summary>
/// <param name="eID">ID of code element to match</param>
/// <param name="mandatory">If true method drops CodeElementNotFound exception on failure</param>
/// <returns></returns>
protected CodeElement matchCodeElement(int eID, bool mandatory)
{
CodeElement e = Toolbox.createCodeElement(eID, this._code, this._offset, this._indentLevel);
if (e != null)
{
this.codeElements.Add(e);
this._offset = e.offset;
}
else if (mandatory)
throw new CodeElementNotFound();
return e;
}
/// <summary>
/// Match selected CodeElement indentified by eI. When successfull add it to codeElements list and icrease parsing offset. Alias for CodeElement MatchCodeElement(int,bool)
/// </summary>
/// <param name="eID">code element identificator taken from enum Toolbox.codeElements</param>
/// <returns></returns>
protected CodeElement matchCodeElement(int eID)
{
return this.matchCodeElement(eID, false);
}
/// <summary>
/// Match selected CodeElement indentified by eI. When successfull add it to codeElements list and icrease parsing offset otherwise throws CodeElementNotFound exception. Alias for CodeElement MatchCodeElement(int,bool)
/// </summary>
/// <param name="eID">code element identificator taken from enum Toolbox.codeElements</param>
/// <returns></returns>
protected CodeElement matchMandatoryCodeElement(int eID)
{
return this.matchCodeElement(eID, true);
}
/// <summary>
/// iterate over _allowedCodeElements property and stops on first match. When no match returns null
/// </summary>
/// <returns>matched code element or null on failure</returns>
protected CodeElement matchAllowedCodeElement()
{
return this.MatchCodeElemntFromArray(this._allowedCodeElements);
}
/// <summary>
/// Iterates over given array of code elements ID's and stops on first match.
/// </summary>
/// <param name="arr">array of CodeElements ID's from Toolbox.codeElements</param>
/// <returns>Matched code element object or NULL</returns>
protected CodeElement MatchCodeElemntFromArray(int[] arr)
{
CodeElement e = null;
foreach (int eId in arr)
if ((e = this.matchCodeElement(eId)) != null)
return e;
return null;
}
/// <summary>
/// skips white chars in code
/// </summary>
protected void skipWhiteChars() {
this.skipWhiteChars(false);
}
/// <summary>
/// skips white chars. When includeNewLines is true also skips new line chars.
/// </summary>
/// <param name="includeNewLines"></param>
protected void skipWhiteChars(bool includeNewLines)
{
this.offset+=this._code.getWhiteChars(this._offset,includeNewLines).Length;
}
/// <summary>
/// Matches <![CDATA[<endofinstructionmarker>]]>
/// </summary>
protected void matchEndOfInstructionMarker()
{
this.matchMandatoryRegexp(Toolbox.stdRegex[Toolbox.RegExpTemplates.endOfInstruction],true);
}
/// <summary>
/// Matches regular expression against the code, automatticaly increases _offset.throws CodeElementNotFound exception onf failure
/// </summary>
/// <param name="re">regular expression to match</param>
/// <param name="skipWhiteChars">skip white chars before the element</param>
/// <returns>matched data</returns>
protected Match matchMandatoryRegexp(Regex re,bool skipWhiteChars)
{
return this.matchRegexp(re, skipWhiteChars, true);
}
/// <summary>
/// Matches regular expression against the code, automatticaly increases _offset.throws CodeElementNotFound exception onf failure
/// </summary>
/// <param name="re">regular expression to match</param>
/// <returns>matched data</returns>
protected Match matchMandatoryRegexp(Regex re)
{
return this.matchRegexp(re,false,true);
}
/// <summary>
/// Matches regular expression against the code, automatticaly increases _offset.
/// </summary>
/// <param name="re">regular expression to match</param>
/// <returns>matched data</returns>
protected Match matchRegexp(Regex re)
{
return this.matchRegexp(re,false,false);
}
/// <summary>
/// Matches given Regex object against the code with current offset. Icrease offset on success
/// </summary>
/// <param name="re">Regex to match</param>
/// <param name="skipWhiteChars">Allows presence of white chars before matching</param>
/// <param name="mandatory">Indicates if method throws CodeElementNotFound exception on failure</param>
/// <returns>Match object</returns>
protected Match matchRegexp(Regex re,bool skipWhiteChars,bool mandatory)
{
if (skipWhiteChars)
this.skipWhiteChars(true);
Match m = this._code.match(re, this._offset);
if (mandatory && !m.Success)
throw new CodeElementNotFound(this._offset, this._code, re.ToString());
this._offset += m.Length;
return m;
}
/// <summary>
/// Calls toCSHarp() for evry contained CodeElement
/// <param name="ns">namespace to put code in</param>
/// <returns>C# code returned by calls</returns>
virtual protected String subobjectsToCSharp(String ns)
{
String cSharpCode = "";
foreach (CodeElement e in this.codeElements)
cSharpCode += e.toCSharp(ns);
return cSharpCode;
}
/// <summary>
/// The main methot that parses the code.
/// </summary>
protected abstract void Parse();
/// <summary>
/// Parse object and all its subobjects to C# code
/// </summary>
/// <returns>C# code</returns>
public virtual String toCSharp(String ns)
{
throw new NotImplementedException();
}
}
}
| 37.43083 | 226 | 0.59208 | [
"BSD-2-Clause"
] | mrozo/jslol.PARSER | CodeElement.cs | 9,472 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace CqsSample.Authorization.Permissions
{
public static class Permissions
{
public static class User
{
public const string Get = "caeef12b-7d29-42c1-b183-bf0b89d31a55";
public const string AddOrUpdate = "c0ee45ce-05fd-4aa8-a8be-bff0c8b40e2c";
}
}
}
| 24 | 85 | 0.671875 | [
"MIT"
] | meinsiedler/cqs-sample | CqsSample/CqsSample.Authorization/Permissions/Permissions.cs | 386 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _07_Bomb_Numbers_2
{
class Program
{
static void Main(string[] args)
{
List<int> sequence = Console.ReadLine().Split().Select(int.Parse).ToList();
string[] inputLine = Console.ReadLine().Split();
int number = int.Parse(inputLine[0]);
int power = int.Parse(inputLine[1]);
for (int i = 0; i < sequence.Count; i++)
{
if (sequence[i] == number)
{
int left = Math.Max(i - power, 0);
int right = Math.Min(i + power, sequence.Count - 1);
int lenght = right - left + 1;
sequence.RemoveRange(left, lenght);
i = -1;
}
}
Console.WriteLine(sequence.Sum());
}
}
}
| 24.175 | 87 | 0.490176 | [
"MIT"
] | Bullsized/Assignments-Fundamentals-Normal | 18 - 19 Lists/2017-06-12/07 Bomb Numbers 2/07 Bomb Numbers 2.cs | 969 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2020 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Web.Editors
{
using YAF.Configuration;
using YAF.Core.Context;
using YAF.Core.Utilities;
using YAF.Types;
using YAF.Types.Extensions;
using YAF.Types.Interfaces;
using YAF.Utils;
/// <summary>
/// The CKEditor BBCode editor.
/// </summary>
public class CKEditorBBCodeEditor : CKEditor
{
#region Properties
/// <summary>
/// Gets Description.
/// </summary>
[NotNull]
public override string Description => "CKEditor (BBCode) - Full";
/// <summary>
/// Gets ModuleId.
/// </summary>
public override string ModuleId => "4";
/// <summary>
/// Gets a value indicating whether UsesBBCode.
/// </summary>
public override bool UsesBBCode => true;
/// <summary>
/// Gets a value indicating whether UsesHTML.
/// </summary>
public override bool UsesHTML => false;
/// <summary>
/// The allows uploads.
/// </summary>
public override bool AllowsUploads => true;
#endregion
#region Methods
/// <summary>
/// The register CKEditor custom JS.
/// </summary>
protected override void RegisterCKEditorCustomJS()
{
var toolbar = this.Get<BoardSettings>().EditorToolbarFull;
if (!(this.Get<BoardSettings>().EnableAlbum && this.PageContext.UsrAlbums > 0
&& this.PageContext.NumAlbums > 0))
{
// remove albums
toolbar = toolbar.Replace(", \"albumsbrowser\"", string.Empty);
}
BoardContext.Current.PageElements.RegisterJsBlock(
"ckeditorinitbbcode",
JavaScriptBlocks.CKEditorLoadJs(
this.TextAreaControl.ClientID,
BoardContext.Current.CultureUser.IsSet()
? BoardContext.Current.CultureUser.Substring(0, 2)
: this.Get<BoardSettings>().Culture.Substring(0, 2),
this.MaxCharacters,
this.Get<ITheme>().BuildThemePath("bootstrap-forum.min.css"),
BoardInfo.GetURLToContent("forum.min.css"),
toolbar));
}
#endregion
}
} | 34.59 | 92 | 0.57878 | [
"Apache-2.0"
] | AlbertoP57/YAFNET | yafsrc/YAF.Web/Editors/CKEditorBBCodeEditor.cs | 3,361 | C# |
using Lombiq.TrainingDemo.Models;
using Lombiq.TrainingDemo.ViewModels;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Views;
using System.Threading.Tasks;
namespace Lombiq.TrainingDemo.Drivers
{
// Drivers inherited from ContentPartDisplayDrivers have a functionality similar to the one described in
// BookDisplayDriver but these are for ContentParts. Don't forget to register this class with the service provider
// (see: Startup.cs).
public class PersonPartDisplayDriver : ContentPartDisplayDriver<PersonPart>
{
// A Display method that we already know. This time it's much simpler because we don't want to create multiple
// shapes for the PersonPart - however we could.
public override IDisplayResult Display(PersonPart part) =>
// Notice that there is no location given for this shape. There's another option of giving these locations
// using Placement.json files. Since it is not possible to put comments in a .json file the explanation is
// here but make sure you check the file while reading this. It's important to give a location somewhere
// otherwise to shape won't be displayed. The shape file should be in the Views folder by default, however,
// it could be outside the Views folder too (e.g. inside the Drivers folder).
// In Placement files you can give specific locations to any shapes generated by Orchard. You can also
// specify rules to match when the location will be applied: like only for certain fields, content types,
// just under a given path. In our Placement file you can see that the PersonPart shape gets the first
// position in the Content zone and the TextField shape gets the second. To make sure that not all the
// TextFields will get the same position a "differentiator" property is given which refers to the part name
// where the field is attached to and the field name. Make sure you also read the documentation to know
// this feature better:
// https://docs.orchardcore.net/en/dev/docs/reference/core/Placement/#placement-files
// NEXT STATION: placement.json (needs to be lowercase) then come back here.
View(nameof(PersonPart), part);
// This is something that wasn't implemented in the BookDisplayDriver (but could've been). It will generate the
// editor shape for the PersonPart.
public override IDisplayResult Edit(PersonPart personPart) =>
// Something similar to the Display method happens: you have a shape helper with a shape name possibly and
// a factory. For editing using Initialize is the best idea. It will instantiate a view model from a type
// given as a generic parameter. In the factory you will map the content part properties to the view model.
Initialize<PersonPartViewModel>($"{nameof(PersonPart)}_Edit", model =>
{
model.PersonPart = personPart;
model.BirthDateUtc = personPart.BirthDateUtc;
model.Name = personPart.Name;
model.Handedness = personPart.Handedness;
}).Location("Content:1");
// NEXT STATION: Startup.cs and find the static constructor.
// So we had an Edit (or EditAsync) that generates the editor shape now it's time to do the content
// part-specific model binding and validation.
public override async Task<IDisplayResult> UpdateAsync(PersonPart model, IUpdateModel updater)
{
var viewModel = new PersonPartViewModel();
// Now it's where the IUpdateModel interface is really used (remember we first used it in
// DisplayManagementController?). With this you will be able to use the Controller's model binding helpers
// here in the driver. The prefix property will be used to distinguish between similarly named input fields
// when building the editor form (so e.g. two content parts composing a content item can have an input
// field called "Name"). By default Orchard Core will use the content part name but if you have multiple
// drivers with editors for a content part you need to override it in the driver.
await updater.TryUpdateModelAsync(viewModel, Prefix);
// Now you can do some validation if needed. One way to do it you can simply write your own validation here
// or you can do it in the view model class.
// Go and check the ViewModels/PersonPartViewModel to see how to do it and then come back here.
// Finally map the view model to the content part. By default these changes won't be persisted if there was
// a validation error. Otherwise these will be automatically stored in the database.
model.BirthDateUtc = viewModel.BirthDateUtc;
model.Name = viewModel.Name;
model.Handedness = viewModel.Handedness;
return Edit(model);
}
}
}
// NEXT STATION: Controllers/PersonListController and go back to the OlderThan30 method where we left. | 64.831325 | 120 | 0.682401 | [
"BSD-2-Clause"
] | Devqon/Orchard-Training-Demo-Module | Drivers/PersonPartDisplayDriver.cs | 5,381 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests
{
public class CommandLineDiagnosticFormatterTests
{
[Fact]
public void GetPathNameRelativeToBaseDirectory()
{
var formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"X:\rootdir\dir",
displayFullPaths: true,
displayEndLocations: true);
Assert.Equal(@"a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\a.cs"));
Assert.Equal(@"temp\a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\temp\a.cs"));
Assert.Equal(@"Y:\rootdir\dir\a.cs", formatter.RelativizeNormalizedPath(@"Y:\rootdir\dir\a.cs"));
formatter = new CommandLineDiagnosticFormatter(
baseDirectory: @"X:\rootdir\..\rootdir\dir",
displayFullPaths: true,
displayEndLocations: true);
Assert.Equal(@"a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\a.cs"));
Assert.Equal(@"temp\a.cs", formatter.RelativizeNormalizedPath(@"X:\rootdir\dir\temp\a.cs"));
Assert.Equal(@"Y:\rootdir\dir\a.cs", formatter.RelativizeNormalizedPath(@"Y:\rootdir\dir\a.cs"));
}
}
}
| 44.59375 | 161 | 0.641906 | [
"Apache-2.0"
] | pottereric/roslyn | src/Compilers/CSharp/Test/CommandLine/CommandLineDiagnosticFormatterTests.cs | 1,429 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Sage.CA.SBS.ERP.Sage300.OE.Resources.Reports {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class QuotesResx {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal QuotesResx() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Sage.CA.SBS.ERP.Sage300.OE.Resources.Reports.QuotesResx", typeof(QuotesResx).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Browse….
/// </summary>
public static string Browse {
get {
return ResourceManager.GetString("Browse", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Include Quotes Already Printed.
/// </summary>
public static string Chkreprint {
get {
return ResourceManager.GetString("Chkreprint", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to O/E Quotes.
/// </summary>
public static string Entity {
get {
return ResourceManager.GetString("Entity", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to flag printed quotes..
/// </summary>
public static string FLAGNOTUPDATED {
get {
return ResourceManager.GetString("FLAGNOTUPDATED", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Use Quote.
/// </summary>
public static string Lblrptfile {
get {
return ResourceManager.GetString("Lblrptfile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OEQUOT01.rpt.
/// </summary>
public static string OEQUOT01 {
get {
return ResourceManager.GetString("OEQUOT01", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OEQUOT02.rpt.
/// </summary>
public static string OEQUOT02 {
get {
return ResourceManager.GetString("OEQUOT02", resourceCulture);
}
}
}
}
| 38.110236 | 201 | 0.566736 | [
"MIT"
] | PeterSorokac/Sage300-SDK | resources/Sage300Resources/Sage.CA.SBS.ERP.Sage300.OE.Resources/Reports/QuotesResx.Designer.cs | 4,844 | C# |
using System.ComponentModel.DataAnnotations;
using Abp.Authorization.Users;
using Abp.AutoMapper;
using Abp.MultiTenancy;
namespace ManageCloudDevices.MultiTenancy.Dto
{
[AutoMapTo(typeof(Tenant))]
public class CreateTenantDto
{
[Required]
[StringLength(AbpTenantBase.MaxTenancyNameLength)]
[RegularExpression(AbpTenantBase.TenancyNameRegex)]
public string TenancyName { get; set; }
[Required]
[StringLength(AbpTenantBase.MaxNameLength)]
public string Name { get; set; }
[Required]
[StringLength(AbpUserBase.MaxEmailAddressLength)]
public string AdminEmailAddress { get; set; }
[StringLength(AbpTenantBase.MaxConnectionStringLength)]
public string ConnectionString { get; set; }
public bool IsActive {get; set;}
}
}
| 28.033333 | 63 | 0.694411 | [
"MIT"
] | hasan-ak1996/ManagerClouddevices | aspnet-core/src/ManageCloudDevices.Application/MultiTenancy/Dto/CreateTenantDto.cs | 841 | C# |
using System;
using System.Buffers.Binary;
using RfpProxyLib;
using RfpProxyLib.Messages;
namespace RfpProxy.Pcap
{
class DnmPcapClient : PcapClient
{
public DnmPcapClient(string socket, string filename) : base(socket, filename)
{
}
protected override int PacketHeaderSize => 6 + 6 + 2 + 4;
protected override ReadOnlyMemory<byte> PreprocessData(ReadOnlyMemory<byte> data)
{
return data.Slice(4);
}
protected override void WritePacketHeader(byte[] header, MessageDirection direction, uint messageId, RfpIdentifier rfp, ReadOnlyMemory<byte> data)
{
rfp.CopyTo(header);
rfp.CopyTo(header.AsSpan(6));
if (direction == MessageDirection.FromOmm)
{
header[6] = 0x02;
}
else
{
header[0] = 0x02;
}
header[12] = 0xa0;
BinaryPrimitives.WriteUInt16BigEndian(header.AsSpan(14), (ushort) data.Length);
header[16] = 0xba;
header[17] = 0xbe;
}
}
} | 27.95 | 154 | 0.569767 | [
"MIT"
] | eventphone/rfpproxy | RfpProxy.Pcap/DnmPcapClient.cs | 1,120 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110
{
using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="ProtectionContainerMappingCollection"
/// />
/// </summary>
public partial class ProtectionContainerMappingCollectionTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="ProtectionContainerMappingCollection"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="ProtectionContainerMappingCollection" /> type, otherwise
/// <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="ProtectionContainerMappingCollection" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="ProtectionContainerMappingCollection" />.</param>
/// <returns>
/// an instance of <see cref="ProtectionContainerMappingCollection" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IProtectionContainerMappingCollection ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IProtectionContainerMappingCollection).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return ProtectionContainerMappingCollection.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return ProtectionContainerMappingCollection.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return ProtectionContainerMappingCollection.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 52.430556 | 245 | 0.593245 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Migrate/generated/api/Models/Api20180110/ProtectionContainerMappingCollection.TypeConverter.cs | 7,407 | C# |
using FeatureSwitcher.Configuration;
using FeatureSwitcher.Specs.Domain;
using Machine.Fakes;
using System.Collections.Generic;
namespace FeatureSwitcher.Specs.BehaviorConfigs
{
public class DatabaseBehaviorConfig
{
OnEstablish context = fakeAccessor =>
{
var config1 = new FeatureConfiguration() { Id = 1, FeatureName = "Test1Feature", ClientId = 1 };
var config2 = new FeatureConfiguration() { Id = 2, FeatureName = "Test1Feature", UseraccountId = 111 };
var config3 = new FeatureConfiguration() { Id = 3, FeatureName = "Test2Feature", Role = UserRole.Normalo };
var features = new List<FeatureConfiguration> { config1, config2, config3 };
fakeAccessor.The<IFeatureConfigurationRepository>()
.WhenToldTo(x => x.FeatureConfigurations)
.Return(features);
};
OnCleanup clean = fakeAccessor => Features.Are.HandledByDefault();
}
}
| 39.08 | 119 | 0.658137 | [
"Apache-2.0"
] | mexx/FeatureSwitcher.Examples | Source/FeatureSwitcher.Specs/BehaviorConfigs/DatabaseBehaviorConfig.cs | 979 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
using IdentityManagerDotNet.Models;
namespace IdentityManagerDotNet.Services
{
public class ConsentService
{
private readonly IClientStore _clientStore;
private readonly IResourceStore _resourceStore;
private readonly IIdentityServerInteractionService _interaction;
private readonly ILogger _logger;
public ConsentService(
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IResourceStore resourceStore,
ILogger logger)
{
_interaction = interaction;
_clientStore = clientStore;
_resourceStore = resourceStore;
_logger = logger;
}
public async Task<ProcessConsentResult> ProcessConsent(ConsentInputModel model)
{
var result = new ProcessConsentResult();
ConsentResponse grantedConsent = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (model.Button == "no")
{
grantedConsent = ConsentResponse.Denied;
}
// user clicked 'yes' - validate the data
else if (model.Button == "yes" && model != null)
{
// if the user consented to some scope, build the response model
if (model.ScopesConsented != null && model.ScopesConsented.Any())
{
var scopes = model.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess);
}
grantedConsent = new ConsentResponse
{
RememberConsent = model.RememberConsent,
ScopesConsented = scopes.ToArray()
};
}
else
{
result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
}
}
else
{
result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
}
if (grantedConsent != null)
{
// validate return url is still valid
var request = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (request == null) return result;
// communicate outcome of consent back to identityserver
await _interaction.GrantConsentAsync(request, grantedConsent);
// indiate that's it ok to redirect back to authorization endpoint
result.RedirectUri = model.ReturnUrl;
}
else
{
// we need to redisplay the consent UI
result.ViewModel = await BuildViewModelAsync(model.ReturnUrl, model);
}
return result;
}
public async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, ConsentInputModel model = null)
{
var request = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (request != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId);
if (client != null)
{
var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested);
if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any()))
{
return CreateConsentViewModel(model, returnUrl, request, client, resources);
}
else
{
_logger.LogError("No scopes matching: {0}", request.ScopesRequested.Aggregate((x, y) => x + ", " + y));
}
}
else
{
_logger.LogError("Invalid client id: {0}", request.ClientId);
}
}
else
{
_logger.LogError("No consent request matching request: {0}", returnUrl);
}
return null;
}
private ConsentViewModel CreateConsentViewModel(
ConsentInputModel model, string returnUrl,
AuthorizationRequest request,
Client client, Resources resources)
{
var vm = new ConsentViewModel();
vm.RememberConsent = model?.RememberConsent ?? true;
vm.ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>();
vm.ReturnUrl = returnUrl;
vm.ClientName = client.ClientName;
vm.ClientUrl = client.ClientUri;
vm.ClientLogoUrl = client.LogoUri;
vm.AllowRememberConsent = client.AllowRememberConsent;
vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess)
{
vm.ResourceScopes = vm.ResourceScopes.Union(new ScopeViewModel[] {
GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null)
});
}
return vm;
}
public ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Name = identity.Name,
DisplayName = identity.DisplayName,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required,
};
}
public ScopeViewModel CreateScopeViewModel(Scope scope, bool check)
{
return new ScopeViewModel
{
Name = scope.Name,
DisplayName = scope.DisplayName,
Description = scope.Description,
Emphasize = scope.Emphasize,
Required = scope.Required,
Checked = check || scope.Required,
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
}
| 38.84456 | 182 | 0.567827 | [
"MIT"
] | zbecknell/IdentityManagerDotNet | src/IdentityManagerDotNet/Services/ConsentService.cs | 7,499 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SlackNameFixer.Persistence;
#nullable disable
namespace SlackNameFixer.Migrations.SqlServer
{
[DbContext(typeof(SlackNameFixerSqlServerContext))]
[Migration("20220321202626_InitMigrationSqlServer")]
partial class InitMigrationSqlServer
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1);
modelBuilder.Entity("SlackNameFixer.Persistence.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("AccessToken")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("PreferredFullName")
.HasColumnType("nvarchar(max)");
b.Property<string>("TeamId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("TeamId", "UserId")
.IsUnique();
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}
| 32.864407 | 84 | 0.570913 | [
"MIT"
] | evman182/SlackNameFixer | src/SlackNameFixer/SlackNameFixer/Migrations/SqlServer/20220321202626_InitMigrationSqlServer.Designer.cs | 1,941 | C# |
using System;
using System.Text;
using DigitalRune.Game;
using DigitalRune.Geometry;
using DigitalRune.Graphics;
using DigitalRune.Graphics.Rendering;
using DigitalRune.Graphics.SceneGraph;
using DigitalRune.Mathematics.Algebra;
using DigitalRune.Mathematics.Interpolation;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Sceelix.Designer.Renderer3D.Interfaces;
using Sceelix.Designer.Services;
using Sceelix.Designer.Utils;
namespace Sceelix.Designer.Renderer3D.GameObjects
{
// Draws a coordinate cross (3 colored arrows) at the world space origin
// using the debug renderer.
public class AxisCross : GameObject, IDrawableElement
{
//private readonly IServiceLocator _services;
private DebugRenderer _debugRenderer;
private IScene _scene;
public AxisCross(DebugRenderer debugRenderer, IScene scene)
{
_debugRenderer = debugRenderer;
_scene = scene;
}
public bool Enabled
{
get;
set;
}
public void Draw(RenderContext context)
{
if (Enabled)
{
//_debugRenderer.DrawAxes(Pose.Identity, 10, true);
_debugRenderer.DrawAxes(new Pose(DigitalRuneUtils.ZUpToYUpRotationMatrix), 10, true); //Pose.Identity
_debugRenderer.DrawText("X", new Vector3F(10, 0, 0), new Color(255, 0, 0), true);
_debugRenderer.DrawText("Y", new Vector3F(0, 0, -10), new Color(0, 127, 0), true);
_debugRenderer.DrawText("Z", new Vector3F(0, 11, 0), new Color(0, 0, 255), true);
}
}
protected override void OnUnload()
{
_debugRenderer = null;
}
private void CreateGizmo() //SpriteFont spriteFont
{
var gizmoNode = new SceneNode
{
Name = "Gizmo",
Children = new SceneNodeCollection(),
PoseLocal = new Pose(new Vector3F(0, 0, 0)),
ScaleLocal = new Vector3F(3f)
};
// Red arrow
var arrow = new PathFigure2F();
arrow.Segments.Add(new LineSegment2F {Point1 = new Vector2F(0, 0), Point2 = new Vector2F(1, 0)});
arrow.Segments.Add(new LineSegment2F {Point1 = new Vector2F(1, 0), Point2 = new Vector2F(0.9f, 0.02f)});
arrow.Segments.Add(new LineSegment2F {Point1 = new Vector2F(1, 0), Point2 = new Vector2F(0.9f, -0.02f)});
var figureNode = new FigureNode(arrow)
{
Name = "Gizmo X",
StrokeThickness = 2,
StrokeColor = new Vector3F(1, 0, 0),
PoseLocal = new Pose(new Vector3F(0, 0, 0))
};
gizmoNode.Children.Add(figureNode);
// Green arrow
var transformedArrow = new TransformedFigure(arrow)
{
Pose = new Pose(Matrix33F.CreateRotationZ(MathHelper.ToRadians(90)))
};
figureNode = new FigureNode(transformedArrow)
{
Name = "Gizmo Y",
StrokeThickness = 2,
StrokeColor = new Vector3F(0, 1, 0),
PoseLocal = new Pose(new Vector3F(0, 0, 0))
};
gizmoNode.Children.Add(figureNode);
// Blue arrow
transformedArrow = new TransformedFigure(arrow)
{
Pose = new Pose(Matrix33F.CreateRotationY(MathHelper.ToRadians(-90)))
};
figureNode = new FigureNode(transformedArrow)
{
Name = "Gizmo Z",
StrokeThickness = 2,
StrokeColor = new Vector3F(0, 0, 1),
PoseLocal = new Pose(new Vector3F(0, 0, 0))
};
gizmoNode.Children.Add(figureNode);
// Red arc
/*var arc = new PathFigure2F();
arc.Segments.Add(
new StrokedSegment2F(
new LineSegment2F { Point1 = new Vector2F(0, 0), Point2 = new Vector2F(1, 0), },
false));
arc.Segments.Add(
new ArcSegment2F
{
Point1 = new Vector2F(1, 0),
Point2 = new Vector2F(0, 1),
Radius = new Vector2F(1, 1)
});
arc.Segments.Add(
new StrokedSegment2F(
new LineSegment2F { Point1 = new Vector2F(0, 1), Point2 = new Vector2F(0, 0), },
false));
var transformedArc = new TransformedFigure(arc)
{
Scale = new Vector3F(0.333f),
Pose = new Pose(Matrix33F.CreateRotationY(MathHelper.ToRadians(-90)))
};
figureNode = new FigureNode(transformedArc)
{
Name = "Gizmo YZ",
StrokeThickness = 2,
StrokeColor = new Vector3F(1, 0, 0),
FillColor = new Vector3F(1, 0, 0),
FillAlpha = 0.5f,
PoseLocal = new Pose(new Vector3F(0, 0, 0))
};
gizmoNode.Children.Add(figureNode);
// Green arc
transformedArc = new TransformedFigure(arc)
{
Scale = new Vector3F(0.333f),
Pose = new Pose(Matrix33F.CreateRotationX(MathHelper.ToRadians(90)))
};
figureNode = new FigureNode(transformedArc)
{
Name = "Gizmo XZ",
StrokeThickness = 2,
StrokeColor = new Vector3F(0, 1, 0),
FillColor = new Vector3F(0, 1, 0),
FillAlpha = 0.5f,
PoseLocal = new Pose(new Vector3F(0, 0, 0))
};
gizmoNode.Children.Add(figureNode);
// Blue arc
transformedArc = new TransformedFigure(arc)
{
Scale = new Vector3F(0.333f),
};
figureNode = new FigureNode(transformedArc)
{
Name = "Gizmo XY",
StrokeThickness = 2,
StrokeColor = new Vector3F(0, 0, 1),
FillColor = new Vector3F(0, 0, 1),
FillAlpha = 0.5f,
PoseLocal = new Pose(new Vector3F(0, 0, 0))
};
gizmoNode.Children.Add(figureNode);*/
// Labels "X", "Y", "Z"
/*var spriteNode = new SpriteNode(new TextSprite("X", spriteFont))
{
Color = new Vector3F(1, 0, 0),
Origin = new Vector2F(0, 1),
PoseLocal = new Pose(new Vector3F(1, 0, 0))
};
gizmoNode.Children.Add(spriteNode);
spriteNode = new SpriteNode(new TextSprite("Y", spriteFont))
{
Color = new Vector3F(0, 1, 0),
Origin = new Vector2F(0, 1),
PoseLocal = new Pose(new Vector3F(0, 1, 0))
};
gizmoNode.Children.Add(spriteNode);
spriteNode = new SpriteNode(new TextSprite("Z", spriteFont))
{
Color = new Vector3F(0, 0, 1),
Origin = new Vector2F(0, 1),
PoseLocal = new Pose(new Vector3F(0, 0, 1))
};
gizmoNode.Children.Add(spriteNode);*/
_scene.Children.Add(gizmoNode);
}
}
} | 35.395238 | 117 | 0.520248 | [
"MIT"
] | IxxyXR/Sceelix | Source/Sceelix.Designer.Renderer3D/GameObjects/AxisCross.cs | 7,435 | C# |
#region License
//// The MIT License (MIT)
////
//// Copyright (c) 2015 Tom van der Kleij
////
//// 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
namespace Smocks.IL
{
internal enum VariableOperation
{
Read,
Write
}
} | 42.322581 | 85 | 0.721799 | [
"MIT"
] | vanderkleij/Smocks | Source/Smocks/IL/VariableOperation.cs | 1,314 | C# |
/*
* File: 18FourSum.cs
* Project: Array
* Created Date: Monday, 5th October 2020 3:15:54 pm
* Author: David Gu (macdavid313@gmail.com)
* Runtime: 336 ms, faster than 33.95% of C# online submissions for 4Sum.
* Memory Usage: 33.4 MB, less than 7.75% of C# online submissions for 4Sum.
* -----
* Last Modified: Monday, 5th October 2020 3:22:35 pm
* Modified By: David Gu (macdavid313@gmail.com>)
* -----
* Copyright (c) David Gu 2020
*/
using System;
using System.Collections.Generic;
namespace FourSum
{
public class Solution
{
public IList<IList<int>> FourSum(int[] nums, int target)
{
Array.Sort(nums);
var res = new List<IList<int>>();
var i = 0;
while (i <= nums.Length - 3)
{
var a = nums[i];
foreach (var (b, c, d) in ThreeSum(nums[(i + 1)..], target - a))
res.Add(new int[] { a, b, c, d });
while (i <= nums.Length - 3 && nums[i] == a) i += 1;
}
return res;
}
IEnumerable<ValueTuple<int, int, int>> ThreeSum(int[] nums, int target)
{
var i = 0;
while (i <= nums.Length - 2)
{
var a = nums[i];
foreach (var (b, c) in TwoSum(nums[(i + 1)..], target - a))
yield return (a, b, c);
while (i <= nums.Length - 2 && nums[i] == a) i += 1;
}
}
IEnumerable<ValueTuple<int, int>> TwoSum(int[] nums, int target)
{
var (lo, hi) = (0, nums.Length - 1);
while (lo < hi)
{
var (left, right) = (nums[lo], nums[hi]);
var sum = left + right;
if (sum < target)
while (lo < hi && nums[lo] == left) lo += 1;
else if (sum > target)
while (lo < hi && nums[hi] == right) hi -= 1;
else
{
yield return (left, right);
while (lo < hi && nums[lo] == left) lo += 1;
while (lo < hi && nums[hi] == right) hi -= 1;
}
}
}
}
} | 31.785714 | 80 | 0.440899 | [
"MIT"
] | macdavid313/LeetCode-CSharp | src/Array/18FourSum.cs | 2,225 | C# |
using Gandalan.IDAS.Client.Contracts.Contracts;
using Gandalan.IDAS.Web;
using Gandalan.IDAS.WebApi.DTO;
using System;
using System.Threading.Tasks;
namespace Gandalan.IDAS.WebApi.Client.BusinessRoutinen
{
public class ProduktFamilienWebRoutinen : WebRoutinenBase
{
public ProduktFamilienWebRoutinen(IWebApiConfig settings) : base(settings) { }
public ProduktFamilieDTO[] GetAll(bool includeVarianten)
{
if (Login())
return Get<ProduktFamilieDTO[]>($"ProduktFamilie?includeVarianten={includeVarianten}&includeUIDefs={includeVarianten}&maxLevel=99");
throw new ApiException("Login fehlgeschlagen");
}
public ProduktFamilieDTO SaveProduktFamilie(ProduktFamilieDTO produktFamilie)
{
if (Login())
return Put<ProduktFamilieDTO>($"ProduktFamilie/{produktFamilie.ProduktFamilieGuid}", produktFamilie);
throw new ApiException("Login fehlgeschlagen");
}
public async Task SaveProduktFamilieAsync(ProduktFamilieDTO produktFamilie) => await Task.Run(() => SaveProduktFamilie(produktFamilie));
public async Task<ProduktFamilieDTO[]> GetAllAsync(bool includeVarianten = true) => await Task.Run(() => GetAll(includeVarianten));
[Obsolete("Funktion 'SaveProduktFamilie()' verwenden")]
public string Save(ProduktFamilieDTO dto)
{
if (Login())
{
return Put("ProduktFamilie/" + dto.ProduktFamilieGuid.ToString(), dto);
}
return null;
}
[Obsolete("Funktion 'SaveProduktFamilieAsync()' verwenden")]
public async Task SaveAsync(ProduktFamilieDTO dto)
{
await Task.Run(() => Save(dto));
}
}
}
| 40.590909 | 148 | 0.657895 | [
"MIT"
] | Saibamen/idas-client-libs | Gandalan.IDAS.WebApi.Client/BusinessRoutinen/ProduktFamilienWebRoutinen.cs | 1,788 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Sultanlar.WUI.Pages.Siparis
{
public class SilModel : PageModel
{
public void OnGet()
{
}
}
} | 19.5 | 42 | 0.705128 | [
"MIT"
] | dogukanalan/Sultanlar | Sultanlar/Sultanlar.WUI/Pages/Siparis/Sil.cshtml.cs | 312 | C# |
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Mvc.Admin.ViewModels.FrameworkUserVms;
namespace WalkingTec.Mvvm.Admin.Api
{
[ActionDescription("用户管理")]
[ApiController]
[Route("api/_FrameworkUserBase")]
public class FrameworkUserController : BaseApiController
{
[ActionDescription("搜索")]
[HttpPost("Search")]
public string Search(FrameworkUserSearcher searcher)
{
var vm = CreateVM<FrameworkUserListVM>();
vm.Searcher = searcher;
return vm.GetJson();
}
[ActionDescription("获取")]
[HttpGet("{id}")]
public FrameworkUserVM Get(Guid id)
{
var vm = CreateVM<FrameworkUserVM>(id);
return vm;
}
[ActionDescription("新建")]
[HttpPost("Add")]
public IActionResult Add(FrameworkUserVM vm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
vm.DoAdd();
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
return Ok(vm.Entity);
}
}
}
[ActionDescription("修改")]
[HttpPut("Edit")]
public IActionResult Edit(FrameworkUserVM vm)
{
ModelState.Remove("Entity.Password");
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
vm.DoEdit(false);
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
return Ok(vm.Entity);
}
}
}
[HttpPost("BatchDelete")]
[ActionDescription("删除")]
public IActionResult BatchDelete(Guid[] ids)
{
var vm = CreateVM<FrameworkUserBatchVM>();
if (ids != null && ids.Count() > 0)
{
vm.Ids = ids;
}
else
{
return Ok();
}
if (!ModelState.IsValid || !vm.DoBatchDelete())
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
return Ok(ids.Count());
}
}
[ActionDescription("导出")]
[HttpPost("ExportExcel")]
public IActionResult ExportExcel(FrameworkUserSearcher searcher)
{
var vm = CreateVM<FrameworkUserListVM>();
vm.Searcher = searcher;
vm.SearcherMode = ListVMSearchModeEnum.Export;
var data = vm.GenerateExcel();
return File(data, "application/vnd.ms-excel", $"Export_FrameworkUse_{DateTime.Now.ToString("yyyy-MM-dd")}.xls");
}
[ActionDescription("勾选导出")]
[HttpPost("ExportExcelByIds")]
public IActionResult ExportExcelByIds(Guid[] ids)
{
var vm = CreateVM<FrameworkUserListVM>();
if (ids != null && ids.Count() > 0)
{
vm.Ids = new List<Guid>(ids);
vm.SearcherMode = ListVMSearchModeEnum.CheckExport;
}
var data = vm.GenerateExcel();
return File(data, "application/vnd.ms-excel", $"Export_FrameworkUse_{DateTime.Now.ToString("yyyy-MM-dd")}.xls");
}
[ActionDescription("下载模板")]
[HttpGet("GetExcelTemplate")]
public IActionResult GetExcelTemplate()
{
var vm = CreateVM<FrameworkUserImportVM>();
var qs = new Dictionary<string, string>();
foreach (var item in Request.Query.Keys)
{
qs.Add(item, Request.Query[item]);
}
vm.SetParms(qs);
var data = vm.GenerateTemplate(out string fileName);
return File(data, "application/vnd.ms-excel", fileName);
}
[ActionDescription("导入")]
[HttpPost("Import")]
public ActionResult Import(FrameworkUserImportVM vm)
{
if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())
{
return BadRequest(vm.GetErrorJson());
}
else
{
return Ok(vm.EntityList.Count);
}
}
[HttpGet("GetFrameworkRoles")]
[ActionDescription("获取角色")]
public ActionResult GetFrameworkRoles()
{
return Ok(DC.Set<FrameworkRole>().GetSelectListItems(LoginUserInfo?.DataPrivileges, null, x => x.RoleName));
}
[HttpGet("GetFrameworkGroups")]
[ActionDescription("获取用户组")]
public ActionResult GetFrameworkGroups()
{
return Ok(DC.Set<FrameworkGroup>().GetSelectListItems(LoginUserInfo?.DataPrivileges, null, x => x.GroupName));
}
}
}
| 29.180328 | 124 | 0.519288 | [
"MIT"
] | HowardTao/WTM | src/WalkingTec.Mvvm.Mvc.Admin/FrameworkUserBaseController.cs | 5,412 | C# |
// 20,21,11,01,12,13,22,32
namespace Assets.Scripts.Levels
{
class Advanced27 : GameLevel
{
public Advanced27()
: base("Advanced27")
{
Initialize(4, 8);
MapButtons = new int[,]
{
{LIT, GRN, OFF, LIT},
{OFF, YLW, YLW, GRN},
{GRN, YLW, YLW, OFF},
{LIT, OFF, GRN, LIT},
};
}
public override GameLevel NextLevel
{
get
{
return new Advanced31();
}
}
}
}
| 20.275862 | 43 | 0.387755 | [
"MIT"
] | magius96/ShortCircuit_Android | Assets/Scripts/Levels/Advanced/2/Advanced27.cs | 590 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS1591
#pragma warning disable CS0108
#pragma warning disable 618
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Space.Common;
using JetBrains.Space.Common.Json.Serialization;
using JetBrains.Space.Common.Json.Serialization.Polymorphism;
using JetBrains.Space.Common.Types;
namespace JetBrains.Space.Client;
public sealed class KotlinPlatform
: IPropagatePropertyAccessPath
{
public KotlinPlatform() { }
public KotlinPlatform(string name, List<string> targets)
{
Name = name;
Targets = targets;
}
private PropertyValue<string> _name = new PropertyValue<string>(nameof(KotlinPlatform), nameof(Name));
[Required]
[JsonPropertyName("name")]
public string Name
{
get => _name.GetValue();
set => _name.SetValue(value);
}
private PropertyValue<List<string>> _targets = new PropertyValue<List<string>>(nameof(KotlinPlatform), nameof(Targets), new List<string>());
[Required]
[JsonPropertyName("targets")]
public List<string> Targets
{
get => _targets.GetValue();
set => _targets.SetValue(value);
}
public void SetAccessPath(string path, bool validateHasBeenSet)
{
_name.SetAccessPath(path, validateHasBeenSet);
_targets.SetAccessPath(path, validateHasBeenSet);
}
}
| 28.28169 | 144 | 0.655378 | [
"Apache-2.0"
] | JetBrains/space-dotnet-sdk | src/JetBrains.Space.Client/Generated/Dtos/KotlinPlatform.generated.cs | 2,008 | C# |
using Domain.Post;
using Domain.ValueObjects;
using DotNetCore.Objects;
using DotNetCoreArchitecture.Domain;
using System;
using System.Collections.Generic;
using System.Text;
namespace Domain.Point
{
public class PointEntity : Entity
{
public long TotalViews { get; set; }
public Coordinate Coordinate { get; set; }
public UserEntity User { get; set; }
public long UserId { get; set; }
public DateTime Created { get; set; } = DateTime.Now;
public ICollection<PostEntity> Posts { get; private set; }
public void AddPost(PostEntity newPost)
{
Posts.Add(newPost);
}
}
}
| 23.068966 | 66 | 0.648729 | [
"MIT"
] | mark-denysenko/TagPoint | source/Domain/Point/PointEntity.cs | 669 | C# |
using System;
using System.Runtime.Serialization;
namespace Dbo
{
[DataContract]
public class User
{
#region variables
private string _login;
private string _pwd;
private string _name;
private string _firstname;
private Byte[] _picture;
private string _role;
private bool _connected;
#endregion
#region getter / setter
/// <summary>
/// indique si l'utilisateur est connecté
/// </summary>
[DataMember]
public bool Connected
{
get { return _connected; }
set { _connected = value; }
}
/// <summary>
/// role de l'utilisateur
/// </summary>
[DataMember]
public string Role
{
get { return _role; }
set { _role = value; }
}
/// <summary>
/// photos de l'utilisateur
/// </summary>
[DataMember]
public Byte[] Picture
{
get { return _picture; }
set { _picture = value; }
}
/// <summary>
/// prénom
/// </summary>
[DataMember]
public string Firstname
{
get { return _firstname; }
set { _firstname = value; }
}
/// <summary>
/// nom
/// </summary>
[DataMember]
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// mot de passe
/// </summary>
[DataMember]
public string Pwd
{
get { return _pwd; }
set { _pwd = value; }
}
/// <summary>
/// login
/// </summary>
[DataMember]
public string Login
{
get { return _login; }
set { _login = value; }
}
#endregion
}
}
| 21.358696 | 49 | 0.440204 | [
"MIT"
] | aparenton/mti-wpf | Wcf-Medical/Dbo/User.cs | 1,969 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Graphics.Backgrounds;
namespace osu.Game.Screens.Backgrounds
{
public class BackgroundScreenCustom : BackgroundScreen
{
private readonly string textureName;
public BackgroundScreenCustom(string textureName)
{
this.textureName = textureName;
AddInternal(new Background(textureName));
}
public override bool Equals(BackgroundScreen other)
{
if (other is BackgroundScreenCustom backgroundScreenCustom)
return base.Equals(other) && textureName == backgroundScreenCustom.textureName;
return false;
}
}
}
| 30.62963 | 96 | 0.649335 | [
"MIT"
] | 02Naitsirk/osu | osu.Game/Screens/Backgrounds/BackgroundScreenCustom.cs | 803 | C# |
#region License
// Copyright (c) 2019 Teramine Ltd
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace Teramine.Interconnect.Models
{
public class ConnectionDescriptor
{
public Version ProtocolVersion { get; set; }
public int MaxFrameSize { get; set; }
public string? Error { get; set; }
public Dictionary<string, string> Data { get; set; }
public ConnectionDescriptor()
{
Data = new Dictionary<string, string>();
}
}
}
| 36.088889 | 68 | 0.721059 | [
"MIT"
] | JamesFinney/Interconnect | Teramine.Interconnect/Models/ConnectionDescriptor.cs | 1,626 | 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.
// ----------------------------------------------------------------------------------
using System;
using Microsoft.Azure.Commands.KeyVault.Models;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
using System.Text;
using System.Xml;
namespace Microsoft.Azure.Commands.KeyVault
{
[Cmdlet( VerbsCommon.Set, CmdletNoun.AzureKeyVaultManagedStorageSasDefinition,
SupportsShouldProcess = true,
HelpUri = Constants.KeyVaultHelpUri,
DefaultParameterSetName = ParameterSetRawSas )]
[OutputType( typeof( ManagedStorageSasDefinition ) )]
public partial class SetAzureKeyVaultManagedStorageSasDefinition : KeyVaultCmdletBase
{
private const string ParameterSetRawSas = "RawSas";
[Parameter( Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Vault name. Cmdlet constructs the FQDN of a vault based on the name and currently selected environment." )]
[ValidateNotNullOrEmpty]
public string VaultName { get; set; }
[Parameter( Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Key Vault managed storage account name. Cmdlet constructs the FQDN of a managed storage account name from vault name, currently " +
"selected environment and manged storage account name." )]
[ValidateNotNullOrEmpty]
[Alias( Constants.StorageAccountName )]
public string AccountName { get; set; }
[Parameter( Mandatory = true,
Position = 2,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Storage sas definition name. Cmdlet constructs the FQDN of a storage sas definition from vault name, currently " +
"selected environment, storage account name and sas definition name." )]
[ValidateNotNullOrEmpty]
[Alias( Constants.SasDefinitionName )]
public string Name { get; set; }
[Parameter( Mandatory = true,
Position = 3,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Sas definition parameters that will be used to create the sas token.",
ParameterSetName = ParameterSetRawSas )]
[Obsolete("-Parameter will be removed and replaced by -TemplateUri and -SasType in May 2018")]
[ValidateNotNull]
public Hashtable Parameter { get; set; }
[Parameter( Mandatory = false,
HelpMessage = "Disables the use of sas definition for generation of sas token." )]
public SwitchParameter Disable { get; set; }
[Parameter( Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "A hashtable representing tags of sas definition." )]
[Alias( Constants.TagsAlias )]
public Hashtable Tag { get; set; }
#region Common SAS Arguments
private const string TargetStorageVersionHelpMessage = "Specifies the signed storage service version to use to authenticate requests made with the SAS token.";
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocAccountSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceBlobSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceContainerSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceFileSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceShareSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceQueueSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceTableSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceBlobSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceContainerSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceFileSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceShareSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceQueueSas )]
[Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceTableSas )]
[ValidateNotNullOrEmpty]
public string TargetStorageVersion
{
get { return _targetStorageVersion; }
set { _targetStorageVersion = value; }
}
private string _targetStorageVersion = "2016-05-31"; // default version
private static class SharedAccessProtocols
{
public const string HttpsOnly = "HttpsOnly";
public const string HttpsOrHttp = "HttpsOrHttp";
}
private const string ProtocolHelpMessage = "Protocol can be used in the request with the SAS token. Possbile values include 'HttpsOnly','HttpsOrHttp'";
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocAccountSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceBlobSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceContainerSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceFileSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceShareSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceQueueSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceTableSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceBlobSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceContainerSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceFileSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceShareSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceQueueSas )]
[Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceTableSas )]
[ValidateNotNull]
[ValidateSet( SharedAccessProtocols.HttpsOnly, SharedAccessProtocols.HttpsOrHttp )]
public string Protocol { get; set; }
// ReSharper disable once InconsistentNaming
private const string IPAddressOrRangeHelpMessage = "IP, or IP range ACL (access control list) of the request that would be accepted by Azure Storage. E.g. '168.1.5.65' or '168.1.5.60-168.1.5.70'";
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocAccountSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceBlobSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceContainerSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceFileSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceShareSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceQueueSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceTableSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceBlobSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceContainerSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceFileSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceShareSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceQueueSas )]
[Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceTableSas )]
[ValidateNotNullOrEmpty]
// ReSharper disable once InconsistentNaming
public string IPAddressOrRange { get; set; }
private const string ValidityPeriodHelpMessage = "Validity period that will get used to set the expiry time of sas token from the time it gets generated";
[Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocAccountSas )]
[Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceBlobSas )]
[Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceContainerSas )]
[Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceShareSas )]
[Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceFileSas )]
[Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceQueueSas )]
[Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceTableSas )]
[ValidateNotNull]
public TimeSpan? ValidityPeriod { get; set; }
private const string PermissionsMessage = "Permissions. Possible values include 'Add','Create','Delete','List','Process','Query','Read','Update','Write'";
[Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocAccountSas )]
[Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceBlobSas )]
[Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceContainerSas )]
[Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceFileSas )]
[Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceShareSas )]
[Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceQueueSas )]
[Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceTableSas )]
[ValidateSet( SasPermissions.Add, SasPermissions.Create, SasPermissions.Delete, SasPermissions.List, SasPermissions.Process, SasPermissions.Read, SasPermissions.Query, SasPermissions.Update, SasPermissions.Write )]
[ValidateNotNull]
public string[] Permission { get; set; }
protected KeyValuePair<string, string>? TargetStorageVersionParameter
{
get
{
if ( string.IsNullOrWhiteSpace( TargetStorageVersion ) ) return null;
return new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedVersion, TargetStorageVersion );
}
}
protected KeyValuePair<string, string>? ProtocolParameter
{
get
{
if ( string.IsNullOrWhiteSpace( Protocol ) ) return null;
if ( Protocol.Equals( SharedAccessProtocols.HttpsOnly, StringComparison.OrdinalIgnoreCase ) )
return new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedProtocols, "https" );
if ( Protocol.Equals( SharedAccessProtocols.HttpsOrHttp, StringComparison.OrdinalIgnoreCase ) )
return new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedProtocols, "https,http" );
throw new ArgumentOutOfRangeException();
}
}
// ReSharper disable once InconsistentNaming
protected KeyValuePair<string, string>? IPAddressOrRangeParameter
{
get
{
if ( string.IsNullOrWhiteSpace( IPAddressOrRange ) ) return null;
return new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedIp, IPAddressOrRange );
}
}
protected KeyValuePair<string, string>? ValidityPeriodParameter
{
get
{
if ( ValidityPeriod == null ) return null;
return new KeyValuePair<string, string>( SasDefinitionParameterConstants.ValidityPeriod, XmlConvert.ToString( ValidityPeriod.Value ) );
}
}
protected void AddIfNotNull( KeyValuePair<string, string>? keyVaultPair, IDictionary<string, string> targetDictionary )
{
if ( keyVaultPair != null ) targetDictionary.Add( keyVaultPair.Value.Key, keyVaultPair.Value.Value );
}
private static class SasPermissions
{
public const string Read = "Read";
public const string Write = "Write";
public const string Delete = "Delete";
public const string List = "List";
public const string Add = "Add";
public const string Create = "Create";
public const string Update = "Update";
public const string Process = "Process";
public const string Query = "Query";
}
private KeyValuePair<string, string>? PermissionParameter
{
get
{
if ( Permission == null || Permission.Length == 0 ) return null;
var builder = new StringBuilder();
var permissionsSet = new HashSet<string>( Permission, StringComparer.OrdinalIgnoreCase );
if ( ParameterSetName.Equals( ParameterSetAdhocAccountSas ) )
{
//order is important here
if ( permissionsSet.Contains( SasPermissions.Read ) ) builder.Append( "r" );
if ( permissionsSet.Contains( SasPermissions.Write ) ) builder.Append( "w" );
if ( permissionsSet.Contains( SasPermissions.Delete ) ) builder.Append( "d" );
if ( permissionsSet.Contains( SasPermissions.List ) ) builder.Append( "l" );
if ( permissionsSet.Contains( SasPermissions.Add ) ) builder.Append( "a" );
if ( permissionsSet.Contains( SasPermissions.Create ) ) builder.Append( "c" );
if ( permissionsSet.Contains( SasPermissions.Update ) ) builder.Append( "u" );
if ( permissionsSet.Contains( SasPermissions.Process ) ) builder.Append( "p" );
// query is not allowed with account sas
if ( permissionsSet.Contains( SasPermissions.Query ) )
throw new ArgumentException( string.Format( CultureInfo.InvariantCulture,
Properties.Resources.InvalidSasPermission, SasPermissions.Query ) );
}
else
{
//order is important here
if ( permissionsSet.Contains( SasPermissions.Query ) ) builder.Append( "r" );
if ( permissionsSet.Contains( SasPermissions.Read ) ) builder.Append( "r" );
if ( permissionsSet.Contains( SasPermissions.Add ) ) builder.Append( "a" );
if ( permissionsSet.Contains( SasPermissions.Create ) ) builder.Append( "c" );
if ( permissionsSet.Contains( SasPermissions.Write ) ) builder.Append( "w" );
if ( permissionsSet.Contains( SasPermissions.Update ) ) builder.Append( "u" );
if ( permissionsSet.Contains( SasPermissions.Delete ) ) builder.Append( "d" );
if ( permissionsSet.Contains( SasPermissions.List ) ) builder.Append( "l" );
if ( permissionsSet.Contains( SasPermissions.Process ) ) builder.Append( "p" );
}
return new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedPermissions, builder.ToString() );
}
}
#endregion
private IDictionary<string, string> GetParameters()
{
switch ( ParameterSetName )
{
case ParameterSetRawSas:
{
var dictionary = new Dictionary<string, string>();
#pragma warning disable CS0618
foreach ( DictionaryEntry p in Parameter )
#pragma warning restore CS0618
{
if ( p.Key == null || string.IsNullOrEmpty( p.Key.ToString() ) )
throw new ArgumentException( "An invalid parameter was specified." );
dictionary[p.Key.ToString()] = ( p.Value == null ) ? string.Empty : p.Value.ToString();
}
return dictionary;
}
case ParameterSetAdhocAccountSas:
return GetParameters( SasDefinitionParameterConstants.AccountSasTypeValue, null, null );
case ParameterSetAdhocServiceContainerSas:
case ParameterSetStoredPolicyServiceContainerSas:
return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeBlobValue, "c" );
case ParameterSetAdhocServiceBlobSas:
case ParameterSetStoredPolicyServiceBlobSas:
return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeBlobValue, "b" );
case ParameterSetAdhocServiceShareSas:
case ParameterSetStoredPolicyServiceShareSas:
return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeFileValue, "s" );
case ParameterSetAdhocServiceFileSas:
case ParameterSetStoredPolicyServiceFileSas:
return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeFileValue, "f" );
case ParameterSetAdhocServiceTableSas:
case ParameterSetStoredPolicyServiceTableSas:
return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeTableValue, null );
case ParameterSetAdhocServiceQueueSas:
case ParameterSetStoredPolicyServiceQueueSas:
return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeQueueValue, null );
default:
throw new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, "Invalid parameter set {0}", ParameterSetName ) );
}
}
private IDictionary<string, string> GetParameters( string sasType, string serviceSasType, string resourceType )
{
var parameters = new Dictionary<string, string>();
AddIfNotNull( new KeyValuePair<string, string>( SasDefinitionParameterConstants.SasType, sasType ), parameters );
AddIfNotNull( string.IsNullOrWhiteSpace( serviceSasType ) ? (KeyValuePair<string, string>?) null : new KeyValuePair<string, string>( SasDefinitionParameterConstants.ServiceSasType, serviceSasType ), parameters );
AddIfNotNull( TargetStorageVersionParameter, parameters );
AddIfNotNull( ProtocolParameter, parameters );
AddIfNotNull( IPAddressOrRangeParameter, parameters );
AddIfNotNull( ValidityPeriodParameter, parameters );
AddIfNotNull( ServicesParameter, parameters );
AddIfNotNull( ResourceTypeParameter, parameters );
AddIfNotNull( string.IsNullOrWhiteSpace( resourceType ) ? (KeyValuePair<string, string>?) null : new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedResourceTypes, resourceType ), parameters );
AddIfNotNull( PermissionParameter, parameters );
AddIfNotNull( ApiVersionParameter, parameters );
AddIfNotNull( BlobParameter, parameters );
AddIfNotNull( ContainerParameter, parameters );
AddIfNotNull( PathParameter, parameters );
AddIfNotNull( ShareParameter, parameters );
AddIfNotNull( QueueParameter, parameters );
AddIfNotNull( TableParameter, parameters );
AddIfNotNull( PolicyParamater, parameters );
AddIfNotNull( SharedAccessBlobHeaderCacheControlParameter, parameters );
AddIfNotNull( SharedAccessBlobHeaderContentDispositionParameter, parameters );
AddIfNotNull( SharedAccessBlobHeaderContentEncodingParameter, parameters );
AddIfNotNull( SharedAccessBlobHeaderContentLanguageParameter, parameters );
AddIfNotNull( SharedAccessBlobHeaderContentTypeParameter, parameters );
AddIfNotNull( StartPartitionKeyParameter, parameters );
AddIfNotNull( EndPartitionKeyParameter, parameters );
AddIfNotNull( StartRowKeyParameter, parameters );
AddIfNotNull( EndRowKeyParameter, parameters );
return parameters;
}
public override void ExecuteCmdlet()
{
if ( ShouldProcess( Name, Properties.Resources.SetManagedStorageSasDefinition ) )
{
var sasDefinition = DataServiceClient.SetManagedStorageSasDefinition( VaultName,
AccountName,
Name,
GetParameters(),
new ManagedStorageSasDefinitionAttributes( !Disable.IsPresent ),
Tag );
WriteObject( sasDefinition );
}
}
}
}
| 65.027397 | 226 | 0.675163 | [
"MIT"
] | CHEEKATLAPRADEEP/azure-powershell | src/ResourceManager/KeyVault/Commands.KeyVault/Commands/ManagedStorageAccounts/SetAzureKeyVaultManagedStorageSasDefinition.cs | 23,373 | C# |
//------------------------------------------------------------------------------
// <copyright file="SavedSearchProvider.cs" company="Aras Corporation">
// © 2017-2019 Aras Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Xml;
namespace Aras.VS.MethodPlugin.ItemSearch
{
public class SavedSearchProvider : ISavedSearchProvider
{
private readonly dynamic innovatorInstance;
private readonly Dictionary<string, List<SavedSearch>> cachedSavedSearches = new Dictionary<string, List<SavedSearch>>();
public SavedSearchProvider(dynamic innovatorInstance)
{
if (innovatorInstance == null) throw new ArgumentNullException(nameof(innovatorInstance));
this.innovatorInstance = innovatorInstance;
}
public List<SavedSearch> GetSavedSearch(string itemTypeName)
{
List<SavedSearch> resultList;
if (!cachedSavedSearches.TryGetValue(itemTypeName, out resultList))
{
resultList = new List<SavedSearch>();
dynamic savedSearches = innovatorInstance.newItem();
savedSearches.loadAML(string.Format(@"
<AML>
<Item type=""SavedSearch"" action=""get"">
<itname>{0}</itname>
<auto_saved>0</auto_saved>
</Item>
</AML>", itemTypeName));
savedSearches = savedSearches.apply();
var searchesCount = savedSearches.getItemCount();
for (int i = 0; i < searchesCount; i++)
{
var search = new SavedSearch();
var savedSearch = savedSearches.getItemByIndex(i);
search.SearchId = savedSearch.getID();
search.SearchName = savedSearch.getProperty("label");
search.ItemName = itemTypeName;
string criteria = savedSearch.getProperty("criteria");
if (!string.IsNullOrEmpty(criteria))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(criteria);
var properties = doc.FirstChild.ChildNodes;
foreach (XmlNode prop in properties)
{
var propertyInfo = new ItemSearchPropertyInfo();
propertyInfo.PropertyName = prop.Name;
propertyInfo.PropertyValue = prop.InnerText;
search.SavedSearchProperties.Add(propertyInfo);
}
}
resultList.Add(search);
}
cachedSavedSearches.Add(itemTypeName, resultList);
}
return resultList;
}
}
}
| 31.118421 | 123 | 0.652854 | [
"MIT"
] | FilenkoAndriy/ArasVSMethodPlugin | Aras.VS.MethodPlugin/ItemSearch/SavedSearchProvider.cs | 2,368 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SPD.Exceptions;
namespace SPD.GUI {
/// <summary>
/// Error Form
/// </summary>
public partial class ShowErrorForm : Form {
private SPDException spdException;
/// <summary>
/// Initializes a new instance of the <see cref="ShowErrorForm" /> class.
/// </summary>
/// <param name="spdException">The SPD exception.</param>
public ShowErrorForm(SPDException spdException) {
InitializeComponent();
this.spdException = spdException;
this.textBoxShortInfo.Text = spdException.GetShortInfo();
this.textBoxDetails.Text = spdException.GetDetailInfo();
}
private void buttonExitSPD_Click(object sender, EventArgs e) {
this.Close();
}
private void buttonCopyToClipboard_Click(object sender, EventArgs e) {
Clipboard.SetText(this.spdException.GetDetailInfo());
}
}
}
| 29 | 82 | 0.618103 | [
"CC0-1.0"
] | tgassner/SPDPatientDocumentation | SPDGUI/ShowErrorForm.cs | 1,162 | C# |
#pragma checksum "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\Account\Manage\ResetAuthenticator.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "afadf5d0524b803de7a6820d86dc80c9ce6430fb"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(RobofestWTECore.Areas.Identity.Pages.Account.Manage.Areas_Identity_Pages_Account_Manage_ResetAuthenticator), @"mvc.1.0.razor-page", @"/Areas/Identity/Pages/Account/Manage/ResetAuthenticator.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.RazorPageAttribute(@"/Areas/Identity/Pages/Account/Manage/ResetAuthenticator.cshtml", typeof(RobofestWTECore.Areas.Identity.Pages.Account.Manage.Areas_Identity_Pages_Account_Manage_ResetAuthenticator), null)]
namespace RobofestWTECore.Areas.Identity.Pages.Account.Manage
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#line 1 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\_ViewImports.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#line 2 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\_ViewImports.cshtml"
using RobofestWTECore.Areas.Identity;
#line default
#line hidden
#line 3 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\_ViewImports.cshtml"
using RobofestWTECore.Models;
#line default
#line hidden
#line 1 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\Account\_ViewImports.cshtml"
using RobofestWTECore.Areas.Identity.Pages.Account;
#line default
#line hidden
#line 1 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\Account\Manage\_ViewImports.cshtml"
using RobofestWTECore.Areas.Identity.Pages.Account.Manage;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"afadf5d0524b803de7a6820d86dc80c9ce6430fb", @"/Areas/Identity/Pages/Account/Manage/ResetAuthenticator.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"8f01af31586d4d71935a25546449a3fe9dd15655", @"/Areas/Identity/Pages/_ViewImports.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"e118981af79542720387edc66dc7e833a3977fef", @"/Areas/Identity/Pages/Account/_ViewImports.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"3bca45448dc0ec8e84b1391bf0219d887ab8b089", @"/Areas/Identity/Pages/Account/Manage/_ViewImports.cshtml")]
public class Areas_Identity_Pages_Account_Manage_ResetAuthenticator : global::Microsoft.AspNetCore.Mvc.RazorPages.Page
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("reset-authenticator-form"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-group"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#line 3 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\Account\Manage\ResetAuthenticator.cshtml"
ViewData["Title"] = "Reset authenticator key";
ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication;
#line default
#line hidden
BeginContext(168, 2, true);
WriteLiteral("\r\n");
EndContext();
BeginContext(171, 51, false);
#line 8 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\Account\Manage\ResetAuthenticator.cshtml"
Write(Html.Partial("_StatusMessage", Model.StatusMessage));
#line default
#line hidden
EndContext();
BeginContext(222, 6, true);
WriteLiteral("\r\n<h4>");
EndContext();
BeginContext(229, 17, false);
#line 9 "C:\Users\djree\source\repos\RobofestOSS\RobofestOSSWeb\RobofestWTECore\Areas\Identity\Pages\Account\Manage\ResetAuthenticator.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
EndContext();
BeginContext(246, 483, true);
WriteLiteral(@"</h4>
<div class=""alert alert-warning"" role=""alert"">
<p>
<span class=""glyphicon glyphicon-warning-sign""></span>
<strong>If you reset your authenticator key your authenticator app will not work until you reconfigure it.</strong>
</p>
<p>
This process disables 2FA until you verify your authenticator app.
If you do not complete your authenticator app configuration you may lose access to your account.
</p>
</div>
<div>
");
EndContext();
BeginContext(729, 201, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c5b821a44afe4b9c9928163cae9ad07c", async() => {
BeginContext(798, 125, true);
WriteLiteral("\r\n <button id=\"reset-authenticator-button\" class=\"btn btn-danger\" type=\"submit\">Reset authenticator key</button>\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(930, 8, true);
WriteLiteral("\r\n</div>");
EndContext();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<ResetAuthenticatorModel> Html { get; private set; }
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ResetAuthenticatorModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ResetAuthenticatorModel>)PageContext?.ViewData;
public ResetAuthenticatorModel Model => ViewData.Model;
}
}
#pragma warning restore 1591
| 66.037975 | 359 | 0.76174 | [
"MIT"
] | HDLOfficial/RobofestOSSWeb | RobofestWTECore/obj/Release/netcoreapp2.1/Razor/Areas/Identity/Pages/Account/Manage/ResetAuthenticator.cshtml.g.cs | 10,434 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class StateMachine
{
private Dictionary<int, IState> m_dictState;
private IState m_curState;
public class NextStateInfo
{
public IState.StateType stateType = IState.StateType.None;
public object mParam1;
public object mParam2;
public NextStateInfo(IState.StateType sType, object param1, object param2)
{
stateType = sType;
mParam1 = param1;
mParam2 = param2;
}
public bool isUse = false;
}
private List<NextStateInfo> m_stateInfoList;
public StateMachine()
{
m_curState = null;
m_dictState = new Dictionary<int, IState>();
m_stateInfoList = new List<NextStateInfo>();
m_stateInfoList.Add(new NextStateInfo(IState.StateType.Grounded, null, null));
m_stateInfoList.Add(new NextStateInfo(IState.StateType.None, null, null));
}
public bool RegistState(IState state)
{
if (null == state)
{
Debug.LogError("StateMachine::RegistState->state is null");
return false;
}
if (m_dictState.ContainsKey((int)state.GetStateType()))
{
Debug.LogError("StateMachine::RegistState->state had exist! state id=" + state.GetStateType());
return false;
}
m_dictState[(int)state.GetStateType()] = state;
return true;
}
public void OnEnterAniState(int hashName)
{
foreach (var item in m_dictState)
{
if (item.Value.HasStateHash(hashName))
{
item.Value.OnAniEnter(hashName);
}
}
}
public void OnExitAniState(int hashName)
{
foreach (var item in m_dictState)
{
if (item.Value.HasStateHash(hashName))
{
item.Value.OnLeave(hashName);
}
}
}
public IState GetState(int iStateId)
{
IState ret = null;
m_dictState.TryGetValue(iStateId, out ret);
return ret;
}
public bool SwitchState(IState.StateType stateType, object param1, object param2)
{
if (null != m_curState && m_curState.GetStateType() == stateType)
{
return m_curState.ExecuteStateAgain(this, param1, param2);
}
if (null != m_curState && !m_curState.mChangeState)
{
// 不可切换,等待此状态完成。
return false;
}
IState newState = null;
m_dictState.TryGetValue((int)stateType, out newState);
if (null == newState)
{
return false;
}
IState oldState = m_curState;
if (null != oldState)
{
oldState.OnLeave(0);
}
m_curState = newState;
if (null != newState)
{
newState.ExecuteState(this, oldState, param1, param2);
}
return true;
}
public bool nextState()
{
NextStateInfo nextStateInfo = null;
for (int i = m_stateInfoList.Count - 1; i >= 0; --i)
{
if (m_stateInfoList[i].stateType != IState.StateType.None)
{
nextStateInfo = m_stateInfoList[i];
if (nextStateInfo.isUse == false)
{
nextStateInfo.isUse = true;
break;
}
}
}
return SetCurrState(nextStateInfo.stateType, nextStateInfo);
}
public IState GetCurState()
{
return m_curState;
}
public bool SetCurrState(IState.StateType stateType, NextStateInfo nextStateInfo = null)
{
if (null != m_curState && m_curState.GetStateType() == stateType) return false;
IState newState = null;
m_dictState.TryGetValue((int)stateType, out newState);
if (null == newState)
{
return false;
}
IState oldState = m_curState;
if (null != m_curState) m_curState.OnLeave(0);
m_curState = newState;
if (null != m_curState)
{
if (nextStateInfo != null)
{
m_curState.ExecuteState(this, oldState, nextStateInfo.mParam1, nextStateInfo.mParam2);
}
//else
//{
// m_curState.ExecuteState(this, oldState, null, null);
//}
}
return true;
}
public void SetNextState(IState.StateType nextStateType, object param1, object param2, int index = 0)
{
if (index >= 0 && index < m_stateInfoList.Count)
{
m_stateInfoList[index].stateType = nextStateType;
m_stateInfoList[index].mParam1 = param1;
m_stateInfoList[index].mParam2 = param2;
m_stateInfoList[index].isUse = false;
}
}
public void CancelNextState(int index = 0)
{
if (index > 0 && index < m_stateInfoList.Count)
{
m_stateInfoList[index].isUse = true;
}
}
public IState.StateType GetCurStateType()
{
IState state = GetCurState();
return (null == state) ? IState.StateType.None : state.GetStateType();
}
public bool IsInState(IState.StateType StateType)
{
if (null == m_curState)
{
return false;
}
return m_curState.GetStateType() == StateType;
}
public void OnUpdate()
{
if (null != m_curState)
{
m_curState.OnUpdate();
}
}
public void OnFixedUpdate()
{
if (null != m_curState)
{
m_curState.OnFixedUpdate();
}
}
public void OnLateUpdate()
{
if (null != m_curState)
{
m_curState.OnLateUpdate();
}
}
public void OnHitEnter(Collider other)
{
if (null != m_curState)
{
m_curState.OnHitEnter(other);
}
}
}
| 24.506122 | 107 | 0.546302 | [
"MIT"
] | 164638896/ARPG | Assets/Scripts/GamePlay/State/StateMachine.cs | 6,032 | 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Printing
{
public enum PrintTicketScope
{
}
} | 39.692308 | 81 | 0.503876 | [
"MIT"
] | 00mjk/wpf | src/Microsoft.DotNet.Wpf/cycle-breakers/ReachFramework/System.Printing.PrintTicketScope.cs | 516 | C# |
using Antd2.cmds;
using Antd2.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Antd2.Jobs {
public class CheckNewDiskJob : Job {
private int _repetitionIntervalTime = (int)TimeSpan.FromSeconds(5).TotalMilliseconds;
#region [ Core Parameter ]
private bool _isRepeatable = true;
public override bool IsRepeatable {
get {
return _isRepeatable;
}
set {
value = _isRepeatable;
}
}
public override int RepetitionIntervalTime {
get {
return _repetitionIntervalTime;
}
set {
value = _repetitionIntervalTime;
}
}
public override string Name {
get {
return GetType().Name;
}
set {
value = GetType().Name;
}
}
#endregion
private static List<string> DiskList = null;
public static readonly IDictionary<string, bool> NewDiskNotify = new Dictionary<string, bool>();
public override void DoJob() {
var disks = Lsblk.GetDisks();
if (DiskList == null) {
DiskList = disks;
foreach (var disk in DiskList) {
NewDiskNotify[disk] = false;
}
}
else {
var addDisks = disks.Except(DiskList).ToList();
foreach (var disk in addDisks) {
NewDiskNotify[disk] = true;
}
//var removedDisks = DiskList.Except(disks).ToList();
DiskList = disks;
}
}
}
}
| 24.943662 | 104 | 0.492942 | [
"BSD-3-Clause"
] | Anthilla/Antd | Antd2/Jobs/CheckNewDiskJob.cs | 1,773 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.