content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Newtonsoft.Json; using Volo.Abp; namespace LINGYUN.Abp.WeChat.Token { /// <summary> /// 微信访问令牌返回对象 /// </summary> public class WeChatTokenResponse { /// <summary> /// 错误码 /// </summary> [JsonProperty("errcode")] public int ErrorCode { get; set; } /// <summary> /// 错误消息 /// </summary> [JsonProperty("errmsg")] public string ErrorMessage { get; set; } /// <summary> /// 访问令牌 /// </summary> [JsonProperty("access_token")] public string AccessToken { get; set; } /// <summary> /// 过期时间,单位(s) /// </summary> [JsonProperty("expires_in")] public int ExpiresIn { get; set; } public WeChatToken ToWeChatToken() { if(ErrorCode != 0) { throw new AbpException(ErrorMessage); } return new WeChatToken(AccessToken, ExpiresIn); } } }
24.809524
60
0.473129
[ "MIT" ]
ZhaoYis/abp-next-admin
aspnet-core/modules/wechat/LINGYUN.Abp.WeChat/LINGYUN/Abp/WeChat/Token/WeChatTokenResponse.cs
1,098
C#
using UnityEngine; using UnityEngine.UI; public class InputFieldPrefSetUtility : MonoBehaviour { public string valueKey, defaultValue; private InputField inputField; private void Start () { inputField = GetComponent<InputField>(); inputField.text = PlayerPrefs.GetString(valueKey, defaultValue); inputField.onEndEdit.AddListener(delegate{ PlayerPrefs.SetString(valueKey, inputField.text); }); } }
19.090909
66
0.769048
[ "MIT" ]
harroo/UtilityBat
UtilityBat/UI/InputField/InputFieldPrefSetUtility.cs
420
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("CiscoAsaNetAclParserTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CiscoAsaNetAclParserTest")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("76ebc02c-acf9-41f7-bc22-c6f7939e1d52")] // 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.1")] [assembly: AssemblyFileVersion("1.0.0.1")]
38.405405
84
0.749472
[ "Apache-2.0" ]
frostyfosse/CiscoAsaNatAclParser
Source/CiscoAsaNetAclParserTest/Properties/AssemblyInfo.cs
1,424
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.InMemory.FunctionalTests; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Conventions; using Microsoft.EntityFrameworkCore.Storage.Internal; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace Microsoft.EntityFrameworkCore.InMemory.Tests { public class InMemoryDatabaseCreatorTest { [Fact] public void EnsureCreated_returns_true_for_first_use_of_persistent_database_and_false_thereafter() { var serviceProvider = InMemoryTestHelpers.Instance.CreateServiceProvider(); var model = CreateModel(); var creator = new InMemoryDatabaseCreator(CreateStore(serviceProvider, persist: true), model); Assert.True(creator.EnsureCreated()); Assert.False(creator.EnsureCreated()); Assert.False(creator.EnsureCreated()); creator = new InMemoryDatabaseCreator(CreateStore(serviceProvider, persist: true), model); Assert.False(creator.EnsureCreated()); } [Fact] public async Task EnsureCreatedAsync_returns_true_for_first_use_of_persistent_database_and_false_thereafter() { var serviceProvider = InMemoryTestHelpers.Instance.CreateServiceProvider(); var model = CreateModel(); var creator = new InMemoryDatabaseCreator(CreateStore(serviceProvider, persist: true), model); Assert.True(await creator.EnsureCreatedAsync()); Assert.False(await creator.EnsureCreatedAsync()); Assert.False(await creator.EnsureCreatedAsync()); creator = new InMemoryDatabaseCreator(CreateStore(serviceProvider, persist: true), model); Assert.False(await creator.EnsureCreatedAsync()); } private static IInMemoryDatabase CreateStore(IServiceProvider serviceProvider, bool persist) { var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseInMemoryDatabase(nameof(InMemoryDatabaseCreatorTest)); return InMemoryTestHelpers.Instance.CreateContextServices(serviceProvider, optionsBuilder.Options).GetRequiredService<IInMemoryDatabase>(); } [Fact] public async Task EnsureDeleted_clears_all_in_memory_data_and_returns_true() { await Delete_clears_all_in_memory_data_test(async: false); } [Fact] public async Task EnsureDeletedAsync_clears_all_in_memory_data_and_returns_true() { await Delete_clears_all_in_memory_data_test(async: true); } private static async Task Delete_clears_all_in_memory_data_test(bool async) { using (var context = new FraggleContext()) { context.Fraggles.AddRange(new Fraggle { Id = 1, Name = "Gobo" }, new Fraggle { Id = 2, Name = "Monkey" }, new Fraggle { Id = 3, Name = "Red" }, new Fraggle { Id = 4, Name = "Wembley" }, new Fraggle { Id = 5, Name = "Boober" }, new Fraggle { Id = 6, Name = "Uncle Traveling Matt" }); await context.SaveChangesAsync(); } using (var context = new FraggleContext()) { Assert.Equal(6, await context.Fraggles.CountAsync()); if (async) { Assert.True(await context.Database.EnsureDeletedAsync()); } else { Assert.True(context.Database.EnsureDeleted()); } Assert.Equal(0, await context.Fraggles.CountAsync()); } using (var context = new FraggleContext()) { Assert.Equal(0, await context.Fraggles.CountAsync()); if (async) { Assert.False(await context.Database.EnsureDeletedAsync()); } else { Assert.False(context.Database.EnsureDeleted()); } } } private class FraggleContext : DbContext { public DbSet<Fraggle> Fraggles { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder.UseInMemoryDatabase(nameof(FraggleContext)); } private class Fraggle { public int Id { get; set; } public string Name { get; set; } } private static IModel CreateModel() { var modelBuilder = new ModelBuilder(new ConventionSet()); modelBuilder.Entity<Test>(b => { b.HasKey(c => c.Id); b.Property(c => c.Name); }); return modelBuilder.Model; } private class Test { public int Id { get; set; } public string Name { get; set; } } } }
36.426573
298
0.610482
[ "Apache-2.0" ]
pmiddleton/EntityFramework
test/EFCore.InMemory.Tests/InMemoryDatabaseCreatorTest.cs
5,209
C#
using System; using System.Collections; using System.Globalization; using System.IO; using System.Text.Encodings.Web; using System.Threading.Tasks; namespace Fluid.Values { public sealed class ObjectValue : FluidValue { private static readonly char[] MemberSeparators = new [] { '.' }; private readonly object _value; public ObjectValue(object value) { _value = value; } public override FluidValues Type => FluidValues.Object; public override bool Equals(FluidValue other) { if (other.IsNil()) { switch (_value) { case ICollection collection: return collection.Count == 0; case IEnumerable enumerable: return !enumerable.GetEnumerator().MoveNext(); } return false; } return other is ObjectValue && ((ObjectValue)other)._value == _value; } public override ValueTask<FluidValue> GetValueAsync(string name, TemplateContext context) { static async ValueTask<FluidValue> Awaited( IAsyncMemberAccessor asyncAccessor, object value, string n, TemplateContext ctx) { return Create(await asyncAccessor.GetAsync(value, n, ctx)); } if (name.Contains(".")) { var accessor = context.MemberAccessStrategy.GetAccessor(_value.GetType(), name); // Try to access the property with dots inside if (accessor != null) { if (accessor is IAsyncMemberAccessor asyncAccessor) { return Awaited(asyncAccessor, _value, name, context); } var directValue = accessor.Get(_value, name, context); if (directValue != null) { return new ValueTask<FluidValue>(FluidValue.Create(directValue)); } } // Otherwise split the name in different segments return GetNestedValueAsync(name, context); } else { var accessor = context.MemberAccessStrategy.GetAccessor(_value.GetType(), name); if (accessor != null) { if (accessor is IAsyncMemberAccessor asyncAccessor) { return Awaited(asyncAccessor, _value, name, context); } return new ValueTask<FluidValue>(FluidValue.Create(accessor.Get(_value, name, context))); } } return new ValueTask<FluidValue>(NilValue.Instance); } private async ValueTask<FluidValue> GetNestedValueAsync(string name, TemplateContext context) { var members = name.Split(MemberSeparators); object target = _value; foreach (var prop in members) { if (target == null) { return NilValue.Instance; } var accessor = context.MemberAccessStrategy.GetAccessor(target.GetType(), prop); if (accessor == null) { return NilValue.Instance; } if (accessor is IAsyncMemberAccessor asyncAccessor) { target = await asyncAccessor.GetAsync(target, prop, context); } else { target = accessor.Get(target, prop, context); } } return FluidValue.Create(target); } public override ValueTask<FluidValue> GetIndexAsync(FluidValue index, TemplateContext context) { return GetValueAsync(index.ToStringValue(), context); } public override bool ToBooleanValue() { return _value != null; } public override decimal ToNumberValue() { return Convert.ToDecimal(_value); } public override void WriteTo(TextWriter writer, TextEncoder encoder, CultureInfo cultureInfo) { if (writer == null) { ExceptionHelper.ThrowArgumentNullException(nameof(writer)); } if (encoder == null) { ExceptionHelper.ThrowArgumentNullException(nameof(encoder)); } encoder.Encode(writer, _value.ToString()); } public override string ToStringValue() { return Convert.ToString(_value); } public override object ToObjectValue() { return _value; } public override bool Equals(object other) { // The is operator will return false if null if (other is ObjectValue otherValue) { return _value.Equals(otherValue._value); } return false; } public override int GetHashCode() { return _value.GetHashCode(); } } }
29.233696
109
0.508459
[ "MIT" ]
CharlotteA44/fluid
Fluid/Values/ObjectValue.cs
5,381
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.cloudesl.Transform; using Aliyun.Acs.cloudesl.Transform.V20200201; namespace Aliyun.Acs.cloudesl.Model.V20200201 { public class BatchInsertItemsRequest : RpcAcsRequest<BatchInsertItemsResponse> { public BatchInsertItemsRequest() : base("cloudesl", "2020-02-01", "BatchInsertItems", "cloudesl", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.cloudesl.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.cloudesl.Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string extraParams; private string storeId; private bool? syncByItemId; private List<ItemInfo> itemInfos = new List<ItemInfo>(){ }; public string ExtraParams { get { return extraParams; } set { extraParams = value; DictionaryUtil.Add(BodyParameters, "ExtraParams", value); } } public string StoreId { get { return storeId; } set { storeId = value; DictionaryUtil.Add(BodyParameters, "StoreId", value); } } public bool? SyncByItemId { get { return syncByItemId; } set { syncByItemId = value; DictionaryUtil.Add(BodyParameters, "SyncByItemId", value.ToString()); } } public List<ItemInfo> ItemInfos { get { return itemInfos; } set { itemInfos = value; for (int i = 0; i < itemInfos.Count; i++) { DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".MemberPrice", itemInfos[i].MemberPrice); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ActionPrice", itemInfos[i].ActionPrice); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".BeSourceCode", itemInfos[i].BeSourceCode); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".BrandName", itemInfos[i].BrandName); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".PromotionStart", itemInfos[i].PromotionStart); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".PriceUnit", itemInfos[i].PriceUnit); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".Rank", itemInfos[i].Rank); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ItemInfoIndex", itemInfos[i].ItemInfoIndex); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ItemBarCode", itemInfos[i].ItemBarCode); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureK", itemInfos[i].CustomizeFeatureK); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureL", itemInfos[i].CustomizeFeatureL); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureM", itemInfos[i].CustomizeFeatureM); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".BePromotion", itemInfos[i].BePromotion); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureN", itemInfos[i].CustomizeFeatureN); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureO", itemInfos[i].CustomizeFeatureO); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".PromotionEnd", itemInfos[i].PromotionEnd); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ItemTitle", itemInfos[i].ItemTitle); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureC", itemInfos[i].CustomizeFeatureC); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureD", itemInfos[i].CustomizeFeatureD); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ItemQrCode", itemInfos[i].ItemQrCode); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureE", itemInfos[i].CustomizeFeatureE); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".InventoryStatus", itemInfos[i].InventoryStatus); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".PromotionReason", itemInfos[i].PromotionReason); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureF", itemInfos[i].CustomizeFeatureF); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureG", itemInfos[i].CustomizeFeatureG); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureH", itemInfos[i].CustomizeFeatureH); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureI", itemInfos[i].CustomizeFeatureI); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureJ", itemInfos[i].CustomizeFeatureJ); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureA", itemInfos[i].CustomizeFeatureA); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CustomizeFeatureB", itemInfos[i].CustomizeFeatureB); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".SuggestPrice", itemInfos[i].SuggestPrice); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ForestFirstId", itemInfos[i].ForestFirstId); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ProductionPlace", itemInfos[i].ProductionPlace); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".Manufacturer", itemInfos[i].Manufacturer); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".SourceCode", itemInfos[i].SourceCode); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ItemId", itemInfos[i].ItemId); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".BeMember", itemInfos[i].BeMember); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".TemplateSceneId", itemInfos[i].TemplateSceneId); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".SalesPrice", itemInfos[i].SalesPrice); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".OriginalPrice", itemInfos[i].OriginalPrice); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ItemShortTitle", itemInfos[i].ItemShortTitle); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ForestSecondId", itemInfos[i].ForestSecondId); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ItemPicUrl", itemInfos[i].ItemPicUrl); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".SupplierName", itemInfos[i].SupplierName); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".Material", itemInfos[i].Material); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".ModelNumber", itemInfos[i].ModelNumber); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".SaleSpec", itemInfos[i].SaleSpec); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".CategoryName", itemInfos[i].CategoryName); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".TaxFee", itemInfos[i].TaxFee); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".EnergyEfficiency", itemInfos[i].EnergyEfficiency); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".PromotionText", itemInfos[i].PromotionText); DictionaryUtil.Add(BodyParameters,"ItemInfo." + (i + 1) + ".SkuId", itemInfos[i].SkuId); } } } public class ItemInfo { private int? memberPrice; private int? actionPrice; private bool? beSourceCode; private string brandName; private string promotionStart; private string priceUnit; private string rank; private int? itemInfoIndex; private string itemBarCode; private string customizeFeatureK; private string customizeFeatureL; private string customizeFeatureM; private bool? bePromotion; private string customizeFeatureN; private string customizeFeatureO; private string promotionEnd; private string itemTitle; private string customizeFeatureC; private string customizeFeatureD; private string itemQrCode; private string customizeFeatureE; private string inventoryStatus; private string promotionReason; private string customizeFeatureF; private string customizeFeatureG; private string customizeFeatureH; private string customizeFeatureI; private string customizeFeatureJ; private string customizeFeatureA; private string customizeFeatureB; private int? suggestPrice; private string forestFirstId; private string productionPlace; private string manufacturer; private string sourceCode; private string itemId; private bool? beMember; private string templateSceneId; private int? salesPrice; private int? originalPrice; private string itemShortTitle; private string forestSecondId; private string itemPicUrl; private string supplierName; private string material; private string modelNumber; private string saleSpec; private string categoryName; private string taxFee; private string energyEfficiency; private string promotionText; private string skuId; public int? MemberPrice { get { return memberPrice; } set { memberPrice = value; } } public int? ActionPrice { get { return actionPrice; } set { actionPrice = value; } } public bool? BeSourceCode { get { return beSourceCode; } set { beSourceCode = value; } } public string BrandName { get { return brandName; } set { brandName = value; } } public string PromotionStart { get { return promotionStart; } set { promotionStart = value; } } public string PriceUnit { get { return priceUnit; } set { priceUnit = value; } } public string Rank { get { return rank; } set { rank = value; } } public int? ItemInfoIndex { get { return itemInfoIndex; } set { itemInfoIndex = value; } } public string ItemBarCode { get { return itemBarCode; } set { itemBarCode = value; } } public string CustomizeFeatureK { get { return customizeFeatureK; } set { customizeFeatureK = value; } } public string CustomizeFeatureL { get { return customizeFeatureL; } set { customizeFeatureL = value; } } public string CustomizeFeatureM { get { return customizeFeatureM; } set { customizeFeatureM = value; } } public bool? BePromotion { get { return bePromotion; } set { bePromotion = value; } } public string CustomizeFeatureN { get { return customizeFeatureN; } set { customizeFeatureN = value; } } public string CustomizeFeatureO { get { return customizeFeatureO; } set { customizeFeatureO = value; } } public string PromotionEnd { get { return promotionEnd; } set { promotionEnd = value; } } public string ItemTitle { get { return itemTitle; } set { itemTitle = value; } } public string CustomizeFeatureC { get { return customizeFeatureC; } set { customizeFeatureC = value; } } public string CustomizeFeatureD { get { return customizeFeatureD; } set { customizeFeatureD = value; } } public string ItemQrCode { get { return itemQrCode; } set { itemQrCode = value; } } public string CustomizeFeatureE { get { return customizeFeatureE; } set { customizeFeatureE = value; } } public string InventoryStatus { get { return inventoryStatus; } set { inventoryStatus = value; } } public string PromotionReason { get { return promotionReason; } set { promotionReason = value; } } public string CustomizeFeatureF { get { return customizeFeatureF; } set { customizeFeatureF = value; } } public string CustomizeFeatureG { get { return customizeFeatureG; } set { customizeFeatureG = value; } } public string CustomizeFeatureH { get { return customizeFeatureH; } set { customizeFeatureH = value; } } public string CustomizeFeatureI { get { return customizeFeatureI; } set { customizeFeatureI = value; } } public string CustomizeFeatureJ { get { return customizeFeatureJ; } set { customizeFeatureJ = value; } } public string CustomizeFeatureA { get { return customizeFeatureA; } set { customizeFeatureA = value; } } public string CustomizeFeatureB { get { return customizeFeatureB; } set { customizeFeatureB = value; } } public int? SuggestPrice { get { return suggestPrice; } set { suggestPrice = value; } } public string ForestFirstId { get { return forestFirstId; } set { forestFirstId = value; } } public string ProductionPlace { get { return productionPlace; } set { productionPlace = value; } } public string Manufacturer { get { return manufacturer; } set { manufacturer = value; } } public string SourceCode { get { return sourceCode; } set { sourceCode = value; } } public string ItemId { get { return itemId; } set { itemId = value; } } public bool? BeMember { get { return beMember; } set { beMember = value; } } public string TemplateSceneId { get { return templateSceneId; } set { templateSceneId = value; } } public int? SalesPrice { get { return salesPrice; } set { salesPrice = value; } } public int? OriginalPrice { get { return originalPrice; } set { originalPrice = value; } } public string ItemShortTitle { get { return itemShortTitle; } set { itemShortTitle = value; } } public string ForestSecondId { get { return forestSecondId; } set { forestSecondId = value; } } public string ItemPicUrl { get { return itemPicUrl; } set { itemPicUrl = value; } } public string SupplierName { get { return supplierName; } set { supplierName = value; } } public string Material { get { return material; } set { material = value; } } public string ModelNumber { get { return modelNumber; } set { modelNumber = value; } } public string SaleSpec { get { return saleSpec; } set { saleSpec = value; } } public string CategoryName { get { return categoryName; } set { categoryName = value; } } public string TaxFee { get { return taxFee; } set { taxFee = value; } } public string EnergyEfficiency { get { return energyEfficiency; } set { energyEfficiency = value; } } public string PromotionText { get { return promotionText; } set { promotionText = value; } } public string SkuId { get { return skuId; } set { skuId = value; } } } public override bool CheckShowJsonItemName() { return false; } public override BatchInsertItemsResponse GetResponse(UnmarshallerContext unmarshallerContext) { return BatchInsertItemsResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
20.432852
138
0.587127
[ "Apache-2.0" ]
aliyun/aliyun-openapi-net-sdk
aliyun-net-sdk-cloudesl/Cloudesl/Model/V20200201/BatchInsertItemsRequest.cs
18,410
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using Moq; using NBitcoin; using Stratis.Bitcoin.Features.Wallet; using Stratis.Features.FederatedPeg.Interfaces; using Stratis.Features.FederatedPeg.TargetChain; using Stratis.Features.FederatedPeg.Wallet; using Stratis.Sidechains.Networks; using Xunit; using Recipient = Stratis.Features.FederatedPeg.Wallet.Recipient; using TransactionBuildContext = Stratis.Features.FederatedPeg.Wallet.TransactionBuildContext; using UnspentOutputReference = Stratis.Features.FederatedPeg.Wallet.UnspentOutputReference; namespace Stratis.Features.FederatedPeg.Tests { public class WithdrawalTransactionBuilderTests { private readonly Network network; private readonly Mock<ILoggerFactory> loggerFactory; private readonly Mock<ILogger> logger; private readonly Mock<IFederationWalletManager> federationWalletManager; private readonly Mock<IFederationWalletTransactionHandler> federationWalletTransactionHandler; private readonly Mock<IFederatedPegSettings> federationGatewaySettings; public WithdrawalTransactionBuilderTests() { this.loggerFactory = new Mock<ILoggerFactory>(); this.network = CirrusNetwork.NetworksSelector.Regtest(); this.federationWalletManager = new Mock<IFederationWalletManager>(); this.federationWalletTransactionHandler = new Mock<IFederationWalletTransactionHandler>(); this.federationGatewaySettings = new Mock<IFederatedPegSettings>(); this.logger = new Mock<ILogger>(); this.loggerFactory.Setup(x => x.CreateLogger(It.IsAny<string>())) .Returns(this.logger.Object); this.federationGatewaySettings.Setup<Money>(x => x.GetWithdrawalTransactionFee(It.IsAny<int>())) .Returns<int>((numInputs) => { return FederatedPegSettings.BaseTransactionFee + FederatedPegSettings.InputTransactionFee * numInputs; }); this.federationWalletManager.Setup(x => x.Secret) .Returns(new WalletSecret()); this.federationWalletTransactionHandler.Setup(x => x.BuildTransaction(It.IsAny<TransactionBuildContext>())) .Returns(this.network.CreateTransaction()); } [Fact] public void FeeIsTakenFromRecipient() { Script redeemScript = PayToMultiSigTemplate.Instance.GenerateScriptPubKey(2, new[] {new Key().PubKey, new Key().PubKey}); this.federationWalletManager.Setup(x => x.GetSpendableTransactionsInWallet(It.IsAny<int>())) .Returns(new List<UnspentOutputReference> { new UnspentOutputReference { Transaction = new FederatedPeg.Wallet.TransactionData { Amount = Money.Coins(105), Id = uint256.One, ScriptPubKey = redeemScript.Hash.ScriptPubKey } } }); this.federationWalletManager.Setup(x => x.GetWallet()) .Returns(new FederationWallet { MultiSigAddress = new MultiSigAddress { RedeemScript = redeemScript } }); var txBuilder = new WithdrawalTransactionBuilder( this.loggerFactory.Object, this.network, this.federationWalletManager.Object, this.federationWalletTransactionHandler.Object, this.federationGatewaySettings.Object ); var recipient = new Recipient { Amount = Money.Coins(101), ScriptPubKey = new Script() }; Transaction ret = txBuilder.BuildWithdrawalTransaction(uint256.One, 100, recipient); Assert.NotNull(ret); // Fee taken from amount should be the total fee. Money expectedAmountAfterFee = recipient.Amount - FederatedPegSettings.CrossChainTransferFee; this.federationWalletTransactionHandler.Verify(x => x.BuildTransaction(It.Is<TransactionBuildContext>(y => y.Recipients.First().Amount == expectedAmountAfterFee))); // Fee used to send transaction should be a smaller amount. Money expectedTxFee = FederatedPegSettings.BaseTransactionFee + 1 * FederatedPegSettings.InputTransactionFee; this.federationWalletTransactionHandler.Verify(x => x.BuildTransaction(It.Is<TransactionBuildContext>(y => y.TransactionFee == expectedTxFee))); } [Fact] public void NoSpendableTransactionsLogWarning() { // Throw a 'no spendable transactions' exception this.federationWalletTransactionHandler.Setup(x => x.BuildTransaction(It.IsAny<TransactionBuildContext>())) .Throws(new WalletException(FederationWalletTransactionHandler.NoSpendableTransactionsMessage)); var txBuilder = new WithdrawalTransactionBuilder( this.loggerFactory.Object, this.network, this.federationWalletManager.Object, this.federationWalletTransactionHandler.Object, this.federationGatewaySettings.Object ); var recipient = new Recipient { Amount = Money.Coins(101), ScriptPubKey = new Script() }; Transaction ret = txBuilder.BuildWithdrawalTransaction(uint256.One, 100, recipient); // Log out a warning in this case, not an error. this.logger.Verify(x=>x.Log<object>(LogLevel.Warning, It.IsAny<EventId>(), It.IsAny<object>(), null, It.IsAny<Func<object, Exception, string>>())); } [Fact] public void NotEnoughFundsLogWarning() { // Throw a 'no spendable transactions' exception this.federationWalletTransactionHandler.Setup(x => x.BuildTransaction(It.IsAny<TransactionBuildContext>())) .Throws(new WalletException(FederationWalletTransactionHandler.NotEnoughFundsMessage)); var txBuilder = new WithdrawalTransactionBuilder( this.loggerFactory.Object, this.network, this.federationWalletManager.Object, this.federationWalletTransactionHandler.Object, this.federationGatewaySettings.Object ); var recipient = new Recipient { Amount = Money.Coins(101), ScriptPubKey = new Script() }; Transaction ret = txBuilder.BuildWithdrawalTransaction(uint256.One, 100, recipient); // Log out a warning in this case, not an error. this.logger.Verify(x => x.Log<object>(LogLevel.Warning, It.IsAny<EventId>(), It.IsAny<object>(), null, It.IsAny<Func<object, Exception, string>>())); } } }
44.197531
176
0.632821
[ "MIT" ]
YakupIpek/StratisBitcoinFullNode
src/Stratis.Features.FederatedPeg.Tests/WithdrawalTransactionBuilderTests.cs
7,162
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class BulletContreoller : MonoBehaviour { GameObject _target; [SerializeField] Rigidbody _rigidbody; [SerializeField] GameObject _particles; [SerializeField,Range(0,100)] float _timeToDie = 5f; private float _speed; private float _power; [SerializeField] AnimationCurve _sizeOverLife; private float distace; public UnityEvent OnExplosion; private void Awake() { OnExplosion.AddListener(AudioManager.Instance.PlayExplosion); } private void Start() { GetComponent<TrailRenderer>().enabled = false; _timeToDie = 1; _rigidbody = GetComponent<Rigidbody>(); _rigidbody.isKinematic = true; _rigidbody.useGravity = false; } private void FixedUpdate() { if(!_rigidbody.isKinematic) { if(_target != null) distace = Vector3.Distance(transform.position, _target.transform.position); transform.localScale = Vector3.one * _sizeOverLife.Evaluate(Mathf.Clamp(distace, 0, 1)); } if (_target != null) { NpcTarget(); } else { NoTarget(); } } private void NoTarget() { _rigidbody.AddRelativeForce(transform.forward * _speed); } private void NpcTarget() { Vector3 direction = _target.transform.position - transform.position; ; _rigidbody.AddForce(direction * _speed ); } public void SetDestination(GameObject position) { GetComponent<TrailRenderer>().enabled = true; _rigidbody.isKinematic = false; _target = position; _rigidbody.AddForce(transform.up * 5, ForceMode.Impulse); Destroy(gameObject, _timeToDie); } private void OnTriggerEnter(Collider other) { if (other.gameObject.GetComponent<NpcController>() && !_rigidbody.isKinematic) { other.gameObject.GetComponent<NpcController>().GiveDamage(_power); } if(!_rigidbody.isKinematic && other.gameObject.GetComponent<NpcController>() ) Destroy(gameObject); } internal void SetUp(float bulletPower, float bulletSpeed) { _speed = bulletSpeed; _power = bulletPower; } private void OnDestroy() { OnExplosion.Invoke(); if (_rigidbody.velocity.magnitude > 2 ) { GameObject particles = Instantiate(_particles, transform.position, transform.rotation); Destroy(particles, 1); } } }
24.972222
100
0.62106
[ "MIT" ]
alkihuri/LavaProject
LavaProject.Unity/Assets/Scripts/GameCore/Player/GunLogic/BulletContreoller.cs
2,697
C#
using Trains.NET.Engine; namespace Trains.NET.Rendering; public interface IDraggableTool : ITool { void StartDrag(int x, int y); void ContinueDrag(int x, int y); }
17.5
39
0.72
[ "MIT" ]
Perksey/Trains.NET
src/Trains.NET.Rendering/IDraggableTool.cs
177
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("Koakuma.Testing1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Koakuma.Testing1")] [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("7a433d85-a4b2-493b-926c-d1aa83516cfd")] // 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.972973
84
0.745196
[ "MIT" ]
WiiPlayer2/Koakuma
Koakuma.Testing1/Properties/AssemblyInfo.cs
1,408
C#
using Fogo_Sprite_Editor.Modules.ObjectViewer.ViewModels; using Gemini.Framework.Services; using System.ComponentModel; using System.Windows.Media.Imaging; using System.Collections.Generic; namespace Fogo_Sprite_Editor.EditorProject { public class GameObject : IGameObject, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _name; public string Name { get { return _name; } set { _name = value; NotifyPropertyChanged("Name"); } } public BitmapSource Spritesheet { get; set; } public bool Selected { get; set; } private List<ObjectFrame> _frames; public List<ObjectFrame> Frames => _frames; public GameObject() { _name = "[New Object]"; _frames = new List<ObjectFrame>(); } private void NotifyPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public void Activate(IShell shell) { var found = false; foreach (var document in shell.Documents) { if (document is ObjectViewModel) { var objectView = (ObjectViewModel)document; if (objectView.GameObject == this) { shell.OpenDocument(objectView); found = true; } } } if (!found) { var document = new ObjectViewModel(); document.SetGameObject(this); shell.OpenDocument(document); } } public void CreateFrame() { var frame = new ObjectFrame(); frame.Name = "Test Name"; _frames.Add(frame); NotifyPropertyChanged("Frames"); } } }
28.013699
86
0.52665
[ "MIT" ]
rafaelalmeidatk/Fogo-Object-Editor
Fogo Sprite Editor/EditorProject/GameObject.cs
2,047
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using Bom.Utils.Math; using Microsoft.SqlServer.Server; using Bom.Core.Utils; using Ch.Knomes.Struct; namespace Bom.Core.Nodes.DbModels { public class Path : ITreeNodeTitle { public const char Separator = '/'; public int PathId { get; protected set; } public short Level { get; protected set; } public string NodePathString { get; protected set; } = ""; public int NodeId { get; internal protected set; } #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. public virtual Node Node { get; internal protected set; } #pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. /// -> outcommented because not working in .net core 3.0 //internal Microsoft.SqlServer.Types.SqlHierarchyId NodePath { get; set; } #region calculated values /// <summary> /// NodeIds as string (not yet converted) /// </summary> internal string[] AllRawNodeIds => PathHelper.GetPathValues(NodePathString); public IEnumerable<long> AllNodeIds => PathHelper.GetNodeIdsFromPath(NodePathString); internal int NofFragments => AllRawNodeIds != null ? AllRawNodeIds.Length : 0; #endregion #pragma warning disable CA1033 // Interface methods should be callable by child types string ITreeNodeTitle.GetTitleString() #pragma warning restore CA1033 // Interface methods should be callable by child types { var node = $"{PathId} '{string.Join(Path.Separator, this.AllNodeIds)}'"; #if DEBUG if (Node != null) { node += $" (Node: '{Node.Title}')"; } #endif return node; } public override string ToString() { var node = $"Path {PathId} '{string.Join(Path.Separator, this.AllNodeIds)}'"; #if DEBUG if (Node != null) { node += $" (Node: '{Node.Title}')"; } #endif return node; } #region basic tests static Path() { #if DEBUG PerformInternalTests(); #endif } [System.Diagnostics.Conditional("DEBUG")] private static void PerformInternalTests() { var errorMessages = new List<string>(); // 1. GetPathValues(string pathString) var path = new Path(); path.NodePathString = "/44/2/7/"; var childPath = PathHelper.GetParentPathForChild(path); // not possible to test in if(childPath != "/44/2/7/") { errorMessages.Add($"{nameof(PathHelper)}.{nameof(PathHelper.GetPathValues)} does not return expected results"); } // summary if (errorMessages.Count > 0) { throw new Exception($"Not all tests were successful: {string.Join(", ", errorMessages)}"); } } #endregion #region outcommented stuff //public PathStuff MorePathInfo { get; } ///// <summary> ///// Indicates the depth in the tree (Root Nodes have Depth 0) ///// </summary> //[Obsolete("replaced by Hierary")] //protected internal int SetDepth { get; set; } //[Obsolete("replaced Depth")] //protected internal string SetParentPath { get; set; } //public class PathStuff //{ // public PathStuff(Path p) // { // this.Path = p; // } // internal Path Path {get;} // public string ParentPath => this.Path.SetParentPath; // public int SetDepth => this.Path.SetDepth; // public string HierarchyNetString => this.Path.Hierarchy.ToString(); //} #endregion } }
28.371429
127
0.57855
[ "MIT" ]
knoepdan/Bom
Source/Bom/Core/Nodes/DbModels/Path.cs
3,974
C#
using System; using System.Collections.Generic; using System.Data.SqlTypes; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.SqlServer.TransactSql.ScriptDom; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Metadata; namespace MarkMpn.Sql4Cds.Engine { static class MetadataExtensions { public static int EntityLogicalNameMaxLength { get; } = 64; public static Type GetAttributeType(this AttributeMetadata attrMetadata) { if (attrMetadata is MultiSelectPicklistAttributeMetadata) return typeof(OptionSetValueCollection); var typeCode = attrMetadata.AttributeType; if (attrMetadata is ManagedPropertyAttributeMetadata managedProp) typeCode = managedProp.ValueAttributeTypeCode; if (attrMetadata is BooleanAttributeMetadata || typeCode == AttributeTypeCode.Boolean) return typeof(bool?); if (attrMetadata is DateTimeAttributeMetadata || typeCode == AttributeTypeCode.DateTime) return typeof(DateTime?); if (attrMetadata is DecimalAttributeMetadata || typeCode == AttributeTypeCode.Decimal) return typeof(decimal?); if (attrMetadata is DoubleAttributeMetadata || typeCode == AttributeTypeCode.Double) return typeof(double?); if (attrMetadata is EntityNameAttributeMetadata || typeCode == AttributeTypeCode.EntityName) return typeof(int?); if (attrMetadata is ImageAttributeMetadata) return typeof(byte[]); if (attrMetadata is IntegerAttributeMetadata || typeCode == AttributeTypeCode.Integer) return typeof(int?); if (attrMetadata is BigIntAttributeMetadata || typeCode == AttributeTypeCode.BigInt) return typeof(long?); if (typeCode == AttributeTypeCode.PartyList) return typeof(EntityCollection); if (attrMetadata is LookupAttributeMetadata || typeCode == AttributeTypeCode.Lookup || typeCode == AttributeTypeCode.Customer || typeCode == AttributeTypeCode.Owner) return typeof(Guid?); if (attrMetadata is MemoAttributeMetadata || typeCode == AttributeTypeCode.Memo) return typeof(string); if (attrMetadata is MoneyAttributeMetadata || typeCode == AttributeTypeCode.Money) return typeof(decimal?); if (attrMetadata is PicklistAttributeMetadata || typeCode == AttributeTypeCode.Picklist) return typeof(int?); if (attrMetadata is StateAttributeMetadata || typeCode == AttributeTypeCode.State) return typeof(int?); if (attrMetadata is StatusAttributeMetadata || typeCode == AttributeTypeCode.Status) return typeof(int?); if (attrMetadata is StringAttributeMetadata || typeCode == AttributeTypeCode.String) return typeof(string); if (attrMetadata is UniqueIdentifierAttributeMetadata || typeCode == AttributeTypeCode.Uniqueidentifier) return typeof(Guid?); if (attrMetadata.AttributeType == AttributeTypeCode.Virtual) return typeof(string); throw new ApplicationException("Unknown attribute type " + attrMetadata.GetType()); } public static DataTypeReference GetAttributeSqlType(this AttributeMetadata attrMetadata, IAttributeMetadataCache cache, bool write) { if (attrMetadata is MultiSelectPicklistAttributeMetadata) return DataTypeHelpers.NVarChar(Int32.MaxValue); var typeCode = attrMetadata.AttributeType; if (attrMetadata is ManagedPropertyAttributeMetadata managedProp) typeCode = managedProp.ValueAttributeTypeCode; if (attrMetadata is BooleanAttributeMetadata || typeCode == AttributeTypeCode.Boolean) return DataTypeHelpers.Bit; if (attrMetadata is DateTimeAttributeMetadata || typeCode == AttributeTypeCode.DateTime) return DataTypeHelpers.DateTime; if (attrMetadata is DecimalAttributeMetadata || typeCode == AttributeTypeCode.Decimal) { short scale = 2; if (attrMetadata is DecimalAttributeMetadata dec && dec.Precision != null) scale = (short)dec.Precision.Value; // Precision property is actually scale (number of decimal places) var precision = (short)(12 + scale); // Max value is 100 Billion, which is 12 digits return DataTypeHelpers.Decimal(precision, scale); } if (attrMetadata is DoubleAttributeMetadata || typeCode == AttributeTypeCode.Double) return DataTypeHelpers.Float; if (attrMetadata is EntityNameAttributeMetadata || typeCode == AttributeTypeCode.EntityName) return DataTypeHelpers.NVarChar(EntityLogicalNameMaxLength); if (attrMetadata is ImageAttributeMetadata) return DataTypeHelpers.VarBinary(Int32.MaxValue); if (attrMetadata is IntegerAttributeMetadata || typeCode == AttributeTypeCode.Integer) return DataTypeHelpers.Int; if (attrMetadata is BigIntAttributeMetadata || typeCode == AttributeTypeCode.BigInt) return DataTypeHelpers.BigInt; if (typeCode == AttributeTypeCode.PartyList) return DataTypeHelpers.NVarChar(Int32.MaxValue); if (attrMetadata is LookupAttributeMetadata || attrMetadata.IsPrimaryId == true || typeCode == AttributeTypeCode.Lookup || typeCode == AttributeTypeCode.Customer || typeCode == AttributeTypeCode.Owner) return DataTypeHelpers.EntityReference; if (attrMetadata is MemoAttributeMetadata || typeCode == AttributeTypeCode.Memo) return DataTypeHelpers.NVarChar(write && attrMetadata is MemoAttributeMetadata memo && memo.MaxLength != null ? memo.MaxLength.Value : Int32.MaxValue); if (attrMetadata is MoneyAttributeMetadata || typeCode == AttributeTypeCode.Money) return DataTypeHelpers.Money; if (attrMetadata is PicklistAttributeMetadata || typeCode == AttributeTypeCode.Picklist) return DataTypeHelpers.Int; if (attrMetadata is StateAttributeMetadata || typeCode == AttributeTypeCode.State) return DataTypeHelpers.Int; if (attrMetadata is StatusAttributeMetadata || typeCode == AttributeTypeCode.Status) return DataTypeHelpers.Int; if (attrMetadata is StringAttributeMetadata || typeCode == AttributeTypeCode.String) { if (attrMetadata.LogicalName.StartsWith("address")) { var parts = attrMetadata.LogicalName.Split('_'); if (parts.Length == 2 && Int32.TryParse(parts[0].Substring(7), out _) && cache.TryGetValue("customeraddress", out var addressMetadata)) { // Attribute is e.g. address1_postalcode. Get the equivalent attribute from the customeraddress // entity as it can have very different max length attrMetadata = addressMetadata.Attributes.SingleOrDefault(a => a.LogicalName == parts[1]) as StringAttributeMetadata ?? attrMetadata; } } var maxLength = Int32.MaxValue; if (attrMetadata is StringAttributeMetadata str) { // MaxLength validation is applied on write, but existing values could be up to DatabaseLength var maxLengthSetting = write ? str.MaxLength : str.DatabaseLength; if (maxLengthSetting != null) maxLength = maxLengthSetting.Value; } return DataTypeHelpers.NVarChar(maxLength); } if (attrMetadata is UniqueIdentifierAttributeMetadata || typeCode == AttributeTypeCode.Uniqueidentifier) return DataTypeHelpers.UniqueIdentifier; if (attrMetadata.AttributeTypeName == AttributeTypeDisplayName.FileType) return DataTypeHelpers.UniqueIdentifier; if (attrMetadata.AttributeType == AttributeTypeCode.Virtual) return DataTypeHelpers.NVarChar(Int32.MaxValue); throw new ApplicationException("Unknown attribute type " + attrMetadata.GetType()); } } }
46.015873
213
0.64827
[ "MIT" ]
skolbin-ssi/Sql4Cds
MarkMpn.Sql4Cds.Engine/MetadataExtensions.cs
8,699
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SoundToggle : MonoBehaviour { private bool isOn; private MainController controller; void Start () { isOn = true; controller = GameObject.FindGameObjectWithTag ("MainController").GetComponent<MainController> (); if (isOn != controller.GetSound ()) StartCoroutine (Foo ()); } // Turn Off or Turn On the sound state and change the button position private void ChangeState() { isOn = !isOn; if (isOn) transform.localPosition = new Vector3(0f, transform.localPosition.y, 0f); else transform.localPosition = new Vector3(100f, transform.localPosition.y, 0f); } // Active when the player press the sound button. public void SoundChange () { ChangeState (); controller.SetSound (isOn); } // I have to call a thread because transform changes can't be done when we are in the Start step of unity public IEnumerator Foo () { yield return new WaitForSeconds (1.0f); ChangeState (); } }
27
107
0.698955
[ "MIT" ]
felipeemidio/SquareTrack
Assets/Scripts/SoundToggle.cs
1,055
C#
 using UnityEditor; using UnityEngine; [CanEditMultipleObjects, CustomEditor(typeof(MegaShapeCircle))] public class MegaShapeCircleEditor : MegaShapeEditor { public override bool Params() { MegaShapeCircle shape = (MegaShapeCircle)target; bool rebuild = false; float radius = EditorGUILayout.FloatField("Radius", shape.Radius); if ( radius != shape.Radius ) { if ( radius < 0.001f ) radius = 0.001f; shape.Radius = radius; rebuild = true; } return rebuild; } }
20.038462
69
0.675624
[ "MIT" ]
oliverellmers/UnityARKitDetection
Assets/Mega-Fiers/Editor/MegaFiers/MegaShape/MegaShapeCircleEditor.cs
523
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Drawing; using DocumentFormat.OpenXml.Drawing.Diagrams; using DocumentFormat.OpenXml.Framework; using DocumentFormat.OpenXml.Framework.Metadata; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation.Schema; using System; using System.Collections.Generic; using System.IO.Packaging; namespace DocumentFormat.OpenXml.Office.Drawing { /// <summary> /// <para>Defines the Drawing Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:drawing.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>ShapeTree &lt;dsp:spTree></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "drawing")] #pragma warning restore CS0618 // Type or member is obsolete public partial class Drawing : OpenXmlPartRootElement { /// <summary> /// Initializes a new instance of the Drawing class. /// </summary> public Drawing() : base() { } /// <summary> /// Initializes a new instance of the Drawing class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Drawing(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Drawing class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Drawing(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Drawing class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Drawing(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "drawing"); builder.AddChild<ShapeTree>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.ShapeTree), 1, 1) }; } /// <summary> /// <para>ShapeTree.</para> /// <para>Represents the following element tag in the schema: dsp:spTree.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public ShapeTree ShapeTree { get => GetElement<ShapeTree>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Drawing>(deep); internal Drawing(DiagramPersistLayoutPart ownerPart) : base(ownerPart) { } /// <summary> /// Loads the DOM from the DiagramPersistLayoutPart /// </summary> /// <param name="openXmlPart">Specifies the part to be loaded.</param> public void Load(DiagramPersistLayoutPart openXmlPart) { LoadFromPart(openXmlPart); } /// <summary> /// Saves the DOM into the DiagramPersistLayoutPart. /// </summary> /// <param name="openXmlPart">Specifies the part to save to.</param> public void Save(DiagramPersistLayoutPart openXmlPart) { base.SaveToPart(openXmlPart); } /// <summary> /// Gets the DiagramPersistLayoutPart associated with this element. /// </summary> public DiagramPersistLayoutPart DiagramPersistLayoutPart { get => OpenXmlPart as DiagramPersistLayoutPart; internal set => OpenXmlPart = value; } } /// <summary> /// <para>Defines the DataModelExtensionBlock Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:dataModelExt.</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "dataModelExt")] #pragma warning restore CS0618 // Type or member is obsolete public partial class DataModelExtensionBlock : OpenXmlLeafElement { /// <summary> /// Initializes a new instance of the DataModelExtensionBlock class. /// </summary> public DataModelExtensionBlock() : base() { } /// <summary> /// <para>relId</para> /// <para>Represents the following attribute in the schema: relId</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "relId")] #pragma warning restore CS0618 // Type or member is obsolete public StringValue RelId { get => GetAttribute<StringValue>(); set => SetAttribute(value); } /// <summary> /// <para>minVer</para> /// <para>Represents the following attribute in the schema: minVer</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "minVer")] #pragma warning restore CS0618 // Type or member is obsolete public StringValue MinVer { get => GetAttribute<StringValue>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "dataModelExt"); builder.AddElement<DataModelExtensionBlock>() .AddAttribute(0, "relId", a => a.RelId) .AddAttribute(0, "minVer", a => a.MinVer, aBuilder => { aBuilder.AddValidator(new StringValidator() { IsUri = (true) }); }); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<DataModelExtensionBlock>(deep); } /// <summary> /// <para>Defines the NonVisualDrawingProperties Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:cNvPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.HyperlinkOnClick &lt;a:hlinkClick></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.HyperlinkOnHover &lt;a:hlinkHover></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "cNvPr")] #pragma warning restore CS0618 // Type or member is obsolete public partial class NonVisualDrawingProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualDrawingProperties class. /// </summary> public NonVisualDrawingProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualDrawingProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualDrawingProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualDrawingProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualDrawingProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualDrawingProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>id</para> /// <para>Represents the following attribute in the schema: id</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "id")] #pragma warning restore CS0618 // Type or member is obsolete public UInt32Value Id { get => GetAttribute<UInt32Value>(); set => SetAttribute(value); } /// <summary> /// <para>name</para> /// <para>Represents the following attribute in the schema: name</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "name")] #pragma warning restore CS0618 // Type or member is obsolete public StringValue Name { get => GetAttribute<StringValue>(); set => SetAttribute(value); } /// <summary> /// <para>descr</para> /// <para>Represents the following attribute in the schema: descr</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "descr")] #pragma warning restore CS0618 // Type or member is obsolete public StringValue Description { get => GetAttribute<StringValue>(); set => SetAttribute(value); } /// <summary> /// <para>hidden</para> /// <para>Represents the following attribute in the schema: hidden</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "hidden")] #pragma warning restore CS0618 // Type or member is obsolete public BooleanValue Hidden { get => GetAttribute<BooleanValue>(); set => SetAttribute(value); } /// <summary> /// <para>title</para> /// <para>Represents the following attribute in the schema: title</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "title")] #pragma warning restore CS0618 // Type or member is obsolete public StringValue Title { get => GetAttribute<StringValue>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "cNvPr"); builder.AddChild<DocumentFormat.OpenXml.Drawing.HyperlinkOnClick>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.HyperlinkOnHover>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList>(); builder.AddElement<NonVisualDrawingProperties>() .AddAttribute(0, "id", a => a.Id, aBuilder => { aBuilder.AddValidator(RequiredValidator.Instance); }) .AddAttribute(0, "name", a => a.Name, aBuilder => { aBuilder.AddValidator(RequiredValidator.Instance); }) .AddAttribute(0, "descr", a => a.Description) .AddAttribute(0, "hidden", a => a.Hidden) .AddAttribute(0, "title", a => a.Title); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.HyperlinkOnClick), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.HyperlinkOnHover), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList), 0, 1) }; } /// <summary> /// <para>HyperlinkOnClick.</para> /// <para>Represents the following element tag in the schema: a:hlinkClick.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.HyperlinkOnClick HyperlinkOnClick { get => GetElement<DocumentFormat.OpenXml.Drawing.HyperlinkOnClick>(); set => SetElement(value); } /// <summary> /// <para>HyperlinkOnHover.</para> /// <para>Represents the following element tag in the schema: a:hlinkHover.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.HyperlinkOnHover HyperlinkOnHover { get => GetElement<DocumentFormat.OpenXml.Drawing.HyperlinkOnHover>(); set => SetElement(value); } /// <summary> /// <para>NonVisualDrawingPropertiesExtensionList.</para> /// <para>Represents the following element tag in the schema: a:extLst.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList NonVisualDrawingPropertiesExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualDrawingProperties>(deep); } /// <summary> /// <para>Defines the NonVisualDrawingShapeProperties Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:cNvSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.ShapeLocks &lt;a:spLocks></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.ExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "cNvSpPr")] #pragma warning restore CS0618 // Type or member is obsolete public partial class NonVisualDrawingShapeProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualDrawingShapeProperties class. /// </summary> public NonVisualDrawingShapeProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualDrawingShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualDrawingShapeProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualDrawingShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualDrawingShapeProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualDrawingShapeProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualDrawingShapeProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Text Box</para> /// <para>Represents the following attribute in the schema: txBox</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "txBox")] #pragma warning restore CS0618 // Type or member is obsolete public BooleanValue TextBox { get => GetAttribute<BooleanValue>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "cNvSpPr"); builder.AddChild<DocumentFormat.OpenXml.Drawing.ShapeLocks>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.ExtensionList>(); builder.AddElement<NonVisualDrawingShapeProperties>() .AddAttribute(0, "txBox", a => a.TextBox); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ShapeLocks), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ExtensionList), 0, 1) }; } /// <summary> /// <para>Shape Locks.</para> /// <para>Represents the following element tag in the schema: a:spLocks.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.ShapeLocks ShapeLocks { get => GetElement<DocumentFormat.OpenXml.Drawing.ShapeLocks>(); set => SetElement(value); } /// <summary> /// <para>ExtensionList.</para> /// <para>Represents the following element tag in the schema: a:extLst.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.ExtensionList ExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.ExtensionList>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualDrawingShapeProperties>(deep); } /// <summary> /// <para>Defines the ShapeNonVisualProperties Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:nvSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualDrawingProperties &lt;dsp:cNvPr></description></item> /// <item><description>NonVisualDrawingShapeProperties &lt;dsp:cNvSpPr></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "nvSpPr")] #pragma warning restore CS0618 // Type or member is obsolete public partial class ShapeNonVisualProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the ShapeNonVisualProperties class. /// </summary> public ShapeNonVisualProperties() : base() { } /// <summary> /// Initializes a new instance of the ShapeNonVisualProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeNonVisualProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeNonVisualProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeNonVisualProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeNonVisualProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ShapeNonVisualProperties(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "nvSpPr"); builder.AddChild<NonVisualDrawingProperties>(); builder.AddChild<NonVisualDrawingShapeProperties>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.NonVisualDrawingProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.NonVisualDrawingShapeProperties), 1, 1) }; } /// <summary> /// <para>NonVisualDrawingProperties.</para> /// <para>Represents the following element tag in the schema: dsp:cNvPr.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public NonVisualDrawingProperties NonVisualDrawingProperties { get => GetElement<NonVisualDrawingProperties>(); set => SetElement(value); } /// <summary> /// <para>NonVisualDrawingShapeProperties.</para> /// <para>Represents the following element tag in the schema: dsp:cNvSpPr.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public NonVisualDrawingShapeProperties NonVisualDrawingShapeProperties { get => GetElement<NonVisualDrawingShapeProperties>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ShapeNonVisualProperties>(deep); } /// <summary> /// <para>Defines the ShapeProperties Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:spPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.Transform2D &lt;a:xfrm></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.CustomGeometry &lt;a:custGeom></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.PresetGeometry &lt;a:prstGeom></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.NoFill &lt;a:noFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.SolidFill &lt;a:solidFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.GradientFill &lt;a:gradFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.BlipFill &lt;a:blipFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.PatternFill &lt;a:pattFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.GroupFill &lt;a:grpFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Outline &lt;a:ln></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.EffectList &lt;a:effectLst></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.EffectDag &lt;a:effectDag></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Scene3DType &lt;a:scene3d></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Shape3DType &lt;a:sp3d></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.ShapePropertiesExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "spPr")] #pragma warning restore CS0618 // Type or member is obsolete public partial class ShapeProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the ShapeProperties class. /// </summary> public ShapeProperties() : base() { } /// <summary> /// Initializes a new instance of the ShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ShapeProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Black and White Mode</para> /// <para>Represents the following attribute in the schema: bwMode</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "bwMode")] #pragma warning restore CS0618 // Type or member is obsolete public EnumValue<DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues> BlackWhiteMode { get => GetAttribute<EnumValue<DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues>>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "spPr"); builder.AddChild<DocumentFormat.OpenXml.Drawing.Transform2D>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.CustomGeometry>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.PresetGeometry>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.NoFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.SolidFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.GradientFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.BlipFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.PatternFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.GroupFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Outline>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.EffectList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.EffectDag>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Scene3DType>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Shape3DType>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.ShapePropertiesExtensionList>(); builder.AddElement<ShapeProperties>() .AddAttribute(0, "bwMode", a => a.BlackWhiteMode, aBuilder => { aBuilder.AddValidator(new StringValidator() { IsToken = (true) }); }); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Transform2D), 0, 1), new CompositeParticle.Builder(ParticleType.Group, 0, 1) { new CompositeParticle.Builder(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.CustomGeometry), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.PresetGeometry), 1, 1) } }, new CompositeParticle.Builder(ParticleType.Group, 0, 1) { new CompositeParticle.Builder(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.NoFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.SolidFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GradientFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.BlipFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.PatternFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GroupFill), 1, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Outline), 0, 1), new CompositeParticle.Builder(ParticleType.Group, 0, 1) { new CompositeParticle.Builder(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectList), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectDag), 1, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Scene3DType), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Shape3DType), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ShapePropertiesExtensionList), 0, 1) }; } /// <summary> /// <para>2D Transform for Individual Objects.</para> /// <para>Represents the following element tag in the schema: a:xfrm.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.Transform2D Transform2D { get => GetElement<DocumentFormat.OpenXml.Drawing.Transform2D>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ShapeProperties>(deep); } /// <summary> /// <para>Defines the ShapeStyle Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:style.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.LineReference &lt;a:lnRef></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.FillReference &lt;a:fillRef></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.EffectReference &lt;a:effectRef></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.FontReference &lt;a:fontRef></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "style")] #pragma warning restore CS0618 // Type or member is obsolete public partial class ShapeStyle : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the ShapeStyle class. /// </summary> public ShapeStyle() : base() { } /// <summary> /// Initializes a new instance of the ShapeStyle class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeStyle(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeStyle class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeStyle(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeStyle class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ShapeStyle(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "style"); builder.AddChild<DocumentFormat.OpenXml.Drawing.LineReference>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.FillReference>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.EffectReference>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.FontReference>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.LineReference), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.FillReference), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectReference), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.FontReference), 1, 1) }; } /// <summary> /// <para>LineReference.</para> /// <para>Represents the following element tag in the schema: a:lnRef.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.LineReference LineReference { get => GetElement<DocumentFormat.OpenXml.Drawing.LineReference>(); set => SetElement(value); } /// <summary> /// <para>FillReference.</para> /// <para>Represents the following element tag in the schema: a:fillRef.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.FillReference FillReference { get => GetElement<DocumentFormat.OpenXml.Drawing.FillReference>(); set => SetElement(value); } /// <summary> /// <para>EffectReference.</para> /// <para>Represents the following element tag in the schema: a:effectRef.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.EffectReference EffectReference { get => GetElement<DocumentFormat.OpenXml.Drawing.EffectReference>(); set => SetElement(value); } /// <summary> /// <para>Font Reference.</para> /// <para>Represents the following element tag in the schema: a:fontRef.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.FontReference FontReference { get => GetElement<DocumentFormat.OpenXml.Drawing.FontReference>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ShapeStyle>(deep); } /// <summary> /// <para>Defines the TextBody Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:txBody.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.BodyProperties &lt;a:bodyPr></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.ListStyle &lt;a:lstStyle></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Paragraph &lt;a:p></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "txBody")] #pragma warning restore CS0618 // Type or member is obsolete public partial class TextBody : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the TextBody class. /// </summary> public TextBody() : base() { } /// <summary> /// Initializes a new instance of the TextBody class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public TextBody(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the TextBody class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public TextBody(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the TextBody class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public TextBody(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "txBody"); builder.AddChild<DocumentFormat.OpenXml.Drawing.BodyProperties>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.ListStyle>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Paragraph>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.BodyProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ListStyle), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Paragraph), 1, 0) }; } /// <summary> /// <para>Body Properties.</para> /// <para>Represents the following element tag in the schema: a:bodyPr.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.BodyProperties BodyProperties { get => GetElement<DocumentFormat.OpenXml.Drawing.BodyProperties>(); set => SetElement(value); } /// <summary> /// <para>Text List Styles.</para> /// <para>Represents the following element tag in the schema: a:lstStyle.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.ListStyle ListStyle { get => GetElement<DocumentFormat.OpenXml.Drawing.ListStyle>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<TextBody>(deep); } /// <summary> /// <para>Defines the Transform2D Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:txXfrm.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.Offset &lt;a:off></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Extents &lt;a:ext></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "txXfrm")] #pragma warning restore CS0618 // Type or member is obsolete public partial class Transform2D : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the Transform2D class. /// </summary> public Transform2D() : base() { } /// <summary> /// Initializes a new instance of the Transform2D class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Transform2D(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Transform2D class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Transform2D(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Transform2D class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Transform2D(string outerXml) : base(outerXml) { } /// <summary> /// <para>Rotation</para> /// <para>Represents the following attribute in the schema: rot</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "rot")] #pragma warning restore CS0618 // Type or member is obsolete public Int32Value Rotation { get => GetAttribute<Int32Value>(); set => SetAttribute(value); } /// <summary> /// <para>Horizontal Flip</para> /// <para>Represents the following attribute in the schema: flipH</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "flipH")] #pragma warning restore CS0618 // Type or member is obsolete public BooleanValue HorizontalFlip { get => GetAttribute<BooleanValue>(); set => SetAttribute(value); } /// <summary> /// <para>Vertical Flip</para> /// <para>Represents the following attribute in the schema: flipV</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "flipV")] #pragma warning restore CS0618 // Type or member is obsolete public BooleanValue VerticalFlip { get => GetAttribute<BooleanValue>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "txXfrm"); builder.AddChild<DocumentFormat.OpenXml.Drawing.Offset>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Extents>(); builder.AddElement<Transform2D>() .AddAttribute(0, "rot", a => a.Rotation) .AddAttribute(0, "flipH", a => a.HorizontalFlip) .AddAttribute(0, "flipV", a => a.VerticalFlip); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Offset), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Extents), 0, 1) }; } /// <summary> /// <para>Offset.</para> /// <para>Represents the following element tag in the schema: a:off.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.Offset Offset { get => GetElement<DocumentFormat.OpenXml.Drawing.Offset>(); set => SetElement(value); } /// <summary> /// <para>Extents.</para> /// <para>Represents the following element tag in the schema: a:ext.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.Extents Extents { get => GetElement<DocumentFormat.OpenXml.Drawing.Extents>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Transform2D>(deep); } /// <summary> /// <para>Defines the OfficeArtExtensionList Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:extLst.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.Extension &lt;a:ext></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "extLst")] #pragma warning restore CS0618 // Type or member is obsolete public partial class OfficeArtExtensionList : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the OfficeArtExtensionList class. /// </summary> public OfficeArtExtensionList() : base() { } /// <summary> /// Initializes a new instance of the OfficeArtExtensionList class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public OfficeArtExtensionList(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the OfficeArtExtensionList class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public OfficeArtExtensionList(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the OfficeArtExtensionList class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public OfficeArtExtensionList(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "extLst"); builder.AddChild<DocumentFormat.OpenXml.Drawing.Extension>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new CompositeParticle.Builder(ParticleType.Group, 1, 1) { new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Extension), 0, 0) } } }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<OfficeArtExtensionList>(deep); } /// <summary> /// <para>Defines the NonVisualGroupDrawingShapeProperties Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:cNvGrpSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.GroupShapeLocks &lt;a:grpSpLocks></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.NonVisualGroupDrawingShapePropsExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "cNvGrpSpPr")] #pragma warning restore CS0618 // Type or member is obsolete public partial class NonVisualGroupDrawingShapeProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the NonVisualGroupDrawingShapeProperties class. /// </summary> public NonVisualGroupDrawingShapeProperties() : base() { } /// <summary> /// Initializes a new instance of the NonVisualGroupDrawingShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualGroupDrawingShapeProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualGroupDrawingShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public NonVisualGroupDrawingShapeProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the NonVisualGroupDrawingShapeProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public NonVisualGroupDrawingShapeProperties(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "cNvGrpSpPr"); builder.AddChild<DocumentFormat.OpenXml.Drawing.GroupShapeLocks>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.NonVisualGroupDrawingShapePropsExtensionList>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GroupShapeLocks), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.NonVisualGroupDrawingShapePropsExtensionList), 0, 1) }; } /// <summary> /// <para>GroupShapeLocks.</para> /// <para>Represents the following element tag in the schema: a:grpSpLocks.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.GroupShapeLocks GroupShapeLocks { get => GetElement<DocumentFormat.OpenXml.Drawing.GroupShapeLocks>(); set => SetElement(value); } /// <summary> /// <para>NonVisualGroupDrawingShapePropsExtensionList.</para> /// <para>Represents the following element tag in the schema: a:extLst.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.NonVisualGroupDrawingShapePropsExtensionList NonVisualGroupDrawingShapePropsExtensionList { get => GetElement<DocumentFormat.OpenXml.Drawing.NonVisualGroupDrawingShapePropsExtensionList>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<NonVisualGroupDrawingShapeProperties>(deep); } /// <summary> /// <para>Defines the GroupShapeNonVisualProperties Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:nvGrpSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>NonVisualDrawingProperties &lt;dsp:cNvPr></description></item> /// <item><description>NonVisualGroupDrawingShapeProperties &lt;dsp:cNvGrpSpPr></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "nvGrpSpPr")] #pragma warning restore CS0618 // Type or member is obsolete public partial class GroupShapeNonVisualProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the GroupShapeNonVisualProperties class. /// </summary> public GroupShapeNonVisualProperties() : base() { } /// <summary> /// Initializes a new instance of the GroupShapeNonVisualProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GroupShapeNonVisualProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShapeNonVisualProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GroupShapeNonVisualProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShapeNonVisualProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public GroupShapeNonVisualProperties(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "nvGrpSpPr"); builder.AddChild<NonVisualDrawingProperties>(); builder.AddChild<NonVisualGroupDrawingShapeProperties>(); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.NonVisualDrawingProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.NonVisualGroupDrawingShapeProperties), 1, 1) }; } /// <summary> /// <para>NonVisualDrawingProperties.</para> /// <para>Represents the following element tag in the schema: dsp:cNvPr.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public NonVisualDrawingProperties NonVisualDrawingProperties { get => GetElement<NonVisualDrawingProperties>(); set => SetElement(value); } /// <summary> /// <para>NonVisualGroupDrawingShapeProperties.</para> /// <para>Represents the following element tag in the schema: dsp:cNvGrpSpPr.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public NonVisualGroupDrawingShapeProperties NonVisualGroupDrawingShapeProperties { get => GetElement<NonVisualGroupDrawingShapeProperties>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<GroupShapeNonVisualProperties>(deep); } /// <summary> /// <para>Defines the GroupShapeProperties Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:grpSpPr.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>DocumentFormat.OpenXml.Drawing.TransformGroup &lt;a:xfrm></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.NoFill &lt;a:noFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.SolidFill &lt;a:solidFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.GradientFill &lt;a:gradFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.BlipFill &lt;a:blipFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.PatternFill &lt;a:pattFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.GroupFill &lt;a:grpFill></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.EffectList &lt;a:effectLst></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.EffectDag &lt;a:effectDag></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.Scene3DType &lt;a:scene3d></description></item> /// <item><description>DocumentFormat.OpenXml.Drawing.ExtensionList &lt;a:extLst></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "grpSpPr")] #pragma warning restore CS0618 // Type or member is obsolete public partial class GroupShapeProperties : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the GroupShapeProperties class. /// </summary> public GroupShapeProperties() : base() { } /// <summary> /// Initializes a new instance of the GroupShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GroupShapeProperties(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShapeProperties class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GroupShapeProperties(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShapeProperties class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public GroupShapeProperties(string outerXml) : base(outerXml) { } /// <summary> /// <para>Black and White Mode</para> /// <para>Represents the following attribute in the schema: bwMode</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "bwMode")] #pragma warning restore CS0618 // Type or member is obsolete public EnumValue<DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues> BlackWhiteMode { get => GetAttribute<EnumValue<DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues>>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "grpSpPr"); builder.AddChild<DocumentFormat.OpenXml.Drawing.TransformGroup>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.NoFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.SolidFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.GradientFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.BlipFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.PatternFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.GroupFill>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.EffectList>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.EffectDag>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.Scene3DType>(); builder.AddChild<DocumentFormat.OpenXml.Drawing.ExtensionList>(); builder.AddElement<GroupShapeProperties>() .AddAttribute(0, "bwMode", a => a.BlackWhiteMode, aBuilder => { aBuilder.AddValidator(new StringValidator() { IsToken = (true) }); }); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.TransformGroup), 0, 1), new CompositeParticle.Builder(ParticleType.Group, 0, 1) { new CompositeParticle.Builder(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.NoFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.SolidFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GradientFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.BlipFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.PatternFill), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.GroupFill), 1, 1) } }, new CompositeParticle.Builder(ParticleType.Group, 0, 1) { new CompositeParticle.Builder(ParticleType.Choice, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectList), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.EffectDag), 1, 1) } }, new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.Scene3DType), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Drawing.ExtensionList), 0, 1) }; } /// <summary> /// <para>2D Transform for Grouped Objects.</para> /// <para>Represents the following element tag in the schema: a:xfrm.</para> /// </summary> /// <remark> /// xmlns:a = http://schemas.openxmlformats.org/drawingml/2006/main /// </remark> public DocumentFormat.OpenXml.Drawing.TransformGroup TransformGroup { get => GetElement<DocumentFormat.OpenXml.Drawing.TransformGroup>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<GroupShapeProperties>(deep); } /// <summary> /// <para>Defines the Shape Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:sp.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>ShapeNonVisualProperties &lt;dsp:nvSpPr></description></item> /// <item><description>ShapeProperties &lt;dsp:spPr></description></item> /// <item><description>ShapeStyle &lt;dsp:style></description></item> /// <item><description>TextBody &lt;dsp:txBody></description></item> /// <item><description>Transform2D &lt;dsp:txXfrm></description></item> /// <item><description>OfficeArtExtensionList &lt;dsp:extLst></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "sp")] #pragma warning restore CS0618 // Type or member is obsolete public partial class Shape : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the Shape class. /// </summary> public Shape() : base() { } /// <summary> /// Initializes a new instance of the Shape class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Shape(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Shape class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Shape(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Shape class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Shape(string outerXml) : base(outerXml) { } /// <summary> /// <para>modelId</para> /// <para>Represents the following attribute in the schema: modelId</para> /// </summary> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(0, "modelId")] #pragma warning restore CS0618 // Type or member is obsolete public StringValue ModelId { get => GetAttribute<StringValue>(); set => SetAttribute(value); } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "sp"); builder.AddChild<ShapeNonVisualProperties>(); builder.AddChild<ShapeProperties>(); builder.AddChild<ShapeStyle>(); builder.AddChild<TextBody>(); builder.AddChild<Transform2D>(); builder.AddChild<OfficeArtExtensionList>(); builder.AddElement<Shape>() .AddAttribute(0, "modelId", a => a.ModelId, aBuilder => { aBuilder.AddValidator(RequiredValidator.Instance); aBuilder.AddUnion(union => { union.AddValidator<Int32Value>(NumberValidator.Instance); union.AddValidator(new StringValidator() { Pattern = ("\\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\\}") }); }); }); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.ShapeNonVisualProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.ShapeProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.ShapeStyle), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.TextBody), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.Transform2D), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.OfficeArtExtensionList), 0, 1) }; } /// <summary> /// <para>ShapeNonVisualProperties.</para> /// <para>Represents the following element tag in the schema: dsp:nvSpPr.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public ShapeNonVisualProperties ShapeNonVisualProperties { get => GetElement<ShapeNonVisualProperties>(); set => SetElement(value); } /// <summary> /// <para>ShapeProperties.</para> /// <para>Represents the following element tag in the schema: dsp:spPr.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public ShapeProperties ShapeProperties { get => GetElement<ShapeProperties>(); set => SetElement(value); } /// <summary> /// <para>ShapeStyle.</para> /// <para>Represents the following element tag in the schema: dsp:style.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public ShapeStyle ShapeStyle { get => GetElement<ShapeStyle>(); set => SetElement(value); } /// <summary> /// <para>TextBody.</para> /// <para>Represents the following element tag in the schema: dsp:txBody.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public TextBody TextBody { get => GetElement<TextBody>(); set => SetElement(value); } /// <summary> /// <para>Transform2D.</para> /// <para>Represents the following element tag in the schema: dsp:txXfrm.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public Transform2D Transform2D { get => GetElement<Transform2D>(); set => SetElement(value); } /// <summary> /// <para>OfficeArtExtensionList.</para> /// <para>Represents the following element tag in the schema: dsp:extLst.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public OfficeArtExtensionList OfficeArtExtensionList { get => GetElement<OfficeArtExtensionList>(); set => SetElement(value); } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<Shape>(deep); } /// <summary> /// <para>Defines the GroupShape Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:grpSp.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>GroupShapeNonVisualProperties &lt;dsp:nvGrpSpPr></description></item> /// <item><description>GroupShapeProperties &lt;dsp:grpSpPr></description></item> /// <item><description>Shape &lt;dsp:sp></description></item> /// <item><description>GroupShape &lt;dsp:grpSp></description></item> /// <item><description>OfficeArtExtensionList &lt;dsp:extLst></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "grpSp")] #pragma warning restore CS0618 // Type or member is obsolete public partial class GroupShape : GroupShapeType { /// <summary> /// Initializes a new instance of the GroupShape class. /// </summary> public GroupShape() : base() { } /// <summary> /// Initializes a new instance of the GroupShape class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GroupShape(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShape class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public GroupShape(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShape class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public GroupShape(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "grpSp"); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.GroupShapeNonVisualProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.GroupShapeProperties), 1, 1), new CompositeParticle.Builder(ParticleType.Choice, 0, 0) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.Shape), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.GroupShape), 1, 1) }, new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.OfficeArtExtensionList), 0, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<GroupShape>(deep); } /// <summary> /// <para>Defines the ShapeTree Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is dsp:spTree.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>GroupShapeNonVisualProperties &lt;dsp:nvGrpSpPr></description></item> /// <item><description>GroupShapeProperties &lt;dsp:grpSpPr></description></item> /// <item><description>Shape &lt;dsp:sp></description></item> /// <item><description>GroupShape &lt;dsp:grpSp></description></item> /// <item><description>OfficeArtExtensionList &lt;dsp:extLst></description></item> /// </list> /// </remark> #pragma warning disable CS0618 // Type or member is obsolete [SchemaAttr(56, "spTree")] #pragma warning restore CS0618 // Type or member is obsolete public partial class ShapeTree : GroupShapeType { /// <summary> /// Initializes a new instance of the ShapeTree class. /// </summary> public ShapeTree() : base() { } /// <summary> /// Initializes a new instance of the ShapeTree class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeTree(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeTree class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ShapeTree(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ShapeTree class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ShapeTree(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.SetSchema(56, "spTree"); builder.Particle = new CompositeParticle.Builder(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.GroupShapeNonVisualProperties), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.GroupShapeProperties), 1, 1), new CompositeParticle.Builder(ParticleType.Choice, 0, 0) { new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.Shape), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.GroupShape), 1, 1) }, new ElementParticle(typeof(DocumentFormat.OpenXml.Office.Drawing.OfficeArtExtensionList), 0, 1) }; } /// <inheritdoc/> public override OpenXmlElement CloneNode(bool deep) => CloneImp<ShapeTree>(deep); } /// <summary> /// <para>Defines the GroupShapeType Class.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is :.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>GroupShapeNonVisualProperties &lt;dsp:nvGrpSpPr></description></item> /// <item><description>GroupShapeProperties &lt;dsp:grpSpPr></description></item> /// <item><description>Shape &lt;dsp:sp></description></item> /// <item><description>GroupShape &lt;dsp:grpSp></description></item> /// <item><description>OfficeArtExtensionList &lt;dsp:extLst></description></item> /// </list> /// </remark> public abstract partial class GroupShapeType : OpenXmlCompositeElement { /// <summary> /// Initializes a new instance of the GroupShapeType class. /// </summary> protected GroupShapeType() : base() { } /// <summary> /// Initializes a new instance of the GroupShapeType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> protected GroupShapeType(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShapeType class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> protected GroupShapeType(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the GroupShapeType class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> protected GroupShapeType(string outerXml) : base(outerXml) { } internal override void ConfigureMetadata(ElementMetadata.Builder builder) { base.ConfigureMetadata(builder); builder.AddChild<GroupShapeNonVisualProperties>(); builder.AddChild<GroupShapeProperties>(); builder.AddChild<Shape>(); builder.AddChild<GroupShape>(); builder.AddChild<OfficeArtExtensionList>(); } /// <summary> /// <para>GroupShapeNonVisualProperties.</para> /// <para>Represents the following element tag in the schema: dsp:nvGrpSpPr.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public GroupShapeNonVisualProperties GroupShapeNonVisualProperties { get => GetElement<GroupShapeNonVisualProperties>(); set => SetElement(value); } /// <summary> /// <para>GroupShapeProperties.</para> /// <para>Represents the following element tag in the schema: dsp:grpSpPr.</para> /// </summary> /// <remark> /// xmlns:dsp = http://schemas.microsoft.com/office/drawing/2008/diagram /// </remark> public GroupShapeProperties GroupShapeProperties { get => GetElement<GroupShapeProperties>(); set => SetElement(value); } } }
42.689474
139
0.625052
[ "MIT" ]
Muppets/Open-XML-SDK
src/DocumentFormat.OpenXml/GeneratedCode/schemas_microsoft_com_office_drawing_2008_diagram.g.cs
81,112
C#
using Lucene.Net.Analysis.Core; using Lucene.Net.Analysis.Standard; using Lucene.Net.Analysis.Tokenattributes; using Lucene.Net.Analysis.Util; using NUnit.Framework; using System; using System.IO; namespace Lucene.Net.Analysis.Miscellaneous { /* * 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. */ /// <summary> /// New WordDelimiterFilter tests... most of the tests are in ConvertedLegacyTest /// TODO: should explicitly test things like protWords and not rely on /// the factory tests in Solr. /// </summary> public class TestWordDelimiterFilter : BaseTokenStreamTestCase { // public void TestPerformance() throws IOException { // String s = "now is the time-for all good men to come to-the aid of their country."; // Token tok = new Token(); // long start = System.currentTimeMillis(); // int ret=0; // for (int i=0; i<1000000; i++) { // StringReader r = new StringReader(s); // TokenStream ts = new WhitespaceTokenizer(r); // ts = new WordDelimiterFilter(ts, 1,1,1,1,0); // // while (ts.next(tok) != null) ret++; // } // // System.out.println("ret="+ret+" time="+(System.currentTimeMillis()-start)); // } [Test] public virtual void TestOffsets() { int flags = WordDelimiterFilter.GENERATE_WORD_PARTS | WordDelimiterFilter.GENERATE_NUMBER_PARTS | WordDelimiterFilter.CATENATE_ALL | WordDelimiterFilter.SPLIT_ON_CASE_CHANGE | WordDelimiterFilter.SPLIT_ON_NUMERICS | WordDelimiterFilter.STEM_ENGLISH_POSSESSIVE; // test that subwords and catenated subwords have // the correct offsets. WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("foo-bar", 5, 12)), WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, flags, null); AssertTokenStreamContents(wdf, new string[] { "foo", "foobar", "bar" }, new int[] { 5, 5, 9 }, new int[] { 8, 12, 12 }); wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("foo-bar", 5, 6)), WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, flags, null); AssertTokenStreamContents(wdf, new string[] { "foo", "bar", "foobar" }, new int[] { 5, 5, 5 }, new int[] { 6, 6, 6 }); } [Test] public virtual void TestOffsetChange() { int flags = WordDelimiterFilter.GENERATE_WORD_PARTS | WordDelimiterFilter.GENERATE_NUMBER_PARTS | WordDelimiterFilter.CATENATE_ALL | WordDelimiterFilter.SPLIT_ON_CASE_CHANGE | WordDelimiterFilter.SPLIT_ON_NUMERICS | WordDelimiterFilter.STEM_ENGLISH_POSSESSIVE; WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("übelkeit)", 7, 16)), WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, flags, null); AssertTokenStreamContents(wdf, new string[] { "übelkeit" }, new int[] { 7 }, new int[] { 15 }); } [Test] public virtual void TestOffsetChange2() { int flags = WordDelimiterFilter.GENERATE_WORD_PARTS | WordDelimiterFilter.GENERATE_NUMBER_PARTS | WordDelimiterFilter.CATENATE_ALL | WordDelimiterFilter.SPLIT_ON_CASE_CHANGE | WordDelimiterFilter.SPLIT_ON_NUMERICS | WordDelimiterFilter.STEM_ENGLISH_POSSESSIVE; WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("(übelkeit", 7, 17)), WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, flags, null); AssertTokenStreamContents(wdf, new string[] { "übelkeit" }, new int[] { 8 }, new int[] { 17 }); } [Test] public virtual void TestOffsetChange3() { int flags = WordDelimiterFilter.GENERATE_WORD_PARTS | WordDelimiterFilter.GENERATE_NUMBER_PARTS | WordDelimiterFilter.CATENATE_ALL | WordDelimiterFilter.SPLIT_ON_CASE_CHANGE | WordDelimiterFilter.SPLIT_ON_NUMERICS | WordDelimiterFilter.STEM_ENGLISH_POSSESSIVE; WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("(übelkeit", 7, 16)), WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, flags, null); AssertTokenStreamContents(wdf, new string[] { "übelkeit" }, new int[] { 8 }, new int[] { 16 }); } [Test] public virtual void TestOffsetChange4() { int flags = WordDelimiterFilter.GENERATE_WORD_PARTS | WordDelimiterFilter.GENERATE_NUMBER_PARTS | WordDelimiterFilter.CATENATE_ALL | WordDelimiterFilter.SPLIT_ON_CASE_CHANGE | WordDelimiterFilter.SPLIT_ON_NUMERICS | WordDelimiterFilter.STEM_ENGLISH_POSSESSIVE; WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new SingleTokenTokenStream(new Token("(foo,bar)", 7, 16)), WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, flags, null); AssertTokenStreamContents(wdf, new string[] { "foo", "foobar", "bar" }, new int[] { 8, 8, 12 }, new int[] { 11, 15, 15 }); } public virtual void doSplit(string input, params string[] output) { int flags = WordDelimiterFilter.GENERATE_WORD_PARTS | WordDelimiterFilter.GENERATE_NUMBER_PARTS | WordDelimiterFilter.SPLIT_ON_CASE_CHANGE | WordDelimiterFilter.SPLIT_ON_NUMERICS | WordDelimiterFilter.STEM_ENGLISH_POSSESSIVE; WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new MockTokenizer(new StringReader(input), MockTokenizer.KEYWORD, false), WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, flags, null); AssertTokenStreamContents(wdf, output); } [Test] public virtual void TestSplits() { doSplit("basic-split", "basic", "split"); doSplit("camelCase", "camel", "Case"); // non-space marking symbol shouldn't cause split // this is an example in Thai doSplit("\u0e1a\u0e49\u0e32\u0e19", "\u0e1a\u0e49\u0e32\u0e19"); // possessive followed by delimiter doSplit("test's'", "test"); // some russian upper and lowercase doSplit("Роберт", "Роберт"); // now cause a split (russian camelCase) doSplit("РобЕрт", "Роб", "Ерт"); // a composed titlecase character, don't split doSplit("aDžungla", "aDžungla"); // a modifier letter, don't split doSplit("ســـــــــــــــــلام", "ســـــــــــــــــلام"); // enclosing mark, don't split doSplit("test⃝", "test⃝"); // combining spacing mark (the virama), don't split doSplit("हिन्दी", "हिन्दी"); // don't split non-ascii digits doSplit("١٢٣٤", "١٢٣٤"); // don't split supplementaries into unpaired surrogates doSplit("𠀀𠀀", "𠀀𠀀"); } public virtual void doSplitPossessive(int stemPossessive, string input, params string[] output) { int flags = WordDelimiterFilter.GENERATE_WORD_PARTS | WordDelimiterFilter.GENERATE_NUMBER_PARTS | WordDelimiterFilter.SPLIT_ON_CASE_CHANGE | WordDelimiterFilter.SPLIT_ON_NUMERICS; flags |= (stemPossessive == 1) ? WordDelimiterFilter.STEM_ENGLISH_POSSESSIVE : 0; WordDelimiterFilter wdf = new WordDelimiterFilter(TEST_VERSION_CURRENT, new MockTokenizer(new StringReader(input), MockTokenizer.KEYWORD, false), flags, null); AssertTokenStreamContents(wdf, output); } /* * Test option that allows disabling the special "'s" stemming, instead treating the single quote like other delimiters. */ [Test] public virtual void TestPossessives() { doSplitPossessive(1, "ra's", "ra"); doSplitPossessive(0, "ra's", "ra", "s"); } /* * Set a large position increment gap of 10 if the token is "largegap" or "/" */ private sealed class LargePosIncTokenFilter : TokenFilter { private readonly TestWordDelimiterFilter outerInstance; internal ICharTermAttribute termAtt; internal IPositionIncrementAttribute posIncAtt; internal LargePosIncTokenFilter(TestWordDelimiterFilter outerInstance, TokenStream input) : base(input) { this.outerInstance = outerInstance; this.termAtt = AddAttribute<ICharTermAttribute>(); this.posIncAtt = AddAttribute<IPositionIncrementAttribute>(); } public override bool IncrementToken() { if (input.IncrementToken()) { if (termAtt.ToString().Equals("largegap") || termAtt.ToString().Equals("/")) { posIncAtt.PositionIncrement = 10; } return true; } else { return false; } } } [Test] public virtual void TestPositionIncrements() { int flags = WordDelimiterFilter.GENERATE_WORD_PARTS | WordDelimiterFilter.GENERATE_NUMBER_PARTS | WordDelimiterFilter.CATENATE_ALL | WordDelimiterFilter.SPLIT_ON_CASE_CHANGE | WordDelimiterFilter.SPLIT_ON_NUMERICS | WordDelimiterFilter.STEM_ENGLISH_POSSESSIVE; CharArraySet protWords = new CharArraySet(TEST_VERSION_CURRENT, new string[] { "NUTCH" }, false); /* analyzer that uses whitespace + wdf */ Analyzer a = new AnalyzerAnonymousInnerClassHelper(this, flags, protWords); /* in this case, works as expected. */ AssertAnalyzesTo(a, "LUCENE / SOLR", new string[] { "LUCENE", "SOLR" }, new int[] { 0, 9 }, new int[] { 6, 13 }, new int[] { 1, 1 }); /* only in this case, posInc of 2 ?! */ AssertAnalyzesTo(a, "LUCENE / solR", new string[] { "LUCENE", "sol", "solR", "R" }, new int[] { 0, 9, 9, 12 }, new int[] { 6, 12, 13, 13 }, new int[] { 1, 1, 0, 1 }); AssertAnalyzesTo(a, "LUCENE / NUTCH SOLR", new string[] { "LUCENE", "NUTCH", "SOLR" }, new int[] { 0, 9, 15 }, new int[] { 6, 14, 19 }, new int[] { 1, 1, 1 }); /* analyzer that will consume tokens with large position increments */ Analyzer a2 = new AnalyzerAnonymousInnerClassHelper2(this, flags, protWords); /* increment of "largegap" is preserved */ AssertAnalyzesTo(a2, "LUCENE largegap SOLR", new string[] { "LUCENE", "largegap", "SOLR" }, new int[] { 0, 7, 16 }, new int[] { 6, 15, 20 }, new int[] { 1, 10, 1 }); /* the "/" had a position increment of 10, where did it go?!?!! */ AssertAnalyzesTo(a2, "LUCENE / SOLR", new string[] { "LUCENE", "SOLR" }, new int[] { 0, 9 }, new int[] { 6, 13 }, new int[] { 1, 11 }); /* in this case, the increment of 10 from the "/" is carried over */ AssertAnalyzesTo(a2, "LUCENE / solR", new string[] { "LUCENE", "sol", "solR", "R" }, new int[] { 0, 9, 9, 12 }, new int[] { 6, 12, 13, 13 }, new int[] { 1, 11, 0, 1 }); AssertAnalyzesTo(a2, "LUCENE / NUTCH SOLR", new string[] { "LUCENE", "NUTCH", "SOLR" }, new int[] { 0, 9, 15 }, new int[] { 6, 14, 19 }, new int[] { 1, 11, 1 }); Analyzer a3 = new AnalyzerAnonymousInnerClassHelper3(this, flags, protWords); AssertAnalyzesTo(a3, "lucene.solr", new string[] { "lucene", "lucenesolr", "solr" }, new int[] { 0, 0, 7 }, new int[] { 6, 11, 11 }, new int[] { 1, 0, 1 }); /* the stopword should add a gap here */ AssertAnalyzesTo(a3, "the lucene.solr", new string[] { "lucene", "lucenesolr", "solr" }, new int[] { 4, 4, 11 }, new int[] { 10, 15, 15 }, new int[] { 2, 0, 1 }); } private class AnalyzerAnonymousInnerClassHelper : Analyzer { private readonly TestWordDelimiterFilter outerInstance; private int flags; private CharArraySet protWords; public AnalyzerAnonymousInnerClassHelper(TestWordDelimiterFilter outerInstance, int flags, CharArraySet protWords) { this.outerInstance = outerInstance; this.flags = flags; this.protWords = protWords; } public override TokenStreamComponents CreateComponents(string field, TextReader reader) { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, tokenizer, flags, protWords)); } } private class AnalyzerAnonymousInnerClassHelper2 : Analyzer { private readonly TestWordDelimiterFilter outerInstance; private int flags; private CharArraySet protWords; public AnalyzerAnonymousInnerClassHelper2(TestWordDelimiterFilter outerInstance, int flags, CharArraySet protWords) { this.outerInstance = outerInstance; this.flags = flags; this.protWords = protWords; } public override TokenStreamComponents CreateComponents(string field, TextReader reader) { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, new LargePosIncTokenFilter(outerInstance, tokenizer), flags, protWords)); } } private class AnalyzerAnonymousInnerClassHelper3 : Analyzer { private readonly TestWordDelimiterFilter outerInstance; private int flags; private CharArraySet protWords; public AnalyzerAnonymousInnerClassHelper3(TestWordDelimiterFilter outerInstance, int flags, CharArraySet protWords) { this.outerInstance = outerInstance; this.flags = flags; this.protWords = protWords; } public override TokenStreamComponents CreateComponents(string field, TextReader reader) { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); StopFilter filter = new StopFilter(TEST_VERSION_CURRENT, tokenizer, StandardAnalyzer.STOP_WORDS_SET); return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, filter, flags, protWords)); } } /// <summary> /// concat numbers + words + all </summary> [Test] public virtual void TestLotsOfConcatenating() { int flags = WordDelimiterFilter.GENERATE_WORD_PARTS | WordDelimiterFilter.GENERATE_NUMBER_PARTS | WordDelimiterFilter.CATENATE_WORDS | WordDelimiterFilter.CATENATE_NUMBERS | WordDelimiterFilter.CATENATE_ALL | WordDelimiterFilter.SPLIT_ON_CASE_CHANGE | WordDelimiterFilter.SPLIT_ON_NUMERICS | WordDelimiterFilter.STEM_ENGLISH_POSSESSIVE; /* analyzer that uses whitespace + wdf */ Analyzer a = new AnalyzerAnonymousInnerClassHelper4(this, flags); AssertAnalyzesTo(a, "abc-def-123-456", new string[] { "abc", "abcdef", "abcdef123456", "def", "123", "123456", "456" }, new int[] { 0, 0, 0, 4, 8, 8, 12 }, new int[] { 3, 7, 15, 7, 11, 15, 15 }, new int[] { 1, 0, 0, 1, 1, 0, 1 }); } private class AnalyzerAnonymousInnerClassHelper4 : Analyzer { private readonly TestWordDelimiterFilter outerInstance; private int flags; public AnalyzerAnonymousInnerClassHelper4(TestWordDelimiterFilter outerInstance, int flags) { this.outerInstance = outerInstance; this.flags = flags; } public override TokenStreamComponents CreateComponents(string field, TextReader reader) { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, tokenizer, flags, null)); } } /// <summary> /// concat numbers + words + all + preserve original </summary> [Test] public virtual void TestLotsOfConcatenating2() { int flags = WordDelimiterFilter.PRESERVE_ORIGINAL | WordDelimiterFilter.GENERATE_WORD_PARTS | WordDelimiterFilter.GENERATE_NUMBER_PARTS | WordDelimiterFilter.CATENATE_WORDS | WordDelimiterFilter.CATENATE_NUMBERS | WordDelimiterFilter.CATENATE_ALL | WordDelimiterFilter.SPLIT_ON_CASE_CHANGE | WordDelimiterFilter.SPLIT_ON_NUMERICS | WordDelimiterFilter.STEM_ENGLISH_POSSESSIVE; /* analyzer that uses whitespace + wdf */ Analyzer a = new AnalyzerAnonymousInnerClassHelper5(this, flags); AssertAnalyzesTo(a, "abc-def-123-456", new string[] { "abc-def-123-456", "abc", "abcdef", "abcdef123456", "def", "123", "123456", "456" }, new int[] { 0, 0, 0, 0, 4, 8, 8, 12 }, new int[] { 15, 3, 7, 15, 7, 11, 15, 15 }, new int[] { 1, 0, 0, 0, 1, 1, 0, 1 }); } private class AnalyzerAnonymousInnerClassHelper5 : Analyzer { private readonly TestWordDelimiterFilter outerInstance; private int flags; public AnalyzerAnonymousInnerClassHelper5(TestWordDelimiterFilter outerInstance, int flags) { this.outerInstance = outerInstance; this.flags = flags; } public override TokenStreamComponents CreateComponents(string field, TextReader reader) { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, tokenizer, flags, null)); } } /// <summary> /// blast some random strings through the analyzer </summary> public virtual void TestRandomStrings() { int numIterations = AtLeast(5); for (int i = 0; i < numIterations; i++) { int flags = Random().Next(512); CharArraySet protectedWords; if (Random().nextBoolean()) { protectedWords = new CharArraySet(TEST_VERSION_CURRENT, new string[] { "a", "b", "cd" }, false); } else { protectedWords = null; } Analyzer a = new AnalyzerAnonymousInnerClassHelper6(this, flags, protectedWords); CheckRandomData(Random(), a, 1000 * RANDOM_MULTIPLIER); } } private class AnalyzerAnonymousInnerClassHelper6 : Analyzer { private readonly TestWordDelimiterFilter outerInstance; private int flags; private CharArraySet protectedWords; public AnalyzerAnonymousInnerClassHelper6(TestWordDelimiterFilter outerInstance, int flags, CharArraySet protectedWords) { this.outerInstance = outerInstance; this.flags = flags; this.protectedWords = protectedWords; } public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, tokenizer, flags, protectedWords)); } } /// <summary> /// blast some enormous random strings through the analyzer </summary> [Test] public virtual void TestRandomHugeStrings() { int numIterations = AtLeast(5); for (int i = 0; i < numIterations; i++) { int flags = Random().Next(512); CharArraySet protectedWords; if (Random().nextBoolean()) { protectedWords = new CharArraySet(TEST_VERSION_CURRENT, new string[] { "a", "b", "cd" }, false); } else { protectedWords = null; } Analyzer a = new AnalyzerAnonymousInnerClassHelper7(this, flags, protectedWords); CheckRandomData(Random(), a, 100 * RANDOM_MULTIPLIER, 8192); } } private class AnalyzerAnonymousInnerClassHelper7 : Analyzer { private readonly TestWordDelimiterFilter outerInstance; private int flags; private CharArraySet protectedWords; public AnalyzerAnonymousInnerClassHelper7(TestWordDelimiterFilter outerInstance, int flags, CharArraySet protectedWords) { this.outerInstance = outerInstance; this.flags = flags; this.protectedWords = protectedWords; } public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, tokenizer, flags, protectedWords)); } } [Test] public virtual void TestEmptyTerm() { Random random = Random(); for (int i = 0; i < 512; i++) { int flags = i; CharArraySet protectedWords; if (random.nextBoolean()) { protectedWords = new CharArraySet(TEST_VERSION_CURRENT, new string[] { "a", "b", "cd" }, false); } else { protectedWords = null; } Analyzer a = new AnalyzerAnonymousInnerClassHelper8(this, flags, protectedWords); // depending upon options, this thing may or may not preserve the empty term CheckAnalysisConsistency(random, a, random.nextBoolean(), ""); } } private class AnalyzerAnonymousInnerClassHelper8 : Analyzer { private readonly TestWordDelimiterFilter outerInstance; private int flags; private CharArraySet protectedWords; public AnalyzerAnonymousInnerClassHelper8(TestWordDelimiterFilter outerInstance, int flags, CharArraySet protectedWords) { this.outerInstance = outerInstance; this.flags = flags; this.protectedWords = protectedWords; } public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { Tokenizer tokenizer = new KeywordTokenizer(reader); return new TokenStreamComponents(tokenizer, new WordDelimiterFilter(TEST_VERSION_CURRENT, tokenizer, flags, protectedWords)); } } } }
48.303393
388
0.623347
[ "Apache-2.0" ]
BlueCurve-Team/lucenenet
src/Lucene.Net.Tests.Analysis.Common/Analysis/Miscellaneous/TestWordDelimiterFilter.cs
24,324
C#
using System.Collections.Generic; using System.Text.Json.Serialization; namespace OrderResults.Models.FormRecognizer { public class Page { [JsonPropertyName("pageNumber")] public int PageNumber { get; set; } [JsonPropertyName("angle")] public double Angle { get; set; } [JsonPropertyName("width")] public double Width { get; set; } [JsonPropertyName("height")] public double Height { get; set; } [JsonPropertyName("unit")] public string Unit { get; set; } [JsonPropertyName("words")] public List<Word> Words { get; set; } [JsonPropertyName("selectionMarks")] public List<SelectionMark> SelectionMarks { get; set; } [JsonPropertyName("lines")] public List<Line> Lines { get; set; } [JsonPropertyName("spans")] public List<Span> Spans { get; set; } } }
25.444444
63
0.605895
[ "MIT" ]
sagar2503/azure-search-dotnet-samples
create-first-app/v11/5-order-results/OrderResults/Models/FormRecognizer/Page.cs
916
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using TestGame.Input; namespace TestGame.Entities { public class Player : Entity { private SoundEffect _fireEffect; private SoundEffectInstance _fireEffectInstance; public Player(TestGame game) : base(game) { } public float Velocity { get; set; } = 150.0f; protected override void LoadContent() { _fireEffect = Game.Content.Load<SoundEffect>("brother1"); _fireEffectInstance = _fireEffect.CreateInstance(); Sprite = new Sprite { Texture = Game.Content.Load<Texture2D>("hulk"), Size = new Vector2(256) }; base.LoadContent(); } public override void Update(GameTime gameTime) { float deltaTime = (float) gameTime.ElapsedGameTime.TotalSeconds; if (Game.InputState.KeysDown(false, Keys.A, Keys.Left)) { Sprite.Position = Sprite.Position.SubX(deltaTime * Velocity); } if (Game.InputState.KeysDown(false, Keys.D, Keys.Right)) { Sprite.Position = Sprite.Position.AddX(deltaTime * Velocity); } if (Game.InputState.KeysDown(false, Keys.S, Keys.Down)) { Sprite.Position = Sprite.Position.AddY(deltaTime * Velocity); } if (Game.InputState.KeysDown(false, Keys.W, Keys.Up)) { Sprite.Position = Sprite.Position.SubY(deltaTime * Velocity); } if (Game.InputState.KeyPressed(Keys.Space) || Game.InputState.MultiMousePressed(false, MouseButton.LeftButton, MouseButton.RightButton)) { _fireEffectInstance.Play(); } if (Game.InputState.KeyPressed(Keys.Q)) { Sprite.Size = Sprite.Size * 2; } if (Game.InputState.KeyPressed(Keys.E)) { Sprite.Size = Sprite.Size / 2; } if (Game.InputState.KeyDown(Keys.Z)) { Sprite.Rotation += deltaTime; } base.Update(gameTime); } } }
28.626506
106
0.544613
[ "MIT" ]
EnsignPayton/MonoGame-Test
TestGame/Entities/Player.cs
2,378
C#
using System; using System.Collections.Generic; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Threading; using FluentAssertions; using NUnit.Framework; using Octopus.Shellfish; using Octopus.Shellfish.Plumbing; using Octopus.Shellfish.Windows; using Tests.Plumbing; namespace Tests { [TestFixture] public class ShellExecutorFixture { const int SIG_TERM = 143; const int SIG_KILL = 137; const string Username = "test-shellexecutor"; static readonly string Command = PlatformDetection.IsRunningOnWindows ? "cmd.exe" : "bash"; static readonly string CommandParam = PlatformDetection.IsRunningOnWindows ? "/c" : "-c"; [Test] public void ExitCode_ShouldBeReturned() { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var arguments = $"{CommandParam} \"exit 99\""; var workingDirectory = ""; var networkCredential = default(NetworkCredential); IDictionary<string, string>? customEnvironmentVariables = null; var exitCode = Execute(Command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); var expectedEncoding = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? WindowsEncodingHelper.GetOemEncoding() : Encoding.UTF8; exitCode.Should().Be(99, "our custom exit code should be reflected"); debugMessages.ToString().Should().ContainEquivalentOf($"Starting {Command} in working directory '' using '{expectedEncoding.EncodingName}' encoding running as '{ProcessIdentity.CurrentUserName}'"); errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); infoMessages.ToString().Should().BeEmpty("no messages should be written to stdout"); } [Test] public void DebugLogging_ShouldContainDiagnosticsInfo_ForDefault() { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var arguments = $"{CommandParam} \"echo hello\""; var workingDirectory = ""; var networkCredential = default(NetworkCredential); var customEnvironmentVariables = new Dictionary<string, string>(); var exitCode = Execute(Command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); exitCode.Should().Be(0, "the process should have run to completion"); debugMessages.ToString() .Should() .ContainEquivalentOf(Command, "the command should be logged") .And.ContainEquivalentOf(ProcessIdentity.CurrentUserName, "the current user details should be logged"); infoMessages.ToString().Should().ContainEquivalentOf("hello"); errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); } [Test] public void RunningAsSameUser_ShouldCopySpecialEnvironmentVariables() { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var arguments = $"{CommandParam} \"echo {EchoEnvironmentVariable("customenvironmentvariable")}\""; var workingDirectory = ""; var networkCredential = default(NetworkCredential); var customEnvironmentVariables = new Dictionary<string, string> { { "customenvironmentvariable", "customvalue" } }; var exitCode = Execute(Command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); exitCode.Should().Be(0, "the process should have run to completion"); infoMessages.ToString().Should().ContainEquivalentOf("customvalue", "the environment variable should have been copied to the child process"); errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); } [Test] [WindowsTest] public void DebugLogging_ShouldContainDiagnosticsInfo_DifferentUser() { var user = new TestUserPrincipal(Username); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var arguments = $"{CommandParam} \"echo %userdomain%\\%username%\""; // Target the CommonApplicationData folder since this is a place the particular user can get to var workingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var networkCredential = user.GetCredential(); var customEnvironmentVariables = new Dictionary<string, string>(); var exitCode = Execute(Command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); exitCode.Should().Be(0, "the process should have run to completion"); debugMessages.ToString() .Should() .ContainEquivalentOf(Command, "the command should be logged") .And.ContainEquivalentOf($@"{user.DomainName}\{user.UserName}", "the custom user details should be logged") .And.ContainEquivalentOf(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "the working directory should be logged"); infoMessages.ToString().Should().ContainEquivalentOf($@"{user.DomainName}\{user.UserName}"); errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); } [Test] [WindowsTest] public void RunningAsDifferentUser_ShouldCopySpecialEnvironmentVariables() { var user = new TestUserPrincipal(Username); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var arguments = $"{CommandParam} \"echo {EchoEnvironmentVariable("customenvironmentvariable")}\""; // Target the CommonApplicationData folder since this is a place the particular user can get to var workingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var networkCredential = user.GetCredential(); var customEnvironmentVariables = new Dictionary<string, string> { { "customenvironmentvariable", "customvalue" } }; var exitCode = Execute(Command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); exitCode.Should().Be(0, "the process should have run to completion"); infoMessages.ToString().Should().ContainEquivalentOf("customvalue", "the environment variable should have been copied to the child process"); errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); } [Test] [WindowsTest] public void RunningAsDifferentUser_ShouldWorkLotsOfTimes() { var user = new TestUserPrincipal(Username); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(120)); for (var i = 0; i < 20; i++) { var arguments = $"{CommandParam} \"echo {EchoEnvironmentVariable("customenvironmentvariable")}%\""; // Target the CommonApplicationData folder since this is a place the particular user can get to var workingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var networkCredential = user.GetCredential(); var customEnvironmentVariables = new Dictionary<string, string> { { "customenvironmentvariable", $"customvalue-{i}" } }; var exitCode = Execute(Command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); exitCode.Should().Be(0, "the process should have run to completion"); infoMessages.ToString().Should().ContainEquivalentOf($"customvalue-{i}", "the environment variable should have been copied to the child process"); errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); } } [Test] [WindowsTest] public void RunningAsDifferentUser_CanWriteToItsOwnTempPath() { var user = new TestUserPrincipal(Username); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); { var arguments = $"{CommandParam} \"echo hello > %temp%hello.txt\""; // Target the CommonApplicationData folder since this is a place the particular user can get to var workingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var networkCredential = user.GetCredential(); var customEnvironmentVariables = new Dictionary<string, string>(); var exitCode = Execute(Command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); exitCode.Should().Be(0, "the process should have run to completion after writing to the temp folder for the other user"); errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); } } [Test] [Retry(3)] public void CancellationToken_ShouldForceKillTheProcess() { // Terminate the process after a very short time so the test doesn't run forever using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1)); // Starting a new instance of cmd.exe will run indefinitely waiting for user input var arguments = ""; var workingDirectory = ""; var networkCredential = default(NetworkCredential); var customEnvironmentVariables = new Dictionary<string, string>(); var exitCode = Execute(Command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); if (PlatformDetection.IsRunningOnWindows) { exitCode.Should().BeLessOrEqualTo(0, "the process should have been terminated"); infoMessages.ToString().Should().ContainEquivalentOf("Microsoft Windows", "the default command-line header would be written to stdout"); } else { exitCode.Should().BeOneOf(SIG_KILL, SIG_TERM, 0); } errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); } [Test] public void EchoHello_ShouldWriteToStdOut() { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var arguments = $"{CommandParam} \"echo hello\""; var workingDirectory = ""; var networkCredential = default(NetworkCredential); var customEnvironmentVariables = new Dictionary<string, string>(); var exitCode = Execute(Command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); exitCode.Should().Be(0, "the process should have run to completion"); errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); infoMessages.ToString().Should().ContainEquivalentOf("hello"); } [Test] public void EchoError_ShouldWriteToStdErr() { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var arguments = $"{CommandParam} \"echo Something went wrong! 1>&2\""; var workingDirectory = ""; var networkCredential = default(NetworkCredential); var customEnvironmentVariables = new Dictionary<string, string>(); var exitCode = Execute(Command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); exitCode.Should().Be(0, "the process should have run to completion"); infoMessages.ToString().Should().BeEmpty("no messages should be written to stdout"); errorMessages.ToString().Should().ContainEquivalentOf("Something went wrong!"); } [Test] public void RunAsCurrentUser_ShouldWork() { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var arguments = PlatformDetection.IsRunningOnWindows ? $"{CommandParam} \"echo {EchoEnvironmentVariable("username")}\"" : $"{CommandParam} \"whoami\""; var workingDirectory = ""; var networkCredential = default(NetworkCredential); var customEnvironmentVariables = new Dictionary<string, string>(); var exitCode = Execute(Command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); exitCode.Should().Be(0, "the process should have run to completion"); errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); infoMessages.ToString().Should().ContainEquivalentOf($@"{Environment.UserName}"); } [Test] [WindowsTest] [TestCase("powershell.exe", "-command \"Write-Host $env:userdomain\\$env:username\"")] public void RunAsCurrentUser_PowerShell_ShouldWork(string command, string arguments) { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var workingDirectory = ""; var networkCredential = default(NetworkCredential); var customEnvironmentVariables = new Dictionary<string, string>(); var exitCode = Execute(command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); exitCode.Should().Be(0, "the process should have run to completion"); errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); infoMessages.ToString().Should().ContainEquivalentOf($@"{Environment.UserDomainName}\{Environment.UserName}"); } [Test] [WindowsTest] [TestCase("cmd.exe", "/c \"echo %userdomain%\\%username%\"")] [TestCase("powershell.exe", "-command \"Write-Host $env:userdomain\\$env:username\"")] public void RunAsDifferentUser_ShouldWork(string command, string arguments) { var user = new TestUserPrincipal(Username); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); // Target the CommonApplicationData folder since this is a place the particular user can get to var workingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var networkCredential = user.GetCredential(); var customEnvironmentVariables = new Dictionary<string, string>(); var exitCode = Execute(command, arguments, workingDirectory, out var debugMessages, out var infoMessages, out var errorMessages, networkCredential, customEnvironmentVariables, cts.Token); exitCode.Should().Be(0, "the process should have run to completion"); errorMessages.ToString().Should().BeEmpty("no messages should be written to stderr"); infoMessages.ToString().Should().ContainEquivalentOf($@"{user.DomainName}\{user.UserName}"); } static string EchoEnvironmentVariable(string varName) => PlatformDetection.IsRunningOnWindows ? $"%{varName}%" : $"${varName}"; static int Execute( string command, string arguments, string workingDirectory, out StringBuilder debugMessages, out StringBuilder infoMessages, out StringBuilder errorMessages, NetworkCredential? networkCredential, IDictionary<string, string>? customEnvironmentVariables, CancellationToken cancel ) { var debug = new StringBuilder(); var info = new StringBuilder(); var error = new StringBuilder(); var exitCode = ShellExecutor.ExecuteCommand( command, arguments, workingDirectory, x => { Console.WriteLine($"{DateTime.UtcNow} DBG: {x}"); debug.Append(x); }, x => { Console.WriteLine($"{DateTime.UtcNow} INF: {x}"); info.Append(x); }, x => { Console.WriteLine($"{DateTime.UtcNow} ERR: {x}"); error.Append(x); }, networkCredential, customEnvironmentVariables, cancel); debugMessages = debug; infoMessages = info; errorMessages = error; return exitCode; } } }
43.039301
209
0.592938
[ "Apache-2.0" ]
OctopusDeploy/Process
source/Tests/ShellExecutorFixture.cs
19,714
C#
namespace Mobet.Infrastructure.Migrations { using System; using System.Data.Entity.Migrations; public partial class _05 : DbMigration { public override void Up() { AlterColumn("dbo.Users", "Subject", c => c.String(nullable: false, maxLength: 50)); } public override void Down() { AlterColumn("dbo.Users", "Subject", c => c.String(nullable: false)); } } }
24.263158
95
0.561822
[ "Apache-2.0" ]
Mobet/mobet
Mobet-Net/Mobet.Infrastructure/Migrations/201604061212004_05.cs
461
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Validation; using System.Linq; using MyWpfFramework.Common.EntityFrameworkToolkit; using MyWpfFramework.Common.PersianToolkit; using MyWpfFramework.Common.UI; using MyWpfFramework.DomainClasses; namespace MyWpfFramework.DataLayer.Context { /// <summary> /// پیاده سازی الگوی واحد کار /// </summary> public class MyDbContextBase : DbContext, IUnitOfWork { /// <summary> /// بازگردانی تغییرات انجام شده در رکوردهای تحت نظر در حافظه به حالت اول /// </summary> public void RejectChanges() { foreach (var entry in this.ChangeTracker.Entries()) { switch (entry.State) { case EntityState.Modified: entry.State = EntityState.Unchanged; break; case EntityState.Added: entry.State = EntityState.Detached; break; } } } private void auditFields(string auditUser) { foreach (var entry in this.ChangeTracker.Entries<BaseEntity>()) { switch (entry.State) { case EntityState.Added: setCreatedOn(auditUser, entry); setModifiedOn(auditUser, entry); break; case EntityState.Modified: setModifiedOn(auditUser, entry); break; } } } private static void setModifiedOn(string auditUser, DbEntityEntry<BaseEntity> entry) { entry.Entity.ModifiedOn = DateTime.Now; entry.Entity.ModifiedBy = auditUser; } private static void setCreatedOn(string auditUser, DbEntityEntry<BaseEntity> entry) { entry.Entity.CreatedOn = DateTime.Now; entry.Entity.CreatedBy = auditUser; entry.Entity.CreatedOnPersian = PersianDate.CurrentSystemShamsiDate("/", true); } /// <summary> /// دسترسی به اعمال قابل انجام با یک موجودیت را فراهم می‌کند /// </summary> /// <typeparam name="TEntity">نوع موجودیت</typeparam> public new IDbSet<TEntity> Set<TEntity>() where TEntity : class { return base.Set<TEntity>(); } /// <summary> /// ذخیره سازی کلیه تغییرات انجام شده در تمامی رکوردهای تحت نظر در حافظه /// </summary> /// <param name="userName">نام کاربر جاری</param> /// <param name="updateAuditFields">آیا فیلدهای ویرایش کننده اطلاعات نیز مقدار دهی شوند؟</param> /// <returns>تعداد رکوردهای تغییر کرده</returns> public int ApplyAllChanges(string userName, bool updateAuditFields = true) { try { if (string.IsNullOrWhiteSpace(userName)) userName = "Program"; if (this.Configuration.AutoDetectChangesEnabled) this.ApplyCorrectYeKe(); if (updateAuditFields) { auditFields(userName); } if (hasValidationErrors()) return 0; return base.SaveChanges(); } catch (DbEntityValidationException validationException) { var errors = new List<string>(); foreach (var error in validationException.EntityValidationErrors) { var entry = error.Entry; errors.Add(entry.Entity.GetType().Name + ": " + entry.State); foreach (var err in error.ValidationErrors) { errors.Add(err.PropertyName + " " + err.ErrorMessage); } } new SendMsg().ShowMsg( new AlertConfirmBoxModel { ErrorTitle = "خطای اعتبار سنجی", Errors = errors, }, validationException); } catch (DbUpdateConcurrencyException concurrencyException) { var errors = "مقادیر در سمت بانک اطلاعاتی تغییر کرده‌اند. لطفا صفحه را ریفرش کنید" + ": " + concurrencyException.Entries.First().Entity.GetType().Name; new SendMsg().ShowMsg( new AlertConfirmBoxModel { ErrorTitle = "خطای همزمانی", Errors = new List<string> { errors }, }, concurrencyException); } catch (DbUpdateException updateException) { var errors = new List<string> { updateException.Message }; if (updateException.InnerException != null) errors.Add(updateException.InnerException.Message); foreach (var entry in updateException.Entries) { errors.Add("Related Entity: " + entry.Entity); } new SendMsg().ShowMsg( new AlertConfirmBoxModel { ErrorTitle = "خطای به روز رسانی", Errors = errors, }, updateException); } return 0; } private bool hasValidationErrors() { var validationErrors = this.GetValidationErrors(); if (validationErrors == null || !validationErrors.Any()) return false; var results = new List<string>(); foreach (var item in validationErrors) { results.Add(string.Join(Environment.NewLine, item.ValidationErrors.Select(x => x.ErrorMessage))); } //نمایش خطاهای اعتبار سنجی به کاربر new SendMsg().ShowMsg( new AlertConfirmBoxModel { ErrorTitle = "لطفا خطاهای زیر را پیش از ثبت نهایی برطرف کنید:", Errors = results }); return true; } /// <summary> /// برای ذخیره سازی تعداد زیادی رکورد با هم کاربرد دارد. در غیراینصورت از آن استفاده نکنید /// </summary> public void DisableChangeTracking() { this.Configuration.AutoDetectChangesEnabled = false; this.Configuration.ValidateOnSaveEnabled = false; } /// <summary> /// آیا در رکوردهای تحت نظر در حافظه تغییری حاصل شده است؟ /// </summary> public bool ContextHasChanges { get { return this.ChangeTracker .Entries() .Any(x => x.State == EntityState.Added || x.State == EntityState.Deleted || x.State == EntityState.Modified); } } } }
35.135922
113
0.504421
[ "Apache-2.0" ]
VahidN/WpfFramework
MyWpfFramework.DataLayer/Context/MyDbContextBase.cs
7,781
C#
// // The MIT License (MIT) // Copyright © 2020 d-exclaimation // using UnityEngine; public class Parallax : MonoBehaviour { public GameObject cam; public float effectMultiplier; public Vector2 offset; public bool ignoreY; private float _length, _startPos; private float camX => cam.transform.position.x; private float camY => cam.transform.position.y; private float currentZ => transform.position.z; private float currentY => transform.position.y; void Start() { _startPos = transform.position.x; _length = GetComponent<SpriteRenderer>().bounds.size.x; } // Update is called once per frame void FixedUpdate() { var temp = camX * (1 - effectMultiplier); var dist = camX * effectMultiplier; transform.position = new Vector3(_startPos + dist + offset.x, ignoreY ? currentY : camY + offset.y, currentZ); if (temp > _startPos + _length) _startPos += _length; else if (temp < _startPos - _length) _startPos -= _length; } }
29.027778
118
0.657416
[ "MIT" ]
d-exclaimation/FlatlinerTheGame
Assets/Scripts/Parallax.cs
1,048
C#
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class DiegoPonceDeLeon : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Diego"; public string LastName => "Ponce de León"; public string StateOrRegion => "Alicante, Spain"; public string EmailAddress => "malandro@gmail.com"; public string ShortBioOrTagLine => "is a freelance software developer"; public Uri WebSite => new Uri("http://xleon.net"); public string TwitterHandle => "diegoxleon"; public string GitHubHandle => "xleon"; public string GravatarHash => "b9371d959d3460b285f7f5f679a45c73"; public GeoPosition Position => new GeoPosition(38.8259465, 0.126317); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://xleon.net/feed.xml"); } } public bool Filter(SyndicationItem item) => item.Links.Any(x => x.Uri.AbsoluteUri.ToLowerInvariant().Contains("xamarin")); } }
38.2
93
0.67452
[ "MIT" ]
JaridKG/planetxamarin
src/Firehose.Web/Authors/DiegoPonceDeLeon.cs
1,149
C#
namespace AgEitilt.Common.Storage { /// <summary> /// Provides access to information about the service providing this file. /// </summary> public interface IStorageItemPropertiesWithProvider : IStorageItemProperties { //TODO: Implement Provider once StorageProvider handling has been // added } }
34
79
0.764706
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Eitilt/CommonHelpers
Storage/Storage/IStorageItemPropertiesWithProvider.cs
308
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Project.Client.Entities; using System.Collections.Generic; using System.Threading.Tasks; using Lib = Project.Domain; namespace Project.Client.Controllers { [Route("api/[controller]")] [ApiController] public class PlayListController : ControllerBase { private readonly Lib.IRepository repository; public PlayListController(Lib.IRepository repository) { this.repository = repository; } // GET api/values [HttpGet] [ProducesResponseType(typeof(Playlist), StatusCodes.Status200OK)] [Produces("application/json")] public async Task<IEnumerable<Playlist>> Get() { IEnumerable<Playlist> plists = await Task.Run(() => Mapper.Map(repository.GetPlayLists())); return plists; } // GET api/values/5 [HttpGet("{id}")] [ProducesResponseType(typeof(Playlist), StatusCodes.Status200OK)] [Produces("application/json")] public async Task<Playlist> Get([FromRoute]int id) { try { Playlist plist = await Task.Run(() => Mapper.Map(repository.GetPlayListById(id))); return plist; } catch { return new Playlist(); } } // POST api/values [HttpPost] [ProducesResponseType(typeof(Playlist), StatusCodes.Status201Created)] [Produces("application/json")] public async Task<IActionResult> Post([FromBody] Playlist plist) { if (!ModelState.IsValid) return BadRequest(); int rowAffected = await Task.Run(() => repository.CreatePlayList(Mapper.Map(plist))); if (rowAffected > 0) return Ok(); return BadRequest(); } //PUT api/values/5 [HttpPut] [ProducesResponseType(typeof(Playlist), StatusCodes.Status202Accepted)] [Produces("application/json")] public async Task<IActionResult> Put([FromBody] Playlist plist) { if (!ModelState.IsValid) return BadRequest(); int rowAffected = await Task.Run(() => repository.UpdatePlayList(Mapper.Map(plist))); if (rowAffected > 0) return Ok(); return NoContent(); } // DELETE api/values/5 [HttpDelete("{id}")] [ProducesResponseType(typeof(Playlist), StatusCodes.Status200OK)] [Produces("application/json")] public async Task<IActionResult> Delete([FromRoute] int id) { try { int rowAffected = await Task.Run(() => repository.DeletePlayList(id)); if (rowAffected > 0) return Ok(); return BadRequest(); } catch { return NoContent(); } } } }
29.435644
103
0.566095
[ "MIT" ]
1905-may06-dotnet/Team2-CobraKai-Project2
Project2Solution/Project.Client/Controllers/PlayListController.cs
2,975
C#
using JetBrains.Annotations; using JetBrains.ProjectModel; namespace GammaJul.ForTea.Core.TemplateProcessing.Services { public static class T4TemplateDataManagerExtensions { public static bool IsPreprocessedTemplate( [NotNull] this IT4TemplateKindProvider manager, [NotNull] IProjectFile file ) => manager.GetTemplateKind(file) == T4TemplateKind.Preprocessed; public static bool IsRootPreprocessedTemplate( [NotNull] this IT4RootTemplateKindProvider manager, [NotNull] IProjectFile file ) => manager.GetRootTemplateKind(file) == T4TemplateKind.Preprocessed; } }
30.894737
72
0.804089
[ "Apache-2.0" ]
denis417/ForTea
Backend/ForTea.Core/TemplateProcessing/Services/T4TemplateDataManagerExtensions.cs
587
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VariableType { class Program { static void Main(string[] args) { int myInt; string myStr,myAtStr,myFileStr; myInt = 123456; myStr = "\"myInt\" is"; myAtStr = @"This string has a line break."; myFileStr = @"C:\Users"; Console.WriteLine($"{myStr} {myInt}"); Console.WriteLine("This string has a\nline break."); Console.WriteLine(myAtStr); Console.WriteLine(myFileStr); Console.ReadKey(); } } }
24.571429
64
0.556686
[ "Apache-2.0" ]
CRThu/csExercise
VariableType/VariableType/Program.cs
690
C#
#region License // Copyright (c) 2007 James Newton-King // // 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; using System.Collections.Generic; using System.Reflection; using System.Runtime.Serialization; using Newtonsoft.JsonV4.Linq; using Newtonsoft.JsonV4.Utilities; namespace Newtonsoft.JsonV4.Serialization { internal enum JsonContractType { None, Object, Array, Primitive, String, Dictionary, #if !(NET35 || NET20 || PORTABLE40) Dynamic, #endif #if !(NETFX_CORE || PORTABLE || PORTABLE40) Serializable, #endif Linq } /// <summary> /// Handles <see cref="JsonSerializer"/> serialization callback events. /// </summary> /// <param name="o">The object that raised the callback event.</param> /// <param name="context">The streaming context.</param> public delegate void SerializationCallback(object o, StreamingContext context); /// <summary> /// Handles <see cref="JsonSerializer"/> serialization error callback events. /// </summary> /// <param name="o">The object that raised the callback event.</param> /// <param name="context">The streaming context.</param> /// <param name="errorContext">The error context.</param> public delegate void SerializationErrorCallback(object o, StreamingContext context, ErrorContext errorContext); /// <summary> /// Sets extension data for an object during deserialization. /// </summary> /// <param name="o">The object to set extension data on.</param> /// <param name="key">The extension data key.</param> /// <param name="value">The extension data value.</param> public delegate void ExtensionDataSetter(object o, string key, object value); /// <summary> /// Gets extension data for an object during serialization. /// </summary> /// <param name="o">The object to set extension data on.</param> public delegate IEnumerable<KeyValuePair<object, object>> ExtensionDataGetter(object o); /// <summary> /// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public abstract class JsonContract { internal bool IsNullable; internal bool IsConvertable; internal bool IsEnum; internal Type NonNullableUnderlyingType; internal ReadType InternalReadType; internal JsonContractType ContractType; internal bool IsReadOnlyOrFixedSize; internal bool IsSealed; internal bool IsInstantiable; private List<SerializationCallback> _onDeserializedCallbacks; private IList<SerializationCallback> _onDeserializingCallbacks; private IList<SerializationCallback> _onSerializedCallbacks; private IList<SerializationCallback> _onSerializingCallbacks; private IList<SerializationErrorCallback> _onErrorCallbacks; private Type _createdType; /// <summary> /// Gets the underlying type for the contract. /// </summary> /// <value>The underlying type for the contract.</value> public Type UnderlyingType { get; private set; } /// <summary> /// Gets or sets the type created during deserialization. /// </summary> /// <value>The type created during deserialization.</value> public Type CreatedType { get { return _createdType; } set { _createdType = value; IsSealed = _createdType.IsSealed(); IsInstantiable = !(_createdType.IsInterface() || _createdType.IsAbstract()); } } /// <summary> /// Gets or sets whether this type contract is serialized as a reference. /// </summary> /// <value>Whether this type contract is serialized as a reference.</value> public bool? IsReference { get; set; } /// <summary> /// Gets or sets the default <see cref="JsonConverter" /> for this contract. /// </summary> /// <value>The converter.</value> public JsonConverter Converter { get; set; } // internally specified JsonConverter's to override default behavour // checked for after passed in converters and attribute specified converters internal JsonConverter InternalConverter { get; set; } /// <summary> /// Gets or sets all methods called immediately after deserialization of the object. /// </summary> /// <value>The methods called immediately after deserialization of the object.</value> public IList<SerializationCallback> OnDeserializedCallbacks { get { if (_onDeserializedCallbacks == null) _onDeserializedCallbacks = new List<SerializationCallback>(); return _onDeserializedCallbacks; } } /// <summary> /// Gets or sets all methods called during deserialization of the object. /// </summary> /// <value>The methods called during deserialization of the object.</value> public IList<SerializationCallback> OnDeserializingCallbacks { get { if (_onDeserializingCallbacks == null) _onDeserializingCallbacks = new List<SerializationCallback>(); return _onDeserializingCallbacks; } } /// <summary> /// Gets or sets all methods called after serialization of the object graph. /// </summary> /// <value>The methods called after serialization of the object graph.</value> public IList<SerializationCallback> OnSerializedCallbacks { get { if (_onSerializedCallbacks == null) _onSerializedCallbacks = new List<SerializationCallback>(); return _onSerializedCallbacks; } } /// <summary> /// Gets or sets all methods called before serialization of the object. /// </summary> /// <value>The methods called before serialization of the object.</value> public IList<SerializationCallback> OnSerializingCallbacks { get { if (_onSerializingCallbacks == null) _onSerializingCallbacks = new List<SerializationCallback>(); return _onSerializingCallbacks; } } /// <summary> /// Gets or sets all method called when an error is thrown during the serialization of the object. /// </summary> /// <value>The methods called when an error is thrown during the serialization of the object.</value> public IList<SerializationErrorCallback> OnErrorCallbacks { get { if (_onErrorCallbacks == null) _onErrorCallbacks = new List<SerializationErrorCallback>(); return _onErrorCallbacks; } } /// <summary> /// Gets or sets the method called immediately after deserialization of the object. /// </summary> /// <value>The method called immediately after deserialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnDeserializedCallbacks collection.")] public MethodInfo OnDeserialized { get { return (OnDeserializedCallbacks.Count > 0) ? OnDeserializedCallbacks[0].Method() : null; } set { OnDeserializedCallbacks.Clear(); OnDeserializedCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called during deserialization of the object. /// </summary> /// <value>The method called during deserialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnDeserializingCallbacks collection.")] public MethodInfo OnDeserializing { get { return (OnDeserializingCallbacks.Count > 0) ? OnDeserializingCallbacks[0].Method() : null; } set { OnDeserializingCallbacks.Clear(); OnDeserializingCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called after serialization of the object graph. /// </summary> /// <value>The method called after serialization of the object graph.</value> [Obsolete("This property is obsolete and has been replaced by the OnSerializedCallbacks collection.")] public MethodInfo OnSerialized { get { return (OnSerializedCallbacks.Count > 0) ? OnSerializedCallbacks[0].Method() : null; } set { OnSerializedCallbacks.Clear(); OnSerializedCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called before serialization of the object. /// </summary> /// <value>The method called before serialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnSerializingCallbacks collection.")] public MethodInfo OnSerializing { get { return (OnSerializingCallbacks.Count > 0) ? OnSerializingCallbacks[0].Method() : null; } set { OnSerializingCallbacks.Clear(); OnSerializingCallbacks.Add(CreateSerializationCallback(value)); } } /// <summary> /// Gets or sets the method called when an error is thrown during the serialization of the object. /// </summary> /// <value>The method called when an error is thrown during the serialization of the object.</value> [Obsolete("This property is obsolete and has been replaced by the OnErrorCallbacks collection.")] public MethodInfo OnError { get { return (OnErrorCallbacks.Count > 0) ? OnErrorCallbacks[0].Method() : null; } set { OnErrorCallbacks.Clear(); OnErrorCallbacks.Add(CreateSerializationErrorCallback(value)); } } /// <summary> /// Gets or sets the default creator method used to create the object. /// </summary> /// <value>The default creator method used to create the object.</value> public Func<object> DefaultCreator { get; set; } /// <summary> /// Gets or sets a value indicating whether the default creator is non public. /// </summary> /// <value><c>true</c> if the default object creator is non-public; otherwise, <c>false</c>.</value> public bool DefaultCreatorNonPublic { get; set; } internal JsonContract(Type underlyingType) { ValidationUtils.ArgumentNotNull(underlyingType, "underlyingType"); UnderlyingType = underlyingType; IsNullable = ReflectionUtils.IsNullable(underlyingType); NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; CreatedType = NonNullableUnderlyingType; IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType); IsEnum = NonNullableUnderlyingType.IsEnum(); if (NonNullableUnderlyingType == typeof(byte[])) { InternalReadType = ReadType.ReadAsBytes; } else if (NonNullableUnderlyingType == typeof(int)) { InternalReadType = ReadType.ReadAsInt32; } else if (NonNullableUnderlyingType == typeof(decimal)) { InternalReadType = ReadType.ReadAsDecimal; } else if (NonNullableUnderlyingType == typeof(string)) { InternalReadType = ReadType.ReadAsString; } else if (NonNullableUnderlyingType == typeof(DateTime)) { InternalReadType = ReadType.ReadAsDateTime; } #if !NET20 else if (NonNullableUnderlyingType == typeof(DateTimeOffset)) { InternalReadType = ReadType.ReadAsDateTimeOffset; } #endif else { InternalReadType = ReadType.Read; } } internal void InvokeOnSerializing(object o, StreamingContext context) { if (_onSerializingCallbacks != null) { foreach (SerializationCallback callback in _onSerializingCallbacks) { callback(o, context); } } } internal void InvokeOnSerialized(object o, StreamingContext context) { if (_onSerializedCallbacks != null) { foreach (SerializationCallback callback in _onSerializedCallbacks) { callback(o, context); } } } internal void InvokeOnDeserializing(object o, StreamingContext context) { if (_onDeserializingCallbacks != null) { foreach (SerializationCallback callback in _onDeserializingCallbacks) { callback(o, context); } } } internal void InvokeOnDeserialized(object o, StreamingContext context) { if (_onDeserializedCallbacks != null) { foreach (SerializationCallback callback in _onDeserializedCallbacks) { callback(o, context); } } } internal void InvokeOnError(object o, StreamingContext context, ErrorContext errorContext) { if (_onErrorCallbacks != null) { foreach (SerializationErrorCallback callback in _onErrorCallbacks) { callback(o, context, errorContext); } } } internal static SerializationCallback CreateSerializationCallback(MethodInfo callbackMethodInfo) { return (o, context) => callbackMethodInfo.Invoke(o, new object[] { context }); } internal static SerializationErrorCallback CreateSerializationErrorCallback(MethodInfo callbackMethodInfo) { return (o, context, econtext) => callbackMethodInfo.Invoke(o, new object[] { context, econtext }); } } }
38.4
165
0.610944
[ "MIT" ]
woodp/Newtonsoft.Json
Src/Newtonsoft.Json/Serialization/JsonContract.cs
15,938
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace CSETWebCore.Business.Question { public class ParameterTextBuilder { private QuestionPoco _poco; private string _textSub; private string _textSubNoLinks; private bool needsParameterization { get { return _poco.Parameters.Any() && !String.IsNullOrEmpty(_poco.Text) && _poco.IsRequirement; } } public ParameterTextBuilder(QuestionPoco poco) { _poco = poco; _textSub = createTextBlock(); _textSubNoLinks = createTextBlock(); } public Tuple<string, string> ReplaceParameterText() { switch (needsParameterization) { case false: processNoParameters(); break; case true: processWithParameters(); break; } return new Tuple<string, string>(_textSub, _textSubNoLinks); } private void processNoParameters() { processForNonParameter(_poco.Text); } private void processWithParameters() { var tokenized = tokenizeText(); foreach (var item in tokenized) { var param = getParameterForText(item); switch (param.HasValue) { case true: processForParameter(param.Value.Key, param.Value.Value); break; case false: processForNonParameter(item); break; } } } private void processForNonParameter(string item) { if (item != null && item.Length > 0) { //_textSub.Inlines.Add(getRunForText(item)); //_textSubNoLinks.Inlines.Add(getRunForText(item)); } } private void processForParameter(int index, ParameterContainer param) { //var link = new Hyperlink(); //link.Click += QuestionListView.FlyOutDisplay; //link.Inlines.Add(getRunForParameter(index)); //link.CommandParameter = new object[] { param, _poco }; //_textSub.Inlines.Add(link); //_textSubNoLinks.Inlines.Add(getRunForParameter(index)); } //private Run getRunForText(string text) //{ // return new Run(text); //} //private Run getRunForParameter(int index) //{ // var run = new Run(); // var binding = new Binding(); // binding.Path = new PropertyPath(String.Format("Parameters[{0}].Value", index)); // binding.Mode = BindingMode.OneWay; // run.SetBinding(Run.TextProperty, binding); // return run; //} private string[] tokenizeText() { var parameterStrings = String.Join("|", _poco.Parameters.Select(t => "(" + Regex.Escape(t.Name) + ")")); return Regex.Split(_poco.Text, parameterStrings); } private KeyValuePair<int, ParameterContainer>? getParameterForText(string item) { var kvp = _poco.Parameters.Select((t, i) => new KeyValuePair<int, ParameterContainer>(i, t)) .FirstOrDefault(t => t.Value.Name == item); if (kvp.Value == null) { return null; } return kvp; } private string createTextBlock() { throw new NotImplementedException("this needs to build the html with the links in it"); //return new string() { DataContext = _poco, TextWrapping=TextWrapping.Wrap, Name="QuestionText" }; } } }
34.982301
116
0.524159
[ "MIT" ]
Project-CSET-RM-Module/cset
CSETWebApi/CSETWeb_Api/CSETWebCore.Business/Question/ParameterTextBuilder.cs
3,955
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using MonoCross.Navigation; using MonoCross.Webkit; using BestSellers; namespace BestSellers.Webkit { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.RouteExistingFiles = false; routes.IgnoreRoute("WebApp/{*pathInfo}"); routes.Ignore("favicon.ico"); routes.MapRoute("", "{*mapUri}", new { controller = "App", action = "Render" }); } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); } protected void Session_Start() { // initialize app MXWebkitContainer.Initialize(new BestSellers.App()); // add views to container MXWebkitContainer.AddView<CategoryList>(new Views.CategoryListView(), ViewPerspective.Read); MXWebkitContainer.AddView<BookList>(new Views.BookListView(), ViewPerspective.Read); MXWebkitContainer.AddView<Book>(new Views.BookView(), ViewPerspective.Read); } } }
31.488372
104
0.65288
[ "MIT" ]
BenButzer/iFactr-Data
MonoCross/BestSellers Sample/BestSellers.Webkit/Global.asax.cs
1,356
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: MethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The type DepOnboardingSettingUnshareForSchoolDataSyncServiceRequestBuilder. /// </summary> public partial class DepOnboardingSettingUnshareForSchoolDataSyncServiceRequestBuilder : BaseActionMethodRequestBuilder<IDepOnboardingSettingUnshareForSchoolDataSyncServiceRequest>, IDepOnboardingSettingUnshareForSchoolDataSyncServiceRequestBuilder { /// <summary> /// Constructs a new <see cref="DepOnboardingSettingUnshareForSchoolDataSyncServiceRequestBuilder"/>. /// </summary> /// <param name="requestUrl">The URL for the request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> public DepOnboardingSettingUnshareForSchoolDataSyncServiceRequestBuilder( string requestUrl, IBaseClient client) : base(requestUrl, client) { } /// <summary> /// A method used by the base class to construct a request class instance. /// </summary> /// <param name="functionUrl">The request URL to </param> /// <param name="options">The query and header options for the request.</param> /// <returns>An instance of a specific request class.</returns> protected override IDepOnboardingSettingUnshareForSchoolDataSyncServiceRequest CreateRequest(string functionUrl, IEnumerable<Option> options) { var request = new DepOnboardingSettingUnshareForSchoolDataSyncServiceRequest(functionUrl, this.Client, options); return request; } } }
46.12766
252
0.653598
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/DepOnboardingSettingUnshareForSchoolDataSyncServiceRequestBuilder.cs
2,168
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.Xml.XPath; namespace MS.Internal.Xml.Cache { /// <summary> /// Base internal class of all XPathDocument XPathNodeIterator implementations. /// </summary> internal abstract class XPathDocumentBaseIterator : XPathNodeIterator { protected XPathDocumentNavigator ctxt; protected int pos; /// <summary> /// Create a new iterator that is initially positioned on the "ctxt" node. /// </summary> protected XPathDocumentBaseIterator(XPathDocumentNavigator ctxt) { this.ctxt = new XPathDocumentNavigator(ctxt); } /// <summary> /// Create a new iterator that is a copy of "iter". /// </summary> protected XPathDocumentBaseIterator(XPathDocumentBaseIterator iter) { this.ctxt = new XPathDocumentNavigator(iter.ctxt); this.pos = iter.pos; } /// <summary> /// Return the current navigator. /// </summary> public override XPathNavigator Current { get { return this.ctxt; } } /// <summary> /// Return the iterator's current position. /// </summary> public override int CurrentPosition { get { return this.pos; } } } /// <summary> /// Iterate over all element children with a particular QName. /// </summary> internal class XPathDocumentElementChildIterator : XPathDocumentBaseIterator { private readonly string _localName, _namespaceUri; /// <summary> /// Create an iterator that ranges over all element children of "parent" having the specified QName. /// </summary> public XPathDocumentElementChildIterator(XPathDocumentNavigator parent, string name, string namespaceURI) : base(parent) { if (namespaceURI == null) throw new ArgumentNullException(nameof(namespaceURI)); _localName = parent.NameTable.Get(name); _namespaceUri = namespaceURI; } /// <summary> /// Create a new iterator that is a copy of "iter". /// </summary> public XPathDocumentElementChildIterator(XPathDocumentElementChildIterator iter) : base(iter) { _localName = iter._localName; _namespaceUri = iter._namespaceUri; } /// <summary> /// Create a copy of this iterator. /// </summary> public override XPathNodeIterator Clone() { return new XPathDocumentElementChildIterator(this); } /// <summary> /// Position the iterator to the next matching child. /// </summary> public override bool MoveNext() { if (this.pos == 0) { if (!this.ctxt.MoveToChild(_localName, _namespaceUri)) return false; } else { if (!this.ctxt.MoveToNext(_localName, _namespaceUri)) return false; } this.pos++; return true; } } /// <summary> /// Iterate over all content children with a particular XPathNodeType. /// </summary> internal class XPathDocumentKindChildIterator : XPathDocumentBaseIterator { private readonly XPathNodeType _typ; /// <summary> /// Create an iterator that ranges over all content children of "parent" having the specified XPathNodeType. /// </summary> public XPathDocumentKindChildIterator(XPathDocumentNavigator parent, XPathNodeType typ) : base(parent) { _typ = typ; } /// <summary> /// Create a new iterator that is a copy of "iter". /// </summary> public XPathDocumentKindChildIterator(XPathDocumentKindChildIterator iter) : base(iter) { _typ = iter._typ; } /// <summary> /// Create a copy of this iterator. /// </summary> public override XPathNodeIterator Clone() { return new XPathDocumentKindChildIterator(this); } /// <summary> /// Position the iterator to the next descendant. /// </summary> public override bool MoveNext() { if (this.pos == 0) { if (!this.ctxt.MoveToChild(_typ)) return false; } else { if (!this.ctxt.MoveToNext(_typ)) return false; } this.pos++; return true; } } /// <summary> /// Iterate over all element descendants with a particular QName. /// </summary> internal class XPathDocumentElementDescendantIterator : XPathDocumentBaseIterator { private readonly XPathDocumentNavigator _end; private readonly string _localName, _namespaceUri; private bool _matchSelf; /// <summary> /// Create an iterator that ranges over all element descendants of "root" having the specified QName. /// </summary> public XPathDocumentElementDescendantIterator(XPathDocumentNavigator root, string name, string namespaceURI, bool matchSelf) : base(root) { if (namespaceURI == null) throw new ArgumentNullException(nameof(namespaceURI)); _localName = root.NameTable.Get(name); _namespaceUri = namespaceURI; _matchSelf = matchSelf; // Find the next non-descendant node that follows "root" in document order if (root.NodeType != XPathNodeType.Root) { _end = new XPathDocumentNavigator(root); _end.MoveToNonDescendant(); } } /// <summary> /// Create a new iterator that is a copy of "iter". /// </summary> public XPathDocumentElementDescendantIterator(XPathDocumentElementDescendantIterator iter) : base(iter) { _end = iter._end; _localName = iter._localName; _namespaceUri = iter._namespaceUri; _matchSelf = iter._matchSelf; } /// <summary> /// Create a copy of this iterator. /// </summary> public override XPathNodeIterator Clone() { return new XPathDocumentElementDescendantIterator(this); } /// <summary> /// Position the iterator to the next descendant. /// </summary> public override bool MoveNext() { if (_matchSelf) { _matchSelf = false; if (this.ctxt.IsElementMatch(_localName, _namespaceUri)) { this.pos++; return true; } } if (!this.ctxt.MoveToFollowing(_localName, _namespaceUri, _end)) return false; this.pos++; return true; } } /// <summary> /// Iterate over all content descendants with a particular XPathNodeType. /// </summary> internal class XPathDocumentKindDescendantIterator : XPathDocumentBaseIterator { private readonly XPathDocumentNavigator _end; private readonly XPathNodeType _typ; private bool _matchSelf; /// <summary> /// Create an iterator that ranges over all content descendants of "root" having the specified XPathNodeType. /// </summary> public XPathDocumentKindDescendantIterator(XPathDocumentNavigator root, XPathNodeType typ, bool matchSelf) : base(root) { _typ = typ; _matchSelf = matchSelf; // Find the next non-descendant node that follows "root" in document order if (root.NodeType != XPathNodeType.Root) { _end = new XPathDocumentNavigator(root); _end.MoveToNonDescendant(); } } /// <summary> /// Create a new iterator that is a copy of "iter". /// </summary> public XPathDocumentKindDescendantIterator(XPathDocumentKindDescendantIterator iter) : base(iter) { _end = iter._end; _typ = iter._typ; _matchSelf = iter._matchSelf; } /// <summary> /// Create a copy of this iterator. /// </summary> public override XPathNodeIterator Clone() { return new XPathDocumentKindDescendantIterator(this); } /// <summary> /// Position the iterator to the next descendant. /// </summary> public override bool MoveNext() { if (_matchSelf) { _matchSelf = false; if (this.ctxt.IsKindMatch(_typ)) { this.pos++; return true; } } if (!this.ctxt.MoveToFollowing(_typ, _end)) return false; this.pos++; return true; } } }
30.976821
145
0.560877
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentIterator.cs
9,355
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using TMPro; public class playgame : MonoBehaviour { public TextMeshProUGUI t; public bool canStart = false; public void PlayGame() { t.text = "PREPARING"; canStart = true; } public void Update() { if (canStart) { canStart = false; master.selectedMap = selectedMap; SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex+1); } } public int selectedMap = 0; // 0 -> regional, 1 -> full public TextMeshProUGUI mapText; public void nextSelectedMap() { if (selectedMap == 0) { selectedMap = 1; mapText.text = "Full"; } else { selectedMap = 0; mapText.text = "Regional"; } } public void quit() { Application.Quit(); } }
20.5625
79
0.554205
[ "MIT" ]
Andallfor/NASA-ADC-2020
NASA_ADC_FINAL/Assets/CODE/Ui/Scripts/playgame.cs
989
C#
using System; using System.Globalization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using static System.FormattableString; namespace DNTCaptcha.Core { /// <summary> /// DNTCaptcha Api /// </summary> public class DNTCaptchaApiProvider : IDNTCaptchaApiProvider { private readonly ICaptchaCryptoProvider _captchaProtectionProvider; private readonly ICaptchaStorageProvider _captchaStorageProvider; private readonly Func<DisplayMode, ICaptchaTextProvider> _captchaTextProvider; private readonly IRandomNumberProvider _randomNumberProvider; private readonly ISerializationProvider _serializationProvider; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IUrlHelper _urlHelper; private readonly DNTCaptchaOptions _captchaOptions; /// <summary> /// DNTCaptcha Api /// </summary> public DNTCaptchaApiProvider( ICaptchaCryptoProvider captchaProtectionProvider, IRandomNumberProvider randomNumberProvider, Func<DisplayMode, ICaptchaTextProvider> captchaTextProvider, ICaptchaStorageProvider captchaStorageProvider, ISerializationProvider serializationProvider, IHttpContextAccessor httpContextAccessor, IUrlHelper urlHelper, IOptions<DNTCaptchaOptions> options) { _captchaProtectionProvider = captchaProtectionProvider ?? throw new ArgumentNullException(nameof(captchaProtectionProvider)); _randomNumberProvider = randomNumberProvider ?? throw new ArgumentNullException(nameof(randomNumberProvider)); _captchaTextProvider = captchaTextProvider ?? throw new ArgumentNullException(nameof(captchaTextProvider)); _captchaStorageProvider = captchaStorageProvider ?? throw new ArgumentNullException(nameof(captchaStorageProvider)); _serializationProvider = serializationProvider ?? throw new ArgumentNullException(nameof(serializationProvider)); _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); _urlHelper = urlHelper ?? throw new ArgumentNullException(nameof(urlHelper)); _captchaOptions = options == null ? throw new ArgumentNullException(nameof(options)) : options.Value; } /// <summary> /// Creates DNTCaptcha /// </summary> /// <param name="captchaAttributes">captcha attributes</param> public DNTCaptchaApiResponse CreateDNTCaptcha(DNTCaptchaTagHelperHtmlAttributes captchaAttributes) { if (captchaAttributes == null) { throw new ArgumentNullException(nameof(captchaAttributes)); } if (_httpContextAccessor.HttpContext == null) { throw new InvalidOperationException("`_httpContextAccessor.HttpContext` is null."); } var number = _randomNumberProvider.NextNumber(captchaAttributes.Min, captchaAttributes.Max); var randomText = _captchaTextProvider(captchaAttributes.DisplayMode).GetText(number, captchaAttributes.Language); var encryptedText = _captchaProtectionProvider.Encrypt(randomText); var captchaImageUrl = getCaptchaImageUrl(captchaAttributes, encryptedText); var captchaDivId = Invariant($"{_captchaOptions.CaptchaClass}{Guid.NewGuid():N}{_randomNumberProvider.NextNumber(captchaAttributes.Min, captchaAttributes.Max)}"); var cookieToken = $".{captchaDivId}"; var hiddenInputToken = _captchaProtectionProvider.Encrypt(cookieToken); _captchaStorageProvider.Add(_httpContextAccessor.HttpContext, cookieToken, randomText); return new DNTCaptchaApiResponse { DntCaptchaImgUrl = captchaImageUrl, DntCaptchaId = captchaDivId, DntCaptchaTextValue = encryptedText, DntCaptchaTokenValue = hiddenInputToken }; } private string getCaptchaImageUrl(DNTCaptchaTagHelperHtmlAttributes captchaAttributes, string encryptedText) { if (_httpContextAccessor.HttpContext == null) { throw new InvalidOperationException("`_httpContextAccessor.HttpContext` is null."); } var values = new CaptchaImageParams { Text = encryptedText, RndDate = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture), ForeColor = captchaAttributes.ForeColor, BackColor = captchaAttributes.BackColor, FontSize = captchaAttributes.FontSize, FontName = captchaAttributes.FontName }; var encryptSerializedValues = _captchaProtectionProvider.Encrypt(_serializationProvider.Serialize(values)); var actionUrl = captchaAttributes.UseRelativeUrls ? _urlHelper.Action(action: nameof(DNTCaptchaImageController.Show), controller: nameof(DNTCaptchaImageController).Replace("Controller", string.Empty, StringComparison.Ordinal), values: new { data = encryptSerializedValues, area = "" }) : _urlHelper.Action(action: nameof(DNTCaptchaImageController.Show), controller: nameof(DNTCaptchaImageController).Replace("Controller", string.Empty, StringComparison.Ordinal), values: new { data = encryptSerializedValues, area = "" }, protocol: _httpContextAccessor.HttpContext.Request.Scheme); if (string.IsNullOrWhiteSpace(actionUrl)) { throw new InvalidOperationException("It's not possible to determine the URL of the `DNTCaptchaImageController.Show` method. Please register the `services.AddControllers()` and `endpoints.MapControllerRoute(...)`."); } return actionUrl; } } }
52.767241
231
0.681261
[ "Apache-2.0" ]
BadrishChaudhari/DNTCaptcha.Core
src/DNTCaptcha.Core/DNTCaptchaApiProvider.cs
6,123
C#
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS"basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The CPR Broker concept was initally developed by * Gentofte Kommune / Municipality of Gentofte, Denmark. * Contributor(s): * Steen Deth * * * The Initial Code for CPR Broker and related components is made in * cooperation between Magenta, Gentofte Kommune and IT- og Telestyrelsen / * Danish National IT and Telecom Agency * * Contributor(s): * Beemen Beshara * * The code is currently governed by IT- og Telestyrelsen / Danish National * IT and Telecom Agency * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using CprBroker.Schemas.Part; namespace CprBroker.Schemas.Part { public interface IAddressSource : ITimedType { AdresseType ToAdresseType(); string ToAddressNoteTekste(); } }
37.87931
77
0.730997
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
OS2CPRbroker/CPRbroker
PART/Source/Core/Schemas/Addresses/IAddressSource.cs
2,199
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Globalization; namespace BigQuery.Linq.Tests.Builder { enum Nano : ulong { Hoge = 1, Huga = 4, Tako = 100 } class Hoge { public double MyProperty { get; set; } } class Huga { public double MyProperty2 { get; set; } } class HogeMoge { public string Hoge { get; set; } public string Huga { get; set; } public int Tako { get; set; } } [TableName("[publicdata:samples.wikipedia]")] class Wikipedia { public string title { get; set; } public long? wp_namespace { get; set; } } [TableName("[publicdata:samples.shakespeare]")] class Shakespeare { public string word { get; set; } public string corpus { get; set; } public int word_count { get; set; } } class Repository { public bool has_downloads { get; set; } } [TestClass] public class StandardQueries { [TestMethod] public void DirectSelect() { var context = new BigQuery.Linq.BigQueryContext(); var s = context.Select(() => new { A = "aaa", B = BqFunc.Abs(-5), FROM = 100, }).ToString().TrimEnd(); s.Is(@"SELECT 'aaa' AS [A], ABS(-5) AS [B], 100 AS [FROM]"); } [TestMethod] public void WhereSelect() { var context = new BigQuery.Linq.BigQueryContext(); var s = context.From<Wikipedia>("tablewikipedia") .Where(x => x.wp_namespace == 100) .Select(x => new { x.title, x.wp_namespace }) .ToString().TrimEnd(); s.Is(@"SELECT [title], [wp_namespace] FROM [tablewikipedia] WHERE ([wp_namespace] = 100)"); } [TestMethod] public void WhereWhere() { var context = new BigQuery.Linq.BigQueryContext(); var s = context.From<Wikipedia>("tablewikipedia") .Where(x => x.wp_namespace == 100) .Where(x => x.title != null) .Where(x => x.title == "AiUeo") .Select(x => new { x.title, x.wp_namespace }) .ToString().TrimEnd(); s.Is(@"SELECT [title], [wp_namespace] FROM [tablewikipedia] WHERE ((([wp_namespace] = 100) AND ([title] IS NOT NULL)) AND ([title] = 'AiUeo'))"); } [TestMethod] public void OrderBy() { var context = new BigQuery.Linq.BigQueryContext(); var s = context.From<BigQuery.Linq.Tests.wikipedia>("tablewikipedia") .OrderByDescending(x => x.title) .ThenBy(x => x.wp_namespace) .ThenByDescending(x => x.language) .ThenBy(x => x.revision_id) .Select(x => new { x.title, x.wp_namespace }) .ToString().TrimEnd(); s.Is(@"SELECT [title], [wp_namespace] FROM [tablewikipedia] ORDER BY [title] DESC, [wp_namespace], [language] DESC, [revision_id]"); } [TestMethod] public void Join() { var context = new BigQuery.Linq.BigQueryContext(); var query1 = context.From<Wikipedia>("[publicdata:samples.wikipedia]") .Join(context.From<Wikipedia>("[publicdata:samples.wikipedia]").Select(x => new { x.title, x.wp_namespace }).Limit(1000), (kp, tp) => new { kp, tp }, // alias selector x => x.tp.title == x.kp.title) // conditional .Select(x => new { x.kp.title, x.tp.wp_namespace }) .OrderBy(x => x.title) .ThenByDescending(x => x.wp_namespace) .Limit(100) .IgnoreCase() .ToString(); query1.Is(@" SELECT [kp.title] AS [title], [tp.wp_namespace] AS [wp_namespace] FROM [publicdata:samples.wikipedia] AS [kp] INNER JOIN ( SELECT [title], [wp_namespace] FROM [publicdata:samples.wikipedia] LIMIT 1000 ) AS [tp] ON ([tp.title] = [kp.title]) ORDER BY [title], [wp_namespace] DESC LIMIT 100 IGNORE CASE".TrimSmart()); } [TestMethod] public void Sample1() { var context = new BigQuery.Linq.BigQueryContext(); var query1 = context.From<Wikipedia>() .Where(x => x.wp_namespace == 0) .Select(x => new { x.title, hash_value = BqFunc.Hash(x.title), included_in_sample = (BqFunc.Abs(BqFunc.Hash(x.title)) % 2 == 1) ? "True" : "False" }) .Limit(5) .ToString(); query1.Is(@" SELECT [title], HASH([title]) AS [hash_value], IF(((ABS(HASH([title])) % 2) = 1), 'True', 'False') AS [included_in_sample] FROM [publicdata:samples.wikipedia] WHERE ([wp_namespace] = 0) LIMIT 5".TrimStart()); } [TestMethod] public void SampleFirstCase() { var context = new BigQuery.Linq.BigQueryContext(); var query1 = context.From<Shakespeare>() .Where(x => x.word.Contains("th")) .Select(x => new { x.word, x.corpus, count = BqFunc.Count(x.word) }) .GroupBy(x => new { x.word, x.corpus }) .ToString() .TrimSmart(); query1.Is(@" SELECT [word], [corpus], COUNT([word]) AS [count] FROM [publicdata:samples.shakespeare] WHERE [word] CONTAINS 'th' GROUP BY [word], [corpus]".TrimSmart()); } [TestMethod] public void GroupByRollup() { var context = new BigQuery.Linq.BigQueryContext(); var query1 = context.From<natality>() .Where(x => x.year >= 2000 && x.year <= 2002) .Select(x => new { x.year, x.is_male, count = BqFunc.Count(1) }) .GroupBy(x => new { x.year, x.is_male }, rollup: true) .OrderBy(x => x.year) .ThenBy(x => x.is_male) .ToString() .TrimSmart(); query1.Is(@" SELECT [year], [is_male], COUNT(1) AS [count] FROM [publicdata:samples.natality] WHERE (([year] >= 2000) AND ([year] <= 2002)) GROUP BY ROLLUP ( [year], [is_male] ) ORDER BY [year], [is_male]".TrimSmart()); } [TestMethod] public void GroupByGrouping() { var context = new BigQuery.Linq.BigQueryContext(); var query1 = context.From<natality>() .Where(x => x.year >= 2000 && x.year <= 2002) .Select(x => new { x.year, rollup_year = BqFunc.Grouping(x.year), x.is_male, rollup_gender = BqFunc.Grouping(x.is_male), count = BqFunc.Count(1) }) .GroupBy(x => new { x.year, x.is_male }, rollup: true) .OrderBy(x => x.year) .ThenBy(x => x.is_male) .ToString() .TrimSmart(); query1.Is(@" SELECT [year], GROUPING([year]) AS [rollup_year], [is_male], GROUPING([is_male]) AS [rollup_gender], COUNT(1) AS [count] FROM [publicdata:samples.natality] WHERE (([year] >= 2000) AND ([year] <= 2002)) GROUP BY ROLLUP ( [year], [is_male] ) ORDER BY [year], [is_male]".TrimSmart()); } [TestMethod] public void WindowFunction() { var context = new BigQuery.Linq.BigQueryContext(); var query1 = context.From<Shakespeare>() .Where(x => x.corpus == "othello") .Select(x => new { x.word, cume_dist = BqFunc.CumulativeDistribution(x) .PartitionBy(y => y.corpus) .OrderByDescending(y => y.word_count) .Value }) .Limit(5) .ToString(); query1.Is(@" SELECT [word], CUME_DIST() OVER (PARTITION BY [corpus] ORDER BY [word_count] DESC) AS [cume_dist] FROM [publicdata:samples.shakespeare] WHERE ([corpus] = 'othello') LIMIT 5".TrimSmart()); } [TestMethod] public void WindowFunction2() { var context = new BigQuery.Linq.BigQueryContext(); var query1 = context.From<Shakespeare>() .Where(x => x.corpus == "othello") .Select(x => new { x.word, lag = BqFunc.Lag(x, y => y.word, 1, "aaa") .PartitionBy(y => y.corpus) .OrderByDescending(y => y.word_count) .Value }) .Limit(5) .ToString(); query1.Is(@" SELECT [word], LAG([word], 1, 'aaa') OVER (PARTITION BY [corpus] ORDER BY [word_count] DESC) AS [lag] FROM [publicdata:samples.shakespeare] WHERE ([corpus] = 'othello') LIMIT 5".TrimSmart()); } [TestMethod] public void RowNumber1() { var context = new BigQuery.Linq.BigQueryContext(); var query1 = context.From<Shakespeare>() .Where(x => x.corpus == "othello" && BqFunc.Length(x.word) > 10) .Select(x => new { x.word, lag = BqFunc.RowNumber(x).Value //.PartitionBy(y => y.corpus) //.OrderByDescending(y => y.word_count) }) .Limit(5) .ToString(); query1.Is(@" SELECT [word], ROW_NUMBER() OVER () AS [lag] FROM [publicdata:samples.shakespeare] WHERE (([corpus] = 'othello') AND (LENGTH([word]) > 10)) LIMIT 5".TrimSmart()); } [TestMethod] public void RowNumber2() { var context = new BigQuery.Linq.BigQueryContext(); var query1 = context.From<Shakespeare>() .Where(x => x.corpus == "othello" && BqFunc.Length(x.word) > 10) .Select(x => new { x.word, lag = BqFunc.RowNumber(x) .PartitionBy(y => y.corpus).Value //.OrderByDescending(y => y.word_count) }) .Limit(5) .ToString(); query1.Is(@" SELECT [word], ROW_NUMBER() OVER (PARTITION BY [corpus]) AS [lag] FROM [publicdata:samples.shakespeare] WHERE (([corpus] = 'othello') AND (LENGTH([word]) > 10)) LIMIT 5".TrimSmart()); } [TestMethod] public void RowNumber3() { var context = new BigQuery.Linq.BigQueryContext(); var query1 = context.From<Shakespeare>() .Where(x => x.corpus == "othello" && BqFunc.Length(x.word) > 10) .Select(x => new { x.word, lag = BqFunc.RowNumber(x) //.PartitionBy(y => y.corpus) .OrderByDescending(y => y.word_count) .Value }) .Limit(5) .ToString(); query1.Is(@" SELECT [word], ROW_NUMBER() OVER (ORDER BY [word_count] DESC) AS [lag] FROM [publicdata:samples.shakespeare] WHERE (([corpus] = 'othello') AND (LENGTH([word]) > 10)) LIMIT 5".TrimSmart()); } [TestMethod] public void RowNumber4() { var context = new BigQuery.Linq.BigQueryContext(); var query1 = context.From<Shakespeare>() .Where(x => x.corpus == "othello" && BqFunc.Length(x.word) > 10) .Select(x => new { x.word, lag = BqFunc.RowNumber(x) .PartitionBy(y => y.corpus) .OrderByDescending(y => y.word_count) .Value }) .Limit(5) .ToString(); query1.Is(@" SELECT [word], ROW_NUMBER() OVER (PARTITION BY [corpus] ORDER BY [word_count] DESC) AS [lag] FROM [publicdata:samples.shakespeare] WHERE (([corpus] = 'othello') AND (LENGTH([word]) > 10)) LIMIT 5".TrimSmart()); } [TestMethod] public void EnumAsValue() { new BigQueryContext().Select(() => new { Nano.Hoge, Nano.Huga, Nano.Tako, }) .ToString() .Is(@" SELECT 1 AS [Hoge], 4 AS [Huga], 100 AS [Tako] ".TrimSmart()); } [TestMethod] public void DateTime() { var local = new DateTime(2014, 10, 16, 21, 0, 0, DateTimeKind.Local); var offset = TimeZone.CurrentTimeZone.GetUtcOffset(local); var offsetLocal = new DateTime(local.Ticks + offset.Ticks, DateTimeKind.Local); new BigQueryContext().Select(() => new { dt = offsetLocal }) .ToString() .Is(@" SELECT '2014-10-16 21:00:00.000000' AS [dt]".TrimSmart()); new BigQueryContext().Select(() => new { dt = new DateTime(2014, 10, 16, 21, 0, 0, DateTimeKind.Utc) }) .ToString() .Is(@" SELECT '2014-10-16 21:00:00.000000' AS [dt]".TrimSmart()); new BigQueryContext().Select(() => new { dt = new DateTimeOffset(2014, 10, 16, 21, 0, 0, TimeSpan.Zero) }) .ToString() .Is(@" SELECT '2014-10-16 21:00:00.000000' AS [dt]".TrimSmart()); } } }
26.651601
137
0.477176
[ "MIT" ]
ataihei/LINQ-to-BigQuery
BigQuery.Linq.Tests/Builder/StandardQueries.cs
14,154
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> //------------------------------------------------------------------------------ // Generation date: 11/28/2021 8:55:09 PM namespace Microsoft.Dynamics.DataEntities { /// <summary> /// There are no comments for CDSInventoryOnHandEntrySingle in the schema. /// </summary> public partial class CDSInventoryOnHandEntrySingle : global::Microsoft.OData.Client.DataServiceQuerySingle<CDSInventoryOnHandEntry> { /// <summary> /// Initialize a new CDSInventoryOnHandEntrySingle object. /// </summary> public CDSInventoryOnHandEntrySingle(global::Microsoft.OData.Client.DataServiceContext context, string path) : base(context, path) {} /// <summary> /// Initialize a new CDSInventoryOnHandEntrySingle object. /// </summary> public CDSInventoryOnHandEntrySingle(global::Microsoft.OData.Client.DataServiceContext context, string path, bool isComposable) : base(context, path, isComposable) {} /// <summary> /// Initialize a new CDSInventoryOnHandEntrySingle object. /// </summary> public CDSInventoryOnHandEntrySingle(global::Microsoft.OData.Client.DataServiceQuerySingle<CDSInventoryOnHandEntry> query) : base(query) {} /// <summary> /// There are no comments for CDSInventoryOnHandRequests in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.Dynamics.DataEntities.CDSInventoryOnHandRequestSingle CDSInventoryOnHandRequests { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._CDSInventoryOnHandRequests == null)) { this._CDSInventoryOnHandRequests = new global::Microsoft.Dynamics.DataEntities.CDSInventoryOnHandRequestSingle(this.Context, GetPath("CDSInventoryOnHandRequests")); } return this._CDSInventoryOnHandRequests; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.Dynamics.DataEntities.CDSInventoryOnHandRequestSingle _CDSInventoryOnHandRequests; /// <summary> /// There are no comments for OperationalSites in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.Dynamics.DataEntities.OperationalSiteSingle OperationalSites { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._OperationalSites == null)) { this._OperationalSites = new global::Microsoft.Dynamics.DataEntities.OperationalSiteSingle(this.Context, GetPath("OperationalSites")); } return this._OperationalSites; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.Dynamics.DataEntities.OperationalSiteSingle _OperationalSites; /// <summary> /// There are no comments for Warehouses in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.Dynamics.DataEntities.WarehouseSingle Warehouses { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._Warehouses == null)) { this._Warehouses = new global::Microsoft.Dynamics.DataEntities.WarehouseSingle(this.Context, GetPath("Warehouses")); } return this._Warehouses; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.Dynamics.DataEntities.WarehouseSingle _Warehouses; } /// <summary> /// There are no comments for CDSInventoryOnHandEntry in the schema. /// </summary> /// <KeyProperties> /// dataAreaId /// RequestId /// InventorySiteId /// InventoryWarehouseId /// ATPDate /// </KeyProperties> [global::Microsoft.OData.Client.Key("dataAreaId", "RequestId", "InventorySiteId", "InventoryWarehouseId", "ATPDate")] [global::Microsoft.OData.Client.EntitySet("CDSInventoryOnHandEntries")] public partial class CDSInventoryOnHandEntry : global::Microsoft.OData.Client.BaseEntityType, global::System.ComponentModel.INotifyPropertyChanged { /// <summary> /// Create a new CDSInventoryOnHandEntry object. /// </summary> /// <param name="dataAreaId">Initial value of dataAreaId.</param> /// <param name="requestId">Initial value of RequestId.</param> /// <param name="inventorySiteId">Initial value of InventorySiteId.</param> /// <param name="inventoryWarehouseId">Initial value of InventoryWarehouseId.</param> /// <param name="aTPDate">Initial value of ATPDate.</param> /// <param name="availableOrderedQuantity">Initial value of AvailableOrderedQuantity.</param> /// <param name="orderQuantity">Initial value of OrderQuantity.</param> /// <param name="onHandQuantity">Initial value of OnHandQuantity.</param> /// <param name="aTPQuantity">Initial value of ATPQuantity.</param> /// <param name="availableOnHandQuantity">Initial value of AvailableOnHandQuantity.</param> /// <param name="projectedIssueQuantity">Initial value of ProjectedIssueQuantity.</param> /// <param name="projectedOnHandQuantity">Initial value of ProjectedOnHandQuantity.</param> /// <param name="onOrderQuantity">Initial value of OnOrderQuantity.</param> /// <param name="totalAvailableQuantity">Initial value of TotalAvailableQuantity.</param> /// <param name="orderedQuantity">Initial value of OrderedQuantity.</param> /// <param name="projectedReceiptQuantity">Initial value of ProjectedReceiptQuantity.</param> /// <param name="unavailableOnHandQuantity">Initial value of UnavailableOnHandQuantity.</param> /// <param name="reservedOrderedQuantity">Initial value of ReservedOrderedQuantity.</param> /// <param name="reservedOnHandQuantity">Initial value of ReservedOnHandQuantity.</param> /// <param name="operationalSites">Initial value of OperationalSites.</param> /// <param name="warehouses">Initial value of Warehouses.</param> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public static CDSInventoryOnHandEntry CreateCDSInventoryOnHandEntry(string dataAreaId, string requestId, string inventorySiteId, string inventoryWarehouseId, global::System.DateTimeOffset aTPDate, decimal availableOrderedQuantity, decimal orderQuantity, decimal onHandQuantity, decimal aTPQuantity, decimal availableOnHandQuantity, decimal projectedIssueQuantity, decimal projectedOnHandQuantity, decimal onOrderQuantity, decimal totalAvailableQuantity, decimal orderedQuantity, decimal projectedReceiptQuantity, decimal unavailableOnHandQuantity, decimal reservedOrderedQuantity, decimal reservedOnHandQuantity, global::Microsoft.Dynamics.DataEntities.OperationalSite operationalSites, global::Microsoft.Dynamics.DataEntities.Warehouse warehouses) { CDSInventoryOnHandEntry cDSInventoryOnHandEntry = new CDSInventoryOnHandEntry(); cDSInventoryOnHandEntry.dataAreaId = dataAreaId; cDSInventoryOnHandEntry.RequestId = requestId; cDSInventoryOnHandEntry.InventorySiteId = inventorySiteId; cDSInventoryOnHandEntry.InventoryWarehouseId = inventoryWarehouseId; cDSInventoryOnHandEntry.ATPDate = aTPDate; cDSInventoryOnHandEntry.AvailableOrderedQuantity = availableOrderedQuantity; cDSInventoryOnHandEntry.OrderQuantity = orderQuantity; cDSInventoryOnHandEntry.OnHandQuantity = onHandQuantity; cDSInventoryOnHandEntry.ATPQuantity = aTPQuantity; cDSInventoryOnHandEntry.AvailableOnHandQuantity = availableOnHandQuantity; cDSInventoryOnHandEntry.ProjectedIssueQuantity = projectedIssueQuantity; cDSInventoryOnHandEntry.ProjectedOnHandQuantity = projectedOnHandQuantity; cDSInventoryOnHandEntry.OnOrderQuantity = onOrderQuantity; cDSInventoryOnHandEntry.TotalAvailableQuantity = totalAvailableQuantity; cDSInventoryOnHandEntry.OrderedQuantity = orderedQuantity; cDSInventoryOnHandEntry.ProjectedReceiptQuantity = projectedReceiptQuantity; cDSInventoryOnHandEntry.UnavailableOnHandQuantity = unavailableOnHandQuantity; cDSInventoryOnHandEntry.ReservedOrderedQuantity = reservedOrderedQuantity; cDSInventoryOnHandEntry.ReservedOnHandQuantity = reservedOnHandQuantity; if ((operationalSites == null)) { throw new global::System.ArgumentNullException("operationalSites"); } cDSInventoryOnHandEntry.OperationalSites = operationalSites; if ((warehouses == null)) { throw new global::System.ArgumentNullException("warehouses"); } cDSInventoryOnHandEntry.Warehouses = warehouses; return cDSInventoryOnHandEntry; } /// <summary> /// There are no comments for Property dataAreaId in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "dataAreaId is required.")] public virtual string dataAreaId { get { return this._dataAreaId; } set { this.OndataAreaIdChanging(value); this._dataAreaId = value; this.OndataAreaIdChanged(); this.OnPropertyChanged("dataAreaId"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private string _dataAreaId; partial void OndataAreaIdChanging(string value); partial void OndataAreaIdChanged(); /// <summary> /// There are no comments for Property RequestId in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "RequestId is required.")] public virtual string RequestId { get { return this._RequestId; } set { this.OnRequestIdChanging(value); this._RequestId = value; this.OnRequestIdChanged(); this.OnPropertyChanged("RequestId"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private string _RequestId; partial void OnRequestIdChanging(string value); partial void OnRequestIdChanged(); /// <summary> /// There are no comments for Property InventorySiteId in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "InventorySiteId is required.")] public virtual string InventorySiteId { get { return this._InventorySiteId; } set { this.OnInventorySiteIdChanging(value); this._InventorySiteId = value; this.OnInventorySiteIdChanged(); this.OnPropertyChanged("InventorySiteId"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private string _InventorySiteId; partial void OnInventorySiteIdChanging(string value); partial void OnInventorySiteIdChanged(); /// <summary> /// There are no comments for Property InventoryWarehouseId in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "InventoryWarehouseId is required.")] public virtual string InventoryWarehouseId { get { return this._InventoryWarehouseId; } set { this.OnInventoryWarehouseIdChanging(value); this._InventoryWarehouseId = value; this.OnInventoryWarehouseIdChanged(); this.OnPropertyChanged("InventoryWarehouseId"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private string _InventoryWarehouseId; partial void OnInventoryWarehouseIdChanging(string value); partial void OnInventoryWarehouseIdChanged(); /// <summary> /// There are no comments for Property ATPDate in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "ATPDate is required.")] public virtual global::System.DateTimeOffset ATPDate { get { return this._ATPDate; } set { this.OnATPDateChanging(value); this._ATPDate = value; this.OnATPDateChanged(); this.OnPropertyChanged("ATPDate"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::System.DateTimeOffset _ATPDate; partial void OnATPDateChanging(global::System.DateTimeOffset value); partial void OnATPDateChanged(); /// <summary> /// There are no comments for Property AvailableOrderedQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "AvailableOrderedQuantity is required.")] public virtual decimal AvailableOrderedQuantity { get { return this._AvailableOrderedQuantity; } set { this.OnAvailableOrderedQuantityChanging(value); this._AvailableOrderedQuantity = value; this.OnAvailableOrderedQuantityChanged(); this.OnPropertyChanged("AvailableOrderedQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _AvailableOrderedQuantity; partial void OnAvailableOrderedQuantityChanging(decimal value); partial void OnAvailableOrderedQuantityChanged(); /// <summary> /// There are no comments for Property OrderQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "OrderQuantity is required.")] public virtual decimal OrderQuantity { get { return this._OrderQuantity; } set { this.OnOrderQuantityChanging(value); this._OrderQuantity = value; this.OnOrderQuantityChanged(); this.OnPropertyChanged("OrderQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _OrderQuantity; partial void OnOrderQuantityChanging(decimal value); partial void OnOrderQuantityChanged(); /// <summary> /// There are no comments for Property OnHandQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "OnHandQuantity is required.")] public virtual decimal OnHandQuantity { get { return this._OnHandQuantity; } set { this.OnOnHandQuantityChanging(value); this._OnHandQuantity = value; this.OnOnHandQuantityChanged(); this.OnPropertyChanged("OnHandQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _OnHandQuantity; partial void OnOnHandQuantityChanging(decimal value); partial void OnOnHandQuantityChanged(); /// <summary> /// There are no comments for Property ATPQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "ATPQuantity is required.")] public virtual decimal ATPQuantity { get { return this._ATPQuantity; } set { this.OnATPQuantityChanging(value); this._ATPQuantity = value; this.OnATPQuantityChanged(); this.OnPropertyChanged("ATPQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _ATPQuantity; partial void OnATPQuantityChanging(decimal value); partial void OnATPQuantityChanged(); /// <summary> /// There are no comments for Property AvailableOnHandQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "AvailableOnHandQuantity is required.")] public virtual decimal AvailableOnHandQuantity { get { return this._AvailableOnHandQuantity; } set { this.OnAvailableOnHandQuantityChanging(value); this._AvailableOnHandQuantity = value; this.OnAvailableOnHandQuantityChanged(); this.OnPropertyChanged("AvailableOnHandQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _AvailableOnHandQuantity; partial void OnAvailableOnHandQuantityChanging(decimal value); partial void OnAvailableOnHandQuantityChanged(); /// <summary> /// There are no comments for Property ProjectedIssueQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "ProjectedIssueQuantity is required.")] public virtual decimal ProjectedIssueQuantity { get { return this._ProjectedIssueQuantity; } set { this.OnProjectedIssueQuantityChanging(value); this._ProjectedIssueQuantity = value; this.OnProjectedIssueQuantityChanged(); this.OnPropertyChanged("ProjectedIssueQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _ProjectedIssueQuantity; partial void OnProjectedIssueQuantityChanging(decimal value); partial void OnProjectedIssueQuantityChanged(); /// <summary> /// There are no comments for Property ProjectedOnHandQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "ProjectedOnHandQuantity is required.")] public virtual decimal ProjectedOnHandQuantity { get { return this._ProjectedOnHandQuantity; } set { this.OnProjectedOnHandQuantityChanging(value); this._ProjectedOnHandQuantity = value; this.OnProjectedOnHandQuantityChanged(); this.OnPropertyChanged("ProjectedOnHandQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _ProjectedOnHandQuantity; partial void OnProjectedOnHandQuantityChanging(decimal value); partial void OnProjectedOnHandQuantityChanged(); /// <summary> /// There are no comments for Property OnOrderQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "OnOrderQuantity is required.")] public virtual decimal OnOrderQuantity { get { return this._OnOrderQuantity; } set { this.OnOnOrderQuantityChanging(value); this._OnOrderQuantity = value; this.OnOnOrderQuantityChanged(); this.OnPropertyChanged("OnOrderQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _OnOrderQuantity; partial void OnOnOrderQuantityChanging(decimal value); partial void OnOnOrderQuantityChanged(); /// <summary> /// There are no comments for Property TotalAvailableQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "TotalAvailableQuantity is required.")] public virtual decimal TotalAvailableQuantity { get { return this._TotalAvailableQuantity; } set { this.OnTotalAvailableQuantityChanging(value); this._TotalAvailableQuantity = value; this.OnTotalAvailableQuantityChanged(); this.OnPropertyChanged("TotalAvailableQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _TotalAvailableQuantity; partial void OnTotalAvailableQuantityChanging(decimal value); partial void OnTotalAvailableQuantityChanged(); /// <summary> /// There are no comments for Property OrderedQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "OrderedQuantity is required.")] public virtual decimal OrderedQuantity { get { return this._OrderedQuantity; } set { this.OnOrderedQuantityChanging(value); this._OrderedQuantity = value; this.OnOrderedQuantityChanged(); this.OnPropertyChanged("OrderedQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _OrderedQuantity; partial void OnOrderedQuantityChanging(decimal value); partial void OnOrderedQuantityChanged(); /// <summary> /// There are no comments for Property ProjectedReceiptQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "ProjectedReceiptQuantity is required.")] public virtual decimal ProjectedReceiptQuantity { get { return this._ProjectedReceiptQuantity; } set { this.OnProjectedReceiptQuantityChanging(value); this._ProjectedReceiptQuantity = value; this.OnProjectedReceiptQuantityChanged(); this.OnPropertyChanged("ProjectedReceiptQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _ProjectedReceiptQuantity; partial void OnProjectedReceiptQuantityChanging(decimal value); partial void OnProjectedReceiptQuantityChanged(); /// <summary> /// There are no comments for Property UnavailableOnHandQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "UnavailableOnHandQuantity is required.")] public virtual decimal UnavailableOnHandQuantity { get { return this._UnavailableOnHandQuantity; } set { this.OnUnavailableOnHandQuantityChanging(value); this._UnavailableOnHandQuantity = value; this.OnUnavailableOnHandQuantityChanged(); this.OnPropertyChanged("UnavailableOnHandQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _UnavailableOnHandQuantity; partial void OnUnavailableOnHandQuantityChanging(decimal value); partial void OnUnavailableOnHandQuantityChanged(); /// <summary> /// There are no comments for Property ReservedOrderedQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "ReservedOrderedQuantity is required.")] public virtual decimal ReservedOrderedQuantity { get { return this._ReservedOrderedQuantity; } set { this.OnReservedOrderedQuantityChanging(value); this._ReservedOrderedQuantity = value; this.OnReservedOrderedQuantityChanged(); this.OnPropertyChanged("ReservedOrderedQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _ReservedOrderedQuantity; partial void OnReservedOrderedQuantityChanging(decimal value); partial void OnReservedOrderedQuantityChanged(); /// <summary> /// There are no comments for Property ReservedOnHandQuantity in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "ReservedOnHandQuantity is required.")] public virtual decimal ReservedOnHandQuantity { get { return this._ReservedOnHandQuantity; } set { this.OnReservedOnHandQuantityChanging(value); this._ReservedOnHandQuantity = value; this.OnReservedOnHandQuantityChanged(); this.OnPropertyChanged("ReservedOnHandQuantity"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private decimal _ReservedOnHandQuantity; partial void OnReservedOnHandQuantityChanging(decimal value); partial void OnReservedOnHandQuantityChanged(); /// <summary> /// There are no comments for Property CDSInventoryOnHandRequests in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.Dynamics.DataEntities.CDSInventoryOnHandRequest CDSInventoryOnHandRequests { get { return this._CDSInventoryOnHandRequests; } set { this.OnCDSInventoryOnHandRequestsChanging(value); this._CDSInventoryOnHandRequests = value; this.OnCDSInventoryOnHandRequestsChanged(); this.OnPropertyChanged("CDSInventoryOnHandRequests"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.Dynamics.DataEntities.CDSInventoryOnHandRequest _CDSInventoryOnHandRequests; partial void OnCDSInventoryOnHandRequestsChanging(global::Microsoft.Dynamics.DataEntities.CDSInventoryOnHandRequest value); partial void OnCDSInventoryOnHandRequestsChanged(); /// <summary> /// There are no comments for Property OperationalSites in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "OperationalSites is required.")] public virtual global::Microsoft.Dynamics.DataEntities.OperationalSite OperationalSites { get { return this._OperationalSites; } set { this.OnOperationalSitesChanging(value); this._OperationalSites = value; this.OnOperationalSitesChanged(); this.OnPropertyChanged("OperationalSites"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.Dynamics.DataEntities.OperationalSite _OperationalSites; partial void OnOperationalSitesChanging(global::Microsoft.Dynamics.DataEntities.OperationalSite value); partial void OnOperationalSitesChanged(); /// <summary> /// There are no comments for Property Warehouses in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "Warehouses is required.")] public virtual global::Microsoft.Dynamics.DataEntities.Warehouse Warehouses { get { return this._Warehouses; } set { this.OnWarehousesChanging(value); this._Warehouses = value; this.OnWarehousesChanged(); this.OnPropertyChanged("Warehouses"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.Dynamics.DataEntities.Warehouse _Warehouses; partial void OnWarehousesChanging(global::Microsoft.Dynamics.DataEntities.Warehouse value); partial void OnWarehousesChanged(); /// <summary> /// This event is raised when the value of the property is changed /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; /// <summary> /// The value of the property is changed /// </summary> /// <param name="property">property name</param> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] protected virtual void OnPropertyChanged(string property) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new global::System.ComponentModel.PropertyChangedEventArgs(property)); } } } }
48.447297
184
0.636747
[ "MIT" ]
NathanClouseAX/AAXDataEntityPerfTest
Projects/AAXDataEntityPerfTest/ODataUtility/Connected Services/D365/CDSInventoryOnHandEntry.cs
35,853
C#
using System; namespace Newtonsoft.Json { /// <summary> /// Specifies type name handling options for the <see cref="JsonConvert"/>. /// </summary> [Flags] public enum TypeNameHandling { /// <summary> /// Do not include the .NET type name when serializing types. /// </summary> None = 0, /// <summary> /// Include the .NET type name when serializing into a JSON object structure. /// </summary> Objects = 1, /// <summary> /// Include the .NET type name when serializing into a JSON array structure. /// </summary> Arrays = 2, /// <summary> /// Always include the .NET type name when serializing. /// </summary> All = 3, /// <summary> /// Include the .NET type name when the type of the object being serialized is not the same as its declared type. /// </summary> Auto = 4 } }
26.888889
121
0.545455
[ "Apache-2.0" ]
curiosity-ai/h5
H5/H5.Newtonsoft.Json/Json/TypeNameHandling.cs
970
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Epam.Task7.UsersAndAwards.DAL.Interface; using Epam.Task7.UsersAndAwards.Entities; namespace Epam.Task7.UsersAndAwards.DAL { public class UserDao : IRepositoryDAO<User> { private const string UsersFile = "users.txt"; private static readonly string Path = AppContext.BaseDirectory + @"\..\usersAndAwards\"; private static readonly Dictionary<int, User> RepositoryUsers = FileWithUsers(); public void Add(User user) { var lastId = RepositoryUsers.Any() ? RepositoryUsers.Keys.Max() : 0; user.Id = ++lastId; RepositoryUsers.Add(user.Id, user); File.AppendAllLines(Path + UsersFile, new[] { user.ToString() }); } public bool Update(int id, User user) { user.Id = id; if (!RepositoryUsers.ContainsKey(id)) { return false; } RepositoryUsers[id] = user; var afterUpdate = RepositoryUsers.Values.Select(x => x.ToString()).ToArray(); File.WriteAllLines(Path + UsersFile, afterUpdate); return true; } public bool Delete(int id) { RepositoryUsers.Remove(id); var afterDelete = RepositoryUsers.Values.Select(x => x.ToString()).ToArray(); File.WriteAllLines(Path + UsersFile, afterDelete); return true; } public User GetById(int id) { if (RepositoryUsers.TryGetValue(id, out var user)) { return user; } return null; } public bool TryGetId(int id) { if (RepositoryUsers.TryGetValue(id, out var user)) { return true; } return false; } public IEnumerable<User> GetAll() { return RepositoryUsers.Values; } public void GiveAward(int idU, int idA) { throw new NotImplementedException(); } public IEnumerable<User> ListOfUserAwards() { throw new NotImplementedException(); } public IEnumerable<User> GetAllUsersWithAwards() { throw new NotImplementedException(); } public void AddImage(int id, byte[] img) { File.WriteAllBytes(Path + @"\ImgUser\" + id, img); RepositoryUsers[id].Img = img; } public bool DeleteImage(int id) { File.Delete(Path + @"\ImgUser\" + id); return true; } private static Dictionary<int, User> FileWithUsers() { Dictionary<int, User> repositoryUsers = new Dictionary<int, User>(); User user; var lines = File.ReadAllLines(Path + UsersFile); foreach (var line in lines) { int fid = int.Parse(line.Split(' ')[0]); string ffirstName = line.Split(' ')[1]; string flastName = line.Split(' ')[2]; string fpatronymic = line.Split(' ')[3]; DateTime fdateOfBirth = DateTime.Parse(line.Split(' ')[4]); byte[] img; if (File.Exists(Path + @"ImgUser\" + fid)) { img = File.ReadAllBytes(Path + @"ImgUser\" + fid); } else { img = File.ReadAllBytes(Path + @"\ImgUser\" + "default"); } user = new User { Id = fid, FirstName = ffirstName, LastName = flastName, Patronymic = fpatronymic, DateOfBirth = fdateOfBirth, Img = img, }; repositoryUsers.Add(int.Parse(line.Split(' ')[0]), user); } return repositoryUsers; } } }
28.413793
96
0.496602
[ "MIT" ]
VeronicaDedova/XT-2018Q4
Task11/Epam.Task7.UsersAndAwards.DAL/UserDao.cs
4,122
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Internal; using Xunit; // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore { public abstract class LoadTestBase<TFixture> : IClassFixture<TFixture> where TFixture : LoadTestBase<TFixture>.LoadFixtureBase { protected LoadTestBase(TFixture fixture) => Fixture = fixture; protected TFixture Fixture { get; } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.Children); context.Entry(parent).State = state; Assert.False(collectionEntry.IsLoaded); if (async) { await collectionEntry.LoadAsync(); } else { collectionEntry.Load(); } Assert.True(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(2, parent.Children.Count()); Assert.All(parent.Children.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<Child>().Single(e => e.Id == 12); ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, child.Parent); Assert.Same(child, parent.Children.Single()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<Single>().Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, single.Parent); Assert.Same(single, parent.Single); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.Single); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var single = context.ChangeTracker.Entries<Single>().Single().Entity; Assert.Same(single, parent.Single); Assert.Same(parent, single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_PK_to_PK_reference_to_principal(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<SinglePkToPk>().Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, single.Parent); Assert.Same(single, parent.SinglePkToPk); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_PK_to_PK_reference_to_dependent(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.SinglePkToPk); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var single = context.ChangeTracker.Entries<SinglePkToPk>().Single().Entity; Assert.Same(single, parent.SinglePkToPk); Assert.Same(parent, single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_using_Query(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.Children); context.Entry(parent).State = state; Assert.False(collectionEntry.IsLoaded); var children = async ? await collectionEntry.Query().ToListAsync() : collectionEntry.Query().ToList(); Assert.False(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(2, children.Count); Assert.Equal(2, parent.Children.Count()); Assert.All(children.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.All(children, p => Assert.Contains(p, parent.Children)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<Child>().Single(e => e.Id == 12); ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, child.Parent); Assert.Same(child, parent.Children.Single()); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<Single>().Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, single.Parent); Assert.Same(single, parent.Single); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_using_Query(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.Single); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); var single = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(single); Assert.Same(single, parent.Single); Assert.Same(parent, single.Parent); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_PK_to_PK_reference_to_principal_using_Query(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<SinglePkToPk>().Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, single.Parent); Assert.Same(single, parent.SinglePkToPk); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_PK_to_PK_reference_to_dependent_using_Query(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.SinglePkToPk); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); var single = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(single); Assert.Same(single, parent.SinglePkToPk); Assert.Same(parent, single.Parent); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_null_FK(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new Child { Id = 767, ParentId = null }).Entity; ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(child.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_null_FK(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new Single { Id = 767, ParentId = null }).Entity; ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_null_FK(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new Child { Id = 767, ParentId = null }).Entity; ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleOrDefaultAsync() : referenceEntry.Query().SingleOrDefault(); Assert.False(referenceEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(child.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_null_FK(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new Single { Id = 767, ParentId = null }).Entity; ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleOrDefaultAsync() : referenceEntry.Query().SingleOrDefault(); Assert.False(referenceEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(single.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_not_found(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Attach(new Parent { Id = 767, AlternateId = "NewRoot" }).Entity; ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.Children); context.Entry(parent).State = state; Assert.False(collectionEntry.IsLoaded); if (async) { await collectionEntry.LoadAsync(); } else { collectionEntry.Load(); } Assert.True(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(0, parent.Children.Count()); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_not_found(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new Child { Id = 767, ParentId = 787 }).Entity; ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(child.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_not_found(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new Single { Id = 767, ParentId = 787 }).Entity; ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_not_found(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Attach(new Parent { Id = 767, AlternateId = "NewRoot" }).Entity; ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.Single); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(parent.Single); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_using_Query_not_found(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Attach(new Parent { Id = 767, AlternateId = "NewRoot" }).Entity; ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.Children); context.Entry(parent).State = state; Assert.False(collectionEntry.IsLoaded); var children = async ? await collectionEntry.Query().ToListAsync() : collectionEntry.Query().ToList(); Assert.False(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(0, children.Count); Assert.Equal(0, parent.Children.Count()); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_not_found(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new Child { Id = 767, ParentId = 787 }).Entity; ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleOrDefaultAsync() : referenceEntry.Query().SingleOrDefault(); Assert.False(referenceEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(child.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_not_found(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new Single { Id = 767, ParentId = 787 }).Entity; ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleOrDefaultAsync() : referenceEntry.Query().SingleOrDefault(); Assert.False(referenceEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(single.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_using_Query_not_found(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Attach(new Parent { Id = 767, AlternateId = "NewRoot" }).Entity; ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.Single); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); var single = async ? await referenceEntry.Query().SingleOrDefaultAsync() : referenceEntry.Query().SingleOrDefault(); Assert.False(referenceEntry.IsLoaded); RecordLog(); Assert.Null(single); Assert.Null(parent.Single); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Include(e => e.Children).Single(); ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.Children); context.Entry(parent).State = state; Assert.True(collectionEntry.IsLoaded); if (async) { await collectionEntry.LoadAsync(); } else { collectionEntry.Load(); } Assert.True(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(2, parent.Children.Count()); Assert.All(parent.Children.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<Child>().Include(e => e.Parent).Single(e => e.Id == 12); ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.True(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, child.Parent); Assert.Same(child, parent.Children.Single()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<Single>().Include(e => e.Parent).Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.True(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, single.Parent); Assert.Same(single, parent.Single); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Include(e => e.Single).Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.Single); context.Entry(parent).State = state; Assert.True(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var single = context.ChangeTracker.Entries<Single>().Single().Entity; Assert.Same(single, parent.Single); Assert.Same(parent, single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_PK_to_PK_reference_to_principal_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<SinglePkToPk>().Include(e => e.Parent).Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.True(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, single.Parent); Assert.Same(single, parent.SinglePkToPk); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_PK_to_PK_reference_to_dependent_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Include(e => e.SinglePkToPk).Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.SinglePkToPk); context.Entry(parent).State = state; Assert.True(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var single = context.ChangeTracker.Entries<SinglePkToPk>().Single().Entity; Assert.Same(single, parent.SinglePkToPk); Assert.Same(parent, single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_using_Query_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Include(e => e.Children).Single(); ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.Children); context.Entry(parent).State = state; Assert.True(collectionEntry.IsLoaded); var children = async ? await collectionEntry.Query().ToListAsync() : collectionEntry.Query().ToList(); Assert.True(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(2, children.Count); Assert.Equal(2, parent.Children.Count()); Assert.All(children.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.All(children, p => Assert.Contains(p, parent.Children)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<Child>().Include(e => e.Parent).Single(e => e.Id == 12); ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.True(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, child.Parent); Assert.Same(child, parent.Children.Single()); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<Single>().Include(e => e.Parent).Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.True(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, single.Parent); Assert.Same(single, parent.Single); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_using_Query_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Include(e => e.Single).Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.Single); context.Entry(parent).State = state; Assert.True(referenceEntry.IsLoaded); var single = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(single); Assert.Same(single, parent.Single); Assert.Same(parent, single.Parent); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_PK_to_PK_reference_to_principal_using_Query_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<SinglePkToPk>().Include(e => e.Parent).Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.True(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, single.Parent); Assert.Same(single, parent.SinglePkToPk); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_PK_to_PK_reference_to_dependent_using_Query_already_loaded(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Include(e => e.SinglePkToPk).Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.SinglePkToPk); context.Entry(parent).State = state; Assert.True(referenceEntry.IsLoaded); var single = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(single); Assert.Same(single, parent.SinglePkToPk); Assert.Same(parent, single.Parent); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Children"); context.Entry(parent).State = state; Assert.False(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(2, parent.Children.Count()); Assert.All(parent.Children.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<Child>().Single(e => e.Id == 12); ClearLog(); var navigationEntry = context.Entry(child).Navigation("Parent"); context.Entry(child).State = state; Assert.False(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, child.Parent); Assert.Same(child, parent.Children.Single()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<Single>().Single(); ClearLog(); var navigationEntry = context.Entry(single).Navigation("Parent"); context.Entry(single).State = state; Assert.False(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, single.Parent); Assert.Same(single, parent.Single); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Single"); context.Entry(parent).State = state; Assert.False(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var single = context.ChangeTracker.Entries<Single>().Single().Entity; Assert.Same(single, parent.Single); Assert.Same(parent, single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_using_Query_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Children"); context.Entry(parent).State = state; Assert.False(navigationEntry.IsLoaded); var children = async ? await navigationEntry.Query().OfType<object>().ToListAsync() : navigationEntry.Query().OfType<object>().ToList(); Assert.False(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(2, children.Count); Assert.Equal(2, parent.Children.Count()); Assert.All(children.Select(e => ((Child)e).Parent), c => Assert.Same(parent, c)); Assert.All(children, p => Assert.Contains(p, parent.Children)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<Child>().Single(e => e.Id == 12); ClearLog(); var navigationEntry = context.Entry(child).Navigation("Parent"); context.Entry(child).State = state; Assert.False(navigationEntry.IsLoaded); var parent = async ? await navigationEntry.Query().OfType<object>().SingleAsync() : navigationEntry.Query().OfType<object>().Single(); Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, child.Parent); Assert.Same(child, ((Parent)parent).Children.Single()); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<Single>().Single(); ClearLog(); var navigationEntry = context.Entry(single).Navigation("Parent"); context.Entry(single).State = state; Assert.False(navigationEntry.IsLoaded); var parent = async ? await navigationEntry.Query().OfType<object>().SingleAsync() : navigationEntry.Query().OfType<object>().Single(); Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, single.Parent); Assert.Same(single, ((Parent)parent).Single); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_using_Query_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Single"); context.Entry(parent).State = state; Assert.False(navigationEntry.IsLoaded); var single = async ? await navigationEntry.Query().OfType<object>().SingleAsync() : navigationEntry.Query().OfType<object>().Single(); Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.NotNull(single); Assert.Same(single, parent.Single); Assert.Same(parent, ((Single)single).Parent); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_not_found_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Attach(new Parent { Id = 767, AlternateId = "NewRoot" }).Entity; ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Children"); context.Entry(parent).State = state; Assert.False(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(0, parent.Children.Count()); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_not_found_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new Child { Id = 767, ParentId = 787 }).Entity; ClearLog(); var navigationEntry = context.Entry(child).Navigation("Parent"); context.Entry(child).State = state; Assert.False(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(child.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_not_found_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new Single { Id = 767, ParentId = 787 }).Entity; ClearLog(); var navigationEntry = context.Entry(single).Navigation("Parent"); context.Entry(single).State = state; Assert.False(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_not_found_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Attach(new Parent { Id = 767, AlternateId = "NewRoot" }).Entity; ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Single"); context.Entry(parent).State = state; Assert.False(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(parent.Single); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_using_Query_not_found_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Attach(new Parent { Id = 767, AlternateId = "NewRoot" }).Entity; ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Children"); context.Entry(parent).State = state; Assert.False(navigationEntry.IsLoaded); var children = async ? await navigationEntry.Query().OfType<object>().ToListAsync() : navigationEntry.Query().OfType<object>().ToList(); Assert.False(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(0, children.Count); Assert.Equal(0, parent.Children.Count()); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_not_found_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new Child { Id = 767, ParentId = 787 }).Entity; ClearLog(); var navigationEntry = context.Entry(child).Navigation("Parent"); context.Entry(child).State = state; Assert.False(navigationEntry.IsLoaded); var parent = async ? await navigationEntry.Query().OfType<object>().SingleOrDefaultAsync() : navigationEntry.Query().OfType<object>().SingleOrDefault(); Assert.False(navigationEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(child.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_not_found_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new Single { Id = 767, ParentId = 787 }).Entity; ClearLog(); var navigationEntry = context.Entry(single).Navigation("Parent"); context.Entry(single).State = state; Assert.False(navigationEntry.IsLoaded); var parent = async ? await navigationEntry.Query().OfType<object>().SingleOrDefaultAsync() : navigationEntry.Query().OfType<object>().SingleOrDefault(); Assert.False(navigationEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(single.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_using_Query_not_found_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Attach(new Parent { Id = 767, AlternateId = "NewRoot" }).Entity; ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Single"); context.Entry(parent).State = state; Assert.False(navigationEntry.IsLoaded); var single = async ? await navigationEntry.Query().OfType<object>().SingleOrDefaultAsync() : navigationEntry.Query().OfType<object>().SingleOrDefault(); Assert.False(navigationEntry.IsLoaded); RecordLog(); Assert.Null(single); Assert.Null(parent.Single); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_already_loaded_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Include(e => e.Children).Single(); ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Children"); context.Entry(parent).State = state; Assert.True(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(2, parent.Children.Count()); Assert.All(parent.Children.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_already_loaded_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<Child>().Include(e => e.Parent).Single(e => e.Id == 12); ClearLog(); var navigationEntry = context.Entry(child).Navigation("Parent"); context.Entry(child).State = state; Assert.True(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, child.Parent); Assert.Same(child, parent.Children.Single()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_already_loaded_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<Single>().Include(e => e.Parent).Single(); ClearLog(); var navigationEntry = context.Entry(single).Navigation("Parent"); context.Entry(single).State = state; Assert.True(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, single.Parent); Assert.Same(single, parent.Single); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_already_loaded_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Include(e => e.Single).Single(); ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Single"); context.Entry(parent).State = state; Assert.True(navigationEntry.IsLoaded); if (async) { await navigationEntry.LoadAsync(); } else { navigationEntry.Load(); } Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var single = context.ChangeTracker.Entries<Single>().Single().Entity; Assert.Same(single, parent.Single); Assert.Same(parent, single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_using_Query_already_loaded_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Include(e => e.Children).Single(); ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Children"); context.Entry(parent).State = state; Assert.True(navigationEntry.IsLoaded); var children = async ? await navigationEntry.Query().OfType<object>().ToListAsync() : navigationEntry.Query().OfType<object>().ToList(); Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.Equal(2, children.Count); Assert.Equal(2, parent.Children.Count()); Assert.All(children.Select(e => ((Child)e).Parent), c => Assert.Same(parent, c)); Assert.All(children, p => Assert.Contains(p, parent.Children)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_already_loaded_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<Child>().Include(e => e.Parent).Single(e => e.Id == 12); ClearLog(); var navigationEntry = context.Entry(child).Navigation("Parent"); context.Entry(child).State = state; Assert.True(navigationEntry.IsLoaded); var parent = async ? await navigationEntry.Query().OfType<object>().SingleAsync() : navigationEntry.Query().OfType<object>().Single(); Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, child.Parent); Assert.Same(child, ((Parent)parent).Children.Single()); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_already_loaded_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<Single>().Include(e => e.Parent).Single(); ClearLog(); var navigationEntry = context.Entry(single).Navigation("Parent"); context.Entry(single).State = state; Assert.True(navigationEntry.IsLoaded); var parent = async ? await navigationEntry.Query().OfType<object>().SingleAsync() : navigationEntry.Query().OfType<object>().Single(); Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, single.Parent); Assert.Same(single, ((Parent)parent).Single); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_using_Query_already_loaded_untyped(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Include(e => e.Single).Single(); ClearLog(); var navigationEntry = context.Entry(parent).Navigation("Single"); context.Entry(parent).State = state; Assert.True(navigationEntry.IsLoaded); var single = async ? await navigationEntry.Query().OfType<object>().SingleAsync() : navigationEntry.Query().OfType<object>().Single(); Assert.True(navigationEntry.IsLoaded); RecordLog(); Assert.NotNull(single); Assert.Same(single, parent.Single); Assert.Same(parent, ((Single)single).Parent); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.ChildrenAk); context.Entry(parent).State = state; Assert.False(collectionEntry.IsLoaded); if (async) { await collectionEntry.LoadAsync(); } else { collectionEntry.Load(); } Assert.True(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(2, parent.ChildrenAk.Count()); Assert.All(parent.ChildrenAk.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<ChildAk>().Single(e => e.Id == 32); ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, child.Parent); Assert.Same(child, parent.ChildrenAk.Single()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<SingleAk>().Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, single.Parent); Assert.Same(single, parent.SingleAk); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.SingleAk); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var single = context.ChangeTracker.Entries<SingleAk>().Single().Entity; Assert.Same(single, parent.SingleAk); Assert.Same(parent, single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_using_Query_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.ChildrenAk); context.Entry(parent).State = state; Assert.False(collectionEntry.IsLoaded); var children = async ? await collectionEntry.Query().ToListAsync() : collectionEntry.Query().ToList(); Assert.False(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(2, children.Count); Assert.Equal(2, parent.ChildrenAk.Count()); Assert.All(children.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.All(children, p => Assert.Contains(p, parent.ChildrenAk)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<ChildAk>().Single(e => e.Id == 32); ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, child.Parent); Assert.Same(child, parent.ChildrenAk.Single()); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<SingleAk>().Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, single.Parent); Assert.Same(single, parent.SingleAk); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_using_Query_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.SingleAk); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); var single = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(single); Assert.Same(single, parent.SingleAk); Assert.Same(parent, single.Parent); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_null_FK_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new ChildAk { Id = 767, ParentId = null }).Entity; ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(child.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_null_FK_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new SingleAk { Id = 767, ParentId = null }).Entity; ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_null_FK_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new ChildAk { Id = 767, ParentId = null }).Entity; ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleOrDefaultAsync() : referenceEntry.Query().SingleOrDefault(); Assert.False(referenceEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(child.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_null_FK_alternate_key(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new SingleAk { Id = 767, ParentId = null }).Entity; ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleOrDefaultAsync() : referenceEntry.Query().SingleOrDefault(); Assert.False(referenceEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(single.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.ChildrenShadowFk); context.Entry(parent).State = state; Assert.False(collectionEntry.IsLoaded); if (async) { await collectionEntry.LoadAsync(); } else { collectionEntry.Load(); } Assert.True(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(2, parent.ChildrenShadowFk.Count()); Assert.All(parent.ChildrenShadowFk.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<ChildShadowFk>().Single(e => e.Id == 52); ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, child.Parent); Assert.Same(child, parent.ChildrenShadowFk.Single()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<SingleShadowFk>().Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, single.Parent); Assert.Same(single, parent.SingleShadowFk); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.SingleShadowFk); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var single = context.ChangeTracker.Entries<SingleShadowFk>().Single().Entity; Assert.Same(single, parent.SingleShadowFk); Assert.Same(parent, single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_using_Query_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.ChildrenShadowFk); context.Entry(parent).State = state; Assert.False(collectionEntry.IsLoaded); var children = async ? await collectionEntry.Query().ToListAsync() : collectionEntry.Query().ToList(); Assert.False(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(2, children.Count); Assert.Equal(2, parent.ChildrenShadowFk.Count()); Assert.All(children.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.All(children, p => Assert.Contains(p, parent.ChildrenShadowFk)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<ChildShadowFk>().Single(e => e.Id == 52); ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, child.Parent); Assert.Same(child, parent.ChildrenShadowFk.Single()); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<SingleShadowFk>().Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, single.Parent); Assert.Same(single, parent.SingleShadowFk); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_using_Query_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.SingleShadowFk); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); var single = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(single); Assert.Same(single, parent.SingleShadowFk); Assert.Same(parent, single.Parent); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_null_FK_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new ChildShadowFk { Id = 767 }).Entity; ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(child.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_null_FK_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new SingleShadowFk { Id = 767 }).Entity; ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_null_FK_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new ChildShadowFk { Id = 767 }).Entity; ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleOrDefaultAsync() : referenceEntry.Query().SingleOrDefault(); Assert.False(referenceEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(child.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_null_FK_shadow_fk(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new SingleShadowFk { Id = 767 }).Entity; ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleOrDefaultAsync() : referenceEntry.Query().SingleOrDefault(); Assert.False(referenceEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(single.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.ChildrenCompositeKey); context.Entry(parent).State = state; Assert.False(collectionEntry.IsLoaded); if (async) { await collectionEntry.LoadAsync(); } else { collectionEntry.Load(); } Assert.True(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(2, parent.ChildrenCompositeKey.Count()); Assert.All(parent.ChildrenCompositeKey.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<ChildCompositeKey>().Single(e => e.Id == 52); ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, child.Parent); Assert.Same(child, parent.ChildrenCompositeKey.Single()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<SingleCompositeKey>().Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var parent = context.ChangeTracker.Entries<Parent>().Single().Entity; Assert.Same(parent, single.Parent); Assert.Same(single, parent.SingleCompositeKey); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.SingleCompositeKey); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); var single = context.ChangeTracker.Entries<SingleCompositeKey>().Single().Entity; Assert.Same(single, parent.SingleCompositeKey); Assert.Same(parent, single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_collection_using_Query_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var collectionEntry = context.Entry(parent).Collection(e => e.ChildrenCompositeKey); context.Entry(parent).State = state; Assert.False(collectionEntry.IsLoaded); var children = async ? await collectionEntry.Query().ToListAsync() : collectionEntry.Query().ToList(); Assert.False(collectionEntry.IsLoaded); RecordLog(); Assert.Equal(2, children.Count); Assert.Equal(2, parent.ChildrenCompositeKey.Count()); Assert.All(children.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.All(children, p => Assert.Contains(p, parent.ChildrenCompositeKey)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Set<ChildCompositeKey>().Single(e => e.Id == 52); ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, child.Parent); Assert.Same(child, parent.ChildrenCompositeKey.Single()); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Set<SingleCompositeKey>().Single(); ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(parent); Assert.Same(parent, single.Parent); Assert.Same(single, parent.SingleCompositeKey); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_dependent_using_Query_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); ClearLog(); var referenceEntry = context.Entry(parent).Reference(e => e.SingleCompositeKey); context.Entry(parent).State = state; Assert.False(referenceEntry.IsLoaded); var single = async ? await referenceEntry.Query().SingleAsync() : referenceEntry.Query().Single(); Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.NotNull(single); Assert.Same(single, parent.SingleCompositeKey); Assert.Same(parent, single.Parent); Assert.Equal(2, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_null_FK_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new ChildCompositeKey { Id = 767, ParentId = 567 }).Entity; ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(child.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_null_FK_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new SingleCompositeKey { Id = 767, ParentAlternateId = "Boot" }).Entity; ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } Assert.True(referenceEntry.IsLoaded); RecordLog(); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.Null(single.Parent); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_many_to_one_reference_to_principal_using_Query_null_FK_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var child = context.Attach(new ChildCompositeKey { Id = 767, ParentAlternateId = "Boot" }).Entity; ClearLog(); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleOrDefaultAsync() : referenceEntry.Query().SingleOrDefault(); Assert.False(referenceEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(child.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Theory] [InlineData(EntityState.Unchanged, true)] [InlineData(EntityState.Unchanged, false)] [InlineData(EntityState.Modified, true)] [InlineData(EntityState.Modified, false)] [InlineData(EntityState.Deleted, true)] [InlineData(EntityState.Deleted, false)] public virtual async Task Load_one_to_one_reference_to_principal_using_Query_null_FK_composite_key(EntityState state, bool async) { using (var context = CreateContext()) { var single = context.Attach(new SingleCompositeKey { Id = 767, ParentId = 567 }).Entity; ClearLog(); var referenceEntry = context.Entry(single).Reference(e => e.Parent); context.Entry(single).State = state; Assert.False(referenceEntry.IsLoaded); var parent = async ? await referenceEntry.Query().SingleOrDefaultAsync() : referenceEntry.Query().SingleOrDefault(); Assert.False(referenceEntry.IsLoaded); RecordLog(); Assert.Null(parent); Assert.Null(single.Parent); Assert.Equal(1, context.ChangeTracker.Entries().Count()); } } [Fact] public virtual void Can_change_IsLoaded_flag_for_collection() { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var collectionEntry = context.Entry(parent).Collection(e => e.Children); Assert.False(collectionEntry.IsLoaded); collectionEntry.IsLoaded = true; Assert.True(collectionEntry.IsLoaded); collectionEntry.Load(); Assert.Equal(0, parent.Children.Count()); Assert.Equal(1, context.ChangeTracker.Entries().Count()); Assert.True(collectionEntry.IsLoaded); collectionEntry.IsLoaded = false; Assert.False(collectionEntry.IsLoaded); collectionEntry.Load(); Assert.Equal(2, parent.Children.Count()); Assert.All(parent.Children.Select(e => e.Parent), c => Assert.Same(parent, c)); Assert.Equal(3, context.ChangeTracker.Entries().Count()); Assert.True(collectionEntry.IsLoaded); } } [Fact] public virtual void Can_change_IsLoaded_flag_for_reference_only_if_null() { using (var context = CreateContext()) { var child = context.Set<Child>().Single(e => e.Id == 12); var referenceEntry = context.Entry(child).Reference(e => e.Parent); Assert.False(referenceEntry.IsLoaded); referenceEntry.IsLoaded = true; Assert.True(referenceEntry.IsLoaded); referenceEntry.Load(); Assert.True(referenceEntry.IsLoaded); Assert.Equal(1, context.ChangeTracker.Entries().Count()); referenceEntry.IsLoaded = true; referenceEntry.IsLoaded = false; referenceEntry.Load(); Assert.Equal(2, context.ChangeTracker.Entries().Count()); Assert.True(referenceEntry.IsLoaded); Assert.Equal( CoreStrings.ReferenceMustBeLoaded("Parent", typeof(Child).Name), Assert.Throws<InvalidOperationException>(() => referenceEntry.IsLoaded = false).Message); } } [Theory] [InlineData(true)] [InlineData(false)] public virtual async Task Load_collection_for_detached_throws(bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var collectionEntry = context.Entry(parent).Collection(e => e.Children); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Children), nameof(Parent)), (await Assert.ThrowsAsync<InvalidOperationException>( async () => { if (async) { await collectionEntry.LoadAsync(); } else { collectionEntry.Load(); } })).Message); } } [Theory] [InlineData(true)] [InlineData(false)] public virtual async Task Load_collection_using_string_for_detached_throws(bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var collectionEntry = context.Entry(parent).Collection(nameof(Parent.Children)); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Children), nameof(Parent)), (await Assert.ThrowsAsync<InvalidOperationException>( async () => { if (async) { await collectionEntry.LoadAsync(); } else { collectionEntry.Load(); } })).Message); } } [Theory] [InlineData(true)] [InlineData(false)] public virtual async Task Load_collection_with_navigation_for_detached_throws(bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var collectionEntry = context.Entry(parent).Navigation(nameof(Parent.Children)); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Children), nameof(Parent)), (await Assert.ThrowsAsync<InvalidOperationException>( async () => { if (async) { await collectionEntry.LoadAsync(); } else { collectionEntry.Load(); } })).Message); } } [Theory] [InlineData(true)] [InlineData(false)] public virtual async Task Load_reference_to_principal_for_detached_throws(bool async) { using (var context = CreateContext()) { var child = context.Set<Child>().Single(e => e.Id == 12); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Child.Parent), nameof(Child)), (await Assert.ThrowsAsync<InvalidOperationException>( async () => { if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } })).Message); } } [Theory] [InlineData(true)] [InlineData(false)] public virtual async Task Load_reference_with_navigation_to_principal_for_detached_throws(bool async) { using (var context = CreateContext()) { var child = context.Set<Child>().Single(e => e.Id == 12); var referenceEntry = context.Entry(child).Navigation(nameof(Child.Parent)); context.Entry(child).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Child.Parent), nameof(Child)), (await Assert.ThrowsAsync<InvalidOperationException>( async () => { if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } })).Message); } } [Theory] [InlineData(true)] [InlineData(false)] public virtual async Task Load_reference_using_string_to_principal_for_detached_throws(bool async) { using (var context = CreateContext()) { var child = context.Set<Child>().Single(e => e.Id == 12); var referenceEntry = context.Entry(child).Reference(nameof(Child.Parent)); context.Entry(child).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Child.Parent), nameof(Child)), (await Assert.ThrowsAsync<InvalidOperationException>( async () => { if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } })).Message); } } [Theory] [InlineData(true)] [InlineData(false)] public virtual async Task Load_reference_to_dependent_for_detached_throws(bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var referenceEntry = context.Entry(parent).Reference(e => e.Single); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Single), nameof(Parent)), (await Assert.ThrowsAsync<InvalidOperationException>( async () => { if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } })).Message); } } [Theory] [InlineData(true)] [InlineData(false)] public virtual async Task Load_reference_to_dependent_with_navigation_for_detached_throws(bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var referenceEntry = context.Entry(parent).Navigation(nameof(Parent.Single)); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Single), nameof(Parent)), (await Assert.ThrowsAsync<InvalidOperationException>( async () => { if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } })).Message); } } [Theory] [InlineData(true)] [InlineData(false)] public virtual async Task Load_reference_to_dependent_using_string_for_detached_throws(bool async) { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var referenceEntry = context.Entry(parent).Reference(nameof(Parent.Single)); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Single), nameof(Parent)), (await Assert.ThrowsAsync<InvalidOperationException>( async () => { if (async) { await referenceEntry.LoadAsync(); } else { referenceEntry.Load(); } })).Message); } } [Fact] public virtual void Query_collection_for_detached_throws() { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var collectionEntry = context.Entry(parent).Collection(e => e.Children); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Children), nameof(Parent)), Assert.Throws<InvalidOperationException>(() => collectionEntry.Query()).Message); } } [Fact] public virtual void Query_collection_using_string_for_detached_throws() { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var collectionEntry = context.Entry(parent).Collection(nameof(Parent.Children)); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Children), nameof(Parent)), Assert.Throws<InvalidOperationException>(() => collectionEntry.Query()).Message); } } [Fact] public virtual void Query_collection_with_navigation_for_detached_throws() { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var collectionEntry = context.Entry(parent).Navigation(nameof(Parent.Children)); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Children), nameof(Parent)), Assert.Throws<InvalidOperationException>(() => collectionEntry.Query()).Message); } } [Fact] public virtual void Query_reference_to_principal_for_detached_throws() { using (var context = CreateContext()) { var child = context.Set<Child>().Single(e => e.Id == 12); var referenceEntry = context.Entry(child).Reference(e => e.Parent); context.Entry(child).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Child.Parent), nameof(Child)), Assert.Throws<InvalidOperationException>(() => referenceEntry.Query()).Message); } } [Fact] public virtual void Query_reference_with_navigation_to_principal_for_detached_throws() { using (var context = CreateContext()) { var child = context.Set<Child>().Single(e => e.Id == 12); var referenceEntry = context.Entry(child).Navigation(nameof(Child.Parent)); context.Entry(child).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Child.Parent), nameof(Child)), Assert.Throws<InvalidOperationException>(() => referenceEntry.Query()).Message); } } [Fact] public virtual void Query_reference_using_string_to_principal_for_detached_throws() { using (var context = CreateContext()) { var child = context.Set<Child>().Single(e => e.Id == 12); var referenceEntry = context.Entry(child).Reference(nameof(Child.Parent)); context.Entry(child).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Child.Parent), nameof(Child)), Assert.Throws<InvalidOperationException>(() => referenceEntry.Query()).Message); } } [Fact] public virtual void Query_reference_to_dependent_for_detached_throws() { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var referenceEntry = context.Entry(parent).Reference(e => e.Single); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Single), nameof(Parent)), Assert.Throws<InvalidOperationException>(() => referenceEntry.Query()).Message); } } [Fact] public virtual void Query_reference_to_dependent_with_navigation_for_detached_throws() { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var referenceEntry = context.Entry(parent).Navigation(nameof(Parent.Single)); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Single), nameof(Parent)), Assert.Throws<InvalidOperationException>(() => referenceEntry.Query()).Message); } } [Fact] public virtual void Query_reference_to_dependent_using_string_for_detached_throws() { using (var context = CreateContext()) { var parent = context.Set<Parent>().Single(); var referenceEntry = context.Entry(parent).Reference(nameof(Parent.Single)); context.Entry(parent).State = EntityState.Detached; Assert.Equal( CoreStrings.CannotLoadDetached(nameof(Parent.Single), nameof(Parent)), Assert.Throws<InvalidOperationException>(() => referenceEntry.Query()).Message); } } protected class Parent { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public string AlternateId { get; set; } public IEnumerable<Child> Children { get; set; } public SinglePkToPk SinglePkToPk { get; set; } public Single Single { get; set; } public IEnumerable<ChildAk> ChildrenAk { get; set; } public SingleAk SingleAk { get; set; } public IEnumerable<ChildShadowFk> ChildrenShadowFk { get; set; } public SingleShadowFk SingleShadowFk { get; set; } public IEnumerable<ChildCompositeKey> ChildrenCompositeKey { get; set; } public SingleCompositeKey SingleCompositeKey { get; set; } } protected class Child { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public int? ParentId { get; set; } public Parent Parent { get; set; } } protected class SinglePkToPk { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public Parent Parent { get; set; } } protected class Single { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public int? ParentId { get; set; } public Parent Parent { get; set; } } protected class ChildAk { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public string ParentId { get; set; } public Parent Parent { get; set; } } protected class SingleAk { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public string ParentId { get; set; } public Parent Parent { get; set; } } protected class ChildShadowFk { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public Parent Parent { get; set; } } protected class SingleShadowFk { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public Parent Parent { get; set; } } protected class ChildCompositeKey { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public int? ParentId { get; set; } public string ParentAlternateId { get; set; } public Parent Parent { get; set; } } protected class SingleCompositeKey { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public int? ParentId { get; set; } public string ParentAlternateId { get; set; } public Parent Parent { get; set; } } protected DbContext CreateContext() => Fixture.CreateContext(); protected virtual void ClearLog() { } protected virtual void RecordLog() { } public abstract class LoadFixtureBase : SharedStoreFixtureBase<DbContext> { protected override string StoreName { get; } = "LoadTest"; protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { modelBuilder.Entity<SingleShadowFk>() .Property<int?>("ParentId"); modelBuilder.Entity<Parent>( b => { b.Property(e => e.AlternateId).ValueGeneratedOnAdd(); b.HasMany(e => e.Children) .WithOne(e => e.Parent) .HasForeignKey(e => e.ParentId); b.HasOne(e => e.SinglePkToPk) .WithOne(e => e.Parent) .HasForeignKey<SinglePkToPk>(e => e.Id) .IsRequired(); b.HasOne(e => e.Single) .WithOne(e => e.Parent) .HasForeignKey<Single>(e => e.ParentId); b.HasMany(e => e.ChildrenAk) .WithOne(e => e.Parent) .HasPrincipalKey(e => e.AlternateId) .HasForeignKey(e => e.ParentId); b.HasOne(e => e.SingleAk) .WithOne(e => e.Parent) .HasPrincipalKey<Parent>(e => e.AlternateId) .HasForeignKey<SingleAk>(e => e.ParentId); b.HasMany(e => e.ChildrenShadowFk) .WithOne(e => e.Parent) .HasPrincipalKey(e => e.Id) .HasForeignKey("ParentId"); b.HasOne(e => e.SingleShadowFk) .WithOne(e => e.Parent) .HasPrincipalKey<Parent>(e => e.Id) .HasForeignKey<SingleShadowFk>("ParentId"); b.HasMany(e => e.ChildrenCompositeKey) .WithOne(e => e.Parent) .HasPrincipalKey(e => new { e.AlternateId, e.Id }) .HasForeignKey(e => new { e.ParentAlternateId, e.ParentId }); b.HasOne(e => e.SingleCompositeKey) .WithOne(e => e.Parent) .HasPrincipalKey<Parent>(e => new { e.AlternateId, e.Id }) .HasForeignKey<SingleCompositeKey>(e => new { e.ParentAlternateId, e.ParentId }); }); } protected override void Seed(DbContext context) { context.Add( (object)new Parent { Id = 707, AlternateId = "Root", Children = new List<Child> { new Child { Id = 11 }, new Child { Id = 12 } }, SinglePkToPk = new SinglePkToPk { Id = 707 }, Single = new Single { Id = 21 }, ChildrenAk = new List<ChildAk> { new ChildAk { Id = 31 }, new ChildAk { Id = 32 } }, SingleAk = new SingleAk { Id = 42 }, ChildrenShadowFk = new List<ChildShadowFk> { new ChildShadowFk { Id = 51 }, new ChildShadowFk { Id = 52 } }, SingleShadowFk = new SingleShadowFk { Id = 62 }, ChildrenCompositeKey = new List<ChildCompositeKey> { new ChildCompositeKey { Id = 51 }, new ChildCompositeKey { Id = 52 } }, SingleCompositeKey = new SingleCompositeKey { Id = 62 } }); context.SaveChanges(); } } } }
34.68041
139
0.539236
[ "Apache-2.0" ]
h0wXD/EntityFrameworkCore
src/EFCore.Specification.Tests/LoadTestBase.cs
155,611
C#
using System.Collections.Generic; using AutoFixture; using Forms.Core.Models.InFlight; namespace Forms.Core.Tests.Builders.Form { public class AnswerBuilder { private Answer Answer { get; } public static AnswerBuilder Build => new AnswerBuilder(); private AnswerBuilder() { var fixture = new Fixture(); Answer = fixture.Build<Answer>().Without(fx => fx.Values).Create(); WithDefaultValue("this is the default value"); } public AnswerBuilder WithDefaultValue(string value) { Answer.Values.Remove("default"); Answer.Values.Add("default", value); return this; } public AnswerBuilder WithType(AnswerType answerType) { Answer.AnswerType = answerType; return this; } public AnswerBuilder WithSpecificKeyValues(Dictionary<string, string> keyValues) { Answer.Values.Clear(); foreach (var (key, value) in keyValues) { Answer.Values.Add(key, value); } return this; } public Answer AnAnswer() { return Answer; } } }
25.959184
88
0.547956
[ "Apache-2.0" ]
mod-veterans/digital-service-web-app
Forms.Core.Tests/Builders/Form/AnswerBuilder.cs
1,272
C#
using System; using System.Text; using NGTDI.Library.Managers; using NGTDI.Library.Objects; using TreeGecko.Library.Common.Enums; using TreeGecko.Library.Common.Helpers; using TreeGecko.Library.Common.Security; using TreeGecko.Library.Net.Enums; using TreeGecko.Library.Net.Objects; namespace NGTDI.Console { class Program { static void Main(string[] _args) { TraceFileHelper.SetupLogging(); if (_args != null && _args.Length > 0) { string action = _args[0].ToLower(); switch (action) { case "builddb": BuildDB(); break; case "adduser": if (_args.Length >= 4) { AddUser(_args[1], _args[2], _args[3]); } break; case "buildcannedemail": BuildEmail(); break; case "buildeula": BuildEula(); break; case "test": Test(); break; default: System.Console.WriteLine("No action requested"); break; } } TraceFileHelper.TearDownLogging(); } public static void Test() { string password = RandomString.GetRandomString(16); byte[] temp = Encoding.ASCII.GetBytes(password); User user = new User(); user.Key = Convert.ToBase64String(temp); user.Salt = TGUserPassword.GenerateSalt(user.Key, 16); AntiResolution ar = new AntiResolution(); ar.SetAntiResolutionText(user, "This is a test"); string test = ar.GetAntiResolutionText(user); } private static void BuildEula() { TGEula eula = new TGEula { Active = true, LastModifiedDateTime = DateTime.UtcNow, Text = "Blah, Blah, Blah" }; NGTDIManager manager = new NGTDIManager(); manager.Persist(eula); } private static void BuildEmail() { NGTDIManager manager = new NGTDIManager(); CannedEmail resetPasswordEmail = new CannedEmail { Active = true, BodyType = EmailBodyType.HTML, Description = "Sent when a user needs to have their password reset", From = "noreply@ngtdi.com", Guid = new Guid("cab0206c-0f96-420e-b384-cb005d90af48"), Name = "Reset Password Email", ReplyTo = "noreply@ngtdi.com", Subject = "NGTDI Password Reset", To = "[[EmailAddress]]", Body = "<p>We have recieved a request to reset your password to the NGTDI system.</p><p>Your username is [[Username]].</p><p>Your password has been changed to [[Password]].</p>" }; manager.Persist(resetPasswordEmail); CannedEmail emailAddressValidateEmail = new CannedEmail { Active = true, BodyType = EmailBodyType.HTML, Description = "Sent when a user needs to verify their email address", From = "noreply@ngtdi.com", Guid = new Guid("b3bf887e-82e7-4662-9335-373f8827374b"), Name = "Validate Email Address", ReplyTo = "noreply@ngtdi.com", Subject = "NGTDI Email Validation", To = "[[EmailAddress]]", Body = "<p>Please click the following link to complete your setup as a NGTDI user. <a href=\"[[SystemUrl]]/emailvalidation/[[ValidationText]]\">Validate my Email</a></p>" }; manager.Persist(emailAddressValidateEmail); } private static void AddUser(string _username, string _email, string _password) { NGTDIManager manager = new NGTDIManager(); Library.Objects.User user = new Library.Objects.User { UserType = UserTypes.User, Username = _username, EmailAddress = _email, IsVerified = true }; manager.Persist(user); TGUserPassword userPassword = TGUserPassword.GetNew(user.Guid, _username, _password); manager.Persist(userPassword); } private static void BuildDB() { NGTDIStructureManager manager = new NGTDIStructureManager(); manager.BuildDB(); } } }
34.595745
190
0.49959
[ "MIT" ]
NGTDI/Server
src/ngtdiConsole/Program.cs
4,880
C#
using EFCore.BulkExtensions.SqlAdapters; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace EFCore.BulkExtensions.Tests { public class EFCoreBatchTestAsync { protected int EntitiesNumber => 1000; [Theory] [InlineData(DbServer.SqlServer)] [InlineData(DbServer.Sqlite)] public async Task BatchTestAsync(DbServer dbServer) { ContextUtil.DbServer = dbServer; await RunDeleteAllAsync(dbServer); await RunInsertAsync(); await RunBatchUpdateAsync(dbServer); int deletedEntities = 1; if (dbServer == DbServer.SqlServer) { deletedEntities = await RunTopBatchDeleteAsync(); } await RunBatchDeleteAsync(); await UpdateSettingAsync(SettingsEnum.Sett1, "Val1UPDATE"); await UpdateByteArrayToDefaultAsync(); using var context = new TestContext(ContextUtil.GetOptions()); var firstItem = (await context.Items.ToListAsync()).First(); var lastItem = (await context.Items.ToListAsync()).Last(); Assert.Equal(1, deletedEntities); Assert.Equal(500, lastItem.ItemId); Assert.Equal("Updated", lastItem.Description); Assert.Null(lastItem.Price); Assert.StartsWith("name ", lastItem.Name); Assert.EndsWith(" Concatenated", lastItem.Name); if (dbServer == DbServer.SqlServer) { Assert.EndsWith(" TOP(1)", firstItem.Name); } } [Fact] public async Task BatchUpdateAsync_correctly_specifies_AnsiString_type_on_the_sql_parameter() { var dbCommandInterceptor = new TestDbCommandInterceptor(); var interceptors = new[] { dbCommandInterceptor }; using var testContext = new TestContext(ContextUtil.GetOptions<TestContext>(DbServer.SqlServer, interceptors)); string oldPhoneNumber = "7756789999"; string newPhoneNumber = "3606789999"; _ = await testContext.Parents .Where(parent => parent.PhoneNumber == oldPhoneNumber) .BatchUpdateAsync(parent => new Parent { PhoneNumber = newPhoneNumber }) .ConfigureAwait(false); var executedCommand = dbCommandInterceptor.ExecutedNonQueryCommands.Last(); Assert.Equal(2, executedCommand.DbParameters.Count); var oldPhoneNumberParameter = (Microsoft.Data.SqlClient.SqlParameter)executedCommand.DbParameters.Single(param => param.ParameterName == "@__oldPhoneNumber_0"); Assert.Equal(System.Data.DbType.AnsiString, oldPhoneNumberParameter.DbType); Assert.Equal(System.Data.SqlDbType.VarChar, oldPhoneNumberParameter.SqlDbType); var newPhoneNumberParameter = (Microsoft.Data.SqlClient.SqlParameter)executedCommand.DbParameters.Single(param => param.ParameterName == "@param_1"); Assert.Equal(System.Data.DbType.AnsiString, newPhoneNumberParameter.DbType); Assert.Equal(System.Data.SqlDbType.VarChar, newPhoneNumberParameter.SqlDbType); var expectedSql = @"UPDATE p SET [p].[PhoneNumber] = @param_1 FROM [Parent] AS [p] WHERE [p].[PhoneNumber] = @__oldPhoneNumber_0"; Assert.Equal(expectedSql.Replace("\r\n", "\n"), executedCommand.Sql.Replace("\r\n", "\n")); } internal async Task RunDeleteAllAsync(DbServer dbServer) { using var context = new TestContext(ContextUtil.GetOptions()); await context.Items.AddAsync(new Item { }); // used for initial add so that after RESEED it starts from 1, not 0 await context.SaveChangesAsync(); await context.Items.BatchDeleteAsync(); await context.BulkDeleteAsync(context.Items.ToList()); // RESET AutoIncrement string deleteTableSql = dbServer switch { DbServer.SqlServer => $"DBCC CHECKIDENT('[dbo].[{nameof(Item)}]', RESEED, 0);", DbServer.Sqlite => $"DELETE FROM sqlite_sequence WHERE name = '{nameof(Item)}';", _ => throw new ArgumentException($"Unknown database type: '{dbServer}'.", nameof(dbServer)), }; context.Database.ExecuteSqlRaw(deleteTableSql); } private async Task RunInsertAsync() { using (var context = new TestContext(ContextUtil.GetOptions())) { var entities = new List<Item>(); for (int i = 1; i <= EntitiesNumber; i++) { var entity = new Item { Name = "name " + i, Description = "info " + Guid.NewGuid().ToString().Substring(0, 3), Quantity = i % 10, Price = i / (i % 5 + 1), TimeUpdated = DateTime.Now, ItemHistories = new List<ItemHistory>() }; entities.Add(entity); } await context.Items.AddRangeAsync(entities); await context.SaveChangesAsync(); } } private async Task RunBatchUpdateAsync(DbServer dbServer) { using var context = new TestContext(ContextUtil.GetOptions()); //var updateColumns = new List<string> { nameof(Item.Quantity) }; // Adding explicitly PropertyName for update to its default value decimal price = 0; var query = context.Items.AsQueryable(); if (dbServer == DbServer.SqlServer) { query = query.Where(a => a.ItemId <= 500 && a.Price >= price); } if (dbServer == DbServer.Sqlite) { query = query.Where(a => a.ItemId <= 500); // Sqlite currently does Not support multiple conditions } await query.BatchUpdateAsync(new Item { Description = "Updated" }/*, updateColumns*/); await query.BatchUpdateAsync(a => new Item { Name = a.Name + " Concatenated", Quantity = a.Quantity + 100, Price = null }); // example of BatchUpdate value Increment/Decrement if (dbServer == DbServer.SqlServer) // Sqlite currently does Not support Take(): LIMIT { query = context.Items.Where(a => a.ItemId <= 500 && a.Price == null); await query.Take(1).BatchUpdateAsync(a => new Item { Name = a.Name + " TOP(1)", Quantity = a.Quantity + 100 }); // example of BatchUpdate with TOP(1) } var list = new List<string>() { "Updated" }; var updatedCount = await context.Set<Item>() .TagWith("From: someCallSite in someClassName") // To test parsing Sql with Tag leading comment .Where(a => list.Contains(a.Description)) .BatchUpdateAsync(a => new Item() { TimeUpdated = DateTime.Now }) .ConfigureAwait(false); if (dbServer == DbServer.SqlServer) // Sqlite Not supported { var newValue = 5; await context.Parents.Where(parent => parent.ParentId == 1) .BatchUpdateAsync(parent => new Parent { Description = parent.Children.Where(child => child.IsEnabled && child.Value == newValue).Sum(child => child.Value).ToString(), Value = newValue }) .ConfigureAwait(false); } } private async Task<int> RunTopBatchDeleteAsync() { using var context = new TestContext(ContextUtil.GetOptions()); return await context.Items.Where(a => a.ItemId > 500).Take(1).BatchDeleteAsync(); } private async Task RunBatchDeleteAsync() { using var context = new TestContext(ContextUtil.GetOptions()); await context.Items.Where(a => a.ItemId > 500).BatchDeleteAsync(); } private async Task UpdateSettingAsync(SettingsEnum settings, object value) { using var context = new TestContext(ContextUtil.GetOptions()); await context.TruncateAsync<Setting>(); await context.Settings.AddAsync(new Setting() { Settings = SettingsEnum.Sett1, Value = "Val1" }).ConfigureAwait(false); await context.SaveChangesAsync().ConfigureAwait(false); // can work with explicit value: .Where(x => x.Settings == SettingsEnum.Sett1) or if named Parameter used then it has to be named (settings) same as Property (Settings) - Case not relevant, it is CaseInsensitive await context.Settings.Where(x => x.Settings == settings).BatchUpdateAsync(x => new Setting { Value = value.ToString() }).ConfigureAwait(false); await context.TruncateAsync<Setting>(); } private async Task UpdateByteArrayToDefaultAsync() { using var context = new TestContext(ContextUtil.GetOptions()); await context.Files.BatchUpdateAsync(new File { DataBytes = null }, updateColumns: new List<string> { nameof(File.DataBytes) }).ConfigureAwait(false); await context.Files.BatchUpdateAsync(a => new File { DataBytes = null }).ConfigureAwait(false); } } }
44.316514
223
0.590726
[ "MIT" ]
AKonyshev/EFCore.BulkExtensions
EFCore.BulkExtensions.Tests/EFCoreBatchTestAsync.cs
9,663
C#
/* * NiFi Rest Api * * The Rest Api provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, definitions of the expected input and output, potential response codes, and the authorizations required to invoke each service. * * OpenAPI spec version: 1.9.1 * Contact: dev@nifi.apache.org * Generated by: https://github.com/swagger-api/swagger-codegen.git */ namespace NiFi.Swagger.Core.Model { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; /// <summary> /// StatusSnapshotDTO /// </summary> [DataContract] public partial class StatusSnapshotDTO : IEquatable<StatusSnapshotDTO>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="StatusSnapshotDTO" /> class. /// </summary> /// <param name="timestamp">The timestamp of the snapshot..</param> /// <param name="statusMetrics">The status metrics..</param> public StatusSnapshotDTO(DateTime? timestamp = default(DateTime?), Dictionary<string, long?> statusMetrics = default(Dictionary<string, long?>)) { this.Timestamp = timestamp; this.StatusMetrics = statusMetrics; } /// <summary> /// The timestamp of the snapshot. /// </summary> /// <value>The timestamp of the snapshot.</value> [DataMember(Name="timestamp", EmitDefaultValue=false)] public DateTime? Timestamp { get; set; } /// <summary> /// The status metrics. /// </summary> /// <value>The status metrics.</value> [DataMember(Name="statusMetrics", EmitDefaultValue=false)] public Dictionary<string, long?> StatusMetrics { 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 StatusSnapshotDTO {\n"); sb.Append(" Timestamp: ").Append(this.Timestamp).Append("\n"); sb.Append(" StatusMetrics: ").Append(this.StatusMetrics).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 StatusSnapshotDTO); } /// <summary> /// Returns true if StatusSnapshotDTO instances are equal /// </summary> /// <param name="input">Instance of StatusSnapshotDTO to be compared</param> /// <returns>Boolean</returns> public bool Equals(StatusSnapshotDTO input) { if (input == null) return false; return ( this.Timestamp == input.Timestamp || (this.Timestamp != null && this.Timestamp.Equals(input.Timestamp)) ) && ( this.StatusMetrics == input.StatusMetrics || this.StatusMetrics != null && this.StatusMetrics.SequenceEqual(input.StatusMetrics) ); } /// <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.Timestamp != null) hashCode = hashCode * 59 + this.Timestamp.GetHashCode(); if (this.StatusMetrics != null) hashCode = hashCode * 59 + this.StatusMetrics.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; } } }
37.326087
478
0.561833
[ "Apache-2.0" ]
mendonca-andre/NiFi.Swagger.Core
NiFi.Swagger.Core/Model/StatusSnapshotDTO.cs
5,151
C#
using System; using System.Linq; using System.Text; using System.Web.UI; using Microsoft.SharePoint.Client; namespace UXModificationWeb { public partial class Default : Page { protected void Page_PreInit(object sender, EventArgs e) { Uri redirectUrl; switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl)) { case RedirectionStatus.Ok: return; case RedirectionStatus.ShouldRedirect: Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true); break; case RedirectionStatus.CanNotRedirect: Response.Write("An error occurred while processing your request."); Response.End(); break; } } protected void Page_Load(object sender, EventArgs e) { // define initial script, needed to render the chrome control string script = @" function chromeLoaded() { $('body').show(); } //function callback to render chrome after SP.UI.Controls.js loads function renderSPChrome() { //Set the chrome options for launching Help, Account, and Contact pages var options = { 'appTitle': document.title, 'onCssLoaded': 'chromeLoaded()' }; //Load the Chrome Control in the divSPChrome element of the page var chromeNavigation = new SP.UI.Controls.Navigation('divSPChrome', options); chromeNavigation.setVisible(true); }"; //register script in page Page.ClientScript.RegisterClientScriptBlock(typeof(Default), "BasePageScript", script, true); } protected void btnSubmit_Click(object sender, EventArgs e) { } protected void btnRemove_Click(object sender, EventArgs e) { } } }
34.45
105
0.564103
[ "MIT" ]
OfficeDev/TrainingContent-Archive
O3658/04 Building UX components with add-in model/Demos/ModifyUserExperience/ModifyUserExperienceWeb/Pages/Default.aspx.cs
2,069
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace OpenVIII { //public abstract class IGMDataItem, IIGMDataItem<T> : IGMDataItem, IIGMDataItem, IIGMDataItem<T> //{ // #region Fields // private T _data; // #endregion Fields // #region Constructors // public IGMDataItem(T data, Rectangle? pos = null, Vector2? scale = null) : base(pos, scale) => // Data = data; // #endregion Constructors // #region Properties // public virtual T Data { get => _data; set => _data = value; } // #endregion Properties //} public abstract class IGMDataItem : Menu_Base { #region Fields protected static Texture2D blank; protected Rectangle _pos; private bool _blink = false; #endregion Fields #region Constructors public IGMDataItem(Rectangle? pos = null, Vector2? scale = null) { Pos = pos ?? Rectangle.Empty; Scale = scale ?? TextScale; if (blank == null) { blank = new Texture2D(Memory.graphics.GraphicsDevice, 1, 1); blank.SetData(new Color[] { Color.White }); } } #endregion Constructors #region Properties public virtual bool Blink { get => _blink; set => _blink = value; } public float Blink_Adjustment { get; set; } public Color Color { get; set; } = Color.White; public int Height { get => _pos.Height; set => _pos.Height = value; } /// <summary> /// Where to draw this item. /// </summary> public virtual Rectangle Pos { get => _pos; set => _pos = value; } public Vector2 Scale { get; set; } public int Width { get => _pos.Width; set => _pos.Width = value; } public int X { get => _pos.X; set => _pos.X = value; } public int Y { get => _pos.Y; set => _pos.Y = value; } public static float Blink_Amount => Menu.Blink_Amount; public static float Fade => Menu.Fade; public static Vector2 TextScale => Menu.TextScale; #endregion Properties #region Methods public static void DrawPointer(Point cursor, Vector2? offset = null, bool blink = false) => Menu.DrawPointer(cursor, offset, blink); public static implicit operator Color(IGMDataItem v) => v.Color; public static implicit operator IGMDataItem(IGMData v) => new IGMDataItem_IGMData(v); public static implicit operator Rectangle(IGMDataItem v) => v.Pos; //public virtual object Data { get; public set; } //public virtual FF8String Data { get; public set; } public override void Draw() { } public override bool Inputs() => false; public override void Refresh() { } public override bool Update() => false; protected override void Init() { } #endregion Methods } }
28.634615
140
0.589657
[ "MIT" ]
RomanMayer7/OpenVIII
Core/Menu/IGMDataItem/IGMDataItem.cs
2,980
C#
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; namespace Amazon.OpsWorks.Model { /// <summary> /// <para>Contains the response to a <c>CreateInstance</c> request.</para> /// </summary> public partial class CreateInstanceResult : AmazonWebServiceResponse { private string instanceId; /// <summary> /// The instance ID. /// /// </summary> public string InstanceId { get { return this.instanceId; } set { this.instanceId = value; } } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this.instanceId != null; } } }
27.98
79
0.644746
[ "Apache-2.0" ]
virajs/aws-sdk-net
AWSSDK_DotNet35/Amazon.OpsWorks/Model/CreateInstanceResult.cs
1,399
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.DataBoxEdge.V20200901Preview.Outputs { [OutputType] public sealed class ClientAccessRightResponse { /// <summary> /// Type of access to be allowed for the client. /// </summary> public readonly string AccessPermission; /// <summary> /// IP of the client. /// </summary> public readonly string Client; [OutputConstructor] private ClientAccessRightResponse( string accessPermission, string client) { AccessPermission = accessPermission; Client = client; } } }
26.388889
81
0.634737
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/DataBoxEdge/V20200901Preview/Outputs/ClientAccessRightResponse.cs
950
C#
 using System.Runtime.InteropServices; namespace FFXIVClientStructs.FFXIV.Client.Graphics.Kernel { // Client::Graphics::Kernel::Device // Client::Graphics::Singleton [StructLayout(LayoutKind.Explicit, Size = 0x210)] public unsafe struct Device { [FieldOffset(0x8)] public void* ContextArray; // Client::Graphics::Kernel::Context array [FieldOffset(0x10)] public void* ImmediateContext; // Client::Graphics::Kernel::Device::ImmediateContext [FieldOffset(0x18)] public void* RenderThread; // Client::Graphics::Kernel::RenderThread [FieldOffset(0x80)] public SwapChain* SwapChain; [FieldOffset(0x94)] public int D3DFeatureLevel; // D3D_FEATURE_LEVEL enum [FieldOffset(0x98)] public void* DXGIFactory; // IDXGIFactory1 [FieldOffset(0xA8)] public void* D3D11Device; // ID3D11Device1 [FieldOffset(0xB0)] public void* D3D11DeviceContext; // ID3D11DeviceContext1 } }
43.272727
112
0.711134
[ "MIT" ]
LeonBlade/FFXIVClientStructs
FFXIV/Client/Graphics/Kernel/Device.cs
954
C#
namespace BGuidinger.Xrm.Sdk.Management { using Newtonsoft.Json; using System.Collections.Generic; public class InstanceReset { [JsonProperty("ApplicationNames")] public string[] ApplicationNames { get; set; } [JsonProperty("BaseLanguageCode")] public int BaseLanguageCode { get; set; } [JsonProperty("Currency")] public Currency Currency { get; set; } [JsonProperty("DomainName")] public string DomainName { get; set; } [JsonProperty("FriendlyName")] public string FriendlyName { get; set; } [JsonProperty("Purpose")] public string Purpose { get; set; } [JsonProperty("PreferredCulture")] public int PreferredCulture { get; set; } [JsonProperty("TargetRelease")] public string TargetRelease { get; set; } [JsonProperty("SecurityGroupId")] public string SecurityGroupId { get; set; } [JsonProperty("AdditionalProperties")] public IDictionary<string, string> AdditionalProperties { get; set; } } }
37.172414
77
0.636364
[ "MIT" ]
bguidinger/Xrm.Sdk.Management
src/Management/Models/InstanceReset.cs
1,080
C#
namespace Serenity.Data { /// <summary> /// Interface for rows that have DeleteUserId and DeleteDate fields. /// </summary> public interface IDeleteLogRow { /// <summary> /// Gets the delete user identifier field. /// </summary> /// <value> /// The delete user identifier field. /// </value> Field DeleteUserIdField { get; } /// <summary> /// Gets the delete date field. /// </summary> /// <value> /// The delete date field. /// </value> DateTimeField DeleteDateField { get; } } }
27.782609
73
0.503912
[ "MIT" ]
ArsenioInojosa/Serenity
src/Serenity.Net.Entity/Contracts/IDeleteLogRow.cs
641
C#
// Copyright 2017 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Microsoft.EntityFrameworkCore; namespace Steeltoe.CloudFoundry.Connector.EFCore.Test { internal class GoodDbContext : DbContext { public GoodDbContext(DbContextOptions<GoodDbContext> options) : base(options) { } } }
32.518519
75
0.726651
[ "Apache-2.0" ]
FrancisChung/steeltoe
src/Connectors/test/Connector.EFCore.Test/GoodDbContext.cs
880
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Elasticsearch.Net; using Elasticsearch.Net.Utf8Json; using Elasticsearch.Net.Utf8Json.Internal; namespace Nest { /// <summary> /// A Watcher action /// </summary> [InterfaceDataContract] public interface IAction { /// <summary> /// The type of action /// </summary> [IgnoreDataMember] ActionType ActionType { get; } /// <summary> /// The name of the action /// </summary> [IgnoreDataMember] string Name { get; set; } /// <summary> /// Limit how often an action is executed, after it has been executed. /// When a throttling period is set, repeated executions of the action are prevented if it has already /// executed within the throttling period time frame (now - throttling period). /// </summary> [IgnoreDataMember] Time ThrottlePeriod { get; set; } /// <summary> /// Trigger the configured action for every element within an array /// defined by the path assigned. /// <para /> /// Valid only in Elasticsearch 7.3.0+ /// </summary> [IgnoreDataMember] string Foreach { get; set; } [IgnoreDataMember] /// <summary>The maximum number of iterations that each watch executes. If this limit is reached, /// the execution is gracefully stopped. Defaults to <c>100</c>. /// </summary> int? MaxIterations { get; set; } /// <summary> /// Transforms the payload before executing the action. The transformation is only applied /// for the payload for this action. /// </summary> [IgnoreDataMember] TransformContainer Transform { get; set; } /// <summary> /// A condition for the action. Allows a single watch to specify multiple actions, but /// further control when each action will be executed. /// </summary> [IgnoreDataMember] ConditionContainer Condition { get; set; } } /// <inheritdoc /> public abstract class ActionBase : IAction { internal ActionBase() { } protected ActionBase(string name) => Name = name; public abstract ActionType ActionType { get; } /// <inheritdoc /> public string Name { get; set; } /// <inheritdoc /> public Time ThrottlePeriod { get; set; } /// <inheritdoc /> public string Foreach { get; set; } /// <inheritdoc /> public int? MaxIterations { get; set; } /// <inheritdoc /> public TransformContainer Transform { get; set; } /// <inheritdoc /> public ConditionContainer Condition { get; set; } public static bool operator false(ActionBase a) => false; public static bool operator true(ActionBase a) => false; public static ActionBase operator &(ActionBase left, ActionBase right) => new ActionCombinator(left, right); } internal class ActionCombinator : ActionBase, IAction { public ActionCombinator(ActionBase left, ActionBase right) : base(null) { AddAction(left); AddAction(right); } public override ActionType ActionType => (ActionType)10; internal List<ActionBase> Actions { get; } = new List<ActionBase>(); private void AddAction(ActionBase agg) { if (agg == null) return; var combinator = agg as ActionCombinator; if ((combinator?.Actions.HasAny()).GetValueOrDefault(false)) Actions.AddRange(combinator.Actions); else Actions.Add(agg); } } internal class ActionsInterfaceFormatter : IJsonFormatter<IActions> { private static readonly ActionsFormatter ActionsFormatter = new ActionsFormatter(); public void Serialize(ref JsonWriter writer, IActions value, IJsonFormatterResolver formatterResolver) { writer.WriteBeginObject(); if (value != null) { var count = 0; foreach (var kvp in value.Where(kv => kv.Value != null)) { if (count > 0) writer.WriteValueSeparator(); var action = kvp.Value; writer.WritePropertyName(kvp.Key); writer.WriteBeginObject(); if (action.ThrottlePeriod != null) { writer.WritePropertyName("throttle_period"); var timeFormatter = formatterResolver.GetFormatter<Time>(); timeFormatter.Serialize(ref writer, action.ThrottlePeriod, formatterResolver); writer.WriteValueSeparator(); } if (!string.IsNullOrEmpty(action.Foreach)) { writer.WritePropertyName("foreach"); writer.WriteString(action.Foreach); writer.WriteValueSeparator(); } if (action.MaxIterations.HasValue) { writer.WritePropertyName("max_iterations"); writer.WriteInt32(action.MaxIterations.Value); writer.WriteValueSeparator(); } if (action.Transform != null) { writer.WritePropertyName("transform"); formatterResolver.GetFormatter<TransformContainer>().Serialize(ref writer, action.Transform, formatterResolver); writer.WriteValueSeparator(); } if (action.Condition != null) { writer.WritePropertyName("condition"); formatterResolver.GetFormatter<ConditionContainer>().Serialize(ref writer, action.Condition, formatterResolver); writer.WriteValueSeparator(); } writer.WritePropertyName(kvp.Value.ActionType.GetStringValue()); switch (action.ActionType) { case ActionType.Email: Serialize<IEmailAction>(ref writer, action, formatterResolver); break; case ActionType.Webhook: Serialize<IWebhookAction>(ref writer, action, formatterResolver); break; case ActionType.Index: Serialize<IIndexAction>(ref writer, action, formatterResolver); break; case ActionType.Logging: Serialize<ILoggingAction>(ref writer, action, formatterResolver); break; case ActionType.Slack: Serialize<ISlackAction>(ref writer, action, formatterResolver); break; case ActionType.PagerDuty: Serialize<IPagerDutyAction>(ref writer, action, formatterResolver); break; default: var actionFormatter = formatterResolver.GetFormatter<IAction>(); actionFormatter.Serialize(ref writer, action, formatterResolver); break; } writer.WriteEndObject(); count++; } } writer.WriteEndObject(); } private static void Serialize<TAction>(ref JsonWriter writer, IAction value, IJsonFormatterResolver formatterResolver) where TAction : class, IAction { var formatter = formatterResolver.GetFormatter<TAction>(); formatter.Serialize(ref writer, value as TAction, formatterResolver); } public IActions Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver) => ActionsFormatter.Deserialize(ref reader, formatterResolver); } internal class ActionsFormatter : IJsonFormatter<Actions> { private static readonly ActionsInterfaceFormatter ActionsInterfaceFormatter = new ActionsInterfaceFormatter(); private static readonly AutomataDictionary Fields = new AutomataDictionary { { "throttle_period", 0 }, { "throttle_period_in_millis", 0 }, { "email", 1 }, { "webhook", 2 }, { "index", 3 }, { "logging", 4 }, { "slack", 5 }, { "pagerduty", 6 }, { "foreach", 7 }, { "transform", 8 }, { "condition", 9 }, { "max_iterations", 10 }, }; public Actions Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver) { var dictionary = new Dictionary<string, IAction>(); var count = 0; while (reader.ReadIsInObject(ref count)) { var name = reader.ReadPropertyName(); var actionCount = 0; Time throttlePeriod = null; IAction action = null; string @foreach = null; int? maxIterations = null; TransformContainer transform = null; ConditionContainer condition = null; while (reader.ReadIsInObject(ref actionCount)) { var propertyName = reader.ReadPropertyNameSegmentRaw(); if (Fields.TryGetValue(propertyName, out var value)) { switch (value) { case 0: throttlePeriod = formatterResolver.GetFormatter<Time>() .Deserialize(ref reader, formatterResolver); break; case 1: action = formatterResolver.GetFormatter<EmailAction>() .Deserialize(ref reader, formatterResolver); break; case 2: action = formatterResolver.GetFormatter<WebhookAction>() .Deserialize(ref reader, formatterResolver); break; case 3: action = formatterResolver.GetFormatter<IndexAction>() .Deserialize(ref reader, formatterResolver); break; case 4: action = formatterResolver.GetFormatter<LoggingAction>() .Deserialize(ref reader, formatterResolver); break; case 5: action = formatterResolver.GetFormatter<SlackAction>() .Deserialize(ref reader, formatterResolver); break; case 6: action = formatterResolver.GetFormatter<PagerDutyAction>() .Deserialize(ref reader, formatterResolver); break; case 7: @foreach = reader.ReadString(); break; case 8: transform = formatterResolver.GetFormatter<TransformContainer>() .Deserialize(ref reader, formatterResolver); break; case 9: condition = formatterResolver.GetFormatter<ConditionContainer>() .Deserialize(ref reader, formatterResolver); break; case 10: maxIterations = reader.ReadInt32(); break; } } else reader.ReadNextBlock(); } if (action != null) { action.Name = name; action.ThrottlePeriod = throttlePeriod; action.Foreach = @foreach; action.MaxIterations = maxIterations; action.Transform = transform; action.Condition = condition; dictionary.Add(name, action); } } return new Actions(dictionary); } public void Serialize(ref JsonWriter writer, Actions value, IJsonFormatterResolver formatterResolver) => ActionsInterfaceFormatter.Serialize(ref writer, value, formatterResolver); } }
30.02381
120
0.680115
[ "Apache-2.0" ]
Atharvpatel21/elasticsearch-net
src/Nest/XPack/Watcher/Action/ActionBase.cs
10,088
C#
using LiveToLift.Web.Infrastructure.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LiveToLift.Services { public interface ITrainingService { List<TrainingViewModel> GetAllTrainings(int skip = 0, int take = 10); TrainingViewModel TrainingById(int id); int CreateNewTraining(TrainingViewModel model); } }
24.277778
77
0.732265
[ "MIT" ]
ivansto01/LiveToFit
LiveToLift.Services/ITrainingService.cs
439
C#
using FluentValidation; namespace Application.VaccineCredential.Queries.GetVaccineCredential { public class GetVaccineCredentialQueryValidator : AbstractValidator<GetVaccineCredentialQuery> { public GetVaccineCredentialQueryValidator() { RuleFor(c => c.Id) .NotEmpty() .MinimumLength(1) .MaximumLength(300); RuleFor(c => c.Pin) .NotEmpty() .MinimumLength(4) .MaximumLength(4); RuleFor(c => c.WalletCode) .Length(1) .When(c => c.WalletCode != null && c.WalletCode != ""); } } }
28.333333
98
0.538235
[ "CC0-1.0" ]
DOH-HTS-ADS/DigitalCovid19VaccineRecord-API
Application/VaccineCredential/Queries/GetVaccineCredential/GetVaccineCredentialQueryValidator.cs
682
C#
// // System.Runtime.InteropServices.CustomMarshalers.EnumerableToDispatchMarshaler // // Authors: // Martin Willemoes Hansen (mwh@sysrq.dk) // // (C) 2003 Martin Willemoes Hansen // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace System.Runtime.InteropServices.CustomMarshalers { public class EnumerableToDispatchMarshaler : ICustomMarshaler { [MonoTODO] public void CleanUpManagedData (object pManagedObj) { throw new NotImplementedException(); } [MonoTODO] public void CleanUpNativeData (IntPtr pNativeData) { throw new NotImplementedException(); } [MonoTODO] public static ICustomMarshaler GetInstance (string pstrCookie) { throw new NotImplementedException(); } [MonoTODO] public int GetNativeDataSize() { throw new NotImplementedException(); } [MonoTODO] public IntPtr MarshalManagedToNative (object pManagedObj) { throw new NotImplementedException(); } [MonoTODO] public object MarshalNativeToManaged (IntPtr pNativeData) { throw new NotImplementedException(); } } }
29.263889
80
0.748932
[ "Apache-2.0" ]
121468615/mono
mcs/class/CustomMarshalers/System.Runtime.InteropServices.CustomMarshalers/EnumerableToDispatchMarshaler.cs
2,107
C#
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SlotMassSumCalc { public partial class App : Application { public App() { InitializeComponent(); MainPage = new MainPage(); } protected override void OnStart() { } protected override void OnSleep() { } protected override void OnResume() { } } }
13.206897
40
0.618799
[ "MIT" ]
YanaPIIDXer/SlotMassSumCalc
SlotMassSumCalc/App.xaml.cs
385
C#
namespace Acklann.Plaid.Identity { /// <summary> /// Represents a response from plaid's '/identity/get' endpoint. The Identity endpoint allows you to retrieve various account holder information on file with the financial institution, including names, emails, phone numbers, and addresses. /// </summary> /// <remarks>Note: This request may take some time to complete if identity was not specified as an initial product when creating the <see cref="Entity.Item" />. This is because Plaid must communicate directly with the institution to retrieve the data.</remarks> /// <seealso cref="Acklann.Plaid.ResponseBase" /> public class GetUserIdentityResponse : ResponseBase { /// <summary> /// Gets or sets the item. /// </summary> /// <value>The item.</value> public Entity.Item Item { get; set; } /// <summary> /// Gets or sets the accounts. /// </summary> /// <value>The accounts.</value> public Entity.Account[] Accounts { get; set; } /// <summary> /// Gets or sets the user information. /// </summary> /// <value>The identity.</value> public Entity.Identity Identity { get; set; } } }
44.214286
265
0.632472
[ "MIT" ]
GeorgeHahn/Plaid.NET
src/Plaid/Identity/GetUserIdentityResponse.cs
1,240
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApp.Models { public class UserModel { public int Id { get; set; } public string Name { get; set; } } }
17.357143
40
0.658436
[ "MIT" ]
yarieldis/DotNetSimpleWeb
WebApp/Models/UserModel.cs
245
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using TwoWayMapper.Configuration; using TwoWayMapper.Conversion; using TwoWayMapper.Engine; namespace TwoWayMapper { public class Mapper<TLeft, TRight> : IMapper<TLeft, TRight> where TLeft : class where TRight : class { private readonly List<MapperMember> expressions = new List<MapperMember>(); private MappingEngine<TLeft, TRight> leftToRight; private MappingEngine<TRight, TLeft> rightToLeft; public ConverterCollection DefaultConverters => ConverterCollection.Default; public MapperMemberConfiguration<TLeft, TLeftValue, TRight, TRightValue> Map<TLeftValue, TRightValue>( Expression<Func<TLeft, TLeftValue>> leftExpr, Expression<Func<TRight, TRightValue>> rightExpr) { if (leftExpr == null) throw new ArgumentNullException(nameof(leftExpr)); if (rightExpr == null) throw new ArgumentNullException(nameof(rightExpr)); var member = AddMappingExpression(leftExpr, rightExpr); return new MapperMemberConfiguration<TLeft, TLeftValue, TRight, TRightValue>(this, member); } public MapperMemberConfiguration<TLeft, TLeftValue, TRight, TRightValue> Map<TLeftValue, TRightValue>( Expression<Func<TLeft, int, TLeftValue>> leftExpr, Expression<Func<TRight, int, TRightValue>> rightExpr) { if (leftExpr == null) throw new ArgumentNullException(nameof(leftExpr)); if (rightExpr == null) throw new ArgumentNullException(nameof(rightExpr)); var member = AddMappingExpression(leftExpr, rightExpr); return new MapperMemberConfiguration<TLeft, TLeftValue, TRight, TRightValue>(this, member); } public MapperMemberConfiguration<TLeft, TLeftValue, TRight, TRightValue> Map<TLeftValue, TRightValue>( Expression<Func<TLeft, int, int, TLeftValue>> leftExpr, Expression<Func<TRight, int, int, TRightValue>> rightExpr) { if (leftExpr == null) throw new ArgumentNullException(nameof(leftExpr)); if (rightExpr == null) throw new ArgumentNullException(nameof(rightExpr)); var member = AddMappingExpression(leftExpr, rightExpr); return new MapperMemberConfiguration<TLeft, TLeftValue, TRight, TRightValue>(this, member); } public void LeftToRight(TLeft source, TRight destination) { if (source == null) throw new ArgumentNullException(nameof(source)); if (destination == null) throw new ArgumentNullException(nameof(destination)); var engine = GetLeftToRightMappingEngine(); engine.Map(source, destination); } public void RightToLeft(TRight source, TLeft destination) { if (source == null) throw new ArgumentNullException(nameof(source)); if (destination == null) throw new ArgumentNullException(nameof(destination)); var engine = GetRightToLeftMappingEngine(); engine.Map(source, destination); } public string[] LeftPathToRightPath(IEnumerable<string> pathes) { if (pathes == null) throw new ArgumentNullException(nameof(pathes)); var engine = GetLeftToRightMappingEngine(); var result = engine.MapPathes(pathes).ToArray(); return result; } public string[] RightPathToLeftPath(IEnumerable<string> pathes) { if (pathes == null) throw new ArgumentNullException(nameof(pathes)); var engine = GetRightToLeftMappingEngine(); return engine.MapPathes(pathes).ToArray(); } public List<TRight> LeftToRightCollection(IEnumerable<TLeft> source) { if (source == null) throw new ArgumentNullException(nameof(source)); var engine = GetLeftToRightMappingEngine(); return engine.MapCollection(source); } public List<TLeft> RightToLeftCollection(IEnumerable<TRight> source) { if (source == null) throw new ArgumentNullException(nameof(source)); var engine = GetRightToLeftMappingEngine(); return engine.MapCollection(source); } private MapperMember AddMappingExpression(Expression left, Expression right) { if (left == null) throw new ArgumentNullException(nameof(left)); if (right == null) throw new ArgumentNullException(nameof(right)); var mapperMember = new MapperMember { Left = left, Right = right }; expressions.Add(mapperMember); return mapperMember; } private MappingEngine<TLeft, TRight> GetLeftToRightMappingEngine() { return leftToRight ?? (leftToRight = new MappingEngine<TLeft, TRight>( expressions.Select( a => new MappingEngineMemberMappingInfo { Source = a.Left, Dest = a.Right, Converter = a.LeftToRightConverter }))); } private MappingEngine<TRight, TLeft> GetRightToLeftMappingEngine() { return rightToLeft ?? (rightToLeft = new MappingEngine<TRight, TLeft>( expressions.Select( a => new MappingEngineMemberMappingInfo { Source = a.Right, Dest = a.Left, Converter = a.RightToLeftConverter }))); } } }
37.557576
110
0.575601
[ "MIT" ]
rd-dev-ukraine/two-way-mapper
TwoWayMapper/Mapper.cs
6,199
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace CorporateEvents.SharePointWeb { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
27.857143
99
0.610256
[ "Apache-2.0" ]
AKrasheninnikov/PnP
Solutions/BusinessApps.CorporateEventsApp/CorporateEvents.SharePointWeb/App_Start/RouteConfig.cs
587
C#
using System; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; using Robust.Shared.Players; using Robust.Shared.Serialization; using Robust.Shared.ViewVariables; namespace Content.Shared.Cooldown { /// <summary> /// Stores a visual "cooldown" for items, that gets displayed in the hands GUI. /// </summary> [RegisterComponent] [NetworkedComponent()] public sealed class ItemCooldownComponent : Component { private TimeSpan? _cooldownEnd; private TimeSpan? _cooldownStart; /// <summary> /// The time when this cooldown ends. /// </summary> /// <remarks> /// If null, no cooldown is displayed. /// </remarks> [ViewVariables] public TimeSpan? CooldownEnd { get => _cooldownEnd; set { _cooldownEnd = value; Dirty(); } } /// <summary> /// The time when this cooldown started. /// </summary> /// <remarks> /// If null, no cooldown is displayed. /// </remarks> [ViewVariables] public TimeSpan? CooldownStart { get => _cooldownStart; set { _cooldownStart = value; Dirty(); } } public override ComponentState GetComponentState() { return new ItemCooldownComponentState { CooldownEnd = CooldownEnd, CooldownStart = CooldownStart }; } public override void HandleComponentState(ComponentState? curState, ComponentState? nextState) { base.HandleComponentState(curState, nextState); if (curState is not ItemCooldownComponentState cast) return; CooldownStart = cast.CooldownStart; CooldownEnd = cast.CooldownEnd; } [Serializable, NetSerializable] private sealed class ItemCooldownComponentState : ComponentState { public TimeSpan? CooldownStart { get; set; } public TimeSpan? CooldownEnd { get; set; } public ItemCooldownComponentState() { } } } }
27.129412
102
0.546401
[ "MIT" ]
Alainx277/space-station-14
Content.Shared/Cooldown/ItemCooldownComponent.cs
2,306
C#
 using System.Collections.Generic; using UdonSharpEditor; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using VRC.Udon; namespace Cyan.PlayerObjectPool { [CustomEditor(typeof(CyanPlayerObjectPool))] public class CyanPlayerObjectPoolEditor : Editor { private readonly GUIContent _settingsFoldoutGuiContent = new GUIContent("Pool Settings", ""); private readonly GUIContent _poolAssignersFoldoutGuiContent = new GUIContent("Pool Types", ""); // Minimum world capacity is 1. private const int MinPoolObjects = 1; // Maximum world capacity is ~82, but allowing more since it doesn't break the system. private const int MaxPoolObjects = 100; private Texture2D _typesBackgroundTexture; private CyanPlayerObjectPool _instance; private UdonBehaviour _udon; private int _poolSize; private bool _multiplePools; private SerializedProperty _sizeProp; private SerializedProperty _debugProp; private bool _showSettings = true; private bool _showPoolAssigners = true; private void Awake() { _instance = (CyanPlayerObjectPool) target; _udon = UdonSharpEditorUtility.GetBackingUdonBehaviour(_instance); _poolSize = _instance.poolSize; _sizeProp = serializedObject.FindProperty(nameof(CyanPlayerObjectPool.poolSize)); _debugProp = serializedObject.FindProperty(nameof(CyanPlayerObjectPool.printDebugLogs)); _typesBackgroundTexture = CyanPlayerObjectPoolEditorHelpers.CreateTexture(3, 3, (x, y) => x == 1 && y == 1 ? CyanPlayerObjectPoolEditorHelpers.BackgroundColor : CyanPlayerObjectPoolEditorHelpers.LineColorDark); _multiplePools = false; if (ShouldCheckScene()) { // Go through all objects to find if there are multiple Object Pool scripts. int count = 0; foreach (var obj in _instance.gameObject.scene.GetRootGameObjects()) { CyanPlayerObjectPool[] pools = obj.GetUdonSharpComponentsInChildren<CyanPlayerObjectPool>(true); count += pools.Length; } _multiplePools = count > 1; // Go through each setup helper and verify their pool size. foreach (var helper in FindObjectsOfType<CyanPoolSetupHelper>()) { helper.VerifyPoolSize(); } } } private bool ShouldCheckScene() { return _udon != null && _udon.gameObject.scene.isLoaded && !EditorSceneManager.IsPreviewSceneObject(_udon); } public override void OnInspectorGUI() { if (UdonSharpGUI.DrawDefaultUdonSharpBehaviourHeader(target)) return; if (!UdonSharpEditorUtility.IsProxyBehaviour(_instance)) return; CyanPlayerObjectPoolEditorHelpers.RenderHeader("Cyan Player Object Pool"); if (_multiplePools) { GUILayout.Space(5); EditorGUILayout.HelpBox("Multiple Object Pools exist in the scene! Please only have one Object Pool!", MessageType.Error); // TODO list all object pools return; } serializedObject.UpdateIfRequiredOrScript(); RenderSettings(); serializedObject.ApplyModifiedProperties(); // Prevent modifying the scene if this is part of a prefab editor. if (!ShouldCheckScene()) { return; } List<CyanPoolSetupHelper> helpers = new List<CyanPoolSetupHelper>(FindObjectsOfType<CyanPoolSetupHelper>()); // Sort based on name helpers.Sort((h1, h2) => h1.name.CompareTo(h2.name)); UpdateHelpers(helpers); RenderObjectAssigners(helpers); } private void RenderSettings() { GUILayout.Space(5); EditorGUILayout.BeginVertical(EditorStyles.helpBox); _showSettings = CyanPlayerObjectPoolEditorHelpers.RenderFoldout(_showSettings, _settingsFoldoutGuiContent); if (_showSettings) { CyanPlayerObjectPoolEditorHelpers.AddIndent(); EditorGUILayout.PropertyField(_sizeProp); EditorGUILayout.PropertyField(_debugProp); // Hard-cap the min and max size of the object pool. int value = _sizeProp.intValue; if (value < MinPoolObjects || value > MaxPoolObjects) { _sizeProp.intValue = Mathf.Clamp(value, MinPoolObjects, MaxPoolObjects); } // Only display button to respawn objects if the scene can be edited. if (ShouldCheckScene() && GUILayout.Button("Respawn All Pool Objects")) { foreach (var helper in FindObjectsOfType<CyanPoolSetupHelper>()) { helper.RespawnAllPoolObjects(); } } CyanPlayerObjectPoolEditorHelpers.RemoveIndent(); } EditorGUILayout.EndVertical(); } private void UpdateHelpers(List<CyanPoolSetupHelper> helpers) { // If the size has changed, notify all helpers to update the spawned number of pool objects. int newSize = _sizeProp.intValue; if (_poolSize != newSize) { _poolSize = newSize; foreach (var helper in helpers) { helper.UpdatePoolSize(_poolSize); } } } private void RenderObjectAssigners(List<CyanPoolSetupHelper> helpers) { GUILayout.Space(5); EditorGUILayout.BeginVertical(EditorStyles.helpBox); _showPoolAssigners = CyanPlayerObjectPoolEditorHelpers.RenderFoldout(_showPoolAssigners, _poolAssignersFoldoutGuiContent); if (_showPoolAssigners) { GUIContent errorIcon = EditorGUIUtility.TrIconContent("console.erroricon", "This pool type does not have the correct number of objects!"); GUIContent warningIcon = EditorGUIUtility.TrIconContent("console.warnicon", "This pool type does not have any objects."); GUILayout.Space(5); var boxStyle = new GUIStyle { border = new RectOffset(1, 1, 1, 1), normal = { background = _typesBackgroundTexture } }; Rect rect = EditorGUILayout.BeginVertical(boxStyle); float width = rect.width; float height = rect.height - 1; float xStart = rect.x; float sectionHeight = 24; float buttonHeight = 18; float labelHeight = EditorGUIUtility.singleLineHeight; float between = 9; float betweenHalf = Mathf.Floor(between / 2f); float indexLabelWidth = 20; float pingWidth = 40; float iconWidth = 25; // Create vertical bars separating the sections GUI.Box(new Rect(rect.x + indexLabelWidth + between, rect.y + 1, 1, height), GUIContent.none, boxStyle); GUI.Box(new Rect(rect.x + indexLabelWidth + pingWidth + between * 2, rect.y + 1, 1, height), GUIContent.none, boxStyle); if (helpers.Count == 0) { GUILayout.Space(sectionHeight); } for (int cur = 0; cur < helpers.Count; ++cur) { var helper = helpers[cur]; rect = EditorGUILayout.BeginHorizontal(GUILayout.Height(sectionHeight)); if (cur + 1 < helpers.Count) { // Create horizontal bar separating the sections GUI.Box(new Rect(rect.x, rect.yMax, width, 1), GUIContent.none, boxStyle); } float textY = rect.y + Mathf.Ceil((rect.height - labelHeight) / 2f); float buttonY = rect.y + Mathf.Ceil((rect.height - buttonHeight) / 2f); float indexLabelStartX = xStart + betweenHalf; float pingStart = indexLabelStartX + indexLabelWidth + between; float objectLabelStartX = pingStart + pingWidth + between; float objectLabelWidth = width - objectLabelStartX - betweenHalf; Rect indexRect = new Rect(indexLabelStartX, textY, indexLabelWidth, labelHeight); Rect pingRect = new Rect(pingStart, buttonY, pingWidth, buttonHeight); Rect objectLabelRect = new Rect(objectLabelStartX, textY, objectLabelWidth, labelHeight); GUI.Label(indexRect, (1 + cur).ToString().PadLeft(2)); if (GUI.Button(pingRect, "Ping")) { EditorGUIUtility.PingObject(helper); } GUIContent objectContent = new GUIContent(helper.name, VRC.Tools.GetGameObjectPath(helper.gameObject)); GUI.Label(objectLabelRect, objectContent); int objCount = helper.GetObjectCount(); if (objCount != _poolSize) { GUIContent content = null; if (objCount == 0) { // Display warning saying no objects content = warningIcon; } else { // Display error saying object count does not match content = errorIcon; } Rect iconRect = new Rect(objectLabelRect.xMax, buttonY, iconWidth, buttonHeight); GUI.Label(iconRect, content); } GUILayout.Space(1); EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndVertical(); GUILayout.Space(5); } EditorGUILayout.EndVertical(); } } }
39.859712
154
0.532804
[ "MIT" ]
CyanLaser/CyanPlayerObjectPool
Cyan/PlayerObjectPool/Scripts/Editor/CyanPlayerObjectPoolEditor.cs
11,083
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.AccessAnalyzer")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.104.14")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
60.237288
315
0.783624
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/AccessAnalyzer/Properties/AssemblyInfo.cs
3,554
C#
/* * Quotes API For Digital Portals * * The quotes API combines endpoints for retrieving security end-of-day, delayed, and realtime prices with performance key figures and basic reference data on the security and market level. The API supports over 20 different price types for each quote and comes with basic search endpoints based on security identifiers and instrument names. Market coverage is included in the *Sample Use Cases* section below. The Digital Portal use case is focused on high-performance applications that are * serving millions of end-users, * accessible by client browsers via the internet, * supporting subscriptions for streamed updates out-of-the-box, * typically combining a wide variety of *for Digital Portals*-APIs into a highly use-case specific solution for customers, * integrated into complex infrastructures such as existing frontend frameworks, authentication services. All APIs labelled *for Digital Portals* have been designed for direct use by client web applications and feature extreme low latency: The average response time across all endpoints is 30 ms whereas 99% of all requests are answered in close to under 300ms. See the Time Series API for Digital Portals for direct access to price histories, and the News API for Digital Portals for searching and fetching related news. * * The version of the OpenAPI document: 2 * 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 = FactSet.SDK.QuotesAPIforDigitalPortals.Client.OpenAPIDateConverter; namespace FactSet.SDK.QuotesAPIforDigitalPortals.Model { /// <summary> /// Annualized ex post ongoing cost of the investment product. This cost includes the ex post management and distribution fees over the period. A research fee could also be included here if applicable and not already included in the ex post transaction cost. /// </summary> [DataContract(Name = "inline_response_200_62_data_costsAndCharges_exPost_ongoingCosts")] public partial class InlineResponse20062DataCostsAndChargesExPostOngoingCosts : IEquatable<InlineResponse20062DataCostsAndChargesExPostOngoingCosts>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="InlineResponse20062DataCostsAndChargesExPostOngoingCosts" /> class. /// </summary> /// <param name="value">Value of the attribute..</param> /// <param name="valueUnit">valueUnit.</param> public InlineResponse20062DataCostsAndChargesExPostOngoingCosts(decimal value = default(decimal), InlineResponse20062DataCostsAndChargesExAnteOneOffEntryCostValueUnit valueUnit = default(InlineResponse20062DataCostsAndChargesExAnteOneOffEntryCostValueUnit)) { this.Value = value; this.ValueUnit = valueUnit; } /// <summary> /// Value of the attribute. /// </summary> /// <value>Value of the attribute.</value> [DataMember(Name = "value", EmitDefaultValue = false)] public decimal Value { get; set; } /// <summary> /// Gets or Sets ValueUnit /// </summary> [DataMember(Name = "valueUnit", EmitDefaultValue = false)] public InlineResponse20062DataCostsAndChargesExAnteOneOffEntryCostValueUnit ValueUnit { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class InlineResponse20062DataCostsAndChargesExPostOngoingCosts {\n"); sb.Append(" Value: ").Append(Value).Append("\n"); sb.Append(" ValueUnit: ").Append(ValueUnit).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 InlineResponse20062DataCostsAndChargesExPostOngoingCosts); } /// <summary> /// Returns true if InlineResponse20062DataCostsAndChargesExPostOngoingCosts instances are equal /// </summary> /// <param name="input">Instance of InlineResponse20062DataCostsAndChargesExPostOngoingCosts to be compared</param> /// <returns>Boolean</returns> public bool Equals(InlineResponse20062DataCostsAndChargesExPostOngoingCosts input) { if (input == null) { return false; } return ( this.Value == input.Value || this.Value.Equals(input.Value) ) && ( this.ValueUnit == input.ValueUnit || (this.ValueUnit != null && this.ValueUnit.Equals(input.ValueUnit)) ); } /// <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.Value.GetHashCode(); if (this.ValueUnit != null) { hashCode = (hashCode * 59) + this.ValueUnit.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
47.291667
1,287
0.660059
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/QuotesAPIforDigitalPortals/v3/src/FactSet.SDK.QuotesAPIforDigitalPortals/Model/InlineResponse20062DataCostsAndChargesExPostOngoingCosts.cs
6,810
C#
using Microsoft.Xna.Framework; using Pathoschild.Stardew.TractorMod.Framework.Config; using StardewValley; using StardewValley.TerrainFeatures; using StardewValley.Tools; using SFarmer = StardewValley.Farmer; using SObject = StardewValley.Object; namespace Pathoschild.Stardew.TractorMod.Framework.Attachments { /// <summary>An attachment for melee weapons.</summary> internal class MeleeWeaponAttachment : BaseAttachment { /********* ** Properties *********/ /// <summary>The attachment settings.</summary> private readonly MeleeWeaponConfig Config; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="config">The attachment settings.</param> public MeleeWeaponAttachment(MeleeWeaponConfig config) { this.Config = config; } /// <summary>Get whether the tool is currently enabled.</summary> /// <param name="player">The current player.</param> /// <param name="tool">The tool selected by the player (if any).</param> /// <param name="item">The item selected by the player (if any).</param> /// <param name="location">The current location.</param> public override bool IsEnabled(SFarmer player, Tool tool, Item item, GameLocation location) { return tool is MeleeWeapon; } /// <summary>Apply the tool to the given tile.</summary> /// <param name="tile">The tile to modify.</param> /// <param name="tileObj">The object on the tile.</param> /// <param name="tileFeature">The feature on the tile.</param> /// <param name="player">The current player.</param> /// <param name="tool">The tool selected by the player (if any).</param> /// <param name="item">The item selected by the player (if any).</param> /// <param name="location">The current location.</param> public override bool Apply(Vector2 tile, SObject tileObj, TerrainFeature tileFeature, SFarmer player, Tool tool, Item item, GameLocation location) { // clear dead crops if (this.Config.ClearDeadCrops && tileFeature is HoeDirt dirt && dirt.crop != null && dirt.crop.dead.Value) return this.UseToolOnTile(tool, tile); // attack monsters if (this.Config.AttackMonsters) { MeleeWeapon weapon = (MeleeWeapon)tool; return this.UseWeaponOnTile(weapon, tile, player, location); } return false; } /********* ** Private methods *********/ /// <summary>Use a weapon on the given tile.</summary> /// <param name="weapon">The weapon to use.</param> /// <param name="tile">The tile to attack.</param> /// <param name="player">The current player.</param> /// <param name="location">The current location.</param> /// <remarks>This is a simplified version of <see cref="MeleeWeapon.DoDamage"/>. This doesn't account for player bonuses (since it's hugely overpowered anyway), doesn't cause particle effects, doesn't trigger animation timers, etc.</remarks> private bool UseWeaponOnTile(MeleeWeapon weapon, Vector2 tile, SFarmer player, GameLocation location) { bool attacked = location.damageMonster( areaOfEffect: this.GetAbsoluteTileArea(tile), minDamage: weapon.minDamage.Value, maxDamage: weapon.maxDamage.Value, isBomb: false, knockBackModifier: weapon.knockback.Value, addedPrecision: weapon.addedPrecision.Value, critChance: weapon.critChance.Value, critMultiplier: weapon.critMultiplier.Value, triggerMonsterInvincibleTimer: weapon.type.Value != MeleeWeapon.dagger, who: player ); if (attacked) location.playSound(weapon.type.Value == MeleeWeapon.club ? "clubhit" : "daggerswipe"); return attacked; } } }
43.778947
249
0.610002
[ "MIT" ]
Sotheros/StardewMods
TractorMod/Framework/Attachments/MeleeWeaponAttachment.cs
4,159
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Immutable; using System.Globalization; using Microsoft.Recognizers.Definitions.Hindi; namespace Microsoft.Recognizers.Text.NumberWithUnit.Hindi { public class AreaExtractorConfiguration : HindiNumberWithUnitExtractorConfiguration { public static readonly ImmutableDictionary<string, string> AreaSuffixList = NumbersWithUnitDefinitions.AreaSuffixList.ToImmutableDictionary(); public AreaExtractorConfiguration() : this(new CultureInfo(Culture.Hindi)) { } public AreaExtractorConfiguration(CultureInfo ci) : base(ci) { } public override ImmutableDictionary<string, string> SuffixList => AreaSuffixList; public override ImmutableDictionary<string, string> PrefixList => null; public override ImmutableList<string> AmbiguousUnitList => null; public override string ExtractType => Constants.SYS_UNIT_AREA; } }
31.676471
89
0.717734
[ "MIT" ]
17000cyh/Recognizers-Text
.NET/Microsoft.Recognizers.Text.NumberWithUnit/Hindi/Extractors/AreaExtractorConfiguration.cs
1,079
C#
// ---------------------------------------------------------------------------------------------------- // Copyright © Guo jin ming. All rights reserved. // Homepage: https://kylin.app/ // E-Mail: kevin@kylin.app // ---------------------------------------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace Kit { /// <summary> /// UGUI 事件监听 /// </summary> public class UGUIEventListener : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerEnterHandler, IPointerExitHandler, IPointerUpHandler { public delegate void VoidDelegate(GameObject go); public string mAudioType = string.Empty; public object[] Args = null; public VoidDelegate onClick = null; public VoidDelegate onDown = null; public VoidDelegate onEnter = null; public VoidDelegate onExit = null; public VoidDelegate onUp = null; public VoidDelegate onLongPress = null; private bool isUp = true; // 与长按配合使用 private float time = 0; #region ... Unity API private void Update() { // 长按 if (!isUp && onLongPress != null && Time.realtimeSinceStartup - time > 1) { onLongPress(gameObject); isUp = true; } } #endregion #region ... PointerHandler public void OnPointerClick(PointerEventData eventData) { if (onClick != null) { if (!string.IsNullOrEmpty(mAudioType) && GetComponent<Button>() != null && GetComponent<Button>().interactable) { // TODO : 播放声音 mAudioType } if (GetComponent<Button>() == null || GetComponent<Button>().interactable) onClick(gameObject); } } public void OnPointerDown(PointerEventData eventData) { if (onDown != null) onDown(gameObject); if (isUp) time = Time.realtimeSinceStartup; isUp = false; } public void OnPointerEnter(PointerEventData eventData) { if (onEnter != null) onEnter(gameObject); } public void OnPointerExit(PointerEventData eventData) { if (onExit != null) onExit(gameObject); } public void OnPointerUp(PointerEventData eventData) { if (onUp != null) onUp(gameObject); isUp = true; time = 0; } #endregion public static UGUIEventListener Get(GameObject go, string clickAudio = "BtnClick", params object[] args) { UGUIEventListener listener = go.GetComponent<UGUIEventListener>(); if (listener == null) listener = go.AddComponent<UGUIEventListener>(); listener.mAudioType = clickAudio; listener.Args = args; return listener; } public static void AddClicks(GameObject[] gos, VoidDelegate onClick, string clickAudio = "BtnClick") { if (gos != null && gos.Length > 0) { for (int i = 0; i < gos.Length; i++) { if (gos[i]) Get(gos[i], clickAudio).onClick = onClick; } } } } }
36.597938
127
0.511831
[ "MIT" ]
BigManager/KIT
UnityProject/Assets/Plugins/Kit/Common/UnityExtend/UI/EventSystem/UGUIEventListener.cs
3,587
C#
class C { private class A { } class B : A { } }
6.625
18
0.490566
[ "Apache-2.0" ]
monoman/cnatural-language
tests/resources/ObjectModelErrorTest/sources/NestedLessAccessibleBaseClass.stab.cs
53
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("SumDigits")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("SumDigits")] [assembly: System.Reflection.AssemblyTitleAttribute("SumDigits")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.791667
80
0.646578
[ "MIT" ]
wuweisage/Softuni-Svetlina-Projects-and-Code
C#/DataTypesAndVariables/SumDigits/SumDigits/obj/Release/netcoreapp3.1/SumDigits.AssemblyInfo.cs
979
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grasshopper { public class GrandMother : Character { public GrandMother(string name, string imageUrl, Point location, int defense) : base(name, imageUrl, location, defense) { } } }
19
86
0.634211
[ "MIT" ]
VProfirov/Telerik-Academy
Team Projects - old/Grasshopper/Grasshopper/Grasshopper/GrandMother.cs
382
C#
using System.Collections.Generic; using System.Linq; namespace OpenVIII.Fields.Scripts { public static class FieldScriptFormatter { #region Methods public static IEnumerable<FormattedObject> FormatAllObjects(Field.ILookupService lookupService) { return lookupService.EnumerateAll().SelectMany(FormatFieldObjects); } public static IEnumerable<FormattedObject> FormatFieldObjects(Field.Info field) { if (!field.TryReadData(Field.Part.Jsm, out var jsmData)) yield break; var gameObjects = Jsm.File.Read(jsmData); if (gameObjects.Count == 0) yield break; IScriptFormatterContext formatterContext = GetFormatterContext(field); var executionContext = StatelessServices.Instance; var sw = new ScriptWriter(); foreach (var obj in gameObjects) { formatterContext.GetObjectScriptNamesById(obj.Id, out var objectName, out _); var formattedScript = FormatObject(obj, sw, formatterContext, executionContext); yield return new FormattedObject(field, objectName, formattedScript); } } private static string FormatObject(Jsm.GameObject gameObject, ScriptWriter sw, IScriptFormatterContext formatterContext, IServices executionContext) { gameObject.FormatType(sw, formatterContext, executionContext); return sw.Release(); } private static ScriptFormatterContext GetFormatterContext(Field.Info field) { var context = new ScriptFormatterContext(); if (field.TryReadData(Field.Part.Sym, out var symData)) context.SetSymbols(Sym.Reader.FromBytes(symData)); if (field.TryReadData(Field.Part.Msd, out var msdData)) context.SetMessages(Msd.Reader.FromBytes(msdData)); return context; } #endregion Methods } }
35.526316
156
0.642469
[ "MIT" ]
FlameHorizon/OpenVIII-monogame
Core/Field/ScriptFormatter/FieldScriptFormatter.cs
2,027
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("Penguin.Airlines")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Penguin.Airlines")] [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("d003282a-1007-4723-8196-6b8b5bb5251c")] // 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.972973
84
0.745196
[ "MIT" ]
VVoev/Telerik-Academy
15.Data-Structures-and-Algorithms/some/Solution1/Penguin.Airlines/Properties/AssemblyInfo.cs
1,408
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 11.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Equal.Complete.NullableTimeSpan.NullableTimeSpan{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.TimeSpan>; using T_DATA2 =System.Nullable<System.TimeSpan>; using T_DATA1_U=System.TimeSpan; using T_DATA2_U=System.TimeSpan; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__04__NN public static class TestSet_504__param__04__NN { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=null; var recs=db.testTable.Where(r => vv1 /*OP{*/ == /*}OP*/ vv2); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=null; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ == /*}OP*/ vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 };//class TestSet_504__param__04__NN //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Equal.Complete.NullableTimeSpan.NullableTimeSpan
26.307143
146
0.53842
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/Equal/Complete/NullableTimeSpan/NullableTimeSpan/TestSet_504__param__04__NN.cs
3,685
C#
using System; using System.IO; using System.Reflection; namespace GitVersionExe.Tests.Helpers { public static class PathHelper { public static string GetCurrentDirectory() { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } public static string GetExecutable() { #if NETFRAMEWORK var executable = Path.Combine(GetExeDirectory(), "GitVersion.exe"); #else var executable = "dotnet"; #endif return executable; } public static string GetExecutableArgs(string args) { #if !NETFRAMEWORK args = $"{Path.Combine(GetExeDirectory(), "GitVersion.dll")} {args}"; #endif return args; } public static string GetTempPath() { return Path.Combine(GetCurrentDirectory(), "TestRepositories", Guid.NewGuid().ToString()); } private static string GetExeDirectory() { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)?.Replace("GitVersionExe.Tests", "GitVersionExe"); } } }
27.046512
133
0.602752
[ "MIT" ]
ShvetsovZE/GitVersion
src/GitVersionExe.Tests/Helpers/PathHelper.cs
1,121
C#
using System.Resources; using System.Reflection; using System.Runtime.InteropServices; #if !RAZZLE_BUILD // 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("vstest.diag")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("vstest.diag")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b56b3849-b498-4045-9e39-a35311543bb7")] // 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: CLSCompliant(false)] [assembly: NeutralResourcesLanguage("en-US")] #endif
36.219512
84
0.742761
[ "Apache-2.0" ]
codito/vstest.diag
vstest.diag/Properties/AssemblyInfo.cs
1,488
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // static field using System; using System.Threading; using System.Runtime.CompilerServices; namespace Precise { internal class Driver { public static void f() { RuntimeHelpers.RunClassConstructor(typeof(test).TypeHandle); } public static int Main() { try { Console.WriteLine("Testing .cctor() invocation by accessing static field across assembly"); Console.WriteLine(); Console.WriteLine("Before calling static field"); // .cctor should not run yet if (measure.a != 0xCC) { Console.WriteLine("in Main(), measure.a is {0}", measure.a); Console.WriteLine("FAILED"); return 1; } // spin up 5 threads Thread[] tasks = new Thread[5]; for (int i = 0; i < 5; i++) { ThreadStart threadStart = new ThreadStart(f); tasks[i] = new Thread(threadStart); tasks[i].Name = "Thread #" + i; } // Start tasks foreach (Thread _thread in tasks) _thread.Start(); // Wait for tasks to finish foreach (Thread _thread in tasks) _thread.Join(); // Should only have accessed .cctor only once Console.WriteLine("After calling static field"); if (measure.a != 212) { Console.WriteLine("in Main(), measure.a is {0}", measure.a); Console.WriteLine("FAILED"); return -1; } } catch (Exception e) { Console.WriteLine(e); Console.WriteLine(e.StackTrace); return -1; } Console.WriteLine(); Console.WriteLine("PASSED"); return 100; } } }
31.857143
107
0.46861
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/Methodical/cctor/misc/threads2.cs
2,230
C#
using System.Reflection; using UnityEditor; using UnityEngine.Assertions; namespace VRWorldToolkit { /// <summary> /// Utility for setting and getting internal model importer values /// </summary> public static class ModelImporterUtil { private static readonly System.Type systemType; private static PropertyInfo mProperty_LegacyBlendShapeNormals; static ModelImporterUtil() { systemType = Assembly.Load("UnityEditor.dll").GetType("UnityEditor.ModelImporter"); Assert.IsNotNull(systemType); } public static bool GetLegacyBlendShapeNormals(ModelImporter importer) { if (mProperty_LegacyBlendShapeNormals == null) mProperty_LegacyBlendShapeNormals = systemType.GetProperty("legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes", BindingFlags.NonPublic | BindingFlags.Instance); Assert.IsNotNull(mProperty_LegacyBlendShapeNormals); return (bool)mProperty_LegacyBlendShapeNormals.GetValue(importer); } public static void SetLegacyBlendShapeNormals(ModelImporter importer, bool value) { if (mProperty_LegacyBlendShapeNormals == null) mProperty_LegacyBlendShapeNormals = systemType.GetProperty("legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes", BindingFlags.NonPublic | BindingFlags.Instance); Assert.IsNotNull(mProperty_LegacyBlendShapeNormals); mProperty_LegacyBlendShapeNormals.SetValue(importer, value, null); } } }
40.74359
191
0.721208
[ "MIT" ]
Codel1417/VRWorldToolkit
Scripts/Editor/ModelImporterUtil.cs
1,591
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 mturk-requester-2017-01-17.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.MTurk.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MTurk.Model.Internal.MarshallTransformations { /// <summary> /// GetFileUploadURL Request Marshaller /// </summary> public class GetFileUploadURLRequestMarshaller : IMarshaller<IRequest, GetFileUploadURLRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetFileUploadURLRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetFileUploadURLRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.MTurk"); string target = "MTurkRequesterServiceV20170117.GetFileUploadURL"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-01-17"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetAssignmentId()) { context.Writer.WritePropertyName("AssignmentId"); context.Writer.Write(publicRequest.AssignmentId); } if(publicRequest.IsSetQuestionIdentifier()) { context.Writer.WritePropertyName("QuestionIdentifier"); context.Writer.Write(publicRequest.QuestionIdentifier); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static GetFileUploadURLRequestMarshaller _instance = new GetFileUploadURLRequestMarshaller(); internal static GetFileUploadURLRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetFileUploadURLRequestMarshaller Instance { get { return _instance; } } } }
35.882883
147
0.627919
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/MTurk/Generated/Model/Internal/MarshallTransformations/GetFileUploadURLRequestMarshaller.cs
3,983
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Windows.Forms { using System.Diagnostics; using System; using System.Threading; using System.Drawing; using Microsoft.Win32; using System.ComponentModel; using System.Drawing.Printing; /// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog"]/*' /> public class PrintControllerWithStatusDialog : PrintController { private PrintController underlyingController; private PrintDocument document; private BackgroundThread backgroundThread; private int pageNumber; private string dialogTitle; /// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.PrintControllerWithStatusDialog"]/*' /> public PrintControllerWithStatusDialog(PrintController underlyingController) : this(underlyingController, string.Format(SR.PrintControllerWithStatusDialog_DialogTitlePrint)) { } /// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.PrintControllerWithStatusDialog1"]/*' /> public PrintControllerWithStatusDialog(PrintController underlyingController, string dialogTitle) { this.underlyingController = underlyingController; this.dialogTitle = dialogTitle; } /// <include file='doc\PreviewPrintController.uex' path='docs/doc[@for="PreviewPrintController.IsPreview"]/*' /> /// <devdoc> /// <para> /// This is new public property which notifies if this controller is used for PrintPreview.. so get the underlying Controller /// and return its IsPreview Property. /// </para> /// </devdoc> public override bool IsPreview { get { if (underlyingController != null) { return underlyingController.IsPreview; } return false; } } /// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.OnStartPrint"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Implements StartPrint by delegating to the underlying controller. /// </para> /// </devdoc> public override void OnStartPrint(PrintDocument document, PrintEventArgs e) { base.OnStartPrint(document, e); this.document = document; pageNumber = 1; if (SystemInformation.UserInteractive) { backgroundThread = new BackgroundThread(this); // starts running & shows dialog automatically } // OnStartPrint does the security check... lots of // extra setup to make sure that we tear down // correctly... // try { underlyingController.OnStartPrint(document, e); } catch { if (backgroundThread != null) { backgroundThread.Stop(); } throw; } finally { if (backgroundThread != null && backgroundThread.canceled) { e.Cancel = true; } } } /// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.OnStartPage"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Implements StartPage by delegating to the underlying controller. /// </para> /// </devdoc> public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e) { base.OnStartPage(document, e); if (backgroundThread != null) { backgroundThread.UpdateLabel(); } Graphics result = underlyingController.OnStartPage(document, e); if (backgroundThread != null && backgroundThread.canceled){ e.Cancel = true; } return result; } /// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.OnEndPage"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Implements EndPage by delegating to the underlying controller. /// </para> /// </devdoc> public override void OnEndPage(PrintDocument document, PrintPageEventArgs e) { underlyingController.OnEndPage(document, e); if (backgroundThread != null && backgroundThread.canceled) { e.Cancel = true; } pageNumber++; base.OnEndPage(document, e); } /// <include file='doc\PrintControllerWithStatusDialog.uex' path='docs/doc[@for="PrintControllerWithStatusDialog.OnEndPrint"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Implements EndPrint by delegating to the underlying controller. /// </para> /// </devdoc> public override void OnEndPrint(PrintDocument document, PrintEventArgs e) { underlyingController.OnEndPrint(document, e); if (backgroundThread != null && backgroundThread.canceled) { e.Cancel = true; } if (backgroundThread != null) { backgroundThread.Stop(); } base.OnEndPrint(document, e); } private class BackgroundThread { private PrintControllerWithStatusDialog parent; private StatusDialog dialog; private Thread thread; internal bool canceled = false; private bool alreadyStopped = false; // Called from any thread internal BackgroundThread(PrintControllerWithStatusDialog parent) { this.parent = parent; // Calling Application.DoEvents() from within a paint event causes all sorts of problems, // so we need to put the dialog on its own thread. thread = new Thread(new ThreadStart(Run)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); } // on correct thread private void Run() { // try { lock (this) { if (alreadyStopped) { return; } dialog = new StatusDialog(this, parent.dialogTitle); ThreadUnsafeUpdateLabel(); dialog.Visible = true; } if (!alreadyStopped) { Application.Run(dialog); } } finally { lock (this) { if (dialog != null) { dialog.Dispose(); dialog = null; } } } } // Called from any thread internal void Stop() { lock (this) { if (dialog != null && dialog.IsHandleCreated) { dialog.BeginInvoke(new MethodInvoker(dialog.Close)); return; } alreadyStopped = true; } } // on correct thread private void ThreadUnsafeUpdateLabel() { // "page {0} of {1}" dialog.label1.Text = string.Format(SR.PrintControllerWithStatusDialog_NowPrinting, parent.pageNumber, parent.document.DocumentName); } // Called from any thread internal void UpdateLabel() { if (dialog != null && dialog.IsHandleCreated) { dialog.BeginInvoke(new MethodInvoker(ThreadUnsafeUpdateLabel)); // Don't wait for a response } } } private class StatusDialog : Form { internal Label label1; private Button button1; private TableLayoutPanel tableLayoutPanel1; private BackgroundThread backgroundThread; internal StatusDialog(BackgroundThread backgroundThread, string dialogTitle) { InitializeComponent(); this.backgroundThread = backgroundThread; this.Text = dialogTitle; this.MinimumSize = Size; } /// <devdoc> /// Tells whether the current resources for this dll have been /// localized for a RTL language. /// </devdoc> private static bool IsRTLResources { get { return SR.RTL != "RTL_False"; } } private void InitializeComponent() { if (IsRTLResources) { this.RightToLeft = RightToLeft.Yes; } this.tableLayoutPanel1 = new TableLayoutPanel(); this.label1 = new Label(); this.button1 = new Button(); label1.AutoSize = true; label1.Location = new Point(8, 16); label1.TextAlign = ContentAlignment.MiddleCenter; label1.Size = new Size(240, 64); label1.TabIndex = 1; label1.Anchor = AnchorStyles.None; button1.AutoSize = true; button1.Size = new Size(75, 23); button1.TabIndex = 0; button1.Text = string.Format(SR.PrintControllerWithStatusDialog_Cancel); button1.Location = new Point(88, 88); button1.Anchor = AnchorStyles.None; button1.Click += new EventHandler(button1_Click); tableLayoutPanel1.AutoSize = true; tableLayoutPanel1.ColumnCount = 1; tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(SizeType.Percent, 100F)); tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); tableLayoutPanel1.RowCount = 2; tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(SizeType.Percent, 50F)); tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(SizeType.Percent, 50F)); tableLayoutPanel1.TabIndex = 0; tableLayoutPanel1.Controls.Add(label1, 0, 0); tableLayoutPanel1.Controls.Add(button1, 0, 1); this.AutoScaleDimensions = new Size(6, 13); this.AutoScaleMode = AutoScaleMode.Font; this.MaximizeBox = false; this.ControlBox = false; this.MinimizeBox = false; Size clientSize = new Size(256, 122); if (DpiHelper.IsScalingRequired) { this.ClientSize = DpiHelper.LogicalToDeviceUnits(clientSize); } else { this.ClientSize = clientSize; } this.CancelButton = button1; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.Controls.Add(tableLayoutPanel1); } private void button1_Click(object sender, System.EventArgs e) { button1.Enabled = false; label1.Text = string.Format(SR.PrintControllerWithStatusDialog_Canceling); backgroundThread.canceled = true; } } } }
40.615894
161
0.540192
[ "MIT" ]
0xflotus/winforms
src/System.Windows.Forms/src/System/Windows/Forms/Printing/PrintControllerWithStatusDialog.cs
12,266
C#
namespace Xms.Security.Abstractions { public class RoleDefaults { public const string ModuleName = "Role"; public const string ADMINISTRATOR = "administrator"; } }
21.444444
60
0.668394
[ "MIT" ]
feilingdeng/xms
Libraries/Security/Xms.Security.Abstractions/RoleDefaults.cs
195
C#
using System.Collections.Generic; using System.Threading.Tasks; using SFA.DAS.Commitments.Api.Types; using SFA.DAS.Commitments.Api.Types.Apprenticeship; using SFA.DAS.Commitments.Api.Types.Commitment; using SFA.DAS.Commitments.Api.Types.DataLock; namespace SFA.DAS.Commitments.Api.Client.Interfaces { public interface IEmployerCommitmentApi { Task<List<CommitmentListItem>> GetEmployerCommitments(long employerAccountId); Task<CommitmentView> GetEmployerCommitment(long employerAccountId, long commitmentId); Task<CommitmentView> GetTransferSenderCommitment(long transferSenderAccountId, long commitmentId); Task<List<Apprenticeship>> GetEmployerApprenticeships(long employerAccountId); Task<IList<Apprenticeship>> GetActiveApprenticeshipsForUln(long employerAccountId, string uln); Task<ApprenticeshipSearchResponse> GetEmployerApprenticeships(long employerAccountId, ApprenticeshipSearchQuery apprenticeshipSearchQuery); Task<Apprenticeship> GetEmployerApprenticeship(long employerAccountId, long apprenticeshipId); Task<List<ApprenticeshipStatusSummary>> GetEmployerAccountSummary(long employerAccountId); Task PatchEmployerCommitment(long employerAccountId, long commitmentId, CommitmentSubmission submission); Task DeleteEmployerCommitment(long employerAccountId, long commitmentId, DeleteRequest deleteRequest); Task PatchEmployerApprenticeship(long employerAccountId, long apprenticeshipId, ApprenticeshipSubmission apprenticeshipSubmission); Task DeleteEmployerApprenticeship(long employerAccountId, long apprenticeshipId, DeleteRequest deleteRequest); Task CreateApprenticeshipUpdate(long employerAccountId, long apprenticeshipId, ApprenticeshipUpdateRequest apprenticeshipUpdateRequest); Task<ApprenticeshipUpdate> GetPendingApprenticeshipUpdate(long employerAccountId, long apprenticeshipId); Task PatchApprenticeshipUpdate(long employerAccountId, long apprenticeshipId, ApprenticeshipUpdateSubmission submission); Task<IEnumerable<PriceHistory>> GetPriceHistory(long employerAccountId, long apprenticeshipId); Task<List<DataLockStatus>> GetDataLocks(long employerAccountId, long apprenticeshipId); Task<DataLockSummary> GetDataLockSummary(long employerAccountId, long apprenticeshipId); Task PatchDataLocks(long employerAccountId, long apprenticeshipId, DataLocksTriageResolutionSubmission submission); Task PutApprenticeshipStopDate(long accountId, long commitmentId, long apprenticeshipId, ApprenticeshipStopDate stopDate); Task ApproveCohort(long employerAccountId, long commitmentId, CommitmentSubmission submission); Task PatchTransferApprovalStatus(long transferSenderId, long commitmentId, long transferRequestId, TransferApprovalRequest request); Task<List<TransferRequestSummary>> GetTransferRequests(string hashedAccountId); Task<TransferRequest> GetTransferRequestForSender(long transferSenderId, long transferRequestId); Task<TransferRequest> GetTransferRequestForReceiver(long transferSenderId, long transferRequestId); Task<IEnumerable<long>> GetAllEmployerAccountIds(); } }
82.589744
147
0.819621
[ "MIT" ]
SkillsFundingAgency/das-commitments
src/SFA.DAS.Commitments.Api.Client/Interfaces/IEmployerCommitmentApi.cs
3,221
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Abp.Authorization; using Abp.Authorization.Users; using Abp.Configuration; using Abp.Domain.Uow; using Cepres.Patients.Authorization.Roles; using Cepres.Patients.Authorization.Users; using Cepres.Patients.MultiTenancy; namespace Cepres.Patients.Identity { public class SignInManager : AbpSignInManager<Tenant, Role, User> { public SignInManager( UserManager userManager, IHttpContextAccessor contextAccessor, UserClaimsPrincipalFactory claimsFactory, IOptions<IdentityOptions> optionsAccessor, ILogger<SignInManager<User>> logger, IUnitOfWorkManager unitOfWorkManager, ISettingManager settingManager, IAuthenticationSchemeProvider schemes, IUserConfirmation<User> userConfirmation) : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, unitOfWorkManager, settingManager, schemes, userConfirmation) { } } }
35.69697
150
0.741087
[ "MIT" ]
Kasper888/Cepres.Patients
aspnet-core/src/Cepres.Patients.Core/Identity/SignInManager.cs
1,180
C#
using System; namespace Sce.Pss.Core.Input { public class TouchData { public bool Skip; public int ID; public TouchStatus Status; public float X; public float Y; } }
12.2
28
0.693989
[ "MIT" ]
weimingtom/Sakura
Sce.Pss.Core/Input/TouchData.cs
185
C#
namespace MovieInfoAPI.Models.DTO.Character { public class CharacterCreateDTO { public string Name { get; set; } public string Alias { get; set; } public string Gender { get; set; } public string URL { get; set; } } }
23.909091
44
0.60076
[ "MIT" ]
MiriTam/MovieCharacterAPI
MovieInfoAPI/Models/DTO/Character/CharacterCreateDTO.cs
265
C#
using System; using System.ComponentModel.Composition; using System.Waf.Applications; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using TumblThree.Applications.ViewModels.DetailsViewModels; using TumblThree.Applications.Views; namespace TumblThree.Presentation.Views { /// <summary> /// Interaction logic for QueueView.xaml. /// </summary> [Export("TwitterBlogView", typeof(IDetailsView))] public partial class DetailsTwitterBlogView : IDetailsView { private readonly Lazy<DetailsTwitterBlogViewModel> viewModel; public DetailsTwitterBlogView() { InitializeComponent(); viewModel = new Lazy<DetailsTwitterBlogViewModel>(() => ViewHelper.GetViewModel<DetailsTwitterBlogViewModel>(this)); } private DetailsTwitterBlogViewModel ViewModel { get { return viewModel.Value; } } public int TabsCount => this.Tabs.Items.Count; private void Preview_OnMouseDown(object sender, MouseButtonEventArgs e) { ViewModel.ViewFullScreenMedia(); } private void View_LostFocus(object sender, RoutedEventArgs e) { if (!((UserControl)sender).IsKeyboardFocusWithin) ViewModel?.ViewLostFocus(); } private void FilenameTemplate_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { e.Handled = !ViewModel.FilenameTemplateValidate(((TextBox)e.Source).Text); } } }
31.16
128
0.679076
[ "Apache-2.0", "MIT" ]
Thomas694/TumblThree
src/TumblThree/TumblThree.Presentation/Views/DetailsViews/DetailsTwitterBlogView.xaml.cs
1,560
C#
using System; using System.Collections.Generic; using Android.Runtime; using Java.Interop; namespace Xamarin.Test { // Metadata.xml XPath class reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']" [global::Android.Runtime.Register ("xamarin/test/SomeObject", DoNotGenerateAcw=true)] public partial class SomeObject : global::Java.Lang.Object { // Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='myStrings']" [Register ("myStrings")] public global::System.Collections.Generic.IList<string> MyStrings { get { const string __id = "myStrings.Ljava/util/List;"; var __v = _members.InstanceFields.GetObjectValue (__id, this); return global::Android.Runtime.JavaList<string>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef); } set { const string __id = "myStrings.Ljava/util/List;"; IntPtr native_value = global::Android.Runtime.JavaList<string>.ToLocalJniHandle (value); try { _members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value)); } finally { JNIEnv.DeleteLocalRef (native_value); } } } // Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='myInts']" [Register ("myInts")] public global::System.Collections.Generic.IList<int> MyInts { get { const string __id = "myInts.Ljava/util/List;"; var __v = _members.InstanceFields.GetObjectValue (__id, this); return global::Android.Runtime.JavaList<int>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef); } set { const string __id = "myInts.Ljava/util/List;"; IntPtr native_value = global::Android.Runtime.JavaList<int>.ToLocalJniHandle (value); try { _members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value)); } finally { JNIEnv.DeleteLocalRef (native_value); } } } // Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='mybools']" [Register ("mybools")] public global::System.Collections.Generic.IList<bool> Mybools { get { const string __id = "mybools.Ljava/util/List;"; var __v = _members.InstanceFields.GetObjectValue (__id, this); return global::Android.Runtime.JavaList<bool>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef); } set { const string __id = "mybools.Ljava/util/List;"; IntPtr native_value = global::Android.Runtime.JavaList<bool>.ToLocalJniHandle (value); try { _members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value)); } finally { JNIEnv.DeleteLocalRef (native_value); } } } // Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='myObjects']" [Register ("myObjects")] public global::System.Collections.Generic.IList<global::Java.Lang.Object> MyObjects { get { const string __id = "myObjects.Ljava/util/List;"; var __v = _members.InstanceFields.GetObjectValue (__id, this); return global::Android.Runtime.JavaList<global::Java.Lang.Object>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef); } set { const string __id = "myObjects.Ljava/util/List;"; IntPtr native_value = global::Android.Runtime.JavaList<global::Java.Lang.Object>.ToLocalJniHandle (value); try { _members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value)); } finally { JNIEnv.DeleteLocalRef (native_value); } } } // Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='myfloats']" [Register ("myfloats")] public global::System.Collections.Generic.IList<float> Myfloats { get { const string __id = "myfloats.Ljava/util/List;"; var __v = _members.InstanceFields.GetObjectValue (__id, this); return global::Android.Runtime.JavaList<float>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef); } set { const string __id = "myfloats.Ljava/util/List;"; IntPtr native_value = global::Android.Runtime.JavaList<float>.ToLocalJniHandle (value); try { _members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value)); } finally { JNIEnv.DeleteLocalRef (native_value); } } } // Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='mydoubles']" [Register ("mydoubles")] public global::System.Collections.Generic.IList<double> Mydoubles { get { const string __id = "mydoubles.Ljava/util/List;"; var __v = _members.InstanceFields.GetObjectValue (__id, this); return global::Android.Runtime.JavaList<double>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef); } set { const string __id = "mydoubles.Ljava/util/List;"; IntPtr native_value = global::Android.Runtime.JavaList<double>.ToLocalJniHandle (value); try { _members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value)); } finally { JNIEnv.DeleteLocalRef (native_value); } } } // Metadata.xml XPath field reference: path="/api/package[@name='xamarin.test']/class[@name='SomeObject']/field[@name='mylongs']" [Register ("mylongs")] public global::System.Collections.Generic.IList<long> Mylongs { get { const string __id = "mylongs.Ljava/util/List;"; var __v = _members.InstanceFields.GetObjectValue (__id, this); return global::Android.Runtime.JavaList<long>.FromJniHandle (__v.Handle, JniHandleOwnership.TransferLocalRef); } set { const string __id = "mylongs.Ljava/util/List;"; IntPtr native_value = global::Android.Runtime.JavaList<long>.ToLocalJniHandle (value); try { _members.InstanceFields.SetValue (__id, this, new JniObjectReference (native_value)); } finally { JNIEnv.DeleteLocalRef (native_value); } } } internal static new readonly JniPeerMembers _members = new JniPeerMembers ("xamarin/test/SomeObject", typeof (SomeObject)); internal static new IntPtr class_ref { get { return _members.JniPeerType.PeerReference.Handle; } } public override global::Java.Interop.JniPeerMembers JniPeerMembers { get { return _members; } } protected override IntPtr ThresholdClass { get { return _members.JniPeerType.PeerReference.Handle; } } protected override global::System.Type ThresholdType { get { return _members.ManagedPeerType; } } protected SomeObject (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} } }
35.820106
134
0.715214
[ "MIT" ]
mattleibow/java.interop
tools/generator/Tests/expected.ji/java.util.List/Xamarin.Test.SomeObject.cs
6,770
C#
using System; namespace master_piece.service.parser { /// <summary> /// Перечисление типов лексем /// </summary> public enum LexemeType { //Операции OpenBracket, CloseBracket, Assign, And, Or, Equal, NotEqual, More, MoreOrEqual, Less, LessOrEqual, //Разделитель Comma, //Значения IntValue, FuzzyValue, //Идентификатор Identifier, //Ошибочный тип лексемы Error } /// <summary> /// Вспомогательный класс по определению супертипа лексемы /// </summary> public static class LexemeTypes { /// <summary> /// true, если переданный тип является операцией, false - в противном случае /// </summary> /// <param name="lexemeType">Тип лексемы</param> public static bool IsOperation(LexemeType lexemeType) { switch (lexemeType) { case LexemeType.And: case LexemeType.Or: case LexemeType.Equal: case LexemeType.NotEqual: case LexemeType.More: case LexemeType.MoreOrEqual: case LexemeType.Less: case LexemeType.LessOrEqual: return true; default: return false; } } /// <summary> /// true, если переданный тип является целочисленным значением, false - в противном случае /// </summary> /// <param name="lexemeType">Тип лексемы</param> public static bool IsIntValue(LexemeType lexemeType) { return lexemeType == LexemeType.IntValue; } /// <summary> /// true, если переданный тип является нечетким значением, false - в противном случае /// </summary> /// <param name="lexemeType">Тип лексемы</param> public static bool IsFuzzyValue(LexemeType lexemeType) { return lexemeType == LexemeType.FuzzyValue; } /// <summary> /// true, если переданный тип является нечетким или целочисленным значением, false - в противном случае /// </summary> /// <param name="lexemeType">Тип лексемы</param> public static bool IsValue(LexemeType lexemeType) { switch (lexemeType) { case LexemeType.IntValue: case LexemeType.FuzzyValue: return true; default: return false; } } /// <summary> /// true, если переданный тип является идентификатором, false - в противном случае /// </summary> /// <param name="lexemeType">Тип лексемы</param> public static bool IsIdentifier(LexemeType lexemeType) { switch (lexemeType) { case LexemeType.Identifier: return true; default: return false; } } } }
28.409091
111
0.51744
[ "MIT" ]
betanets/master-piece
master-piece/master-piece/service/parser/LexemeType.cs
3,609
C#
using System; using Xunit; namespace RavenPlayground.Tests { public class UnitTest1 { [Fact] public void Test1() { } } }
11.133333
31
0.532934
[ "MIT" ]
MarkZither/RavenPlayground
RavenPlayground.Tests/UnitTest1.cs
167
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.AlertsManagement.V20190601.Outputs { [OutputType] public sealed class ActionGroupsInformationResponse { /// <summary> /// An optional custom email subject to use in email notifications. /// </summary> public readonly string? CustomEmailSubject; /// <summary> /// An optional custom web-hook payload to use in web-hook notifications. /// </summary> public readonly string? CustomWebhookPayload; /// <summary> /// The Action Group resource IDs. /// </summary> public readonly ImmutableArray<string> GroupIds; [OutputConstructor] private ActionGroupsInformationResponse( string? customEmailSubject, string? customWebhookPayload, ImmutableArray<string> groupIds) { CustomEmailSubject = customEmailSubject; CustomWebhookPayload = customWebhookPayload; GroupIds = groupIds; } } }
30.744186
81
0.652799
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/AlertsManagement/V20190601/Outputs/ActionGroupsInformationResponse.cs
1,322
C#
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\shared\ks.h(1466,1) using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct KSDATAFORMAT_TYPE_STREAM { } }
23.636364
84
0.703846
[ "MIT" ]
Steph55/DirectN
DirectN/DirectN/Generated/KSDATAFORMAT_TYPE_STREAM.cs
262
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; using XNodeEditor; #endif namespace InteractML.DataTypeNodes { [CustomNodeEditor(typeof(IntegerNode))] public class IntegerNodeEditor : IMLNodeEditor { /// <summary> /// Reference to the node itself /// </summary> private IntegerNode m_IntegerNode; public override void OnHeaderGUI() { // Get reference to the current node m_IntegerNode = (target as IntegerNode); NodeName = "LIVE INT DATA"; base.OnHeaderGUI(); } public override void OnBodyGUI() { InputPortsNamesOverride = new Dictionary<string, string>(); OutputPortsNamesOverride = new Dictionary<string, string>(); base.InputPortsNamesOverride.Add("m_In", "Int\nData In"); base.OutputPortsNamesOverride.Add("m_Out", "Int\nData Out"); base.nodeTips = m_IntegerNode.tooltips; m_BodyRect.height = 80; base.OnBodyGUI(); } protected override void ShowBodyFields() { DataInToggle(m_IntegerNode.ReceivingData, m_InnerBodyRect, m_BodyRect); } protected override void DrawPositionValueTogglesAndLabels(GUIStyle style) { GUILayout.BeginHorizontal(); GUILayout.Space(bodySpace); // If something is connected to the input port show incoming data if (m_IntegerNode.InputConnected) { m_IntegerNode.int_switch = EditorGUILayout.Toggle(m_IntegerNode.int_switch, style); EditorGUILayout.LabelField("Int: " + System.Math.Round(m_IntegerNode.FeatureValues.Values[0], 3).ToString(), m_NodeSkin.GetStyle("Node Body Label")); } // If there is nothing connected to the input port show editable fields else { m_IntegerNode.int_switch = EditorGUILayout.Toggle(m_IntegerNode.int_switch, style, GUILayout.MaxWidth(dataWidth)); EditorGUILayout.LabelField("Int: ", m_NodeSkin.GetStyle("Node Body Label"), GUILayout.MaxWidth(dataWidth)); m_IntegerNode.m_UserInput = EditorGUILayout.IntField(m_IntegerNode.m_UserInput, GUILayout.MaxWidth(inputWidth)); } GUILayout.EndHorizontal(); } } }
36.294118
165
0.623987
[ "MIT" ]
brightcxy/iml-unity
Assets/InteractML/Scripts/IML Nodes/Data Type Nodes/Editor/IntegerNodeEditor.cs
2,470
C#
using System; using System.Linq.Expressions; namespace FluentData { public interface IDeleteBuilder<T> : IExecute { BuilderData Data { get; } IDeleteBuilder<T> Where(Expression<Func<T, object>> expression, DataTypes parameterType = DataTypes.Object, int size = 0); IDeleteBuilder<T> Where(string columnName, object value, DataTypes parameterType = DataTypes.Object, int size = 0); } }
32.833333
124
0.761421
[ "MIT" ]
shuaiagain/orm-fluentdata
FluentData/sourceCode/sourceCode/Source/Main/FluentData/Builders/Delete/Interfaces/IDeleteBuilderGeneric.cs
394
C#
using System.Collections.Generic; namespace CodeFirstExercies { public class Genre { public Genre() { Videos = new HashSet<Video>(); } public int Id { get; set; } public string Name { get; set; } public ICollection<Video> Videos { get; set; } } }
18.941176
54
0.546584
[ "MIT" ]
tuvshinot/csharp
Entity/CodeFirstExercies/CodeFirstExercies/Genre.cs
324
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; using TTY.GMP.Entity.Common; using TTY.GMP.Entity.Enum; namespace TTY.GMP.Entity.Web.User.Response { /// <summary> /// 用户数据权限信息 /// </summary> public class UserDataLimitView { /// <summary> /// 构造函数 /// </summary> /// <param name="type"></param> /// <param name="areas"></param> /// <param name="shops"></param> public UserDataLimitView(int type, List<DataLimitAreaView> areas, List<DataLimitShopView> shops) { this.Type = type; this.Areas = areas; this.Shops = shops; } /// <summary> /// 类型 /// <see cref="DataLimitTypeEnum"/> /// </summary> public int Type { get; set; } /// <summary> /// 地区 /// </summary> public List<DataLimitAreaView> Areas { get; set; } /// <summary> /// 选择的地区 /// </summary> public List<long> MyAreas { get; set; } /// <summary> /// 门店 /// </summary> public List<DataLimitShopView> Shops { get; set; } } /// <summary> /// 地区 /// </summary> public class DataLimitAreaView { public long Id { get; set; } /// <summary> /// 类型 /// <see cref="Enum.AreaLevelEnum"/> /// </summary> public string Level { get; set; } /// <summary> /// 名称 /// </summary> public string Name { get; set; } /// <summary> /// 子地区 /// </summary> public List<DataLimitAreaView> Children { get; set; } } /// <summary> /// 门店 /// </summary> public class DataLimitShopView { /// <summary> /// 门店ID /// </summary> public long Id { get; set; } /// <summary> /// 名称 /// </summary> public string Name { get; set; } } }
22.2
104
0.476476
[ "MIT" ]
chenjian8541/gmp
src/TTY.GMP.Entity/Web/User/Response/UserDataLimitView.cs
2,076
C#
using System; using System.Collections.Generic; using System.Linq; using MonoMac.Foundation; using MonoMac.AppKit; namespace GlossyClock { public partial class MainWindow : MonoMac.AppKit.NSWindow { public MainWindow (IntPtr handle) : base(handle) { } [Export("initWithCoder:")] public MainWindow (NSCoder coder) : base(coder) { } public override void AwakeFromNib () { IsOpaque = false; BackgroundColor = NSColor.Clear; MovableByWindowBackground = true; Level = NSWindowLevel.PopUpMenu; StyleMask = NSWindowStyle.Borderless; IsVisible = true; } } }
18.090909
58
0.718593
[ "MIT" ]
Devolutions/monomac
samples/GlossyClock/MainWindow.cs
597
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Script.Extensions; using Microsoft.Azure.WebJobs.Script.WebHost.Configuration; using Microsoft.Azure.WebJobs.Script.WebHost.Middleware; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace Microsoft.Azure.WebJobs.Script.WebHost { public static class WebJobsApplicationBuilderExtension { public static IApplicationBuilder UseWebJobsScriptHost(this IApplicationBuilder builder, IApplicationLifetime applicationLifetime) { return UseWebJobsScriptHost(builder, applicationLifetime, null); } public static IApplicationBuilder UseWebJobsScriptHost(this IApplicationBuilder builder, IApplicationLifetime applicationLifetime, Action<WebJobsRouteBuilder> routes) { IEnvironment environment = builder.ApplicationServices.GetService<IEnvironment>() ?? SystemEnvironment.Instance; IOptionsMonitor<StandbyOptions> standbyOptions = builder.ApplicationServices.GetService<IOptionsMonitor<StandbyOptions>>(); IOptionsMonitor<HttpBodyControlOptions> httpBodyControlOptions = builder.ApplicationServices.GetService<IOptionsMonitor<HttpBodyControlOptions>>(); IOptionsMonitor<HttpOptions> httpOptions = builder.ApplicationServices.GetService<IOptionsMonitor<HttpOptions>>(); builder.UseMiddleware<SystemTraceMiddleware>(); builder.UseMiddleware<HostnameFixupMiddleware>(); if (environment.IsLinuxConsumption()) { builder.UseMiddleware<EnvironmentReadyCheckMiddleware>(); } if (standbyOptions.CurrentValue.InStandbyMode) { builder.UseMiddleware<PlaceholderSpecializationMiddleware>(); } // Specialization can change the CompatMode setting, so this must run later than // the PlaceholderSpecializationMiddleware builder.UseWhen(context => httpBodyControlOptions.CurrentValue.AllowSynchronousIO || context.Request.IsAdminDownloadRequest(), config => { config.UseMiddleware<AllowSynchronousIOMiddleware>(); }); // This middleware must be registered before we establish the request service provider. builder.UseWhen(context => !context.Request.IsAdminRequest(), config => { config.UseMiddleware<HostAvailabilityCheckMiddleware>(); }); builder.UseWhen(context => HostWarmupMiddleware.IsWarmUpRequest(context.Request, standbyOptions.CurrentValue.InStandbyMode, environment), config => { builder.UseMiddleware<HostWarmupMiddleware>(); }); // This middleware must be registered before any other middleware depending on // JobHost/ScriptHost scoped services. builder.UseMiddleware<ScriptHostRequestServiceProviderMiddleware>(); if (environment.IsLinuxConsumption()) { builder.UseMiddleware<AppServiceHeaderFixupMiddleware>(); } builder.UseMiddleware<ExceptionMiddleware>(); builder.UseWhen(HomepageMiddleware.IsHomepageRequest, config => { config.UseMiddleware<HomepageMiddleware>(); }); builder.UseWhen(context => HttpThrottleMiddleware.ShouldEnable(httpOptions.CurrentValue) && !context.Request.IsAdminRequest(), config => { config.UseMiddleware<HttpThrottleMiddleware>(); }); builder.UseMiddleware<ResponseContextItemsCheckMiddleware>(); builder.UseMiddleware<JobHostPipelineMiddleware>(); builder.UseMiddleware<FunctionInvocationMiddleware>(); // Register /admin/vfs, and /admin/zip to the VirtualFileSystem middleware. builder.UseWhen(VirtualFileSystemMiddleware.IsVirtualFileSystemRequest, config => config.UseMiddleware<VirtualFileSystemMiddleware>()); // Ensure the HTTP binding routing is registered after all middleware builder.UseHttpBindingRouting(applicationLifetime, routes); builder.UseMvc(); return builder; } } }
48.623656
174
0.698364
[ "MIT" ]
ankitkumarr/azure-functions-host
src/WebJobs.Script.WebHost/WebJobsApplicationBuilderExtension.cs
4,522
C#
// <auto-generated> using KyGunCo.Counterpoint.Sdk.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace KyGunCo.Counterpoint.Sdk.Configuration { // VI_INV_HIST_QTY public class ViInvHistQtyConfiguration : IEntityTypeConfiguration<ViInvHistQty> { public void Configure(EntityTypeBuilder<ViInvHistQty> builder) { builder.ToView("VI_INV_HIST_QTY", "dbo"); builder.HasNoKey(); builder.Property(x => x.Type).HasColumnName(@"TYPE").HasColumnType("varchar(1)").IsRequired().IsUnicode(false).HasMaxLength(1); builder.Property(x => x.FullType).HasColumnName(@"FULL_TYPE").HasColumnType("varchar(1)").IsRequired().IsUnicode(false).HasMaxLength(1); builder.Property(x => x.EventNo).HasColumnName(@"EVENT_NO").HasColumnType("varchar(15)").IsRequired(false).IsUnicode(false).HasMaxLength(15); builder.Property(x => x.ItemNo).HasColumnName(@"ITEM_NO").HasColumnType("varchar(20)").IsRequired().IsUnicode(false).HasMaxLength(20); builder.Property(x => x.LocId).HasColumnName(@"LOC_ID").HasColumnType("varchar(10)").IsRequired(false).IsUnicode(false).HasMaxLength(10); builder.Property(x => x.Qty).HasColumnName(@"QTY").HasColumnType("decimal(38,14)").IsRequired(false); builder.Property(x => x.TrxDat).HasColumnName(@"TRX_DAT").HasColumnType("datetime").IsRequired(false); builder.Property(x => x.ExtCost).HasColumnName(@"EXT_COST").HasColumnType("decimal(21,8)").IsRequired(false); builder.Property(x => x.ExtRet).HasColumnName(@"EXT_RET").HasColumnType("decimal(35,8)").IsRequired(false); builder.Property(x => x.TotCostCorr).HasColumnName(@"TOT_COST_CORR").HasColumnType("decimal(21,8)").IsRequired(false); builder.Property(x => x.ExtPrc).HasColumnName(@"EXT_PRC").HasColumnType("decimal(21,8)").IsRequired(false); builder.Property(x => x.DocNo).HasColumnName(@"DOC_NO").HasColumnType("varchar(15)").IsRequired(false).IsUnicode(false).HasMaxLength(15); builder.Property(x => x.Descr).HasColumnName(@"DESCR").HasColumnType("varchar(50)").IsRequired(false).IsUnicode(false).HasMaxLength(50); builder.Property(x => x.CategCod).HasColumnName(@"CATEG_COD").HasColumnType("varchar(10)").IsRequired(false).IsUnicode(false).HasMaxLength(10); builder.Property(x => x.SubcatCod).HasColumnName(@"SUBCAT_COD").HasColumnType("varchar(10)").IsRequired(false).IsUnicode(false).HasMaxLength(10); builder.Property(x => x.ItemVendNo).HasColumnName(@"ITEM_VEND_NO").HasColumnType("varchar(15)").IsRequired(false).IsUnicode(false).HasMaxLength(15); builder.Property(x => x.OthrLoc).HasColumnName(@"OTHR_LOC").HasColumnType("varchar(10)").IsRequired(false).IsUnicode(false).HasMaxLength(10); builder.Property(x => x.UnitRetl).HasColumnName(@"UNIT_RETL").HasColumnType("decimal(38,11)").IsRequired(false); builder.Property(x => x.UnitRegPrc).HasColumnName(@"UNIT_REG_PRC").HasColumnType("decimal(38,11)").IsRequired(false); builder.Property(x => x.UnitCalcPrc).HasColumnName(@"UNIT_CALC_PRC").HasColumnType("decimal(38,11)").IsRequired(false); builder.Property(x => x.UnitPrc).HasColumnName(@"UNIT_PRC").HasColumnType("decimal(38,11)").IsRequired(false); builder.Property(x => x.UnitPrc1).HasColumnName(@"UNIT_PRC_1").HasColumnType("decimal(38,11)").IsRequired(false); builder.Property(x => x.UnitCost).HasColumnName(@"UNIT_COST").HasColumnType("decimal(38,11)").IsRequired(false); } } } // </auto-generated>
81.733333
160
0.700653
[ "MIT" ]
kygunco/KyGunCo.Counterpoint
Source/KyGunCo.Counterpoint.Sdk/Configuration/ViInvHistQtyConfiguration.cs
3,678
C#
using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.Localization; using S22.IMAP.Models; using S22.IMAP.Services; using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Web; namespace S22.IMAP.Drivers { /// <summary> /// We define a specific driver instead of using a TemplateFilterForRecord, because we need the model to be the part and not the record. /// Thus the encryption/decryption will be done when accessing the part's property /// </summary> public class IMAPSettingPartDriver : ContentPartDriver<IMAPSettingPart> { private const string TemplateName = "Parts/IMAPSettings"; private readonly IIMAPHostRecordService imapHostRecordService; public IMAPSettingPartDriver(IIMAPHostRecordService imapHostRecordService) { this.imapHostRecordService = imapHostRecordService; T = NullLocalizer.Instance; } public Localizer T { get; set; } protected override string Prefix { get { return "IMAPSettings"; } } protected override DriverResult Editor(IMAPSettingPart part, dynamic shapeHelper) { return ContentShape("Parts_IMAPSettings_Edit", () => shapeHelper.EditorTemplate(TemplateName: TemplateName, Model: part, Prefix: Prefix)) .OnGroup("IMAP email"); } protected override DriverResult Editor(IMAPSettingPart part, IUpdateModel updater, dynamic shapeHelper) { var previousPassword = part.Password; updater.TryUpdateModel(part, Prefix, null, null); // check whether the form is posted or not IsRenderedModel temp = new IsRenderedModel(); updater.TryUpdateModel(temp, Prefix, null, null); if (!temp.IsRendered) { return null; } if (!part.IsValid()) { return null; } part.Host = part.Host.Trim(); var record = this.imapHostRecordService.Get(part.Host); if (record != null && part.EmailsFromMinutesBefore != 0) { var date = DateTime.UtcNow.AddMinutes(-part.EmailsFromMinutesBefore); record = record ?? this.imapHostRecordService.Create(part.Host, 0, date); record.EmailUid = 0; record.FromDate = date; this.imapHostRecordService.Save(record); } else { var from = DateTime.UtcNow.AddMinutes(-part.EmailsFromMinutesBefore); record = record ?? this.imapHostRecordService.Create(part.Host, 0, from); record.FromDate = from; this.imapHostRecordService.Save(record); } part.LastSuccessfullConnectionTime = null; part.LatestError = string.Empty; part.LatestErrorTime = null; return ContentShape("Parts_IMAPSettings_Edit", () => { // restore password if the input is empty, meaning it has not been reseted if (string.IsNullOrEmpty(part.Password)) { part.Password = previousPassword; } return shapeHelper.EditorTemplate(TemplateName: TemplateName, Model: part, Prefix: Prefix); }) .OnGroup("IMAP email"); } /// <summary> /// The class is used to check whether the part is posted or not, because by visiting any /// Part of the SiteSetting, Orchard tries to update all of the Parts of the SiteSetting /// </summary> private class IsRenderedModel { public bool IsRendered { get; set; } } } }
38.076923
142
0.586111
[ "MIT" ]
AccentureRapid/OrchardCollaboration
src/Orchard.Web/Modules/S22.IMAP/Drivers/IMAPSettingPartDriver.cs
3,962
C#